@remotex-labs/xbuild 2.4.4 → 2.4.5

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 CHANGED
@@ -21,7 +21,7 @@ __ _| |_/ /_ _ _| | __| |
21
21
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
22
22
  `;function Pt(){return`
23
23
  \r${Qe.burntOrange(ti)}
24
- \rVersion: ${Qe.brightPink("2.4.4")}
24
+ \rVersion: ${Qe.brightPink("2.4.5")}
25
25
  \r`}function I(){return Qe.lightCoral("[xBuild]")}import{readdir as ii,stat as oi,readFile as ni}from"fs/promises";import{xterm as Ie}from"@remotex-labs/xansi/xterm.component";var ge=class{constructor(e,t){this.config=e;this.rootDir=ri(t),this.config.port||=0,this.config.host||="localhost"}config;server;rootDir;framework=u(b);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(I(),Ie.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(I(),Ie.dim("Server stopped.")),this.server=void 0}async restart(){console.log(I(),Ie.burntOrange("Restarting server...")),await this.stop(),await this.start()}setActualPort(){if(this.config.port===0){let e=this.server.address();e&&typeof e=="object"&&e.port&&(this.config.port=e.port)}}startHttpServer(){return new Promise(e=>{this.server=$t.createServer((t,i)=>{this.handleRequest(t,i,()=>this.defaultResponse(t,i))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort(),this.config.onStart?.({host:this.config.host,port:this.config.port,url:`http://${this.config.host}:${this.config.port}`}),e()})})}startHttpsServer(){return new Promise(e=>{let t={key:Mt(this.config.key??Ce(this.framework.distPath,"..","certs","server.key")),cert:Mt(this.config.cert??Ce(this.framework.distPath,"..","certs","server.crt"))};this.server=Bt.createServer(t,(i,o)=>{this.handleRequest(i,o,()=>this.defaultResponse(i,o))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort(),this.config.onStart?.({host:this.config.host,port:this.config.port,url:`https://${this.config.host}:${this.config.port}`}),e()})})}handleRequest(e,t,i){try{this.config.verbose&&console.log(`${I()} Request ${Ie.lightCoral(e.url?.toString()??"")}`),this.config.onRequest?this.config.onRequest(e,t,i):i()}catch(o){this.sendError(t,o)}}getContentType(e){return{html:"text/html",css:"text/css",js:"application/javascript",cjs:"application/javascript",mjs:"application/javascript",ts:"text/plain",map:"application/json",json:"application/json",png:"image/png",jpg:"image/jpeg",gif:"image/gif",txt:"text/plain"}[e]||"application/octet-stream"}async defaultResponse(e,t){let i=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",o=Ce(this.rootDir,i);if(!o.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await oi(o);n.isDirectory()?await this.handleDirectory(o,i,t):n.isFile()&&await this.handleFile(o,t)}catch(n){let s=n.message;s.includes("favicon")||console.log(I(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let n=(await ii(e)).map(l=>{let p=Ce(t,l),f=Rt(l).slice(1)||"folder";return f==="folder"?`
26
26
  <a href="/${p}" class="folder-row">
27
27
  <div class="icon"><i class="fa-solid fa-folder"></i></div>
@@ -42,7 +42,7 @@ __ _| |_/ /_ _ _| | __| |
42
42
  `)}
43
43
  };`)}return l.length>0&&o.push(...l),o.join(`
44
44
  `)}};import{dirname as Ti}from"@remotex-labs/xmap";import{mkdir as Oi,writeFile as Fi}from"fs/promises";import{xterm as ki}from"@remotex-labs/xansi/xterm.component";var Fe=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}languageService;languageHostService;static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${ki.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let o=[],n=t.getSourceFiles();for(let s=0;s<n.length;s++){let a=n[s];this.shouldEmitFile(a,t,i)&&o.push(a)}o.length!==0&&await Promise.all(o.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let o=Ze(e.fileName,i),n=r.emittedVersions.get(o),s=this.languageHostService.getScriptVersion(e.fileName);return!n||n!==s?(r.emittedVersions.set(o,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let o=i.outputFiles[0].text,n=Ze(e.fileName,t);o=Te(o),o=this.languageHostService.resolveAliases(o,e.fileName,".d.ts"),await Oi(Ti(n),{recursive:!0}),await Fi(n,o,"utf8")}};import ee from"typescript";import{relative as Ai,dirname as Pi}from"@remotex-labs/xmap";var te=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=ee.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}compilerOptions;static sys=ee.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=ee.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static reload(){let e=u(v);e.getTrackedFilePaths().map(t=>{e.touchFile(t)})}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,o,n){return r.sys.readDirectory(e,t,i,o,n)}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 ee.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 ee.resolveModuleName(e,t,this.compilerOptions,ee.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let o=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,o),o}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(o,n)=>{let s=this.resolveModuleFileName(n,t);if(!s)return o;let a=s.replace(/\.tsx?$/,i),c=Ai(Pi(t),a);return o.replace(n,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(o=>o.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var Vt,tt;Vt=[A({providers:[{useValue:"tsconfig.json"}]})];var N=class N{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:o}=this.acquireLanguageService();this.config=t,this.languageService=o,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new Fe(o,i),this.bundlerService=new Oe(o,i)}configPath;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(o=>t.getSourceFile(o)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(o=>this.shouldCheckFile(o)).flatMap(o=>this.collectDiagnostics(o)):[]}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){if(!e||e.fileName.includes("node_modules"))return!1;if(this.config.raw?.exclude){for(let t of this.config.raw.exclude)if(Ri(Mi(this.config.options.rootDir,e.fileName),t))return!1}return!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 te(e.options),i=G.createLanguageService(t,G.createDocumentRegistry()),o={config:e,host:t,service:i,refCount:1};return N.serviceCache.set(this.configPath,o),o}parseConfig(){let e=G.getParsedCommandLineOfConfigFile(this.configPath,{sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0},{...G.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:G.ScriptTarget.ESNext,module:G.ModuleKind.NodeNext,sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0,moduleResolution:G.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:G.flattenDiagnosticMessageText(e.messageText,`
45
- `),category:e.category};if(e.file&&e.start!==void 0){let{line:i,character:o}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=o+1,t.code=e.code}return t}};tt=O(null),N=k(tt,0,"TypescriptService",Vt,N),F(tt,1,N);var re=N;import{cwd as ke}from"process";import{build as rt}from"esbuild";var _t={write:!1,bundle:!0,minify:!0,outdir:`${ke()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Ut(r,e={}){try{return await rt({absWorkingDir:ke(),..._t,...e,metafile:!0,entryPoints:r})}catch(t){if(V(t)){let i=new AggregateError([],"Failed to build entryPoints");throw de(t.errors,i.errors),i}throw t}}async function zt(r,e,t={}){return await rt({absWorkingDir:ke(),..._t,...t,stdin:{loader:"ts",contents:r,resolveDir:ke(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Wt(r,e={}){try{return await rt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(V(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw de(t.errors,i.errors),i}throw t}}import{relative as ji,resolve as Li,join as qt,dirname as Hi}from"@remotex-labs/xmap";function Gt(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=we(r,e)),t}else if(e&&typeof e=="object")return e;throw new S("Unsupported entry points format")}var Ae=class{constructor(e,t,i,o={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=o;if(!this.buildConfig?.esbuild)throw new S(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new re(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),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(n=>({variantConfig:n.variants?.[this.name],commonConfig:n.common})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}name;lifecycle;buildConfig;argv;dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(x);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)return;this.applyInjections();let e=Object.assign({},this.buildConfig.esbuild);if(this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&Object.assign(e,{entryPoints:this.dependenciesFile}),this.config.define&&e.define)for(let[t,i]of Object.entries(this.config.define))typeof i=="function"&&(e.define[t]=JSON.stringify(i()));try{let t=await Bi(e);return await this.packageTypeComponent(),t}catch(t){if(V(t)){if(t.errors.filter(o=>o.location).length>0)throw t;return{errors:t?.errors??[],warnings:t?.warnings??[]}}}}getConfig(e,t={}){return e?z({},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;if(typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError){let o=new R("Type checking failed",t);e.warnings?.push({detail:o,location:void 0})}else{let o=[],n=[],s=new R("Type checking failed",o),a=new R("Type checking failed",n);for(let c of t)(c.category===$i.DiagnosticCategory.Error?o:n).push(c);o.length&&e.errors?.push({detail:s,location:void 0}),n.length&&e.warnings?.push({detail:a,location:void 0})}return e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(typeof e.buildResult.metafile?.outputs=="object"){let s=Object.keys(e.buildResult.metafile?.outputs);for(let a of s){if(!a.endsWith(".map"))continue;let c=Hi(a),l=await Di(a,"utf8"),p=JSON.parse(l);p.sources=p.sources.map(f=>f.startsWith("http")?f:qt(c,f)),await Kt(a,JSON.stringify(p),"utf8")}}if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,o=typeof i=="object"?i.bundle!==!1:!0,n=typeof i=="object"?i.outDir:void 0;try{o?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,n):await this.typescriptModule.emit(n)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:o,onEnd:n,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),o&&this.lifecycle.onLoad(o),n&&this.lifecycle.onEnd(n),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Ni(e,{recursive:!0}),await Kt(qt(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new S(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints&&!e.esbuild.stdin)throw new S("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).flatMap(([o,n])=>typeof n=="function"?[]:[[o,JSON.stringify(n)]])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=Gt(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.outdir&&i.esbuild.outfile&&(this.buildConfig.esbuild.outdir=void 0),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new re(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,t={...e,plugins:void 0},{metafile:i}=await Wt(e.entryPoints,t),o={};for(let n of Object.keys(i.inputs)){let s=ji(this.typescriptModule.config.options.rootDir,Li(n)),a=this.stripExtension(s);o[a]=n}return o}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[o,n]of Object.entries(t))i[e][o]=typeof n=="function"?n(this.name,this.argv):n}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Vi}from"fs/promises";import{resolve as _i}from"@remotex-labs/xmap";var Pe=class{constructor(e,t){this.variantName=e;this.argv=t}variantName;argv;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,options:e.initialOptions,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(this.executeStartHooks.bind(this,t,e)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(this.executeEndHooks.bind(this,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},this.executeResolveHooks.bind(this,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},this.executeLoadHooks.bind(this,t))}}}pushError(e,t,i,o=this.variantName){e.push({id:t,detail:i,location:null,pluginName:o})}async executeStartHooks(e,t){e.stage.startTime=new Date;let i=[],o=[],n={build:t,...e};for(let[s,a]of this.startHooks.entries())try{let c=await a(n);c?.errors&&i.push(...c.errors),c?.warnings&&o.push(...c.warnings)}catch(c){this.pushError(i,"startHook",c,s)}return{errors:i,warnings:o}}async executeEndHooks(e,t){let{errors:i,warnings:o}=t,n=Date.now()-e.stage.startTime.getTime(),s={buildResult:t,duration:n,...e};for(let[a,c]of this.endHooks.entries())try{let l=await c(s);l?.errors&&i.push(...l.errors),l?.warnings&&o.push(...l.warnings)}catch(l){this.pushError(i,"endHook",l,a)}if(t.errors.length===0)for(let[a,c]of this.successHooks.entries())try{await c(s)}catch(l){this.pushError(i,"endHook",l,a)}}async executeResolveHooks(e,t){let i={errors:[]},o={args:t,...e};for(let[n,s]of this.resolveHooks.entries())try{let a=await s(o);if(!a)continue;i={...i,...a}}catch(a){this.pushError(i.errors,"endResolve",a,n)}return i}async executeLoadHooks(e,t){let i=[],o=[],n="default",s=_i(t.path),a=this.filesModel.getSnapshot(s),c;try{c=a?.contentSnapshot?a.contentSnapshot.text:await Vi(s,"utf8")}catch{return e.options.logOverride?.["lifecycle-file-ignored"]!=="silent"&&o.push({id:"",text:`${t.path} ignored`,pluginName:"lifecycle"}),{warnings:o,errors:i,loader:n}}for(let[l,p]of this.loadHooks.entries())try{let f=await p({contents:c,loader:n,args:t,...e});if(!f)continue;f.contents!==void 0&&(c=f.contents),f.loader&&(n=f.loader),f.errors&&i.push(...f.errors),f.warnings&&o.push(...f.warnings)}catch(f){this.pushError(i,"loadHook",f,l)}return{contents:c,loader:n,errors:i,warnings:o}}};import h from"typescript";import{highlightCode as rr}from"@remotex-labs/xmap/highlighter.component";import D from"typescript";var Ui="$$ifdef";function zi(r,e,t,i=!1){let o=i?"export function ":"function ";return D.isArrowFunction(e)||D.isFunctionExpression(e)?Wi(r,e,t,o):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Wi(r,e,t,i){let n=e.modifiers?.some(l=>l.kind===D.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=Gi(e,t);return`${n}${i}${r}(${s})${a} ${c}`}function Gi(r,e){let t=r.body.getText(e);return D.isArrowFunction(r)&&!D.isBlock(r.body)?`{ return ${t}; }`:t}function Ki(r,e,t="",i="();"){return D.isArrowFunction(r)||D.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===D.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Yt(r,e,t){let i=r in t&&!!t[r];return e===Ui===i}function Xt(r,e,t,i){let[o,n]=e.arguments;if(!D.isStringLiteral(o))return!1;let s=e.expression.text,a=o.text;if(!Yt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return zi(c,n,i.sourceFile,t)}function Re(r,e,t,i=!1,o){let[n,s]=r.arguments;if(!D.isStringLiteral(n))return!1;let a=n.text,c=r.expression.text;if(!Yt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),Ki(s,e.sourceFile,l,o)}import M from"typescript";import{createRequire as Xi}from"module";var Me=class extends y{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=L(e,{lineOffset:t}),this.stack=H(this.errorMetadata,this.name,this.message)}};import{Script as qi,createContext as Yi}from"vm";async function Jt(r,e={},t={}){let i=new qi(r,t),o=Yi(e);return await i.runInContext(o,{breakOnSigint:!0,displayErrors:!1})}import{dirname as Ji,relative as Qi}from"@remotex-labs/xmap";async function Qt(r,e,t){let[i,o]=(await zt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let n={exports:{}},s=Xi(e.sourceFile.fileName),a=Zi(e.sourceFile.fileName,n,s);a.context=e.context;let c=await Jt(o.text,a,{filename:e.sourceFile.fileName});return c===null?"undefined":typeof c=="number"||typeof c=="boolean"?String(c):JSON.stringify(c)}catch(n){eo(n,e,i.text,t)}return"undefined"}function Zi(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:Ji(r),__filename:r}}function eo(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let o=i.getStart(e.sourceFile),{line:n}=e.sourceFile.getLineAndCharacterOfPosition(o);u(b).setSource(t,e.sourceFile.fileName);let s=new Me(r,n);e.errors.push({text:s.message,detail:s})}function to(r,e){let t=null,i=o=>{if(!t){if(M.isFunctionDeclaration(o)&&o.name?.text===r){t=o;return}M.isVariableStatement(o)&&(t=ro(o,r),t)||M.forEachChild(o,i)}};return i(e),t}function ro(r,e){for(let t of r.declarationList.declarations)if(M.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(M.isArrowFunction(t.initializer)||M.isFunctionExpression(t.initializer)))return t.initializer;return null}function Zt(r){return`module.exports = (${r})();`}function io(r){return r&M.NodeFlags.Const?"const":r&M.NodeFlags.Let?"let":"var"}function er(r,e){return r?M.isIdentifier(r)?oo(r,e):M.isArrowFunction(r)||M.isFunctionExpression(r)?{node:r,data:Zt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function oo(r,e){let t=to(r.text,e.sourceFile);return t?{node:t,data:Zt(t.getText(e.sourceFile))}:(no(r.text,e,r),{data:"",node:r})}function no(r,e,t){let i=t.getStart(e.sourceFile),{line:o,character:n}=e.sourceFile.getLineAndCharacterOfPosition(i),s=Qi(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:o+1,column:n,file:e.sourceFile.fileName,lineText:"asd"}})}async function tr(r,e,t,i,o){let n=t.arguments[0],s=er(n,o);if(!s)return!1;let a=await Qt(s.data,o,s.node),c=io(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(o.sourceFile);return`${l}${c} ${p} = ${a};`}async function it(r,e){let t=r[0],i=er(t,e);return i?Qt(i.data,e,i.node):!1}var so=/\.(ts|js)$/,K=["$$ifdef","$$ifndef","$$inline"];function ot(r,e){return K.some(t=>r.getText(e).includes(t))}function ir(r){return r===K[2]?1:2}async function ao(r,e,t){let i=!1;for(let o of r.declarationList.declarations){let n="",s,a=o.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,n=`(${a.arguments.map(f=>f.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(!K.includes(c))continue;if(s.arguments.length!==ir(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new W({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:p+1,column:f}})}let l=r.modifiers?.some(p=>p.kind===h.SyntaxKind.ExportKeyword)??!1;c===K[2]?i=await tr(o,r,s,l,t):n?i=Re(s,t,o,l,n):i=Xt(o,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function co(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let o=i.expression.text;if(!K.includes(o))return!1;if(i.arguments.length!==ir(o)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new W({text:`Invalid macro call: ${o} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let n=!1;return o==K[2]?(await it(i.arguments,t),n="undefined"):n=Re(i,t),n!==!1&&e.add({replacement:n,end:i.getEnd(),start:i.getStart(t.sourceFile)}),n!==!1}async function lo(r,e,t){if(!h.isCallExpression(r)||!ot(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===K[2]){let s=await it(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let n=Re(i,t);return n===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:n}),!0)}async function fo(r,e="unknow"){let t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let o=[r.sourceFile],n=new Set;for(;o.length>0;){let c=o.pop(),l=c?.kind;if(!c||!l||i&&(l===h.SyntaxKind.VariableStatement&&await ao(c,n,r)||l===h.SyntaxKind.ExpressionStatement&&ot(c,r.sourceFile)&&await co(c,n,r)||l===h.SyntaxKind.CallExpression&&ot(c,r.sourceFile)&&await lo(c,n,r)))continue;if(t.size>0){if(l===h.SyntaxKind.CallExpression){let f=c;h.isIdentifier(f.expression)&&t.has(f.expression.text)&&n.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}else if(l===h.SyntaxKind.Identifier){let f=c;if(t.has(f.text)){let d=c.parent??c;if(d&&!h.isImportSpecifier(d)&&!h.isExportSpecifier(d)){let m=d?.getText(r.sourceFile);(!h.isCallExpression(d)||d.expression!==c)&&(!m||K.every(P=>!m.includes(P)))&&n.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}}}}let p=c.getChildren(r.sourceFile);for(let f=p.length-1;f>=0;f--)o.push(p[f])}if(n.size===0)return r.contents;let s=Array.from(n);s.sort((c,l)=>l.start-c.start),r.stage.replacementInfo??={},r.stage.replacementInfo[e]??=[];let a=r.stage.replacementInfo[e];for(let{start:c,end:l,replacement:p}of s)a.push({source:rr(r.contents.slice(c,l)),replacement:rr(p)}),r.contents=r.contents.slice(0,c)+p+r.contents.slice(l);return r.contents}async function or(r,e){let{args:t,loader:i,stage:o,contents:n,variantName:s,options:a,argv:c}=e;if(t.path.includes("node_modules")||n.length<1||!so.test(t.path))return;let l=r.typescript.languageHostService,p=r.typescript.languageService;l.hasScriptSnapshot(t.path)||l.touchFile(t.path);let f=p.getProgram()?.getSourceFile(t.path);if(!f)return;let d={stage:o,errors:[],contents:n.toString(),warnings:[],defines:r.config.define??{},sourceFile:f,context:{argv:c,options:a,variantName:s}},m=await fo(d,r.name);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(m=r.typescript.languageHostService.resolveAliases(m,t.path,".js")),{loader:i,contents:m,warnings:d.warnings,errors:d.errors}}var nr="$$",sr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function po(r,e,t,i){let o=1;for(let s=0;s<i;s++)r[s]===`
45
+ `),category:e.category};if(e.file&&e.start!==void 0){let{line:i,character:o}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=o+1,t.code=e.code}return t}};tt=O(null),N=k(tt,0,"TypescriptService",Vt,N),F(tt,1,N);var re=N;import{cwd as ke}from"process";import{build as rt}from"esbuild";var _t={write:!1,bundle:!0,minify:!0,outdir:`${ke()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Ut(r,e={}){try{return await rt({absWorkingDir:ke(),..._t,...e,metafile:!0,entryPoints:r})}catch(t){if(V(t)){let i=new AggregateError([],"Failed to build entryPoints");throw de(t.errors,i.errors),i}throw t}}async function zt(r,e,t={}){return await rt({absWorkingDir:ke(),..._t,...t,stdin:{loader:"ts",contents:r,resolveDir:ke(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Wt(r,e={}){try{return await rt({...e,outdir:"tmp",write:!1,bundle:!0,outfile:void 0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(V(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw de(t.errors,i.errors),i}throw t}}import{relative as ji,resolve as Li,join as qt,dirname as Hi}from"@remotex-labs/xmap";function Gt(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=we(r,e)),t}else{if(e&&typeof e=="object")return e;if(e===void 0)return}throw new S("Unsupported entry points format")}var Ae=class{constructor(e,t,i,o={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=o;if(!this.buildConfig?.esbuild)throw new S(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new re(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),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(n=>({variantConfig:n.variants?.[this.name],commonConfig:n.common})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}name;lifecycle;buildConfig;argv;dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(x);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)return;this.applyInjections();let e=Object.assign({},this.buildConfig.esbuild);if(this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&Object.assign(e,{entryPoints:this.dependenciesFile}),this.config.define&&e.define)for(let[t,i]of Object.entries(this.config.define))typeof i=="function"&&(e.define[t]=JSON.stringify(i()));try{let t=await Bi(e);return await this.packageTypeComponent(),t}catch(t){if(V(t)){if(t.errors.filter(o=>o.location).length>0)throw t;return{errors:t?.errors??[],warnings:t?.warnings??[]}}}}getConfig(e,t={}){return e?z({},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;if(typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError){let o=new R("Type checking failed",t);e.warnings?.push({detail:o,location:void 0})}else{let o=[],n=[],s=new R("Type checking failed",o),a=new R("Type checking failed",n);for(let c of t)(c.category===$i.DiagnosticCategory.Error?o:n).push(c);o.length&&e.errors?.push({detail:s,location:void 0}),n.length&&e.warnings?.push({detail:a,location:void 0})}return e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(typeof e.buildResult.metafile?.outputs=="object"){let s=Object.keys(e.buildResult.metafile?.outputs);for(let a of s){if(!a.endsWith(".map"))continue;let c=Hi(a),l=await Di(a,"utf8"),p=JSON.parse(l);p.sources=p.sources.map(f=>f.startsWith("http")?f:qt(c,f)),await Kt(a,JSON.stringify(p),"utf8")}}if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,o=typeof i=="object"?i.bundle!==!1:!0,n=typeof i=="object"?i.outDir:void 0;try{o?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,n):await this.typescriptModule.emit(n)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:o,onEnd:n,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),o&&this.lifecycle.onLoad(o),n&&this.lifecycle.onEnd(n),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Ni(e,{recursive:!0}),await Kt(qt(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new S(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints&&!e.esbuild.stdin)throw new S("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).flatMap(([o,n])=>typeof n=="function"?[]:[[o,JSON.stringify(n)]])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=Gt(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.outdir&&i.esbuild.outfile&&(this.buildConfig.esbuild.outdir=void 0),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new re(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,t={...e,plugins:void 0},{metafile:i}=await Wt(e.entryPoints,t),o={};for(let n of Object.keys(i.inputs)){let s=ji(this.typescriptModule.config.options.rootDir,Li(n)),a=this.stripExtension(s);o[a]=n}return o}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[o,n]of Object.entries(t))i[e][o]=typeof n=="function"?n(this.name,this.argv):n}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Vi}from"fs/promises";import{resolve as _i}from"@remotex-labs/xmap";var Pe=class{constructor(e,t){this.variantName=e;this.argv=t}variantName;argv;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,options:e.initialOptions,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(this.executeStartHooks.bind(this,t,e)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(this.executeEndHooks.bind(this,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},this.executeResolveHooks.bind(this,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},this.executeLoadHooks.bind(this,t))}}}pushError(e,t,i,o=this.variantName){e.push({id:t,detail:i,location:null,pluginName:o})}async executeStartHooks(e,t){e.stage.startTime=new Date;let i=[],o=[],n={build:t,...e};for(let[s,a]of this.startHooks.entries())try{let c=await a(n);c?.errors&&i.push(...c.errors),c?.warnings&&o.push(...c.warnings)}catch(c){this.pushError(i,"startHook",c,s)}return{errors:i,warnings:o}}async executeEndHooks(e,t){let{errors:i,warnings:o}=t,n=Date.now()-e.stage.startTime.getTime(),s={buildResult:t,duration:n,...e};for(let[a,c]of this.endHooks.entries())try{let l=await c(s);l?.errors&&i.push(...l.errors),l?.warnings&&o.push(...l.warnings)}catch(l){this.pushError(i,"endHook",l,a)}if(t.errors.length===0)for(let[a,c]of this.successHooks.entries())try{await c(s)}catch(l){this.pushError(i,"endHook",l,a)}}async executeResolveHooks(e,t){let i={errors:[]},o={args:t,...e};for(let[n,s]of this.resolveHooks.entries())try{let a=await s(o);if(!a)continue;i={...i,...a}}catch(a){this.pushError(i.errors,"endResolve",a,n)}return i}async executeLoadHooks(e,t){let i=[],o=[],n="default",s=_i(t.path),a=this.filesModel.getSnapshot(s),c;try{c=a?.contentSnapshot?a.contentSnapshot.text:await Vi(s,"utf8")}catch{return e.options.logOverride?.["lifecycle-file-ignored"]!=="silent"&&o.push({id:"",text:`${t.path} ignored`,pluginName:"lifecycle"}),{warnings:o,errors:i,loader:n}}for(let[l,p]of this.loadHooks.entries())try{let f=await p({contents:c,loader:n,args:t,...e});if(!f)continue;f.contents!==void 0&&(c=f.contents),f.loader&&(n=f.loader),f.errors&&i.push(...f.errors),f.warnings&&o.push(...f.warnings)}catch(f){this.pushError(i,"loadHook",f,l)}return{contents:c,loader:n,errors:i,warnings:o}}};import h from"typescript";import{highlightCode as rr}from"@remotex-labs/xmap/highlighter.component";import D from"typescript";var Ui="$$ifdef";function zi(r,e,t,i=!1){let o=i?"export function ":"function ";return D.isArrowFunction(e)||D.isFunctionExpression(e)?Wi(r,e,t,o):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Wi(r,e,t,i){let n=e.modifiers?.some(l=>l.kind===D.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=Gi(e,t);return`${n}${i}${r}(${s})${a} ${c}`}function Gi(r,e){let t=r.body.getText(e);return D.isArrowFunction(r)&&!D.isBlock(r.body)?`{ return ${t}; }`:t}function Ki(r,e,t="",i="();"){return D.isArrowFunction(r)||D.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===D.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Yt(r,e,t){let i=r in t&&!!t[r];return e===Ui===i}function Xt(r,e,t,i){let[o,n]=e.arguments;if(!D.isStringLiteral(o))return!1;let s=e.expression.text,a=o.text;if(!Yt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return zi(c,n,i.sourceFile,t)}function Re(r,e,t,i=!1,o){let[n,s]=r.arguments;if(!D.isStringLiteral(n))return!1;let a=n.text,c=r.expression.text;if(!Yt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),Ki(s,e.sourceFile,l,o)}import M from"typescript";import{createRequire as Xi}from"module";var Me=class extends y{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=L(e,{lineOffset:t}),this.stack=H(this.errorMetadata,this.name,this.message)}};import{Script as qi,createContext as Yi}from"vm";async function Jt(r,e={},t={}){let i=new qi(r,t),o=Yi(e);return await i.runInContext(o,{breakOnSigint:!0,displayErrors:!1})}import{dirname as Ji,relative as Qi}from"@remotex-labs/xmap";async function Qt(r,e,t){let[i,o]=(await zt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let n={exports:{}},s=Xi(e.sourceFile.fileName),a=Zi(e.sourceFile.fileName,n,s);a.context=e.context;let c=await Jt(o.text,a,{filename:e.sourceFile.fileName});return c===null?"undefined":typeof c=="number"||typeof c=="boolean"?String(c):JSON.stringify(c)}catch(n){eo(n,e,i.text,t)}return"undefined"}function Zi(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:Ji(r),__filename:r}}function eo(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let o=i.getStart(e.sourceFile),{line:n}=e.sourceFile.getLineAndCharacterOfPosition(o);u(b).setSource(t,e.sourceFile.fileName);let s=new Me(r,n);e.errors.push({text:s.message,detail:s})}function to(r,e){let t=null,i=o=>{if(!t){if(M.isFunctionDeclaration(o)&&o.name?.text===r){t=o;return}M.isVariableStatement(o)&&(t=ro(o,r),t)||M.forEachChild(o,i)}};return i(e),t}function ro(r,e){for(let t of r.declarationList.declarations)if(M.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(M.isArrowFunction(t.initializer)||M.isFunctionExpression(t.initializer)))return t.initializer;return null}function Zt(r){return`module.exports = (${r})();`}function io(r){return r&M.NodeFlags.Const?"const":r&M.NodeFlags.Let?"let":"var"}function er(r,e){return r?M.isIdentifier(r)?oo(r,e):M.isArrowFunction(r)||M.isFunctionExpression(r)?{node:r,data:Zt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function oo(r,e){let t=to(r.text,e.sourceFile);return t?{node:t,data:Zt(t.getText(e.sourceFile))}:(no(r.text,e,r),{data:"",node:r})}function no(r,e,t){let i=t.getStart(e.sourceFile),{line:o,character:n}=e.sourceFile.getLineAndCharacterOfPosition(i),s=Qi(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:o+1,column:n,file:e.sourceFile.fileName,lineText:"asd"}})}async function tr(r,e,t,i,o){let n=t.arguments[0],s=er(n,o);if(!s)return!1;let a=await Qt(s.data,o,s.node),c=io(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(o.sourceFile);return`${l}${c} ${p} = ${a};`}async function it(r,e){let t=r[0],i=er(t,e);return i?Qt(i.data,e,i.node):!1}var so=/\.(ts|js)$/,K=["$$ifdef","$$ifndef","$$inline"];function ot(r,e){return K.some(t=>r.getText(e).includes(t))}function ir(r){return r===K[2]?1:2}async function ao(r,e,t){let i=!1;for(let o of r.declarationList.declarations){let n="",s,a=o.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,n=`(${a.arguments.map(f=>f.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(!K.includes(c))continue;if(s.arguments.length!==ir(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new W({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:p+1,column:f}})}let l=r.modifiers?.some(p=>p.kind===h.SyntaxKind.ExportKeyword)??!1;c===K[2]?i=await tr(o,r,s,l,t):n?i=Re(s,t,o,l,n):i=Xt(o,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function co(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let o=i.expression.text;if(!K.includes(o))return!1;if(i.arguments.length!==ir(o)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new W({text:`Invalid macro call: ${o} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let n=!1;return o==K[2]?(await it(i.arguments,t),n="undefined"):n=Re(i,t),n!==!1&&e.add({replacement:n,end:i.getEnd(),start:i.getStart(t.sourceFile)}),n!==!1}async function lo(r,e,t){if(!h.isCallExpression(r)||!ot(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===K[2]){let s=await it(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let n=Re(i,t);return n===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:n}),!0)}async function fo(r,e="unknow"){let t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let o=[r.sourceFile],n=new Set;for(;o.length>0;){let c=o.pop(),l=c?.kind;if(!c||!l||i&&(l===h.SyntaxKind.VariableStatement&&await ao(c,n,r)||l===h.SyntaxKind.ExpressionStatement&&ot(c,r.sourceFile)&&await co(c,n,r)||l===h.SyntaxKind.CallExpression&&ot(c,r.sourceFile)&&await lo(c,n,r)))continue;if(t.size>0){if(l===h.SyntaxKind.CallExpression){let f=c;h.isIdentifier(f.expression)&&t.has(f.expression.text)&&n.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}else if(l===h.SyntaxKind.Identifier){let f=c;if(t.has(f.text)){let d=c.parent??c;if(d&&!h.isImportSpecifier(d)&&!h.isExportSpecifier(d)){let m=d?.getText(r.sourceFile);(!h.isCallExpression(d)||d.expression!==c)&&(!m||K.every(P=>!m.includes(P)))&&n.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}}}}let p=c.getChildren(r.sourceFile);for(let f=p.length-1;f>=0;f--)o.push(p[f])}if(n.size===0)return r.contents;let s=Array.from(n);s.sort((c,l)=>l.start-c.start),r.stage.replacementInfo??={},r.stage.replacementInfo[e]??=[];let a=r.stage.replacementInfo[e];for(let{start:c,end:l,replacement:p}of s)a.push({source:rr(r.contents.slice(c,l)),replacement:rr(p)}),r.contents=r.contents.slice(0,c)+p+r.contents.slice(l);return r.contents}async function or(r,e){let{args:t,loader:i,stage:o,contents:n,variantName:s,options:a,argv:c}=e;if(t.path.includes("node_modules")||n.length<1||!so.test(t.path))return;let l=r.typescript.languageHostService,p=r.typescript.languageService;l.hasScriptSnapshot(t.path)||l.touchFile(t.path);let f=p.getProgram()?.getSourceFile(t.path);if(!f)return;let d={stage:o,errors:[],contents:n.toString(),warnings:[],defines:r.config.define??{},sourceFile:f,context:{argv:c,options:a,variantName:s}},m=await fo(d,r.name);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(m=r.typescript.languageHostService.resolveAliases(m,t.path,".js")),{loader:i,contents:m,warnings:d.warnings,errors:d.errors}}var nr="$$",sr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function po(r,e,t,i){let o=1;for(let s=0;s<i;s++)r[s]===`
46
46
  `&&o++;let n=r.lastIndexOf(`
47
47
  `,i-1)+1;return{file:t,line:o,column:r.indexOf(e,n)-n}}function uo(r,e){let t=r.lastIndexOf(`
48
48
  `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],o=r[t+1];return i==="/"&&(o==="/"||o==="*")||i==="*"}async function ar(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],o=u(v),n=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=o.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=o.resolve(a);sr.lastIndex=0;for(let p of c.matchAll(sr)){let f=p.index;if(uo(c,f))continue;let[,d,m,P]=p;if(t.filesWithMacros.add(l),!d||(d.startsWith(nr)||i.push({text:`Macro function '${d}' not start with '${nr}' prefix to avoid conflicts`,location:po(c,d,a,f)}),m==="inline"))continue;let _=!!n[P];m==="ifndef"===_&&t.disabledMacroNames.add(d)}}return{warnings:i}}var ye=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}argv;onEndCallback;onStartCallback;variants={};configuration=u(x);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload({config:e,clearCache:t=!1}={}){t&&te.reload(),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={cache:new Map,errors:[],results:{}};this.validateDependencies(e);let i=e??Object.keys(this.variants);if(await Promise.all(i.map(o=>this.buildVariant(o,t))),t.errors.length)throw new AggregateError(t.errors,"Build failed");return t.results}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await ar(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let o of t.errors)i.push({detail:o,text:o.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(n=>!(n in e))]}parseVariants(){if(!this.config.variants)throw new S("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new Pe(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new Ae(e,t,this.config.variants[e],this.argv),t.onLoad(or.bind({},this.variants[e]),"build-service")}}getDependOn(e){let{dependOn:t}=this.config.variants?.[e]??{};return t?Array.isArray(t)?t:[t]:[]}validateDependencies(e){let t=new Set,i=new Set,o=(n,s)=>{if(i.has(n))throw new S(`Circular dependency detected: ${[...s,n].join(" \u2192 ")}`);if(!t.has(n)){i.add(n);for(let a of this.getDependOn(n))this.variants[a]&&o(a,[...s,n]);i.delete(n),t.add(n)}};for(let n of e??Object.keys(this.variants))o(n,[])}async executeBuild(e,t){let i=this.getDependOn(e).filter(n=>this.variants[n]);await Promise.all(i.map(n=>this.buildVariant(n,t)));let o=this.variants[e];if(o)try{let n=await o.build();n&&(t.results[e]=me(n))}catch(n){V(n)||n instanceof AggregateError?t.errors.push(...me({errors:n.errors}).errors):t.errors.push(n instanceof Error?n:new Error(String(n)))}}buildVariant(e,t){let i=t.cache.get(e);if(i)return i;let o=this.executeBuild(e,t);return t.cache.set(e,o),o}};function cr(r){u(x).reload(r)}function lr(r){u(x).patch(r)}import{platform as go,exit as ho,stdin as $e,stdout as st}from"process";import{xterm as Be}from"@remotex-labs/xansi/xterm.component";var nt={SIGINT:"",SIGQUIT:""},w={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},fr={win32:"start",darwin:"open",linux:"xdg-open"};function yo(r=!1){let e=["\u{1F680} Shortcuts"],t=Be.dim(" press "),i=(o,n)=>{e.push(`${t}${Be.bold(o)}${Be.dim(n)}`)};return r&&(i(w.SHOW_URL," to show server url"),i(w.OPEN_BROWSER," to open in browser")),i(w.VERBOSE," to enable / disable verbose mode"),i(w.RELOAD," to reload"),i(w.CLEAR," to clear console"),i(w.QUIT,` to quit