From 6ef58c98c849f6ad9bb7300afc34e06b172eb233 Mon Sep 17 00:00:00 2001 From: solvedDev Date: Sat, 23 Jul 2022 15:16:05 +0200 Subject: [PATCH] v0.9.15 - fix: file collection containing file with name of template file not generating file - upd: make useTemplate function accept an options object instead of raw boolean towards bridge-core/editor#132 --- dist/Plugins/BuiltIn/GeneratorScripts/Module.d.ts | 6 +++++- dist/dash-compiler.bundled.es.js | 6 +++--- dist/dash-compiler.bundled.umd.js | 2 +- dist/dash-compiler.es.js | 6 +++--- dist/dash-compiler.umd.js | 2 +- package.json | 2 +- src/Plugins/BuiltIn/GeneratorScripts/Module.ts | 9 ++++++++- src/Plugins/BuiltIn/GeneratorScripts/Plugin.ts | 7 +++++-- 8 files changed, 27 insertions(+), 13 deletions(-) diff --git a/dist/Plugins/BuiltIn/GeneratorScripts/Module.d.ts b/dist/Plugins/BuiltIn/GeneratorScripts/Module.d.ts index 190230f..b95d7b7 100644 --- a/dist/Plugins/BuiltIn/GeneratorScripts/Module.d.ts +++ b/dist/Plugins/BuiltIn/GeneratorScripts/Module.d.ts @@ -7,7 +7,11 @@ export interface IModuleOpts { fileSystem: FileSystem; console: Console; } +interface IUseTemplateOptions { + omitTemplate?: boolean; +} export declare function createModule({ generatorPath, omitUsedTemplates, fileSystem, console, }: IModuleOpts): { - useTemplate: (filePath: string, omitTemplate?: boolean) => Promise; + useTemplate: (filePath: string, { omitTemplate }?: IUseTemplateOptions) => Promise; createCollection: () => Collection; }; +export {}; diff --git a/dist/dash-compiler.bundled.es.js b/dist/dash-compiler.bundled.es.js index 4218718..da70d5e 100644 --- a/dist/dash-compiler.bundled.es.js +++ b/dist/dash-compiler.bundled.es.js @@ -7661,7 +7661,7 @@ function createModule({ console: console2 }) { return { - useTemplate: (filePath, omitTemplate = true) => { + useTemplate: (filePath, { omitTemplate = true } = {}) => { const templatePath = pathBrowserify.join(pathBrowserify.dirname(generatorPath), filePath); if (omitTemplate) omitUsedTemplates.add(templatePath); @@ -7747,13 +7747,13 @@ const GeneratorScriptsPlugin = ({ } return module.__default__; } + }, + finalizeBuild(filePath, fileContent) { if (fileCollection.get(filePath)) { if (filePath.endsWith(".json") && typeof fileContent !== "string") return JSON.stringify(fileContent, null, " "); return fileContent; } - }, - finalizeBuild(filePath, fileContent) { if (omitUsedTemplates.has(filePath)) return null; if (isGeneratorScript(filePath)) { diff --git a/dist/dash-compiler.bundled.umd.js b/dist/dash-compiler.bundled.umd.js index 90e8428..c310dba 100644 --- a/dist/dash-compiler.bundled.umd.js +++ b/dist/dash-compiler.bundled.umd.js @@ -35,7 +35,7 @@ const ${i.specifiers[0].local.value} = await ___require(${i.source.raw});`);else await ___require(${i.source.raw});`:` const {${D.join(", ")}} = await ___require(${i.source.raw});`;g(i.span.start,i.span.end,w)}}),C.toString()+E}class sE{constructor(A){if(this.evaluatedModules=new Map,this.baseModules=new Map,this.env={},A)for(const[I,C]of A)this.registerModule(I,C)}async run(A,I={},C){return this.env=I,await this.eval(A,C)}clearCache(){this.evaluatedModules.clear()}registerModule(A,I){this.baseModules.set(A,I)}async eval(A,I){const C=this.evaluatedModules.get(A);if(C)return C;const g=W.dirname(A),B=A.endsWith(".js")?"ecmascript":"typescript";if(I||(I=await this.readFile(A).catch(()=>{})),!I)throw new Error(`File "${A}" not found`);if(RI===null)throw new Error("You must call initRuntimes() before using the runtime");await RI;let E=CE(oQ(I,{filename:W.basename(A),jsc:{parser:{syntax:B,preserveAllComments:!1,topLevelAwait:!0},target:"es2020"}}).code,{compress:!1,mangle:!1,format:{beautify:!0}}).code;const{type:i,body:D}=QE(E,{syntax:B,target:"es2022"}),w=D[0].span.start,M=GE(E,D,w),o={};try{await this.runSrc(M,Object.assign({},this.env,{___module:o,___require:N=>this.require(N,g)}))}catch(N){throw new Error(`Error in ${A}: ${N}`)}return this.evaluatedModules.set(A,o),o}async require(A,I){const C=this.baseModules.get(A);if(C)return typeof C=="function"?await C():C;if(A.startsWith("https://")){const E=await(await fetch(A)).text();return await this.eval(A,E)}if(A.startsWith(".")&&(A=W.join(I,A)),A.endsWith(".json")){const B=await this.readFile(A).catch(()=>{});if(B){let E={};try{E=cA.parse(B)}catch{throw new Error(`File "${A}" contains invalid JSON`)}return{__default__:E,...E}}}const g=[".ts",".js"];for(const B of g){const E=`${A}${B}`;let i=await this.readFile(E).catch(()=>{});if(!!i)return await this.eval(E,i)}throw new Error(`Module "${A}" not found`)}async runSrc(A,I){return new Function(...Object.keys(I),`return (async () => { ${A} -})()`)(...Object.values(I))}}let RI=null;function kE(Q){RI=MQ(Q).then(()=>null)}const LE=({options:Q})=>({async transformPath(A){if(!!(A!=null&&A.endsWith(".ts")))return`${A.slice(0,-3)}.js`},async read(A,I){if(!A.endsWith(".ts")||!I)return;const C=await I.getFile();return await(C==null?void 0:C.text())},async load(A,I){if(!!A.endsWith(".ts"))return await RI,oQ(I,{filename:W.basename(A),sourceMaps:Q!=null&&Q.inlineSourceMap?"inline":void 0,jsc:{parser:{syntax:"typescript"},target:"es2020"}}).code},finalizeBuild(A,I){if(A.endsWith(".ts")&&typeof I=="string")return I}}),FE=({options:Q,outputFileSystem:A,projectRoot:I,packType:C,fileType:g,console:B})=>{Q.packName||(Q.packName="bridge project");const E=M=>M.split(/\\|\//g).filter(o=>o!==".."&&o!==".").slice(1).join("/"),i=M=>{const o=C.getId(M),N=W.relative(I,M);if(o==="behaviorPack"||o==="resourcePack"||o==="skinPack")return W.join(I,"builds/dist",o,E(N))},D=M=>{const o=C.getId(M),N=W.relative(I,M);if(o==="worldTemplate")return W.join(I,"builds/dist",E(N));if(o==="behaviorPack"||o==="resourcePack")return W.join(I,"builds/dist",o==="behaviorPack"?"behavior_packs":"resource_packs",Q.packName,E(N))},w=M=>g.getId(M)==="worldManifest"?null:D(M);return{async buildStart(){await A.unlink(`${I}/builds/dist`).catch(()=>{})},transformPath(M){if(!!M)switch(Q.format){case"mcaddon":return i(M);case"mcworld":return w(M);case"mctemplate":return D(M);default:B.error(`Unknown packaging format: ${Q.format}`)}}}},JE=({projectConfig:Q,packType:A,options:I})=>{const C=Object.keys(Q.getAvailablePacks()),g=Object.fromEntries(C.map(E=>[E,[]])),B=E=>{const i=A.getId(E);if(i!=="unknown")return[i,Q.resolvePackPath(i,"contents.json")]};return I.buildType!=="fullBuild"?{}:{include(){return C.map(E=>[Q.resolvePackPath(E,"contents.json"),{isVirtual:!0}])},read(E){const i=B(E);if(!i)return;const[D,w]=i;if(E!==w)return g[D]},transformPath(E){if(!E)return;const i=A.getId(E);i!=="unknown"&&g[i].push(E)},finalizeBuild(E){const i=B(E);if(!i)return;const[D,w]=i;if(E!==w)return JSON.stringify(g[D])}}},hE=({fileType:Q})=>{const A=[];for(const C of Q.all)C.formatVersionMap&&A.push(C.id);const I=C=>C&&A.includes(Q.getId(C));return{async read(C,g){if(!!g&&I(C)){const B=await g.getFile();if(!B)return;try{return cA.parse(await B.text())}catch(E){console.error(E)}}},load(C,g){if(I(C))return g},transform(C,g){if(I(C)){const B=Q.get(C),E=B==null?void 0:B.formatVersionMap;if(!E)return;const i=g==null?void 0:g.format_version;return i&&E[i]&&(g.format_version=E[i]),g}},finalizeBuild(C,g){if(I(C))return JSON.stringify(g)}}};class CC{constructor(A,I){this.console=A,this.baseDir=I,this.files=new Map}get hasFiles(){return this.files.size>0}getAll(){return[...this.files.entries()]}get(A){return this.files.get(A)}clear(){this.files.clear()}add(A,I){const C=this.baseDir?W.join(this.baseDir,A):A;if(this.files.has(C)){this.console.warn(`Omitting file "${C}" from collection because it would overwrite a previously generated file!`);return}this.files.set(C,I)}addFrom(A){for(const[I,C]of A.getAll())this.add(I,C)}}function aE({generatorPath:Q,omitUsedTemplates:A,fileSystem:I,console:C}){return{useTemplate:(g,B=!0)=>{const E=W.join(W.dirname(Q),g);return B&&A.add(E),g.endsWith(".json")?I.readJson(E):I.readFile(E).then(i=>i.text())},createCollection:()=>new CC(C,W.dirname(Q))}}const RE=({fileType:Q,console:A,jsRuntime:I,fileSystem:C,compileFiles:g})=>{const B=new Set(["gameTest","customCommand","customComponent"]),E=N=>Q.getId(N),i=N=>{var R;const F=Q.get(N);return F?(R=F.type)!=null?R:"json":"raw"},D=N=>!B.has(E(N))&&(N.endsWith(".js")||N.endsWith(".ts")),w=N=>{var R,a,G,s;return i(N)==="json"?".json":(s=(G=(a=(R=Q.get(N))==null?void 0:R.detect)==null?void 0:a.fileExtensions)==null?void 0:G[0])!=null?s:".txt"},M=new Set,o=new CC(A);return{buildStart(){o.clear(),M.clear()},transformPath(N){if(N&&D(N))return N.replace(/\.(js|ts)$/,w(N))},async read(N,F){if(D(N)&&F){const a=await F.getFile();return a?a.text():void 0}const R=o.get(N);if(R)return R},async load(N,F){if(I.registerModule("@bridge/generate",aE({generatorPath:N,fileSystem:C,omitUsedTemplates:M,console:A})),D(N)){if(!F)return null;const R=await I.run(N,{console:A},F).catch(a=>(A.error(`Failed to execute generator script "${N}": ${a}`),null));return R?R.__default__?R.__default__:(A.error(`Expected generator script "${N}" to provide file content as default export!`),null):null}if(o.get(N))return N.endsWith(".json")&&typeof F!="string"?JSON.stringify(F,null," "):F},finalizeBuild(N,F){if(M.has(N))return null;if(D(N))return F===null?null:F instanceof CC?(o.addFrom(F),null):typeof F=="object"?JSON.stringify(F):F},async buildEnd(){I.deleteModule("@bridge/generate"),o.hasFiles&&await g(o.getAll().map(([N])=>N))}}};class sQ extends sE{constructor(A,I){super(I),this.fs=A}readFile(A){return this.fs.readFile(A).then(I=>I.text())}deleteModule(A){this.baseModules.delete(A)}}const kQ={simpleRewrite:ng,rewriteForPackaging:FE,moLang:OB,entityIdentifierAlias:pB,customEntityComponents:PB,customItemComponents:eB,customBlockComponents:rB,customCommands:$B,typeScript:LE,contentsFile:JE,formatVersionCorrection:hE,generatorScripts:RE};class YE{constructor(A){this.dash=A,this.plugins=[],this.pluginRuntime=new sQ(this.dash.fileSystem)}async loadPlugins(A={}){var B,E;this.plugins=[],this.pluginRuntime.clearCache();const I=[...(await this.dash.fileSystem.readdir(W.join(this.dash.projectRoot,".bridge/extensions")).catch(()=>[])).map(i=>i.kind==="directory"?W.join(this.dash.projectRoot,".bridge/extensions",i.name):void 0),...(await this.dash.fileSystem.readdir("extensions").catch(()=>[])).map(i=>i.kind==="directory"?W.join("extensions",i.name):void 0)],C={};for(const i of I){if(!i)continue;let D;try{D=await this.dash.fileSystem.readJson(W.join(i,"manifest.json"))}catch{continue}if(!!((B=D==null?void 0:D.compiler)!=null&&B.plugins))for(const w in D.compiler.plugins)C[w]=W.join(i,D.compiler.plugins[w])}const g=(E=(await this.getCompilerOptions()).plugins)!=null?E:[];for(const i of g){const D=typeof i=="string"?i:i[0],w=typeof i=="string"?{}:i[1];if(C[D]){const M=await this.pluginRuntime.run(C[D],{console:this.dash.console,...A}).catch(o=>(this.dash.console.error(`Failed to execute plugin ${D}: ${o}`),null));if(!M)continue;typeof M.__default__=="function"?this.plugins.push(new XC(this.dash,D,M.__default__(await this.getPluginContext(D,w)))):this.dash.console.error(`Plugin ${D} is invalid: It does not provide a function as a default export.`)}else kQ[D]?this.plugins.push(new XC(this.dash,D,kQ[D](await this.getPluginContext(D,w)))):this.dash.console.error(`Unknown compiler plugin: ${D}`)}}async getCompilerOptions(){var I;const A=await this.dash.getCompilerConfigPath();return A?await this.dash.fileSystem.readJson(A):(I=this.dash.projectConfig.get().compiler)!=null?I:{}}async getPluginContext(A,I={}){const C=this.dash;return{options:{get mode(){return C.getMode()},get buildType(){return C.buildType},...I},jsRuntime:this.dash.jsRuntime,console:this.dash.console,fileSystem:this.dash.fileSystem,outputFileSystem:this.dash.outputFileSystem,projectConfig:this.dash.projectConfig,projectRoot:this.dash.projectRoot,packType:this.dash.packType,fileType:this.dash.fileType,targetVersion:this.dash.projectConfig.get().targetVersion,requestJsonData:this.dash.requestJsonData,getAliases:g=>{var B,E;return[...(E=(B=this.dash.includedFiles.get(g))==null?void 0:B.aliases)!=null?E:[]]},hasComMojangDirectory:this.dash.fileSystem!==this.dash.outputFileSystem,compileFiles:g=>this.dash.compileVirtualFiles(g)}}async runBuildStartHooks(){for(const A of this.plugins)await A.runBuildStartHook()}async runIncludeHooks(){let A=[];for(const I of this.plugins){const C=await I.runIncludeHook();Array.isArray(C)&&A.push(...C)}return A}async runTransformPathHooks(A){let I=A;for(const C of this.plugins){const g=await C.runTransformPathHook(I);if(g===null)return null;g!==void 0&&(I=g)}return I}async runReadHooks(A,I){for(const C of this.plugins){const g=await C.runReadHook(A,I);if(g!=null)return g}}async runLoadHooks(A,I){let C=I;for(const g of this.plugins){const B=await g.runLoadHook(A,C);B!==void 0&&(C=B)}return C}async runRegisterAliasesHooks(A,I){const C=new Set;for(const g of this.plugins){const B=await g.runRegisterAliasesHook(A,I);B!=null&&(Array.isArray(B)?B.forEach(E=>C.add(E)):C.add(B))}return C}async runRequireHooks(A,I){const C=new Set;for(const g of this.plugins){const B=await g.runRequireHook(A,I);B!=null&&(Array.isArray(B)?B.forEach(E=>C.add(E)):C.add(B))}return C}async runTransformHooks(A){const I=Object.fromEntries([...A.requiredFiles].map(g=>this.dash.includedFiles.query(g)).flat().map(g=>[[g.filePath,g.data],...[...g.aliases].map(B=>[B,g.data])]).flat());let C=A.data;for(const g of this.plugins){const B=await g.runTransformHook(A.filePath,C,I);B!==void 0&&(C=B)}return C}async runFinalizeBuildHooks(A){for(const I of this.plugins){const C=await I.runFinalizeBuildHook(A.filePath,A.data);if(C!==void 0)return C}}async runBuildEndHooks(){for(const A of this.plugins)await A.runBuildEndHook()}}/*! +})()`)(...Object.values(I))}}let RI=null;function kE(Q){RI=MQ(Q).then(()=>null)}const LE=({options:Q})=>({async transformPath(A){if(!!(A!=null&&A.endsWith(".ts")))return`${A.slice(0,-3)}.js`},async read(A,I){if(!A.endsWith(".ts")||!I)return;const C=await I.getFile();return await(C==null?void 0:C.text())},async load(A,I){if(!!A.endsWith(".ts"))return await RI,oQ(I,{filename:W.basename(A),sourceMaps:Q!=null&&Q.inlineSourceMap?"inline":void 0,jsc:{parser:{syntax:"typescript"},target:"es2020"}}).code},finalizeBuild(A,I){if(A.endsWith(".ts")&&typeof I=="string")return I}}),FE=({options:Q,outputFileSystem:A,projectRoot:I,packType:C,fileType:g,console:B})=>{Q.packName||(Q.packName="bridge project");const E=M=>M.split(/\\|\//g).filter(o=>o!==".."&&o!==".").slice(1).join("/"),i=M=>{const o=C.getId(M),N=W.relative(I,M);if(o==="behaviorPack"||o==="resourcePack"||o==="skinPack")return W.join(I,"builds/dist",o,E(N))},D=M=>{const o=C.getId(M),N=W.relative(I,M);if(o==="worldTemplate")return W.join(I,"builds/dist",E(N));if(o==="behaviorPack"||o==="resourcePack")return W.join(I,"builds/dist",o==="behaviorPack"?"behavior_packs":"resource_packs",Q.packName,E(N))},w=M=>g.getId(M)==="worldManifest"?null:D(M);return{async buildStart(){await A.unlink(`${I}/builds/dist`).catch(()=>{})},transformPath(M){if(!!M)switch(Q.format){case"mcaddon":return i(M);case"mcworld":return w(M);case"mctemplate":return D(M);default:B.error(`Unknown packaging format: ${Q.format}`)}}}},JE=({projectConfig:Q,packType:A,options:I})=>{const C=Object.keys(Q.getAvailablePacks()),g=Object.fromEntries(C.map(E=>[E,[]])),B=E=>{const i=A.getId(E);if(i!=="unknown")return[i,Q.resolvePackPath(i,"contents.json")]};return I.buildType!=="fullBuild"?{}:{include(){return C.map(E=>[Q.resolvePackPath(E,"contents.json"),{isVirtual:!0}])},read(E){const i=B(E);if(!i)return;const[D,w]=i;if(E!==w)return g[D]},transformPath(E){if(!E)return;const i=A.getId(E);i!=="unknown"&&g[i].push(E)},finalizeBuild(E){const i=B(E);if(!i)return;const[D,w]=i;if(E!==w)return JSON.stringify(g[D])}}},hE=({fileType:Q})=>{const A=[];for(const C of Q.all)C.formatVersionMap&&A.push(C.id);const I=C=>C&&A.includes(Q.getId(C));return{async read(C,g){if(!!g&&I(C)){const B=await g.getFile();if(!B)return;try{return cA.parse(await B.text())}catch(E){console.error(E)}}},load(C,g){if(I(C))return g},transform(C,g){if(I(C)){const B=Q.get(C),E=B==null?void 0:B.formatVersionMap;if(!E)return;const i=g==null?void 0:g.format_version;return i&&E[i]&&(g.format_version=E[i]),g}},finalizeBuild(C,g){if(I(C))return JSON.stringify(g)}}};class CC{constructor(A,I){this.console=A,this.baseDir=I,this.files=new Map}get hasFiles(){return this.files.size>0}getAll(){return[...this.files.entries()]}get(A){return this.files.get(A)}clear(){this.files.clear()}add(A,I){const C=this.baseDir?W.join(this.baseDir,A):A;if(this.files.has(C)){this.console.warn(`Omitting file "${C}" from collection because it would overwrite a previously generated file!`);return}this.files.set(C,I)}addFrom(A){for(const[I,C]of A.getAll())this.add(I,C)}}function aE({generatorPath:Q,omitUsedTemplates:A,fileSystem:I,console:C}){return{useTemplate:(g,{omitTemplate:B=!0}={})=>{const E=W.join(W.dirname(Q),g);return B&&A.add(E),g.endsWith(".json")?I.readJson(E):I.readFile(E).then(i=>i.text())},createCollection:()=>new CC(C,W.dirname(Q))}}const RE=({fileType:Q,console:A,jsRuntime:I,fileSystem:C,compileFiles:g})=>{const B=new Set(["gameTest","customCommand","customComponent"]),E=N=>Q.getId(N),i=N=>{var R;const F=Q.get(N);return F?(R=F.type)!=null?R:"json":"raw"},D=N=>!B.has(E(N))&&(N.endsWith(".js")||N.endsWith(".ts")),w=N=>{var R,a,G,s;return i(N)==="json"?".json":(s=(G=(a=(R=Q.get(N))==null?void 0:R.detect)==null?void 0:a.fileExtensions)==null?void 0:G[0])!=null?s:".txt"},M=new Set,o=new CC(A);return{buildStart(){o.clear(),M.clear()},transformPath(N){if(N&&D(N))return N.replace(/\.(js|ts)$/,w(N))},async read(N,F){if(D(N)&&F){const a=await F.getFile();return a?a.text():void 0}const R=o.get(N);if(R)return R},async load(N,F){if(I.registerModule("@bridge/generate",aE({generatorPath:N,fileSystem:C,omitUsedTemplates:M,console:A})),D(N)){if(!F)return null;const R=await I.run(N,{console:A},F).catch(a=>(A.error(`Failed to execute generator script "${N}": ${a}`),null));return R?R.__default__?R.__default__:(A.error(`Expected generator script "${N}" to provide file content as default export!`),null):null}},finalizeBuild(N,F){if(o.get(N))return N.endsWith(".json")&&typeof F!="string"?JSON.stringify(F,null," "):F;if(M.has(N))return null;if(D(N))return F===null?null:F instanceof CC?(o.addFrom(F),null):typeof F=="object"?JSON.stringify(F):F},async buildEnd(){I.deleteModule("@bridge/generate"),o.hasFiles&&await g(o.getAll().map(([N])=>N))}}};class sQ extends sE{constructor(A,I){super(I),this.fs=A}readFile(A){return this.fs.readFile(A).then(I=>I.text())}deleteModule(A){this.baseModules.delete(A)}}const kQ={simpleRewrite:ng,rewriteForPackaging:FE,moLang:OB,entityIdentifierAlias:pB,customEntityComponents:PB,customItemComponents:eB,customBlockComponents:rB,customCommands:$B,typeScript:LE,contentsFile:JE,formatVersionCorrection:hE,generatorScripts:RE};class YE{constructor(A){this.dash=A,this.plugins=[],this.pluginRuntime=new sQ(this.dash.fileSystem)}async loadPlugins(A={}){var B,E;this.plugins=[],this.pluginRuntime.clearCache();const I=[...(await this.dash.fileSystem.readdir(W.join(this.dash.projectRoot,".bridge/extensions")).catch(()=>[])).map(i=>i.kind==="directory"?W.join(this.dash.projectRoot,".bridge/extensions",i.name):void 0),...(await this.dash.fileSystem.readdir("extensions").catch(()=>[])).map(i=>i.kind==="directory"?W.join("extensions",i.name):void 0)],C={};for(const i of I){if(!i)continue;let D;try{D=await this.dash.fileSystem.readJson(W.join(i,"manifest.json"))}catch{continue}if(!!((B=D==null?void 0:D.compiler)!=null&&B.plugins))for(const w in D.compiler.plugins)C[w]=W.join(i,D.compiler.plugins[w])}const g=(E=(await this.getCompilerOptions()).plugins)!=null?E:[];for(const i of g){const D=typeof i=="string"?i:i[0],w=typeof i=="string"?{}:i[1];if(C[D]){const M=await this.pluginRuntime.run(C[D],{console:this.dash.console,...A}).catch(o=>(this.dash.console.error(`Failed to execute plugin ${D}: ${o}`),null));if(!M)continue;typeof M.__default__=="function"?this.plugins.push(new XC(this.dash,D,M.__default__(await this.getPluginContext(D,w)))):this.dash.console.error(`Plugin ${D} is invalid: It does not provide a function as a default export.`)}else kQ[D]?this.plugins.push(new XC(this.dash,D,kQ[D](await this.getPluginContext(D,w)))):this.dash.console.error(`Unknown compiler plugin: ${D}`)}}async getCompilerOptions(){var I;const A=await this.dash.getCompilerConfigPath();return A?await this.dash.fileSystem.readJson(A):(I=this.dash.projectConfig.get().compiler)!=null?I:{}}async getPluginContext(A,I={}){const C=this.dash;return{options:{get mode(){return C.getMode()},get buildType(){return C.buildType},...I},jsRuntime:this.dash.jsRuntime,console:this.dash.console,fileSystem:this.dash.fileSystem,outputFileSystem:this.dash.outputFileSystem,projectConfig:this.dash.projectConfig,projectRoot:this.dash.projectRoot,packType:this.dash.packType,fileType:this.dash.fileType,targetVersion:this.dash.projectConfig.get().targetVersion,requestJsonData:this.dash.requestJsonData,getAliases:g=>{var B,E;return[...(E=(B=this.dash.includedFiles.get(g))==null?void 0:B.aliases)!=null?E:[]]},hasComMojangDirectory:this.dash.fileSystem!==this.dash.outputFileSystem,compileFiles:g=>this.dash.compileVirtualFiles(g)}}async runBuildStartHooks(){for(const A of this.plugins)await A.runBuildStartHook()}async runIncludeHooks(){let A=[];for(const I of this.plugins){const C=await I.runIncludeHook();Array.isArray(C)&&A.push(...C)}return A}async runTransformPathHooks(A){let I=A;for(const C of this.plugins){const g=await C.runTransformPathHook(I);if(g===null)return null;g!==void 0&&(I=g)}return I}async runReadHooks(A,I){for(const C of this.plugins){const g=await C.runReadHook(A,I);if(g!=null)return g}}async runLoadHooks(A,I){let C=I;for(const g of this.plugins){const B=await g.runLoadHook(A,C);B!==void 0&&(C=B)}return C}async runRegisterAliasesHooks(A,I){const C=new Set;for(const g of this.plugins){const B=await g.runRegisterAliasesHook(A,I);B!=null&&(Array.isArray(B)?B.forEach(E=>C.add(E)):C.add(B))}return C}async runRequireHooks(A,I){const C=new Set;for(const g of this.plugins){const B=await g.runRequireHook(A,I);B!=null&&(Array.isArray(B)?B.forEach(E=>C.add(E)):C.add(B))}return C}async runTransformHooks(A){const I=Object.fromEntries([...A.requiredFiles].map(g=>this.dash.includedFiles.query(g)).flat().map(g=>[[g.filePath,g.data],...[...g.aliases].map(B=>[B,g.data])]).flat());let C=A.data;for(const g of this.plugins){const B=await g.runTransformHook(A.filePath,C,I);B!==void 0&&(C=B)}return C}async runFinalizeBuildHooks(A){for(const I of this.plugins){const C=await I.runFinalizeBuildHook(A.filePath,A.data);if(C!==void 0)return C}}async runBuildEndHooks(){for(const A of this.plugins)await A.runBuildEndHook()}}/*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. diff --git a/dist/dash-compiler.es.js b/dist/dash-compiler.es.js index b390e27..b347e06 100644 --- a/dist/dash-compiler.es.js +++ b/dist/dash-compiler.es.js @@ -1489,7 +1489,7 @@ function createModule({ console: console2 }) { return { - useTemplate: (filePath, omitTemplate = true) => { + useTemplate: (filePath, { omitTemplate = true } = {}) => { const templatePath = join(dirname(generatorPath), filePath); if (omitTemplate) omitUsedTemplates.add(templatePath); @@ -1575,13 +1575,13 @@ const GeneratorScriptsPlugin = ({ } return module.__default__; } + }, + finalizeBuild(filePath, fileContent) { if (fileCollection.get(filePath)) { if (filePath.endsWith(".json") && typeof fileContent !== "string") return JSON.stringify(fileContent, null, " "); return fileContent; } - }, - finalizeBuild(filePath, fileContent) { if (omitUsedTemplates.has(filePath)) return null; if (isGeneratorScript(filePath)) { diff --git a/dist/dash-compiler.umd.js b/dist/dash-compiler.umd.js index 45c054b..3e4b713 100644 --- a/dist/dash-compiler.umd.js +++ b/dist/dash-compiler.umd.js @@ -1,4 +1,4 @@ (function(b,T){typeof exports=="object"&&typeof module!="undefined"?T(exports,require("mc-project-core"),require("path-browserify"),require("molang"),require("bridge-common-utils"),require("json5"),require("@swc/wasm-web"),require("bridge-js-runtime"),require("is-glob")):typeof define=="function"&&define.amd?define(["exports","mc-project-core","path-browserify","molang","bridge-common-utils","json5","@swc/wasm-web","bridge-js-runtime","is-glob"],T):(b=typeof globalThis!="undefined"?globalThis:b||self,T(b.DashCompiler={},b.mcProjectCore,b.pathBrowserify,b.molang,b.bridgeCommonUtils,b.json5,b.wasmWeb,b.bridgeJsRuntime,b.isGlob))})(this,function(b,T,v,O,j,Q,Y,q,Z){"use strict";function H(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}var A=H(Q),ee=H(Z);class te extends T.ProjectConfig{constructor(e,s){super(v.dirname(s)),this.fileSystem=e,this.configPath=s}readConfig(){return this.fileSystem.readJson(this.configPath)}writeConfig(e){return this.fileSystem.writeJson(this.configPath,e)}}class N{constructor(e,s,t){this.dash=e,this.pluginId=s,this.plugin=t}async runBuildStartHook(){var e,s;try{return await((s=(e=this.plugin).buildStart)==null?void 0:s.call(e))}catch(t){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "buildStart" hook:`,t)}}async runIncludeHook(){var e,s;try{return await((s=(e=this.plugin).include)==null?void 0:s.call(e))}catch(t){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "include" hook:`,t)}}async runTransformPathHook(e){var s,t;try{return await((t=(s=this.plugin).transformPath)==null?void 0:t.call(s,e))}catch(i){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "transformPath" hook for "${e}":`,i)}}async runReadHook(e,s){var t,i;try{return await((i=(t=this.plugin).read)==null?void 0:i.call(t,e,s))}catch(n){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "read" hook for "${e}":`,n)}}async runLoadHook(e,s){var t,i;try{return await((i=(t=this.plugin).load)==null?void 0:i.call(t,e,s))}catch(n){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "load" hook for "${e}":`,n)}}async runRegisterAliasesHook(e,s){var t,i;try{return await((i=(t=this.plugin).registerAliases)==null?void 0:i.call(t,e,s))}catch(n){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "registerAliases" hook for "${e}":`,n)}}async runRequireHook(e,s){var t,i;try{return await((i=(t=this.plugin).require)==null?void 0:i.call(t,e,s))}catch(n){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "require" hook for "${e}":`,n)}}async runTransformHook(e,s,t){var i,n;try{return await((n=(i=this.plugin).transform)==null?void 0:n.call(i,e,s,t))}catch(a){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "transform" hook for "${e}":`,a)}}async runFinalizeBuildHook(e,s){var t,i;try{return await((i=(t=this.plugin).finalizeBuild)==null?void 0:i.call(t,e,s))}catch(n){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "finalizeBuild" hook for "${e}":`,n)}}async runBuildEndHook(){var e,s;try{return await((s=(e=this.plugin).buildEnd)==null?void 0:s.call(e))}catch(t){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "buildEnd" hook:`,t)}}}const se=({options:r,outputFileSystem:e,hasComMojangDirectory:s,projectConfig:t,projectRoot:i,packType:n})=>{var u;r.buildName||(r.buildName=r.mode==="development"?"dev":"dist"),r.packName||(r.packName="Bridge"),(u=r.rewriteToComMojang)==null||u||(s=!1);const a={behaviorPack:"development_behavior_packs",resourcePack:"development_resource_packs",skinPack:"skin_packs",worldTemplate:"minecraftWorlds"},c=m=>s&&r.mode==="development"?`${a[m]}`:`${i}/builds/${r.buildName}`,l=(m,d)=>`${c(m)}/${r.packName} ${d}`;return{async buildStart(){if(r.mode==="production"||r.buildType==="fullBuild")if(s)for(const m in a){const d=n.getFromId(m);!d||await e.unlink(l(m,d.defaultPackPath)).catch(()=>{})}else await e.unlink(c("BP")).catch(()=>{})},transformPath(m){if(!m||m.includes("BP/scripts/gametests/")&&r.mode==="production")return;const d=n==null?void 0:n.get(m);if(!d)return;const o=t.getAbsolutePackRoot(d.id),f=v.relative(o,m);if(["behaviorPack","resourcePack","skinPack","worldTemplate"].includes(d.id))return v.join(l(d.id,d.defaultPackPath),f)}}},ie=({fileType:r,projectConfig:e,requestJsonData:s,options:t,console:i,jsRuntime:n})=>{const a=(o,f)=>e.resolvePackPath(o,f),c=new O.CustomMoLang({}),l=o=>o==null?void 0:o.endsWith(".molang"),u=o=>o==null?void 0:o.startsWith(e.resolvePackPath("behaviorPack","scripts/molang/")),m=o=>{var f;return(f=Object.entries(t.include).find(([p])=>(r==null?void 0:r.getId(o))===p))==null?void 0:f[1]};let d=[];return{async buildStart(){t.include=Object.assign(await s("data/packages/minecraftBedrock/location/validMoLang.json"),t.include)},transformPath(o){if(l(o)||u(o))return null},async read(o,f){if((l(o)||u(o))&&f){const p=await f.getFile();return await(p==null?void 0:p.text())}else if(m(o)&&o.endsWith(".json")&&f){const p=await f.getFile();if(!p)return;try{return A.default.parse(await p.text())}catch(w){return t.buildType!=="fileRequest"&&i.error(`Error within file "${o}": ${w}`),{__error__:`Failed to load original file: ${w}`}}}},async load(o,f){if(l(o)&&f)c.parse(f);else if(u(o)){const p=await n.run(o,{console:i},f).catch(w=>(i.error(`Failed to execute Molang AST script "${o}": ${w}`),null));if(!p)return null;typeof p.__default__=="function"&&d.push(p.__default__)}},async require(o){if(m(o))return[a("behaviorPack","scripts/molang/**/*.[jt]s"),a("behaviorPack","molang/**/*.molang"),a("resourcePack","molang/**/*.molang")]},async transform(o,f){const p=m(o);p&&p.length>0&&p.forEach(w=>j.setObjectAt(w,f,h=>{if(typeof h!="string"||h[0]==="/"||h[0]==="@")return h;if(d.length>0){let g=null;try{g=c.parse(h)}catch(F){t.buildType!=="fileRequest"&&i.error(`Error within file "${o}"; script "${h}": ${F}`)}if(g){for(const F of d)g=g.walk(F);h=g.toString()}}try{return c.transform(h)}catch(g){return t.buildType!=="fileRequest"&&i.error(`Error within file "${o}"; script "${h}": ${g}`),h}}))},finalizeBuild(o,f){if(m(o)&&typeof f!="string")return JSON.stringify(f,null," ")},buildEnd(){d=[]}}},ne=({fileType:r})=>({registerAliases(e,s){var t,i,n,a;if((r==null?void 0:r.getId(e))==="entity"&&((i=(t=s==null?void 0:s["minecraft:entity"])==null?void 0:t.description)==null?void 0:i.identifier))return[(a=(n=s==null?void 0:s["minecraft:entity"])==null?void 0:n.description)==null?void 0:a.identifier]}});function re(r,e){const s=D(r),t=D(e),i=s.pop(),n=t.pop(),a=V(s,t);return a!==0?a:i&&n?V(i.split("."),n.split(".")):i||n?i?-1:1:0}const ae=(r,e,s)=>{ue(s);const t=re(r,e);return z[s].includes(t)},oe=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,D=r=>{if(typeof r!="string")throw new TypeError("Invalid argument expected string");const e=r.match(oe);if(!e)throw new Error(`Invalid argument not valid semver ('${r}' received)`);return e.shift(),e},W=r=>r==="*"||r==="x"||r==="X",J=r=>{const e=parseInt(r,10);return isNaN(e)?r:e},ce=(r,e)=>typeof r!=typeof e?[String(r),String(e)]:[r,e],le=(r,e)=>{if(W(r)||W(e))return 0;const[s,t]=ce(J(r),J(e));return s>t?1:s{for(let s=0;s":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1]},B=Object.keys(z),ue=r=>{if(typeof r!="string")throw new TypeError(`Invalid operator type, expected string but got ${typeof r}`);if(B.indexOf(r)===-1)throw new Error(`Invalid operator, expected one of ${B.join("|")}`)},de=(r,e)=>({register:s=>{var t;((t=s.type)!=null?t:"entity")===e&&(r.component=({name:i,schema:n,template:a})=>{const c=new s;i(s.component_name),n(R(Object.values(c.onPropose())[0])),a((l,{create:u})=>{u(c.onApply(l,"components")[`minecraft:${e}`])})})}});function R(r){const e={},s=Object.keys(r);if(s.length===1&&s[0].startsWith("$dynamic.list."))return{type:"array",items:R(Object.values(r)[0])};for(const[t,i]of Object.entries(r))t.startsWith("$")||(typeof i=="string"?e[t]=he(i):Array.isArray(i)?e[t]={enum:i}:i==="object"&&(e[t]=R(i)));return{type:"object",properties:e}}function he(r){switch(r){case"$general.boolean":return{type:"boolean"};case"$general.number":return{type:"integer"};case"$general.decimal":return{type:"number"};default:return{type:["number","integer","string","boolean","object","array"]}}}class L{constructor(e,s,t,i,n,a){this.console=e,this.fileType=s,this.componentSrc=t,this.mode=i,this.v1Compat=n,this.targetVersion=a,this.animations=[],this.animationControllers=[],this.createOnPlayer=[],this.dialogueScenes={},this.serverFiles=[],this.clientFiles={},this.lifecycleHookCount={activated:0,deactivated:0}}setProjectConfig(e){this.projectConfig=e}get name(){return this._name}async load(e,s,t){let i={component:null};const n=await e.run(s,{defineComponent:u=>u,console:this.console,Bridge:this.v1Compat?de(i,this.fileType):void 0}).catch(()=>(this.console.error(`Failed to execute component ${s}`),null));if(!n)return!1;if(typeof n.__default__!="function")if(i.component)n.__default__=i.component;else return this.console.error(`Component ${s} is not a valid component. Expected a function as the default export.`),!1;const a=u=>this._name=u;let c=u=>this.schema=u,l=()=>{};return(!t||t==="server")&&(c=()=>{},l=u=>{this.template=(m,d)=>{try{u(m,d)}catch(o){this.console.log(u.toString()),this.console.error(o)}}}),await n.__default__({name:a,schema:c,template:l}),!0}reset(){this.animations=[],this.animationControllers=[],this.clientFiles={},this.serverFiles=[]}getSchema(){return this.schema}toString(){return this.componentSrc}create(e,s,t=`minecraft:${this.fileType}`,i){var l;const n=t.split("/"),a=n.pop(),c=this.getObjAtLocation(e,[...n]);c[a]=(i?(u,m)=>i(j.deepMerge,u,m):j.deepMerge)((l=c[a])!=null?l:{},s!=null?s:{})}getObjAtLocation(e,s){let t=e;for(;s.length>0;){const i=s.shift();t[i]===void 0?t[Number(i)]!==void 0?t=t[Number(i)]:(t[i]={},t=t[i]):t=t[i]}return t}async processTemplates(e,s,t){var h,g,F,$,C,S;if(typeof this.template!="function")return;const i=(F=(g=(h=e[`minecraft:${this.fileType}`])==null?void 0:h.description)==null?void 0:g.identifier)!=null?F:"bridge:no_identifier",n=await j.hashString(`${this.name}/${i}`),a=(S=(C=($=this.projectConfig)==null?void 0:$.get())==null?void 0:C.namespace)!=null?S:"bridge",c=(y,k)=>(this.animations.push([y,k]),this.getShortAnimName("a",n,this.animations.length-1)),l=(y,k)=>(this.animationControllers.push([y,k]),this.getShortAnimName("ac",n,this.animationControllers.length-1)),u=y=>{const k=`loot_tables/bridge/${this.getShortAnimName("lt",n,this.serverFiles.length)}.json`;return this.serverFiles.push([k,y]),k},m=y=>{const k=`trading/bridge/${this.getShortAnimName("tt",n,this.serverFiles.length)}.json`;return this.serverFiles.push([k,y]),k},d=y=>{this.serverFiles.push([`recipes/bridge/${this.getShortAnimName("recipe",n,this.serverFiles.length)}.json`,y])},o=y=>{this.serverFiles.push([`spawn_rules/bridge/${this.getShortAnimName("sr",n,this.serverFiles.length)}.json`,y])},f=(await j.hashString(`${this.name}/${t}`)).slice(0,16),p=y=>this.registerLifecycleHook(e,t,y,f,"activated"),w=y=>this.registerLifecycleHook(e,t,y,f,"deactivated");this.fileType==="entity"?this.template(s!=null?s:{},{mode:this.mode,compilerMode:this.mode,sourceEntity:()=>JSON.parse(JSON.stringify(e)),create:(y,k,_)=>this.create(e,y,k,_),location:t,identifier:i,projectNamespace:a,animationController:l,animation:c,lootTable:u,tradeTable:m,spawnRule:o,dialogueScene:!this.targetVersion||ae(this.targetVersion,"1.17.10",">=")?(y,k=!0)=>{this.dialogueScenes[n]||(this.dialogueScenes[n]=[]),this.dialogueScenes[n].push(y),y.scene_tag&&k&&p({run_command:{command:[`/dialogue open @s @p ${y.scene_tag}`]}})}:void 0,onActivated:p,onDeactivated:w,client:{create:(y,k="1.10.0")=>{this.clientFiles[`entity/bridge/${n}.json`]={format_version:k,"minecraft:client_entity":Object.assign({description:{identifier:i}},y)}}}}):this.fileType==="item"?this.template(s!=null?s:{},{mode:this.mode,compilerMode:this.mode,sourceItem:()=>JSON.parse(JSON.stringify(e)),create:(y,k,_)=>this.create(e,y,k,_),location:t,identifier:i,projectNamespace:a,lootTable:u,recipe:d,player:{animationController:l,animation:c,create:(y,k,_)=>this.createOnPlayer.push([k!=null?k:"minecraft:entity",y,_])}}):this.fileType==="block"&&this.template(s!=null?s:{},{mode:this.mode,compilerMode:this.mode,sourceBlock:()=>JSON.parse(JSON.stringify(e)),create:(y,k,_)=>this.create(e,y,k,_),lootTable:u,recipe:d,location:t,identifier:i,projectNamespace:a})}async processAdditionalFiles(e,s){var u,m,d,o,f,p;const t=(m=(u=this.projectConfig)==null?void 0:u.getRelativePackRoot("behaviorPack"))!=null?m:"BP",i=(d=this.projectConfig)==null?void 0:d.getRelativePackRoot("resourcePack"),n=(p=(f=(o=s[`minecraft:${this.fileType}`])==null?void 0:o.description)==null?void 0:f.identifier)!=null?p:"bridge:no_identifier",a=await j.hashString(`${this.name}/${n}`),c=`${t}/animations/bridge/${a}.json`,l=`${t}/animation_controllers/bridge/${a}.json`;return n==="minecraft:player"&&this.createOnPlayer.forEach(([w,h,g])=>{this.create(s,h,w,g)}),i||(this.clientFiles={},this.console.error(`[${this.name}] Dash was unable to load the root of your resource pack and therefore cannot generate client files for this component.`)),{[c]:{baseFile:e,fileContent:this.createAnimations(a,s)},[l]:{baseFile:e,fileContent:this.createAnimationControllers(a,s)},[v.join(t,`dialogue/bridge/${a}.json`)]:this.dialogueScenes[a]&&this.dialogueScenes[a].length>0?{baseFile:e,fileContent:JSON.stringify({format_version:this.targetVersion,"minecraft:npc_dialogue":{scenes:this.dialogueScenes[a]}},null," ")}:void 0,...Object.fromEntries(this.serverFiles.map(([w,h])=>[v.join(t,w),{baseFile:e,fileContent:JSON.stringify(h,null," ")}])),...Object.fromEntries(Object.entries(this.clientFiles).map(([w,h])=>[v.join(i,w),{baseFile:e,fileContent:JSON.stringify(h,null," ")}]))}}createAnimations(e,s){if(this.animations.length===0)return;let t=0;const i={format_version:"1.10.0",animations:{}};for(const[n,a]of this.animations){if(!n){t++;continue}const c=this.getAnimName("animation",e,t),l=this.getShortAnimName("a",e,t);i.animations[c]=n,this.create(s,{animations:{[l]:c}},"minecraft:entity/description"),a!==!1&&this.create(s,{scripts:{animate:[a?{[l]:a}:l]}},"minecraft:entity/description"),t++}return JSON.stringify(i,null," ")}createAnimationControllers(e,s){if(this.animationControllers.length===0)return;let t=0;const i={format_version:"1.10.0",animation_controllers:{}};for(const[n,a]of this.animationControllers){if(!n){t++;continue}const c=this.getAnimName("controller.animation",e,t),l=this.getShortAnimName("ac",e,t);i.animation_controllers[c]=n,this.create(s,{animations:{[l]:c}},"minecraft:entity/description"),a!==!1&&this.create(s,{scripts:{animate:[a?{[l]:a}:l]}},"minecraft:entity/description"),t++}return JSON.stringify(i,null," ")}getAnimName(e,s,t){return`${e}.${s}_${t}`}getShortAnimName(e,s,t){var i;return`${(i=s.slice(0,16))!=null?i:"bridge_auto"}_${e}_${t}`}registerLifecycleHook(e,s,t,i,n){e[`minecraft:${this.fileType}`].events||(e[`minecraft:${this.fileType}`].events={});const a=e[`minecraft:${this.fileType}`].events;if(n==="activated"&&s===`minecraft:${this.fileType}/components`)a["minecraft:entity_spawned"]||(a["minecraft:entity_spawned"]={}),this.addEventReponse(a["minecraft:entity_spawned"],t);else if(this.fileType==="entity"&&s.startsWith(`minecraft:${this.fileType}/component_groups/`)){const c=s.split("/").pop();this.findComponentGroupReferences(a,n==="activated"?"add":"remove",c).forEach(u=>this.addEventReponse(u,t))}else if(s.startsWith(`minecraft:${this.fileType}/permutations/`)){const c=s.split("/");if(c.pop()!=="components")throw new Error("Invalid component location inside of permutation");const l=this.getObjAtLocation(e,[...c]),u=`bridge:${i}_${n}_${n==="activated"?this.lifecycleHookCount.activated++:this.lifecycleHookCount.deactivated++}`;l.condition&&this.animationControllers.push([{states:{default:{on_entry:[`@s ${u}`]}}},n==="activated"?l.condition:`!(${l.condition})`]),a[u]=t}}addEventReponse(e,s){if(Array.isArray(e.sequence))e.sequence.push(s);else if(Object.keys(e).length===0)Object.assign(e,s);else{let t=Object.assign({},e,{filters:void 0});for(const i in e)i!=="filters"&&(e[i]=void 0);e.sequence=[t,s]}}findComponentGroupReferences(e,s,t){var n,a;let i=[];for(const c in e){const l=e[c];Array.isArray(l.sequence)?i.push(...this.findComponentGroupReferences(l.sequence,s,t)):Array.isArray(l.randomize)?i.push(...this.findComponentGroupReferences(l.randomize,s,t)):((a=(n=l[s])==null?void 0:n.component_groups)!=null?a:[]).includes(t)&&i.push(l)}return i}}function fe(r){const e=[];for(const[s,t]of r)e.push(...me(t,s));return e}function me(r,e){const s=[];for(const t in r)t.startsWith("minecraft:")||t.startsWith("tag:")||s.push([t,e]);return s}function E({fileType:r,getComponentObjects:e}){const s=new Map;let t={};return({console:i,projectConfig:n,projectRoot:a,compileFiles:c,getAliases:l,options:u,jsRuntime:m,targetVersion:d,fileType:o})=>{const f=(h,g)=>h&&r==="item"&&(o==null?void 0:o.getId(h))==="entity"&&g(h).includes("minecraft:player"),p=h=>u.v1CompatMode?h==null?void 0:h.includes("/components/"):h&&(o==null?void 0:o.getId(h))==="customComponent"&&h.includes(`/${r}/`),w=h=>h&&(o==null?void 0:o.getId(h))===r;return{buildStart(){s.clear(),t={}},transformPath(h){if(p(h)&&u.buildType!=="fileRequest")return null},async read(h,g){if(!g)return t[h]?A.default.parse(t[h].fileContent):void 0;if(p(h)&&h.endsWith(".js")){const F=await g.getFile();return await(F==null?void 0:F.text())}else if(w(h)||f(h,l)){const F=await g.getFile();if(!F)return;try{return A.default.parse(await F.text())}catch($){return u.buildType!=="fileRequest"&&i.error(`Error within file "${h}": ${$}`),{__error__:`Failed to load original file: ${$}`}}}},async load(h,g){if(p(h)&&typeof g=="string"){const F=new L(i,r,g,u.mode,!!u.v1CompatMode,d);return F.setProjectConfig(n),await F.load(m,h)?F:g}},async registerAliases(h,g){if(p(h))return[`${r}Component#${g.name}`]},async require(h,g){if(f(h,l))return[`.${n.getRelativePackRoot("behaviorPack")}/components/item/**/*.[jt]s`,`.${n.getRelativePackRoot("behaviorPack")}/items/**/*.json`];if(w(h)){const F=fe(e(g));return s.set(h,F),F.map($=>`${r}Component#${$[0]}`)}else if(t[h])return[t[h].baseFile]},async transform(h,g,F={}){var $;if(f(h,l)){const C=Object.entries(F).filter(([S])=>S.startsWith("itemComponent#")).map(([S,y])=>y);for(const S of C){if(!S)return;t=j.deepMerge(t,await S.processAdditionalFiles(h,g))}}else if(w(h)){const C=new Set;for(const[S,y]of($=s.get(h))!=null?$:[]){const k=F[`${r}Component#${S}`];if(!k)continue;const _=j.get(g,y.split("/"),{}),Me=_[S];delete _[S],await k.processTemplates(g,Me,y),C.add(k)}for(const S of C)t=j.deepMerge(t,await S.processAdditionalFiles(h,g));for(const S of C)S.reset()}},finalizeBuild(h,g){if(p(h)&&g)return g.toString();if(w(h)||t[h])return JSON.stringify(g,null," ")},async buildEnd(){if(u.buildType==="fileRequest")return;t=Object.fromEntries(Object.entries(t).filter(([g,F])=>(F==null?void 0:F.fileContent)!==void 0).map(([g,F])=>[v.join(a,g),F]));const h=Object.keys(t);h.length>0&&await c(h),t={}}}}}const pe=E({fileType:"entity",getComponentObjects:r=>{var e,s,t,i,n,a;return[["minecraft:entity/components",(s=(e=r==null?void 0:r["minecraft:entity"])==null?void 0:e.components)!=null?s:{}],...Object.entries((i=(t=r==null?void 0:r["minecraft:entity"])==null?void 0:t.component_groups)!=null?i:{}).map(([c,l])=>[`minecraft:entity/component_groups/${c}`,l]),...((a=(n=r==null?void 0:r["minecraft:entity"])==null?void 0:n.permutations)!=null?a:[]).map((c,l)=>{var u;return[`minecraft:entity/permutations/${l}/components`,(u=c==null?void 0:c.components)!=null?u:{}]})]}}),ge=E({fileType:"item",getComponentObjects:r=>{var e,s;return[["minecraft:item/components",(s=(e=r==null?void 0:r["minecraft:item"])==null?void 0:e.components)!=null?s:{}]]}}),ye=E({fileType:"block",getComponentObjects:r=>{var e,s,t,i;return[["minecraft:block/components",(s=(e=r==null?void 0:r["minecraft:block"])==null?void 0:e.components)!=null?s:{}],...((i=(t=r==null?void 0:r["minecraft:block"])==null?void 0:t.permutations)!=null?i:[]).map((n,a)=>{var c;return[`minecraft:block/permutations/${a}/components`,(c=n.components)!=null?c:{}]})]}});function M(r,e,s,t=0){const i=[];for(const n of r){if(!n.startsWith("/")){i.push(n);continue}const[a,...c]=j.tokenizeCommand(n.slice(1)).tokens.map(({word:u})=>u),l=e[`command#${a}`];if(a==="execute"){let u=4;if(c[u]==="detect"&&(u+=6),c[u]===void 0){i.push(n);continue}const[m,...d]=c.slice(u),o=e[`command#${m}`];if(!(o instanceof I)){i.push(n);continue}i.push(...o.process(`${m} ${d.join(" ")}`,e,t+1).map(f=>f.startsWith("/")?`/execute ${c.slice(0,u).join(" ")} ${f.slice(1)}`:f));continue}else if(!(l instanceof I)){i.push(n);continue}i.push(...l.process(n,e,t))}return i.filter(n=>s||!n.startsWith("#")).map(n=>n.trim())}const we=r=>({register:e=>{r.command=({name:s,schema:t,template:i})=>{s(e.command_name),t([]),i(n=>new e().onApply(n))}}});class I{constructor(e,s,t,i){this.console=e,this.commandSrc=s,this.mode=t,this.v1Compat=i}get name(){var e;return(e=this._name)!=null?e:"unknown"}async load(e,s,t){const i={command:null},n=await e.run(s,{console:this.console,defineCommand:u=>u,Bridge:this.v1Compat?we(i):void 0}).catch(u=>(this.console.error(`Failed to execute command ${this.name}: ${u}`),null));if(!n)return null;if(typeof n.__default__!="function")if(i.command)n.__default__=i.command;else return this.console.error(`Component ${s} is not a valid component. Expected a function as the default export.`),!1;const a=u=>this._name=u;let c=u=>this.schema=u,l=()=>{};(!t||t==="server")&&(c=()=>{},l=u=>{this.template=(m,d)=>{try{return u(m,d)}catch(o){return this.console.error(o),[]}}}),await n.__default__({name:a,schema:c,template:l})}process(e,s,t){var l;e.startsWith("/")&&(e=e.slice(1));const[i,...n]=j.tokenizeCommand(e).tokens.map(({word:u})=>u),a=(l=this.template)==null?void 0:l.call(this,n.map(u=>j.castType(u)),{compilerMode:this.mode,commandNestingDepth:t,compileCommands:u=>M(u.map(m=>m.startsWith("/")?m:`/${m}`),s,!1,t+1).map(m=>m.startsWith("/")?m.slice(1):m)});let c=[];if(typeof a=="string")c=a.split(` `);else if(Array.isArray(a))c=a.filter(u=>typeof u=="string");else{const u=`Failed to process command ${this._name}; Invalid command template return type: Expected string[] or string, received ${typeof a}`;this.console.error(u),c.push(`# ${u}`)}return c.map(u=>u.startsWith("/")||u.startsWith("#")?u:`/${u}`)}getSchema(){if(this.schema){if(Array.isArray(this.schema))return this.schema.length===0?[{commandName:this.name}]:this.schema.map(e=>({commandName:this.name,...e}))}else return[{commandName:this.name}];return this.schema.commandName||(this.schema.commandName=this.name),[this.schema]}toString(){return this.commandSrc}}const Fe=({projectConfig:r,jsRuntime:e,console:s,fileType:t,requestJsonData:i,options:n})=>{const a=(d,o)=>r.resolvePackPath(d,o),c=d=>d&&t.getId(d)==="customCommand",l=d=>d&&t.getId(d)==="function",u=d=>{var o;return(o=Object.entries(n.include).find(([f])=>t.getId(d)===f))==null?void 0:o[1]},m=d=>{var o,f,p;return(p=(f=(o=t.get(d))==null?void 0:o.meta)==null?void 0:f.commandsUseSlash)!=null?p:!1};return{async buildStart(){n.include=Object.assign(await i("data/packages/minecraftBedrock/location/validCommand.json"),n.include)},transformPath(d){if(c(d)&&n.buildType!=="fileRequest")return null},async read(d,o){if(!!o){if(c(d)&&d.endsWith(".js")){const f=await o.getFile();return await(f==null?void 0:f.text())}else if(l(d)){const f=await o.getFile();return await(f==null?void 0:f.text())}else if(u(d)&&o){const f=await o.getFile();if(!f)return;try{return A.default.parse(await f.text())}catch(p){s.error(p)}}}},async load(d,o){var f;if(c(d)){const p=new I(s,o,n.mode,(f=n.v1CompatMode)!=null?f:!1);return await p.load(e,d),p}},async registerAliases(d,o){if(c(d))return[`command#${o.name}`]},async require(d){if(u(d)||l(d))return[a("behaviorPack","commands/**/*.[jt]s"),a("behaviorPack","commands/*.[jt]s")]},async transform(d,o,f={}){const p=u(d);if(p&&p.length>0){const w=m(d);p.forEach(h=>j.setObjectAt(h,o,g=>{if(!g)return g;g=Array.isArray(g)?g:[g];const F=[];for(const $ of g){if(typeof $=="string"){F.push($);continue}s.error(`The file "${d}" contains invalid commands. Expected type "string" within array but got type "${typeof $}"`)}return M(F.map($=>!w&&!$.startsWith("/")?`/${$}`:$),f,!1).map($=>w?$:$.slice(1))}))}else if(l(d)){const w=o.split(` `).map(h=>h.trim()).filter(h=>h!==""&&!h.startsWith("#")).map(h=>`/${h}`);return M(w,f,!0).map(h=>h.startsWith("/")?h.slice(1):h).join(` -`)}},finalizeBuild(d,o){if(c(d)&&o)return o.toString();if(u(d)&&typeof o!="string")return JSON.stringify(o,null," ")}}},ve=({options:r})=>({async transformPath(e){if(!!(e!=null&&e.endsWith(".ts")))return`${e.slice(0,-3)}.js`},async read(e,s){if(!e.endsWith(".ts")||!s)return;const t=await s.getFile();return await(t==null?void 0:t.text())},async load(e,s){if(!!e.endsWith(".ts"))return await q.loadedWasm,Y.transformSync(s,{filename:v.basename(e),sourceMaps:r!=null&&r.inlineSourceMap?"inline":void 0,jsc:{parser:{syntax:"typescript"},target:"es2020"}}).code},finalizeBuild(e,s){if(e.endsWith(".ts")&&typeof s=="string")return s}}),ke=({options:r,outputFileSystem:e,projectRoot:s,packType:t,fileType:i,console:n})=>{r.packName||(r.packName="bridge project");const a=m=>m.split(/\\|\//g).filter(d=>d!==".."&&d!==".").slice(1).join("/"),c=m=>{const d=t.getId(m),o=v.relative(s,m);if(d==="behaviorPack"||d==="resourcePack"||d==="skinPack")return v.join(s,"builds/dist",d,a(o))},l=m=>{const d=t.getId(m),o=v.relative(s,m);if(d==="worldTemplate")return v.join(s,"builds/dist",a(o));if(d==="behaviorPack"||d==="resourcePack")return v.join(s,"builds/dist",d==="behaviorPack"?"behavior_packs":"resource_packs",r.packName,a(o))},u=m=>i.getId(m)==="worldManifest"?null:l(m);return{async buildStart(){await e.unlink(`${s}/builds/dist`).catch(()=>{})},transformPath(m){if(!!m)switch(r.format){case"mcaddon":return c(m);case"mcworld":return u(m);case"mctemplate":return l(m);default:n.error(`Unknown packaging format: ${r.format}`)}}}},$e=({projectConfig:r,packType:e,options:s})=>{const t=Object.keys(r.getAvailablePacks()),i=Object.fromEntries(t.map(a=>[a,[]])),n=a=>{const c=e.getId(a);if(c!=="unknown")return[c,r.resolvePackPath(c,"contents.json")]};return s.buildType!=="fullBuild"?{}:{include(){return t.map(a=>[r.resolvePackPath(a,"contents.json"),{isVirtual:!0}])},read(a){const c=n(a);if(!c)return;const[l,u]=c;if(a!==u)return i[l]},transformPath(a){if(!a)return;const c=e.getId(a);c!=="unknown"&&i[c].push(a)},finalizeBuild(a){const c=n(a);if(!c)return;const[l,u]=c;if(a!==u)return JSON.stringify(i[l])}}},be=({fileType:r})=>{const e=[];for(const t of r.all)t.formatVersionMap&&e.push(t.id);const s=t=>t&&e.includes(r.getId(t));return{async read(t,i){if(!!i&&s(t)){const n=await i.getFile();if(!n)return;try{return A.default.parse(await n.text())}catch(a){console.error(a)}}},load(t,i){if(s(t))return i},transform(t,i){if(s(t)){const n=r.get(t),a=n==null?void 0:n.formatVersionMap;if(!a)return;const c=i==null?void 0:i.format_version;return c&&a[c]&&(i.format_version=a[c]),i}},finalizeBuild(t,i){if(s(t))return JSON.stringify(i)}}};class P{constructor(e,s){this.console=e,this.baseDir=s,this.files=new Map}get hasFiles(){return this.files.size>0}getAll(){return[...this.files.entries()]}get(e){return this.files.get(e)}clear(){this.files.clear()}add(e,s){const t=this.baseDir?v.join(this.baseDir,e):e;if(this.files.has(t)){this.console.warn(`Omitting file "${t}" from collection because it would overwrite a previously generated file!`);return}this.files.set(t,s)}addFrom(e){for(const[s,t]of e.getAll())this.add(s,t)}}function Se({generatorPath:r,omitUsedTemplates:e,fileSystem:s,console:t}){return{useTemplate:(i,n=!0)=>{const a=v.join(v.dirname(r),i);return n&&e.add(a),i.endsWith(".json")?s.readJson(a):s.readFile(a).then(c=>c.text())},createCollection:()=>new P(t,v.dirname(r))}}const je=({fileType:r,console:e,jsRuntime:s,fileSystem:t,compileFiles:i})=>{const n=new Set(["gameTest","customCommand","customComponent"]),a=o=>r.getId(o),c=o=>{var p;const f=r.get(o);return f?(p=f.type)!=null?p:"json":"raw"},l=o=>!n.has(a(o))&&(o.endsWith(".js")||o.endsWith(".ts")),u=o=>{var p,w,h,g;return c(o)==="json"?".json":(g=(h=(w=(p=r.get(o))==null?void 0:p.detect)==null?void 0:w.fileExtensions)==null?void 0:h[0])!=null?g:".txt"},m=new Set,d=new P(e);return{buildStart(){d.clear(),m.clear()},transformPath(o){if(o&&l(o))return o.replace(/\.(js|ts)$/,u(o))},async read(o,f){if(l(o)&&f){const w=await f.getFile();return w?w.text():void 0}const p=d.get(o);if(p)return p},async load(o,f){if(s.registerModule("@bridge/generate",Se({generatorPath:o,fileSystem:t,omitUsedTemplates:m,console:e})),l(o)){if(!f)return null;const p=await s.run(o,{console:e},f).catch(w=>(e.error(`Failed to execute generator script "${o}": ${w}`),null));return p?p.__default__?p.__default__:(e.error(`Expected generator script "${o}" to provide file content as default export!`),null):null}if(d.get(o))return o.endsWith(".json")&&typeof f!="string"?JSON.stringify(f,null," "):f},finalizeBuild(o,f){if(m.has(o))return null;if(l(o))return f===null?null:f instanceof P?(d.addFrom(f),null):typeof f=="object"?JSON.stringify(f):f},async buildEnd(){s.deleteModule("@bridge/generate"),d.hasFiles&&await i(d.getAll().map(([o])=>o))}}};class G extends q.Runtime{constructor(e,s){super(s),this.fs=e}readFile(e){return this.fs.readFile(e).then(s=>s.text())}deleteModule(e){this.baseModules.delete(e)}}const U={simpleRewrite:se,rewriteForPackaging:ke,moLang:ie,entityIdentifierAlias:ne,customEntityComponents:pe,customItemComponents:ge,customBlockComponents:ye,customCommands:Fe,typeScript:ve,contentsFile:$e,formatVersionCorrection:be,generatorScripts:je};class _e{constructor(e){this.dash=e,this.plugins=[],this.pluginRuntime=new G(this.dash.fileSystem)}async loadPlugins(e={}){var n,a;this.plugins=[],this.pluginRuntime.clearCache();const s=[...(await this.dash.fileSystem.readdir(v.join(this.dash.projectRoot,".bridge/extensions")).catch(()=>[])).map(c=>c.kind==="directory"?v.join(this.dash.projectRoot,".bridge/extensions",c.name):void 0),...(await this.dash.fileSystem.readdir("extensions").catch(()=>[])).map(c=>c.kind==="directory"?v.join("extensions",c.name):void 0)],t={};for(const c of s){if(!c)continue;let l;try{l=await this.dash.fileSystem.readJson(v.join(c,"manifest.json"))}catch{continue}if(!!((n=l==null?void 0:l.compiler)!=null&&n.plugins))for(const u in l.compiler.plugins)t[u]=v.join(c,l.compiler.plugins[u])}const i=(a=(await this.getCompilerOptions()).plugins)!=null?a:[];for(const c of i){const l=typeof c=="string"?c:c[0],u=typeof c=="string"?{}:c[1];if(t[l]){const m=await this.pluginRuntime.run(t[l],{console:this.dash.console,...e}).catch(d=>(this.dash.console.error(`Failed to execute plugin ${l}: ${d}`),null));if(!m)continue;typeof m.__default__=="function"?this.plugins.push(new N(this.dash,l,m.__default__(await this.getPluginContext(l,u)))):this.dash.console.error(`Plugin ${l} is invalid: It does not provide a function as a default export.`)}else U[l]?this.plugins.push(new N(this.dash,l,U[l](await this.getPluginContext(l,u)))):this.dash.console.error(`Unknown compiler plugin: ${l}`)}}async getCompilerOptions(){var s;const e=await this.dash.getCompilerConfigPath();return e?await this.dash.fileSystem.readJson(e):(s=this.dash.projectConfig.get().compiler)!=null?s:{}}async getPluginContext(e,s={}){const t=this.dash;return{options:{get mode(){return t.getMode()},get buildType(){return t.buildType},...s},jsRuntime:this.dash.jsRuntime,console:this.dash.console,fileSystem:this.dash.fileSystem,outputFileSystem:this.dash.outputFileSystem,projectConfig:this.dash.projectConfig,projectRoot:this.dash.projectRoot,packType:this.dash.packType,fileType:this.dash.fileType,targetVersion:this.dash.projectConfig.get().targetVersion,requestJsonData:this.dash.requestJsonData,getAliases:i=>{var n,a;return[...(a=(n=this.dash.includedFiles.get(i))==null?void 0:n.aliases)!=null?a:[]]},hasComMojangDirectory:this.dash.fileSystem!==this.dash.outputFileSystem,compileFiles:i=>this.dash.compileVirtualFiles(i)}}async runBuildStartHooks(){for(const e of this.plugins)await e.runBuildStartHook()}async runIncludeHooks(){let e=[];for(const s of this.plugins){const t=await s.runIncludeHook();Array.isArray(t)&&e.push(...t)}return e}async runTransformPathHooks(e){let s=e;for(const t of this.plugins){const i=await t.runTransformPathHook(s);if(i===null)return null;i!==void 0&&(s=i)}return s}async runReadHooks(e,s){for(const t of this.plugins){const i=await t.runReadHook(e,s);if(i!=null)return i}}async runLoadHooks(e,s){let t=s;for(const i of this.plugins){const n=await i.runLoadHook(e,t);n!==void 0&&(t=n)}return t}async runRegisterAliasesHooks(e,s){const t=new Set;for(const i of this.plugins){const n=await i.runRegisterAliasesHook(e,s);n!=null&&(Array.isArray(n)?n.forEach(a=>t.add(a)):t.add(n))}return t}async runRequireHooks(e,s){const t=new Set;for(const i of this.plugins){const n=await i.runRequireHook(e,s);n!=null&&(Array.isArray(n)?n.forEach(a=>t.add(a)):t.add(n))}return t}async runTransformHooks(e){const s=Object.fromEntries([...e.requiredFiles].map(i=>this.dash.includedFiles.query(i)).flat().map(i=>[[i.filePath,i.data],...[...i.aliases].map(n=>[n,i.data])]).flat());let t=e.data;for(const i of this.plugins){const n=await i.runTransformHook(e.filePath,t,s);n!==void 0&&(t=n)}return t}async runFinalizeBuildHooks(e){for(const s of this.plugins){const t=await s.runFinalizeBuildHook(e.filePath,e.data);if(t!==void 0)return t}}async runBuildEndHooks(){for(const e of this.plugins)await e.runBuildEndHook()}}class x{constructor(e,s,t=!1){this.dash=e,this.filePath=s,this.isVirtual=t,this.isDone=!1,this.requiredFiles=new Set,this.aliases=new Set,this.updateFiles=new Set,this.outputPath=s,this.isVirtual||this.setDefaultFileHandle()}setFileHandle(e){this.fileHandle=e}setDefaultFileHandle(){this.setFileHandle({getFile:()=>this.dash.fileSystem.readFile(this.filePath).catch(()=>null)})}setOutputPath(e){this.outputPath=e}setReadData(e){this.data=e}setAliases(e){for(const s of e)this.dash.includedFiles.addAlias(s,this);this.aliases=e}setRequiredFiles(e){this.requiredFiles=e}setUpdateFiles(e){this.updateFiles=new Set(e.map(s=>this.dash.includedFiles.get(s)).filter(s=>s!==void 0))}addUpdateFile(e){this.updateFiles.add(e)}removeUpdateFile(e){this.updateFiles.delete(e)}getHotUpdateChain(){const e=new Set([this]);for(const s of this.updateFiles)s.getHotUpdateChain().forEach(t=>{e.add(t)});return e}filesToLoadForHotUpdate(e=new Set,s=!0){const t=new Set;if(e.has(this))return t;e.add(this);for(const i of this.requiredFiles){const n=this.dash.includedFiles.query(i);for(const a of n)a.filesToLoadForHotUpdate(e,!1).forEach(c=>{t.add(c)})}if(t.add(this),s)for(const i of this.updateFiles)i.filesToLoadForHotUpdate(e,!0).forEach(n=>{t.add(n)});return t}async processAfterLoad(e){if((this.data===null||this.data===void 0)&&(this.isDone=!0,this.filePath!==this.outputPath&&this.outputPath!==null&&!this.isVirtual&&e)){const s=await this.dash.fileSystem.readFile(this.filePath);await this.dash.outputFileSystem.writeFile(this.outputPath,new Uint8Array(await s.arrayBuffer()))}}serialize(){return{isVirtual:this.isVirtual,filePath:this.filePath,aliases:[...this.aliases],requiredFiles:[...this.requiredFiles],updateFiles:[...this.updateFiles].map(e=>e.filePath)}}reset(){this.isDone=!1,this.data=null,this.isVirtual||this.setDefaultFileHandle()}}class Ce{constructor(e){this.dash=e,this.files=new Map,this.aliases=new Map,this.queryCache=new Map}all(){return[...this.files.values()]}filtered(e){return this.all().filter(s=>e(s))}get(e){var s;return(s=this.aliases.get(e))!=null?s:this.files.get(e)}query(e){if(ee.default(e))return this.queryGlob(e);const s=this.aliases.get(e);if(s)return[s];const t=this.files.get(e);return t?[t]:[]}addAlias(e,s){this.aliases.set(e,s)}queryGlob(e){if(this.queryCache.has(e))return this.queryCache.get(e);const s=this.filtered(t=>j.isMatch(t.filePath,e));return this.queryCache.set(e,s),s}async loadAll(){this.queryCache=new Map;const e=new Set,s=this.dash.projectConfig.getAvailablePackPaths();for(const i of s){const n=await this.dash.fileSystem.allFiles(i).catch(a=>(this.dash.console.warn(a),[]));for(const a of n)e.add(a)}const t=await this.dash.plugins.runIncludeHooks();for(const i of t)typeof i=="string"?e.add(i):this.addOne(i[0],i[1].isVirtual);this.add([...e])}addOne(e,s=!1){const t=new x(this.dash,e,s);return this.files.set(e,t),t}add(e,s=!1){let t=[];for(const i of e){const n=this.files.get(i);if(n){t.push(n);continue}t.push(new x(this.dash,i,s)),this.files.set(i,t[t.length-1])}return t}remove(e){const s=this.files.get(e);if(!!s){this.files.delete(e);for(const t of s.aliases)this.aliases.delete(t)}}async save(e){await this.dash.fileSystem.writeJson(e,this.all().map(s=>s.serialize()))}async load(e){this.removeAll();const s=await this.dash.fileSystem.readJson(e),t=[];for(const i of s){const n=new x(this.dash,i.filePath,i.isVirtual);n.setAliases(new Set(i.aliases)),n.setRequiredFiles(new Set(i.requiredFiles)),t.push(n);for(const a of i.aliases)this.aliases.set(a,n)}this.files=new Map(t.map(i=>[i.filePath,i]));for(let i=0;ithis.onChangeCbs.delete(e)}}setTotal(e){this.total=e,this.current=0,this.onChangeCbs.forEach(s=>s(this))}updateCurrent(e){this.current=e,this.onChangeCbs.forEach(s=>s(this))}advance(){this.current++,this.onChangeCbs.forEach(e=>e(this))}addToTotal(e){this.total+=e,this.onChangeCbs.forEach(s=>s(this))}}class K{constructor(){this._timers=new Map}time(e){if(this._timers.has(e)){this.warn(`Timer "${e}" already exists.`);return}else this._timers.set(e,Date.now())}timeEnd(e){const s=this._timers.get(e);if(s)this._timers.delete(e),this.log(`${e}: ${Date.now()-s}ms`);else{this.warn(`Timer "${e}" does not exist.`);return}}}class X extends K{log(...e){console.log(...e)}error(...e){console.error(...e)}warn(...e){console.warn(...e)}info(...e){console.info(...e)}}class Re{constructor(e,s,t){var i;this.fileSystem=e,this.options=t,this.progress=new qe,this.plugins=new _e(this),this.includedFiles=new Ce(this),this.loadFiles=new Ae(this),this.fileOrderResolver=new Te(this),this.fileTransformer=new Ie(this),this.buildType="fullBuild",this.outputFileSystem=s!=null?s:e,this.projectRoot=v.dirname(t.config),this.projectConfig=new te(e,t.config),this.console=(i=t.console)!=null?i:new X,this.jsRuntime=new G(this.fileSystem,[["@molang/expressions",O.expressions],["@molang/core",{MoLang:O.MoLang}],["molang",{MoLang:O.MoLang,...O.expressions}],["@bridge/compiler",{mode:t.mode}]]),this.packType=t.packType,this.fileType=t.fileType}getMode(){var e;return(e=this.options.mode)!=null?e:"development"}getCompilerConfigPath(){return this.options.compilerConfig}get requestJsonData(){return this.options.requestJsonData}get dashFilePath(){return v.join(this.projectRoot,`.bridge/.dash.${this.getMode()}.json`)}async setup(e){var s,t,i,n;try{await this.projectConfig.setup()}catch(a){this.console.error("Failed to load project config: "+a)}(s=this.fileType)==null||s.setProjectConfig(this.projectConfig),(t=this.packType)==null||t.setProjectConfig(this.projectConfig),await((i=this.fileType)==null?void 0:i.setup(e)),await((n=this.packType)==null?void 0:n.setup(e)),await this.plugins.loadPlugins(this.options.pluginEnvironment)}async reload(){try{await this.projectConfig.refreshConfig()}catch{}await this.plugins.loadPlugins(this.options.pluginEnvironment)}get isCompilerActivated(){const e=this.projectConfig.get();return e.compiler!==void 0&&Array.isArray(e.compiler.plugins)}async build(){if(this.console.log("Starting compilation..."),!this.isCompilerActivated)return;this.jsRuntime.clearCache(),this.buildType="fullBuild",this.includedFiles.removeAll();const e=Date.now();this.progress.setTotal(7),await this.plugins.runBuildStartHooks(),this.progress.advance(),await this.includedFiles.loadAll(),this.progress.advance(),await this.compileIncludedFiles(),await this.plugins.runBuildEndHooks(),this.progress.advance(),this.getMode()==="development"&&await this.saveDashFile(),this.includedFiles.resetAll(),this.progress.advance(),this.console.log(`Dash compiled ${this.includedFiles.all().length} files in ${Date.now()-e}ms!`)}async updateFiles(e,s=!0){var c;if(!this.isCompilerActivated||e.length===0)return;this.buildType="hotUpdate",this.jsRuntime.clearCache(),this.progress.setTotal(8),this.console.log(`Dash is starting to update ${e.length} files...`),await this.includedFiles.load(this.dashFilePath),await this.plugins.runBuildStartHooks();const t=[];for(const l of e){let u=this.includedFiles.get(l);u||([u]=this.includedFiles.add([l])),t.push(u)}this.progress.advance();const i=[];for(const l of t)i.push(new Set([...l.requiredFiles]));this.progress.advance(),await this.loadFiles.run(t),this.progress.advance();for(let l=0;l!i[l].has(o)).forEach(o=>this.includedFiles.query(o).forEach(f=>f.addUpdateFile(u))),[...i[l]].filter(o=>!u.requiredFiles.has(o)).forEach(o=>this.includedFiles.query(o).forEach(f=>f.removeUpdateFile(u)))}this.progress.advance();const n=new Set(t.map(l=>[...l.filesToLoadForHotUpdate()]).flat());this.console.log(`Dash is loading ${n.size} files...`),await this.loadFiles.run([...n.values()].filter(l=>!t.includes(l))),this.progress.advance();const a=new Set(t.map(l=>[...l.getHotUpdateChain()]).flat());for(const l of n)l.isDone||(l.data=(c=await this.plugins.runTransformHooks(l))!=null?c:l.data,a.has(l)||(l.isDone=!0));this.progress.advance(),this.console.log(`Dash is compiling ${a.size} files...`),await this.fileTransformer.run(a,!0),this.progress.advance(),await this.plugins.runBuildEndHooks(),s&&await this.saveDashFile(),this.includedFiles.resetAll(),this.console.log(`Dash finished updating ${a.size} files!`),this.progress.advance()}async compileFile(e,s){var a;if(!this.isCompilerActivated)return[[],s];this.buildType="fileRequest",this.jsRuntime.clearCache(),this.progress.setTotal(7),await this.plugins.runBuildStartHooks(),await this.includedFiles.load(this.dashFilePath);let t=this.includedFiles.get(e);t||([t]=this.includedFiles.add([e])),t.setFileHandle({getFile:async()=>new File([s],v.basename(e))}),await this.loadFiles.loadFile(t,!1),await this.loadFiles.loadRequiredFiles(t),this.progress.advance();const i=t.filesToLoadForHotUpdate();await this.loadFiles.run([...i.values()].filter(c=>t!==c),!1),this.progress.advance();for(const c of i)c.isDone||(c.data=(a=await this.plugins.runTransformHooks(c))!=null?a:c.data);this.progress.advance();const n=await this.fileTransformer.transformFile(t,!0,!0);return this.progress.advance(),await this.includedFiles.load(this.dashFilePath),this.progress.advance(),await this.plugins.runBuildEndHooks(),[[...i].map(c=>c.filePath),n]}async unlinkMultiple(e){if(!(!this.isCompilerActivated||e.length===0)){for(const s of e)await this.unlink(s,!1);await this.saveDashFile()}}async unlink(e,s=!0){if(!this.isCompilerActivated)return;const t=await this.plugins.runTransformPathHooks(e);!t||t===e||(await this.outputFileSystem.unlink(t),this.includedFiles.remove(e),s&&await this.saveDashFile())}async rename(e,s){!this.isCompilerActivated||(await this.unlink(e,!1),await this.updateFiles([s],!1),await this.saveDashFile())}async getCompilerOutputPath(e){if(!this.isCompilerActivated)return;const s=await this.plugins.runTransformPathHooks(e);if(!!s)return s}async getFileDependencies(e){if(!this.isCompilerActivated)return[];await this.includedFiles.load(this.dashFilePath);const s=this.includedFiles.get(e);return s?[...s.filesToLoadForHotUpdate()].map(t=>t.isVirtual?t.outputPath:t.filePath).filter(t=>t!==null&&t!==e):[]}async saveDashFile(){await this.includedFiles.save(this.dashFilePath)}async compileIncludedFiles(e=this.includedFiles.all()){await this.loadFiles.run(e),this.progress.advance();const s=this.fileOrderResolver.run(e);this.progress.advance(),await this.fileTransformer.run(s),this.progress.advance()}async compileVirtualFiles(e){const s=this.includedFiles.add(e,!0);this.progress.addToTotal(3),s.forEach(t=>t.reset()),await this.compileIncludedFiles(s)}}class Ee{async allFiles(e){const s=[],t=await this.readdir(e);for(const{name:i,kind:n}of t)n==="directory"?s.push(...await this.allFiles(v.join(e,i))):n==="file"&&s.push(v.join(e,i));return s}async writeJson(e,s,t=!0){await this.writeFile(e,JSON.stringify(s,null,t?" ":0))}async readJson(e){const s=await this.readFile(e);try{return await A.default.parse(await s.text())}catch{throw new Error(`Invalid JSON: ${e}`)}}watchDirectory(e,s){console.warn("Watching a directory for changes is not supported on this platform!")}}Object.defineProperty(b,"initRuntimes",{enumerable:!0,get:function(){return q.initRuntimes}}),b.Command=I,b.Component=L,b.Console=K,b.Dash=Re,b.DefaultConsole=X,b.FileSystem=Ee,Object.defineProperty(b,"__esModule",{value:!0}),b[Symbol.toStringTag]="Module"}); +`)}},finalizeBuild(d,o){if(c(d)&&o)return o.toString();if(u(d)&&typeof o!="string")return JSON.stringify(o,null," ")}}},ve=({options:r})=>({async transformPath(e){if(!!(e!=null&&e.endsWith(".ts")))return`${e.slice(0,-3)}.js`},async read(e,s){if(!e.endsWith(".ts")||!s)return;const t=await s.getFile();return await(t==null?void 0:t.text())},async load(e,s){if(!!e.endsWith(".ts"))return await q.loadedWasm,Y.transformSync(s,{filename:v.basename(e),sourceMaps:r!=null&&r.inlineSourceMap?"inline":void 0,jsc:{parser:{syntax:"typescript"},target:"es2020"}}).code},finalizeBuild(e,s){if(e.endsWith(".ts")&&typeof s=="string")return s}}),ke=({options:r,outputFileSystem:e,projectRoot:s,packType:t,fileType:i,console:n})=>{r.packName||(r.packName="bridge project");const a=m=>m.split(/\\|\//g).filter(d=>d!==".."&&d!==".").slice(1).join("/"),c=m=>{const d=t.getId(m),o=v.relative(s,m);if(d==="behaviorPack"||d==="resourcePack"||d==="skinPack")return v.join(s,"builds/dist",d,a(o))},l=m=>{const d=t.getId(m),o=v.relative(s,m);if(d==="worldTemplate")return v.join(s,"builds/dist",a(o));if(d==="behaviorPack"||d==="resourcePack")return v.join(s,"builds/dist",d==="behaviorPack"?"behavior_packs":"resource_packs",r.packName,a(o))},u=m=>i.getId(m)==="worldManifest"?null:l(m);return{async buildStart(){await e.unlink(`${s}/builds/dist`).catch(()=>{})},transformPath(m){if(!!m)switch(r.format){case"mcaddon":return c(m);case"mcworld":return u(m);case"mctemplate":return l(m);default:n.error(`Unknown packaging format: ${r.format}`)}}}},$e=({projectConfig:r,packType:e,options:s})=>{const t=Object.keys(r.getAvailablePacks()),i=Object.fromEntries(t.map(a=>[a,[]])),n=a=>{const c=e.getId(a);if(c!=="unknown")return[c,r.resolvePackPath(c,"contents.json")]};return s.buildType!=="fullBuild"?{}:{include(){return t.map(a=>[r.resolvePackPath(a,"contents.json"),{isVirtual:!0}])},read(a){const c=n(a);if(!c)return;const[l,u]=c;if(a!==u)return i[l]},transformPath(a){if(!a)return;const c=e.getId(a);c!=="unknown"&&i[c].push(a)},finalizeBuild(a){const c=n(a);if(!c)return;const[l,u]=c;if(a!==u)return JSON.stringify(i[l])}}},be=({fileType:r})=>{const e=[];for(const t of r.all)t.formatVersionMap&&e.push(t.id);const s=t=>t&&e.includes(r.getId(t));return{async read(t,i){if(!!i&&s(t)){const n=await i.getFile();if(!n)return;try{return A.default.parse(await n.text())}catch(a){console.error(a)}}},load(t,i){if(s(t))return i},transform(t,i){if(s(t)){const n=r.get(t),a=n==null?void 0:n.formatVersionMap;if(!a)return;const c=i==null?void 0:i.format_version;return c&&a[c]&&(i.format_version=a[c]),i}},finalizeBuild(t,i){if(s(t))return JSON.stringify(i)}}};class P{constructor(e,s){this.console=e,this.baseDir=s,this.files=new Map}get hasFiles(){return this.files.size>0}getAll(){return[...this.files.entries()]}get(e){return this.files.get(e)}clear(){this.files.clear()}add(e,s){const t=this.baseDir?v.join(this.baseDir,e):e;if(this.files.has(t)){this.console.warn(`Omitting file "${t}" from collection because it would overwrite a previously generated file!`);return}this.files.set(t,s)}addFrom(e){for(const[s,t]of e.getAll())this.add(s,t)}}function Se({generatorPath:r,omitUsedTemplates:e,fileSystem:s,console:t}){return{useTemplate:(i,{omitTemplate:n=!0}={})=>{const a=v.join(v.dirname(r),i);return n&&e.add(a),i.endsWith(".json")?s.readJson(a):s.readFile(a).then(c=>c.text())},createCollection:()=>new P(t,v.dirname(r))}}const je=({fileType:r,console:e,jsRuntime:s,fileSystem:t,compileFiles:i})=>{const n=new Set(["gameTest","customCommand","customComponent"]),a=o=>r.getId(o),c=o=>{var p;const f=r.get(o);return f?(p=f.type)!=null?p:"json":"raw"},l=o=>!n.has(a(o))&&(o.endsWith(".js")||o.endsWith(".ts")),u=o=>{var p,w,h,g;return c(o)==="json"?".json":(g=(h=(w=(p=r.get(o))==null?void 0:p.detect)==null?void 0:w.fileExtensions)==null?void 0:h[0])!=null?g:".txt"},m=new Set,d=new P(e);return{buildStart(){d.clear(),m.clear()},transformPath(o){if(o&&l(o))return o.replace(/\.(js|ts)$/,u(o))},async read(o,f){if(l(o)&&f){const w=await f.getFile();return w?w.text():void 0}const p=d.get(o);if(p)return p},async load(o,f){if(s.registerModule("@bridge/generate",Se({generatorPath:o,fileSystem:t,omitUsedTemplates:m,console:e})),l(o)){if(!f)return null;const p=await s.run(o,{console:e},f).catch(w=>(e.error(`Failed to execute generator script "${o}": ${w}`),null));return p?p.__default__?p.__default__:(e.error(`Expected generator script "${o}" to provide file content as default export!`),null):null}},finalizeBuild(o,f){if(d.get(o))return o.endsWith(".json")&&typeof f!="string"?JSON.stringify(f,null," "):f;if(m.has(o))return null;if(l(o))return f===null?null:f instanceof P?(d.addFrom(f),null):typeof f=="object"?JSON.stringify(f):f},async buildEnd(){s.deleteModule("@bridge/generate"),d.hasFiles&&await i(d.getAll().map(([o])=>o))}}};class G extends q.Runtime{constructor(e,s){super(s),this.fs=e}readFile(e){return this.fs.readFile(e).then(s=>s.text())}deleteModule(e){this.baseModules.delete(e)}}const U={simpleRewrite:se,rewriteForPackaging:ke,moLang:ie,entityIdentifierAlias:ne,customEntityComponents:pe,customItemComponents:ge,customBlockComponents:ye,customCommands:Fe,typeScript:ve,contentsFile:$e,formatVersionCorrection:be,generatorScripts:je};class _e{constructor(e){this.dash=e,this.plugins=[],this.pluginRuntime=new G(this.dash.fileSystem)}async loadPlugins(e={}){var n,a;this.plugins=[],this.pluginRuntime.clearCache();const s=[...(await this.dash.fileSystem.readdir(v.join(this.dash.projectRoot,".bridge/extensions")).catch(()=>[])).map(c=>c.kind==="directory"?v.join(this.dash.projectRoot,".bridge/extensions",c.name):void 0),...(await this.dash.fileSystem.readdir("extensions").catch(()=>[])).map(c=>c.kind==="directory"?v.join("extensions",c.name):void 0)],t={};for(const c of s){if(!c)continue;let l;try{l=await this.dash.fileSystem.readJson(v.join(c,"manifest.json"))}catch{continue}if(!!((n=l==null?void 0:l.compiler)!=null&&n.plugins))for(const u in l.compiler.plugins)t[u]=v.join(c,l.compiler.plugins[u])}const i=(a=(await this.getCompilerOptions()).plugins)!=null?a:[];for(const c of i){const l=typeof c=="string"?c:c[0],u=typeof c=="string"?{}:c[1];if(t[l]){const m=await this.pluginRuntime.run(t[l],{console:this.dash.console,...e}).catch(d=>(this.dash.console.error(`Failed to execute plugin ${l}: ${d}`),null));if(!m)continue;typeof m.__default__=="function"?this.plugins.push(new N(this.dash,l,m.__default__(await this.getPluginContext(l,u)))):this.dash.console.error(`Plugin ${l} is invalid: It does not provide a function as a default export.`)}else U[l]?this.plugins.push(new N(this.dash,l,U[l](await this.getPluginContext(l,u)))):this.dash.console.error(`Unknown compiler plugin: ${l}`)}}async getCompilerOptions(){var s;const e=await this.dash.getCompilerConfigPath();return e?await this.dash.fileSystem.readJson(e):(s=this.dash.projectConfig.get().compiler)!=null?s:{}}async getPluginContext(e,s={}){const t=this.dash;return{options:{get mode(){return t.getMode()},get buildType(){return t.buildType},...s},jsRuntime:this.dash.jsRuntime,console:this.dash.console,fileSystem:this.dash.fileSystem,outputFileSystem:this.dash.outputFileSystem,projectConfig:this.dash.projectConfig,projectRoot:this.dash.projectRoot,packType:this.dash.packType,fileType:this.dash.fileType,targetVersion:this.dash.projectConfig.get().targetVersion,requestJsonData:this.dash.requestJsonData,getAliases:i=>{var n,a;return[...(a=(n=this.dash.includedFiles.get(i))==null?void 0:n.aliases)!=null?a:[]]},hasComMojangDirectory:this.dash.fileSystem!==this.dash.outputFileSystem,compileFiles:i=>this.dash.compileVirtualFiles(i)}}async runBuildStartHooks(){for(const e of this.plugins)await e.runBuildStartHook()}async runIncludeHooks(){let e=[];for(const s of this.plugins){const t=await s.runIncludeHook();Array.isArray(t)&&e.push(...t)}return e}async runTransformPathHooks(e){let s=e;for(const t of this.plugins){const i=await t.runTransformPathHook(s);if(i===null)return null;i!==void 0&&(s=i)}return s}async runReadHooks(e,s){for(const t of this.plugins){const i=await t.runReadHook(e,s);if(i!=null)return i}}async runLoadHooks(e,s){let t=s;for(const i of this.plugins){const n=await i.runLoadHook(e,t);n!==void 0&&(t=n)}return t}async runRegisterAliasesHooks(e,s){const t=new Set;for(const i of this.plugins){const n=await i.runRegisterAliasesHook(e,s);n!=null&&(Array.isArray(n)?n.forEach(a=>t.add(a)):t.add(n))}return t}async runRequireHooks(e,s){const t=new Set;for(const i of this.plugins){const n=await i.runRequireHook(e,s);n!=null&&(Array.isArray(n)?n.forEach(a=>t.add(a)):t.add(n))}return t}async runTransformHooks(e){const s=Object.fromEntries([...e.requiredFiles].map(i=>this.dash.includedFiles.query(i)).flat().map(i=>[[i.filePath,i.data],...[...i.aliases].map(n=>[n,i.data])]).flat());let t=e.data;for(const i of this.plugins){const n=await i.runTransformHook(e.filePath,t,s);n!==void 0&&(t=n)}return t}async runFinalizeBuildHooks(e){for(const s of this.plugins){const t=await s.runFinalizeBuildHook(e.filePath,e.data);if(t!==void 0)return t}}async runBuildEndHooks(){for(const e of this.plugins)await e.runBuildEndHook()}}class x{constructor(e,s,t=!1){this.dash=e,this.filePath=s,this.isVirtual=t,this.isDone=!1,this.requiredFiles=new Set,this.aliases=new Set,this.updateFiles=new Set,this.outputPath=s,this.isVirtual||this.setDefaultFileHandle()}setFileHandle(e){this.fileHandle=e}setDefaultFileHandle(){this.setFileHandle({getFile:()=>this.dash.fileSystem.readFile(this.filePath).catch(()=>null)})}setOutputPath(e){this.outputPath=e}setReadData(e){this.data=e}setAliases(e){for(const s of e)this.dash.includedFiles.addAlias(s,this);this.aliases=e}setRequiredFiles(e){this.requiredFiles=e}setUpdateFiles(e){this.updateFiles=new Set(e.map(s=>this.dash.includedFiles.get(s)).filter(s=>s!==void 0))}addUpdateFile(e){this.updateFiles.add(e)}removeUpdateFile(e){this.updateFiles.delete(e)}getHotUpdateChain(){const e=new Set([this]);for(const s of this.updateFiles)s.getHotUpdateChain().forEach(t=>{e.add(t)});return e}filesToLoadForHotUpdate(e=new Set,s=!0){const t=new Set;if(e.has(this))return t;e.add(this);for(const i of this.requiredFiles){const n=this.dash.includedFiles.query(i);for(const a of n)a.filesToLoadForHotUpdate(e,!1).forEach(c=>{t.add(c)})}if(t.add(this),s)for(const i of this.updateFiles)i.filesToLoadForHotUpdate(e,!0).forEach(n=>{t.add(n)});return t}async processAfterLoad(e){if((this.data===null||this.data===void 0)&&(this.isDone=!0,this.filePath!==this.outputPath&&this.outputPath!==null&&!this.isVirtual&&e)){const s=await this.dash.fileSystem.readFile(this.filePath);await this.dash.outputFileSystem.writeFile(this.outputPath,new Uint8Array(await s.arrayBuffer()))}}serialize(){return{isVirtual:this.isVirtual,filePath:this.filePath,aliases:[...this.aliases],requiredFiles:[...this.requiredFiles],updateFiles:[...this.updateFiles].map(e=>e.filePath)}}reset(){this.isDone=!1,this.data=null,this.isVirtual||this.setDefaultFileHandle()}}class Ce{constructor(e){this.dash=e,this.files=new Map,this.aliases=new Map,this.queryCache=new Map}all(){return[...this.files.values()]}filtered(e){return this.all().filter(s=>e(s))}get(e){var s;return(s=this.aliases.get(e))!=null?s:this.files.get(e)}query(e){if(ee.default(e))return this.queryGlob(e);const s=this.aliases.get(e);if(s)return[s];const t=this.files.get(e);return t?[t]:[]}addAlias(e,s){this.aliases.set(e,s)}queryGlob(e){if(this.queryCache.has(e))return this.queryCache.get(e);const s=this.filtered(t=>j.isMatch(t.filePath,e));return this.queryCache.set(e,s),s}async loadAll(){this.queryCache=new Map;const e=new Set,s=this.dash.projectConfig.getAvailablePackPaths();for(const i of s){const n=await this.dash.fileSystem.allFiles(i).catch(a=>(this.dash.console.warn(a),[]));for(const a of n)e.add(a)}const t=await this.dash.plugins.runIncludeHooks();for(const i of t)typeof i=="string"?e.add(i):this.addOne(i[0],i[1].isVirtual);this.add([...e])}addOne(e,s=!1){const t=new x(this.dash,e,s);return this.files.set(e,t),t}add(e,s=!1){let t=[];for(const i of e){const n=this.files.get(i);if(n){t.push(n);continue}t.push(new x(this.dash,i,s)),this.files.set(i,t[t.length-1])}return t}remove(e){const s=this.files.get(e);if(!!s){this.files.delete(e);for(const t of s.aliases)this.aliases.delete(t)}}async save(e){await this.dash.fileSystem.writeJson(e,this.all().map(s=>s.serialize()))}async load(e){this.removeAll();const s=await this.dash.fileSystem.readJson(e),t=[];for(const i of s){const n=new x(this.dash,i.filePath,i.isVirtual);n.setAliases(new Set(i.aliases)),n.setRequiredFiles(new Set(i.requiredFiles)),t.push(n);for(const a of i.aliases)this.aliases.set(a,n)}this.files=new Map(t.map(i=>[i.filePath,i]));for(let i=0;ithis.onChangeCbs.delete(e)}}setTotal(e){this.total=e,this.current=0,this.onChangeCbs.forEach(s=>s(this))}updateCurrent(e){this.current=e,this.onChangeCbs.forEach(s=>s(this))}advance(){this.current++,this.onChangeCbs.forEach(e=>e(this))}addToTotal(e){this.total+=e,this.onChangeCbs.forEach(s=>s(this))}}class K{constructor(){this._timers=new Map}time(e){if(this._timers.has(e)){this.warn(`Timer "${e}" already exists.`);return}else this._timers.set(e,Date.now())}timeEnd(e){const s=this._timers.get(e);if(s)this._timers.delete(e),this.log(`${e}: ${Date.now()-s}ms`);else{this.warn(`Timer "${e}" does not exist.`);return}}}class X extends K{log(...e){console.log(...e)}error(...e){console.error(...e)}warn(...e){console.warn(...e)}info(...e){console.info(...e)}}class Re{constructor(e,s,t){var i;this.fileSystem=e,this.options=t,this.progress=new qe,this.plugins=new _e(this),this.includedFiles=new Ce(this),this.loadFiles=new Ae(this),this.fileOrderResolver=new Te(this),this.fileTransformer=new Ie(this),this.buildType="fullBuild",this.outputFileSystem=s!=null?s:e,this.projectRoot=v.dirname(t.config),this.projectConfig=new te(e,t.config),this.console=(i=t.console)!=null?i:new X,this.jsRuntime=new G(this.fileSystem,[["@molang/expressions",O.expressions],["@molang/core",{MoLang:O.MoLang}],["molang",{MoLang:O.MoLang,...O.expressions}],["@bridge/compiler",{mode:t.mode}]]),this.packType=t.packType,this.fileType=t.fileType}getMode(){var e;return(e=this.options.mode)!=null?e:"development"}getCompilerConfigPath(){return this.options.compilerConfig}get requestJsonData(){return this.options.requestJsonData}get dashFilePath(){return v.join(this.projectRoot,`.bridge/.dash.${this.getMode()}.json`)}async setup(e){var s,t,i,n;try{await this.projectConfig.setup()}catch(a){this.console.error("Failed to load project config: "+a)}(s=this.fileType)==null||s.setProjectConfig(this.projectConfig),(t=this.packType)==null||t.setProjectConfig(this.projectConfig),await((i=this.fileType)==null?void 0:i.setup(e)),await((n=this.packType)==null?void 0:n.setup(e)),await this.plugins.loadPlugins(this.options.pluginEnvironment)}async reload(){try{await this.projectConfig.refreshConfig()}catch{}await this.plugins.loadPlugins(this.options.pluginEnvironment)}get isCompilerActivated(){const e=this.projectConfig.get();return e.compiler!==void 0&&Array.isArray(e.compiler.plugins)}async build(){if(this.console.log("Starting compilation..."),!this.isCompilerActivated)return;this.jsRuntime.clearCache(),this.buildType="fullBuild",this.includedFiles.removeAll();const e=Date.now();this.progress.setTotal(7),await this.plugins.runBuildStartHooks(),this.progress.advance(),await this.includedFiles.loadAll(),this.progress.advance(),await this.compileIncludedFiles(),await this.plugins.runBuildEndHooks(),this.progress.advance(),this.getMode()==="development"&&await this.saveDashFile(),this.includedFiles.resetAll(),this.progress.advance(),this.console.log(`Dash compiled ${this.includedFiles.all().length} files in ${Date.now()-e}ms!`)}async updateFiles(e,s=!0){var c;if(!this.isCompilerActivated||e.length===0)return;this.buildType="hotUpdate",this.jsRuntime.clearCache(),this.progress.setTotal(8),this.console.log(`Dash is starting to update ${e.length} files...`),await this.includedFiles.load(this.dashFilePath),await this.plugins.runBuildStartHooks();const t=[];for(const l of e){let u=this.includedFiles.get(l);u||([u]=this.includedFiles.add([l])),t.push(u)}this.progress.advance();const i=[];for(const l of t)i.push(new Set([...l.requiredFiles]));this.progress.advance(),await this.loadFiles.run(t),this.progress.advance();for(let l=0;l!i[l].has(o)).forEach(o=>this.includedFiles.query(o).forEach(f=>f.addUpdateFile(u))),[...i[l]].filter(o=>!u.requiredFiles.has(o)).forEach(o=>this.includedFiles.query(o).forEach(f=>f.removeUpdateFile(u)))}this.progress.advance();const n=new Set(t.map(l=>[...l.filesToLoadForHotUpdate()]).flat());this.console.log(`Dash is loading ${n.size} files...`),await this.loadFiles.run([...n.values()].filter(l=>!t.includes(l))),this.progress.advance();const a=new Set(t.map(l=>[...l.getHotUpdateChain()]).flat());for(const l of n)l.isDone||(l.data=(c=await this.plugins.runTransformHooks(l))!=null?c:l.data,a.has(l)||(l.isDone=!0));this.progress.advance(),this.console.log(`Dash is compiling ${a.size} files...`),await this.fileTransformer.run(a,!0),this.progress.advance(),await this.plugins.runBuildEndHooks(),s&&await this.saveDashFile(),this.includedFiles.resetAll(),this.console.log(`Dash finished updating ${a.size} files!`),this.progress.advance()}async compileFile(e,s){var a;if(!this.isCompilerActivated)return[[],s];this.buildType="fileRequest",this.jsRuntime.clearCache(),this.progress.setTotal(7),await this.plugins.runBuildStartHooks(),await this.includedFiles.load(this.dashFilePath);let t=this.includedFiles.get(e);t||([t]=this.includedFiles.add([e])),t.setFileHandle({getFile:async()=>new File([s],v.basename(e))}),await this.loadFiles.loadFile(t,!1),await this.loadFiles.loadRequiredFiles(t),this.progress.advance();const i=t.filesToLoadForHotUpdate();await this.loadFiles.run([...i.values()].filter(c=>t!==c),!1),this.progress.advance();for(const c of i)c.isDone||(c.data=(a=await this.plugins.runTransformHooks(c))!=null?a:c.data);this.progress.advance();const n=await this.fileTransformer.transformFile(t,!0,!0);return this.progress.advance(),await this.includedFiles.load(this.dashFilePath),this.progress.advance(),await this.plugins.runBuildEndHooks(),[[...i].map(c=>c.filePath),n]}async unlinkMultiple(e){if(!(!this.isCompilerActivated||e.length===0)){for(const s of e)await this.unlink(s,!1);await this.saveDashFile()}}async unlink(e,s=!0){if(!this.isCompilerActivated)return;const t=await this.plugins.runTransformPathHooks(e);!t||t===e||(await this.outputFileSystem.unlink(t),this.includedFiles.remove(e),s&&await this.saveDashFile())}async rename(e,s){!this.isCompilerActivated||(await this.unlink(e,!1),await this.updateFiles([s],!1),await this.saveDashFile())}async getCompilerOutputPath(e){if(!this.isCompilerActivated)return;const s=await this.plugins.runTransformPathHooks(e);if(!!s)return s}async getFileDependencies(e){if(!this.isCompilerActivated)return[];await this.includedFiles.load(this.dashFilePath);const s=this.includedFiles.get(e);return s?[...s.filesToLoadForHotUpdate()].map(t=>t.isVirtual?t.outputPath:t.filePath).filter(t=>t!==null&&t!==e):[]}async saveDashFile(){await this.includedFiles.save(this.dashFilePath)}async compileIncludedFiles(e=this.includedFiles.all()){await this.loadFiles.run(e),this.progress.advance();const s=this.fileOrderResolver.run(e);this.progress.advance(),await this.fileTransformer.run(s),this.progress.advance()}async compileVirtualFiles(e){const s=this.includedFiles.add(e,!0);this.progress.addToTotal(3),s.forEach(t=>t.reset()),await this.compileIncludedFiles(s)}}class Ee{async allFiles(e){const s=[],t=await this.readdir(e);for(const{name:i,kind:n}of t)n==="directory"?s.push(...await this.allFiles(v.join(e,i))):n==="file"&&s.push(v.join(e,i));return s}async writeJson(e,s,t=!0){await this.writeFile(e,JSON.stringify(s,null,t?" ":0))}async readJson(e){const s=await this.readFile(e);try{return await A.default.parse(await s.text())}catch{throw new Error(`Invalid JSON: ${e}`)}}watchDirectory(e,s){console.warn("Watching a directory for changes is not supported on this platform!")}}Object.defineProperty(b,"initRuntimes",{enumerable:!0,get:function(){return q.initRuntimes}}),b.Command=I,b.Component=L,b.Console=K,b.Dash=Re,b.DefaultConsole=X,b.FileSystem=Ee,Object.defineProperty(b,"__esModule",{value:!0}),b[Symbol.toStringTag]="Module"}); diff --git a/package.json b/package.json index 60da372..732b7fa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dash-compiler", - "version": "0.9.14", + "version": "0.9.15", "description": "A fast compiler for Minecraft Add-Ons", "scripts": { "build:types": "tsc --project tsconfig.json", diff --git a/src/Plugins/BuiltIn/GeneratorScripts/Module.ts b/src/Plugins/BuiltIn/GeneratorScripts/Module.ts index a7fc149..fabe32e 100644 --- a/src/Plugins/BuiltIn/GeneratorScripts/Module.ts +++ b/src/Plugins/BuiltIn/GeneratorScripts/Module.ts @@ -10,6 +10,10 @@ export interface IModuleOpts { console: Console } +interface IUseTemplateOptions { + omitTemplate?: boolean +} + export function createModule({ generatorPath, omitUsedTemplates, @@ -17,7 +21,10 @@ export function createModule({ console, }: IModuleOpts) { return { - useTemplate: (filePath: string, omitTemplate = true) => { + useTemplate: ( + filePath: string, + { omitTemplate = true }: IUseTemplateOptions = {} + ) => { const templatePath = join(dirname(generatorPath), filePath) if (omitTemplate) omitUsedTemplates.add(templatePath) diff --git a/src/Plugins/BuiltIn/GeneratorScripts/Plugin.ts b/src/Plugins/BuiltIn/GeneratorScripts/Plugin.ts index 85b86bb..4665831 100644 --- a/src/Plugins/BuiltIn/GeneratorScripts/Plugin.ts +++ b/src/Plugins/BuiltIn/GeneratorScripts/Plugin.ts @@ -96,7 +96,10 @@ export const GeneratorScriptsPlugin: TCompilerPluginFactory<{}> = ({ return module.__default__ } + }, + finalizeBuild(filePath, fileContent) { + // 1. Handle generated virtual files if (fileCollection.get(filePath)) { if ( filePath.endsWith('.json') && @@ -105,11 +108,11 @@ export const GeneratorScriptsPlugin: TCompilerPluginFactory<{}> = ({ return JSON.stringify(fileContent, null, '\t') return fileContent } - }, - finalizeBuild(filePath, fileContent) { + // 2. Omit unused template if (omitUsedTemplates.has(filePath)) return null + // 3. Handle transformed generator script if (isGeneratorScript(filePath)) { if (fileContent === null) return null