@remotex-labs/xbuild 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bash.js +11 -11
- package/dist/bash.js.map +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -351,7 +351,7 @@ ${t}
|
|
|
351
351
|
`)}
|
|
352
352
|
};`)}return l.length>0&&n.push(...l),n.join(`
|
|
353
353
|
`)}};import{mkdir as kr,writeFile as Or}from"fs/promises";import{xterm as Pr}from"@remotex-labs/xansi/xterm.component";var me=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Pr.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let n=[],o=t.getSourceFiles();for(let s=0;s<o.length;s++){let a=o[s];this.shouldEmitFile(a,t,i)&&n.push(a)}n.length!==0&&await Promise.all(n.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let n=Me(e.fileName,i),o=r.emittedVersions.get(n),s=this.languageHostService.getScriptVersion(e.fileName);return!o||o!==s?(r.emittedVersions.set(n,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let n=i.outputFiles[0].text,o=Me(e.fileName,t);n=ue(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await kr(T(o),{recursive:!0}),await Or(o,n,"utf8")}};import Y from"typescript";var ge=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Y.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=Y.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(v);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Y.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,n,o){return r.sys.readDirectory(e,t,i,n,o)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return Y.getDefaultLibFilePath(e)}getScriptVersion(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.version.toString():"0"}hasScriptSnapshot(e){return this.trackFiles.has(this.filesCache.resolve(e))}getScriptSnapshot(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.contentSnapshot:this.touchFile(e).contentSnapshot}resolveModuleName(e,t){return Y.resolveModuleName(e,t,this.compilerOptions,Y.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let n=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,n),n}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(n,o)=>{let s=this.resolveModuleFileName(o,t);if(!s)return n;let a=s.replace(/\.tsx?$/,i),c=F(t,a);return n.replace(o,c.startsWith(".")?c:"./"+c)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(n=>n.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var lt,je;lt=[A({providers:[{useValue:"tsconfig.json"}]})];var N=class N{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:n}=this.acquireLanguageService();this.config=t,this.languageService=n,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new me(n,i),this.bundlerService=new de(n,i)}config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(n=>t.getSourceFile(n)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(n=>this.shouldCheckFile(n)).flatMap(n=>this.collectDiagnostics(n)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=N.serviceCache.get(this.configPath);i.config=this.parseConfig(),i.host.options=i.config.options}}async emitBundle(e,t){await this.bundlerService.emit(e,t)}async emit(e){await this.emitterService.emit(e)}dispose(e){let t=N.serviceCache.get(e);t&&(t.refCount--,N.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=N.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new ge(e.options),i=V.createLanguageService(t,V.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return N.serviceCache.set(this.configPath,n),n}parseConfig(){let e=V.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...V.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:V.ScriptTarget.ESNext,module:V.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:V.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:V.flattenDiagnosticMessageText(e.messageText,`
|
|
354
|
-
`)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};je=O(null),N=R(je,0,"TypescriptService",lt,N),P(je,1,N);var Q=N;import{cwd as De}from"process";import{build as pt}from"esbuild";var Rr={write:!1,bundle:!0,minify:!0,outdir:`${De()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function ft(r,e,t={}){return await pt({absWorkingDir:De(),...Rr,...t,stdin:{loader:"js",contents:r,resolveDir:De(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function ut(r,e={}){try{return await pt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(J(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw pe(t.errors,i.errors),i}throw t}}function dt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Je(r,e)),t}else if(e&&typeof e=="object")return e;throw new M("Unsupported entry points format")}var he=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new M(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new Q(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(b);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ar(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(J(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?L({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new W("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Nr(e,{recursive:!0}),await Mr(h(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new M(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new M("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=dt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new Q(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await ut(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=F(this.typescriptModule.config.options.rootDir,I(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as jr}from"fs/promises";var ve=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(v);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=I(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await jr(s,"utf8");for(let c of this.loadHooks.values()){let l=await c({contents:i,loader:n,args:e,...t});l&&(l.contents!==void 0&&(i=l.contents),l.loader&&(n=l.loader),l.errors&&o.errors.push(...l.errors),l.warnings&&o.warnings.push(...l.warnings))}return{contents:i,loader:n,...o}}};import y from"typescript";import H from"typescript";var Dr="$$ifdef";function Br(r,e,t,i=!1){let n=i?"export function ":"function ";return H.isArrowFunction(e)||H.isFunctionExpression(e)?$r(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function $r(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Lr(e,t);return`${i}${r}(${n})${o} ${s}`}function Lr(r,e){let t=r.body.getText(e);return H.isArrowFunction(r)&&!H.isBlock(r.body)?`{ return ${t}; }`:t}function Vr(r,e){return H.isArrowFunction(r)||H.isFunctionExpression(r)?`(${r.getText(e)})()`:`(() => { return ${r.getText(e)}; })()`}function mt(r,e,t){let i=r in t&&!!t[r];return e===Dr===i}function gt(r,e,t,i){let[n,o]=e.arguments;if(!H.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!mt(a,s,i.defines))return"";let c=r.name.getText(i.sourceFile);return Br(c,o,i.sourceFile,t)}function ht(r,e,t){let[i,n]=r;if(!H.isStringLiteral(i))return!1;let o=i.text;return mt(o,e,t.defines)?Vr(n,t.sourceFile):""}import k from"typescript";import{createRequire as zr}from"module";var ye=class extends S{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=G(e,{},t),this.stack=K(this.errorMetadata,this.name,this.message)}};import{Script as Hr,createContext as _r}from"vm";async function vt(r,e={},t={}){let i=new Hr(r,t),n=_r(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function yt(r,e,t){let[i,n]=(await ft(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=zr(e.sourceFile.fileName),a=await vt(n.text,Ur(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){qr(o,e,i.text,t)}return"undefined"}function Ur(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:T(r),__filename:r}}function qr(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(C).setSource(t,e.sourceFile.fileName);let s=new ye(r,o);e.errors.push({text:s.message,detail:s})}function Wr(r,e){let t=null,i=n=>{if(!t){if(k.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}k.isVariableStatement(n)&&(t=Gr(n,r),t)||k.forEachChild(n,i)}};return i(e),t}function Gr(r,e){for(let t of r.declarationList.declarations)if(k.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(k.isArrowFunction(t.initializer)||k.isFunctionExpression(t.initializer)))return t.initializer;return null}function xt(r){return`module.exports = (${r})();`}function Kr(r){return r&k.NodeFlags.Const?"const":r&k.NodeFlags.Let?"let":"var"}function bt(r,e){return r?k.isIdentifier(r)?Xr(r,e):k.isArrowFunction(r)||k.isFunctionExpression(r)?{node:r,data:xt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xr(r,e){let t=Wr(r.text,e.sourceFile);return t?{node:t,data:xt(t.getText(e.sourceFile))}:(Jr(r.text,e,r),{data:"",node:r})}function Jr(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=F(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function St(r,e,t,i,n){let o=t.arguments[0],s=bt(o,n);if(!s)return!1;let a=await yt(s.data,n,s.node),c=Kr(e.declarationList.flags),l=i?"export ":"",f=r.name.getText(n.sourceFile);return`${l}${c} ${f} = ${a};`}async function Be(r,e){let t=r[0],i=bt(t,e);return i?yt(i.data,e,i.node):!1}var Yr=/\.(ts|js)$/,D=["$$ifdef","$$ifndef","$$inline"];async function Qr(r,e,t){for(let i of r.declarationList.declarations){let n=i.initializer;if(!n||!y.isCallExpression(n)||!y.isIdentifier(n.expression))continue;let o=n.expression.text;if(!D.includes(o))continue;let s=o==D[2]?1:2;if(!D.includes(o)||n.arguments.length<s){e.add({replacement:"undefined",end:r.getEnd(),start:r.getStart(t.sourceFile)});return}let a=r.modifiers?.some(l=>l.kind===y.SyntaxKind.ExportKeyword)??!1,c=!1;o===D[2]?c=await St(i,r,n,a,t):c=gt(i,n,a,t),c!==!1&&e.add({replacement:c,end:r.getEnd(),start:r.getStart(t.sourceFile)})}}async function Zr(r,e,t){let i=r.expression;if(!y.isIdentifier(i.expression))return;let n=i.expression.text,o=n==D[2]?1:2;if(!D.includes(n)||i.arguments.length<o){e.add({replacement:"undefined",end:r.getEnd(),start:r.getStart(t.sourceFile)});return}let s=!1;n==D[2]?s=await Be(i.arguments,t):s=ht(i.arguments,n,t),s!==!1&&e.add({replacement:s,end:r.getEnd(),start:r.getStart(t.sourceFile)})}async function ei(r){let e=new Set,t=r.stage.defineMetadata.disabledMacroNames,i=async o=>{if(y.isVariableStatement(o))await Qr(o,e,r);else if(y.isExpressionStatement(o)&&y.isCallExpression(o.expression))await Zr(o,e,r);else if(y.isCallExpression(o)&&y.isIdentifier(o.expression)&&o.expression.text===D[2]){let a=o.parent;if(!a||!y.isVariableDeclaration(a)&&!y.isExpressionStatement(a)){let c=await Be(o.arguments,r);c!==!1&&e.add({replacement:c,end:o.getEnd(),start:o.getStart(r.sourceFile)})}}else if(y.isCallExpression(o)&&y.isIdentifier(o.expression)&&t.has(o.expression.text))e.add({start:o.getStart(r.sourceFile),end:o.getEnd(),replacement:"undefined"});else if(y.isIdentifier(o)&&t.has(o.text)){let a=o.parent,c=a?.getText(r.sourceFile);(!a||!y.isCallExpression(a)||a.expression!==o)&&(!c||D.every(l=>!c.includes(l)))&&e.add({start:o.getStart(r.sourceFile),end:o.getEnd(),replacement:"undefined"})}let s=o.getChildren(r.sourceFile);for(let a of s)await i(a)};if(await i(r.sourceFile),e.size===0)return r.contents;let n=Array.from(e);n.sort((o,s)=>s.start-o.start);for(let{start:o,end:s,replacement:a}of n)r.contents=r.contents.slice(0,o)+a+r.contents.slice(s);return r.contents}async function wt(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Yr.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c=o.toString(),l={stage:n,errors:[],contents:c,warnings:[],defines:r.config.define??{},sourceFile:a};return a&&(c=await ei(l)),r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(c=r.typescript.languageHostService.resolveAliases(c,t.path,".js")),{loader:i,contents:c,warnings:l.warnings,errors:l.errors}}var Ct="$$",It=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef)\s*\(\s*['"]([^'"]+)['"]/g;function ti(r,e,t,i){let n=1;for(let o=0;o<i;o++)r[o]===`
|
|
354
|
+
`)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};je=O(null),N=R(je,0,"TypescriptService",lt,N),P(je,1,N);var Q=N;import{cwd as De}from"process";import{build as pt}from"esbuild";var Rr={write:!1,bundle:!0,minify:!0,outdir:`${De()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function ft(r,e,t={}){return await pt({absWorkingDir:De(),...Rr,...t,stdin:{loader:"js",contents:r,resolveDir:De(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function ut(r,e={}){try{return await pt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(J(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw pe(t.errors,i.errors),i}throw t}}function dt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Je(r,e)),t}else if(e&&typeof e=="object")return e;throw new M("Unsupported entry points format")}var he=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new M(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new Q(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(b);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ar(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(J(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?L({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new W("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Nr(e,{recursive:!0}),await Mr(h(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new M(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new M("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=dt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new Q(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await ut(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=F(this.typescriptModule.config.options.rootDir,I(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as jr}from"fs/promises";var ve=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(v);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=I(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await jr(s,"utf8");for(let c of this.loadHooks.values()){let l=await c({contents:i,loader:n,args:e,...t});l&&(l.contents!==void 0&&(i=l.contents),l.loader&&(n=l.loader),l.errors&&o.errors.push(...l.errors),l.warnings&&o.warnings.push(...l.warnings))}return{contents:i,loader:n,...o}}};import y from"typescript";import H from"typescript";var Dr="$$ifdef";function Br(r,e,t,i=!1){let n=i?"export function ":"function ";return H.isArrowFunction(e)||H.isFunctionExpression(e)?$r(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function $r(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Lr(e,t);return`${i}${r}(${n})${o} ${s}`}function Lr(r,e){let t=r.body.getText(e);return H.isArrowFunction(r)&&!H.isBlock(r.body)?`{ return ${t}; }`:t}function Vr(r,e){return H.isArrowFunction(r)||H.isFunctionExpression(r)?`(${r.getText(e)})()`:`(() => { return ${r.getText(e)}; })()`}function mt(r,e,t){let i=r in t&&!!t[r];return e===Dr===i}function gt(r,e,t,i){let[n,o]=e.arguments;if(!H.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!mt(a,s,i.defines))return"";let c=r.name.getText(i.sourceFile);return Br(c,o,i.sourceFile,t)}function ht(r,e,t){let[i,n]=r;if(!H.isStringLiteral(i))return!1;let o=i.text;return mt(o,e,t.defines)?Vr(n,t.sourceFile):""}import k from"typescript";import{createRequire as zr}from"module";var ye=class extends S{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=G(e,{},t),this.stack=K(this.errorMetadata,this.name,this.message)}};import{Script as Hr,createContext as _r}from"vm";async function vt(r,e={},t={}){let i=new Hr(r,t),n=_r(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function yt(r,e,t){let[i,n]=(await ft(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=zr(e.sourceFile.fileName),a=await vt(n.text,Ur(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){qr(o,e,i.text,t)}return"undefined"}function Ur(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:T(r),__filename:r}}function qr(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(C).setSource(t,e.sourceFile.fileName);let s=new ye(r,o);e.errors.push({text:s.message,detail:s})}function Wr(r,e){let t=null,i=n=>{if(!t){if(k.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}k.isVariableStatement(n)&&(t=Gr(n,r),t)||k.forEachChild(n,i)}};return i(e),t}function Gr(r,e){for(let t of r.declarationList.declarations)if(k.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(k.isArrowFunction(t.initializer)||k.isFunctionExpression(t.initializer)))return t.initializer;return null}function xt(r){return`module.exports = (${r})();`}function Kr(r){return r&k.NodeFlags.Const?"const":r&k.NodeFlags.Let?"let":"var"}function bt(r,e){return r?k.isIdentifier(r)?Xr(r,e):k.isArrowFunction(r)||k.isFunctionExpression(r)?{node:r,data:xt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xr(r,e){let t=Wr(r.text,e.sourceFile);return t?{node:t,data:xt(t.getText(e.sourceFile))}:(Jr(r.text,e,r),{data:"",node:r})}function Jr(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=F(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function St(r,e,t,i,n){let o=t.arguments[0],s=bt(o,n);if(!s)return!1;let a=await yt(s.data,n,s.node),c=Kr(e.declarationList.flags),l=i?"export ":"",f=r.name.getText(n.sourceFile);return`${l}${c} ${f} = ${a};`}async function Be(r,e){let t=r[0],i=bt(t,e);return i?yt(i.data,e,i.node):!1}var Yr=/\.(ts|js)$/,D=["$$ifdef","$$ifndef","$$inline"];async function Qr(r,e,t){for(let i of r.declarationList.declarations){let n=i.initializer;if(!n||!y.isCallExpression(n)||!y.isIdentifier(n.expression))continue;let o=n.expression.text;if(!D.includes(o))continue;let s=o==D[2]?1:2;if(!D.includes(o))return;if(n.arguments.length<s)throw new Error(`Invalid macro call: ${o} with ${n.arguments.length} arguments`);let a=r.modifiers?.some(l=>l.kind===y.SyntaxKind.ExportKeyword)??!1,c=!1;o===D[2]?c=await St(i,r,n,a,t):c=gt(i,n,a,t),c!==!1&&e.add({replacement:c,end:r.getEnd(),start:r.getStart(t.sourceFile)})}}async function Zr(r,e,t){let i=r.expression;if(!y.isIdentifier(i.expression))return;let n=i.expression.text,o=n==D[2]?1:2;if(!D.includes(n))return;if(i.arguments.length<o)throw new Error(`Invalid macro call: ${n} with ${i.arguments.length} arguments`);let s=!1;n==D[2]?s=await Be(i.arguments,t):s=ht(i.arguments,n,t),s!==!1&&e.add({replacement:s,end:r.getEnd(),start:r.getStart(t.sourceFile)})}async function ei(r){let e=new Set,t=r.stage.defineMetadata.disabledMacroNames,i=async o=>{if(y.isVariableStatement(o))await Qr(o,e,r);else if(y.isExpressionStatement(o)&&y.isCallExpression(o.expression))await Zr(o,e,r);else if(y.isCallExpression(o)&&y.isIdentifier(o.expression)&&o.expression.text===D[2]){let a=o.parent;if(!a||!y.isVariableDeclaration(a)&&!y.isExpressionStatement(a)){let c=await Be(o.arguments,r);c!==!1&&e.add({replacement:c,end:o.getEnd(),start:o.getStart(r.sourceFile)})}}else if(y.isCallExpression(o)&&y.isIdentifier(o.expression)&&t.has(o.expression.text))e.add({start:o.getStart(r.sourceFile),end:o.getEnd(),replacement:"undefined"});else if(y.isIdentifier(o)&&t.has(o.text)){let a=o.parent,c=a?.getText(r.sourceFile);(!a||!y.isCallExpression(a)||a.expression!==o)&&(!c||D.every(l=>!c.includes(l)))&&e.add({start:o.getStart(r.sourceFile),end:o.getEnd(),replacement:"undefined"})}let s=o.getChildren(r.sourceFile);for(let a of s)await i(a)};if(await i(r.sourceFile),e.size===0)return r.contents;let n=Array.from(e);n.sort((o,s)=>s.start-o.start);for(let{start:o,end:s,replacement:a}of n)r.contents=r.contents.slice(0,o)+a+r.contents.slice(s);return r.contents}async function wt(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Yr.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c=o.toString(),l={stage:n,errors:[],contents:c,warnings:[],defines:r.config.define??{},sourceFile:a};return a&&(c=await ei(l)),r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(c=r.typescript.languageHostService.resolveAliases(c,t.path,".js")),{loader:i,contents:c,warnings:l.warnings,errors:l.errors}}var Ct="$$",It=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef)\s*\(\s*['"]([^'"]+)['"]/g;function ti(r,e,t,i){let n=1;for(let o=0;o<i;o++)r[o]===`
|
|
355
355
|
`&&n++;return{file:t,line:n,column:r.indexOf(e,i)-i}}function ri(r,e){let t=r.lastIndexOf(`
|
|
356
356
|
`,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function Et(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(v),o=r.config.define??{},s=Object.keys(r.dependencies);if(!s)return Promise.resolve({warnings:i});for(let a of s){let l=(n.getSnapshot(a)??n.touchFile(a))?.contentSnapshot?.text;if(l){It.lastIndex=0;for(let f of l.matchAll(It)){if(ri(l,f.index))continue;t.filesWithMacros.add(n.resolve(a));let[,p,g,m]=f;if(!p)continue;let B=m in o&&!!o[m];g==="ifndef"===B&&t.disabledMacroNames.add(p),p.startsWith(Ct)||i.push({text:`Macro function '${p}' not start with '${Ct}' prefix to avoid conflicts`,location:ti(l,p,a,f.index)})}}}return{warnings:i}}var $e=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(b);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=Pe(a))}catch(a){if(J(a)||a instanceof AggregateError){let c=Pe({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await Et(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new M("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new ve(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new he(e,t,this.config.variants[e],this.argv),t.onLoad(wt.bind({},this.variants[e]),"build-service")}}};function Rs(r){u(b).reload(r)}function As(r){u(b).patch(r)}export{$e as BuildService,Re as ServerModule,Ae as WatchService,Je as collectFilesFromGlob,Pe as enhancedBuildResult,J as isBuildResultError,Ut as isDirectoryExcluded,ce as matchesAny,cr as normalizeMessageToError,Rs as overwriteConfig,zt as parseGlobs,As as patchConfig,pe as processEsbuildMessages,Ai as shouldIncludeFile};
|
|
357
357
|
//# sourceMappingURL=index.js.map
|