@remotex-labs/xbuild 1.3.0 → 1.3.2

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.
@@ -9,13 +9,12 @@ import type { ConfigurationInterface } from "../configuration/interfaces/configu
9
9
  * - If the format is `esm`, the `type` will be set to `"module"`.
10
10
  * - If the format is `cjs`, the `type` will be set to `"commonjs"`.
11
11
  *
12
- * The function will ensure that the output directory exists, and if it doesn't,
12
+ * The function will ensure that the specified output directory exists, and if it doesn't,
13
13
  * it will create the necessary directories before writing the `package.json` file.
14
14
  *
15
- * @param {ConfigurationInterface} config - The build configuration object containing
16
- * esbuild-related settings, such as the output directory (`outdir`) and format (`format`).
15
+ * @param config - The build configuration object containing
16
+ * esbuild-related settings, such as the format (`format`).
17
17
  *
18
- * - `config.esbuild.outdir`: The output directory where the `package.json` will be created.
19
18
  * - `config.esbuild.format`: The module format, either `'esm'` or `'cjs'`, that determines the `type` field.
20
19
  *
21
20
  * @throws Will throw an error if there is a problem creating the directory or writing the file.
@@ -25,7 +24,6 @@ import type { ConfigurationInterface } from "../configuration/interfaces/configu
25
24
  * ```ts
26
25
  * const config = {
27
26
  * esbuild: {
28
- * outdir: 'dist',
29
27
  * format: 'esm'
30
28
  * }
31
29
  * };
@@ -232,10 +232,55 @@ export interface ConfigurationInterface {
232
232
  * Enables watching for file changes during development.
233
233
  */
234
234
  watch: boolean;
235
+ /**
236
+ * The directory where the generated `package.json` file will be saved,
237
+ * indicating the module type (`"commonjs"` or `"module"`).
238
+ *
239
+ * - If the format is `esm`, the `package.json` file will contain `"type": "module"`.
240
+ * - If the format is `cjs`, the `package.json` file will contain `"type": "commonjs"`.
241
+ *
242
+ * If this field is not set (`undefined`), the `package.json` file will be saved in the
243
+ * `outdir` specified in the esbuild configuration.
244
+ *
245
+ * Example:
246
+ *
247
+ * ```ts
248
+ * {
249
+ * esbuild: {
250
+ * outdir: 'dist',
251
+ * format: 'esm'
252
+ * },
253
+ * moduleTypeOutDir: 'custom/dist'
254
+ * }
255
+ * // This will create 'custom/dist/package.json' with the content: {"type": "module"}
256
+ *
257
+ * // If moduleTypeOutDir is not provided:
258
+ * {
259
+ * esbuild: {
260
+ * outdir: 'dist',
261
+ * format: 'cjs'
262
+ * }
263
+ * }
264
+ * // This will create 'dist/package.json' with the content: {"type": "commonjs"}
265
+ * ```
266
+ */
267
+ moduleTypeOutDir?: string;
235
268
  /**
236
269
  * Generates TypeScript declaration files.
237
270
  */
238
271
  declaration: boolean;
272
+ /**
273
+ * Overrides the output directory for TypeScript declaration files (.d.ts).
274
+ *
275
+ * If this option is not set, the output directory specified in the `outDir`
276
+ * field of your `tsconfig.json` will be used.
277
+ * This allows for custom control
278
+ * over where the declaration files are emitted, separate from the main
279
+ * output directory for compiled JavaScript files.
280
+ *
281
+ * @default The `outDir` from `tsconfig.json` will be used if this is not provided.
282
+ */
283
+ declarationOutDir?: string;
239
284
  /**
240
285
  * Continues building even if TypeScript type errors are present.
241
286
  */
@@ -1,9 +1,6 @@
1
1
  /**
2
2
  * Import will remove at compile time
3
3
  */
4
- /**
5
- * Imports
6
- */
7
4
  import type { SourceService } from '@remotex-labs/xmap';
8
5
  import type { ErrorType } from "./interfaces/stack.interface";
9
6
  /**
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import{cwd as de}from"process";import{readFileSync as me}from"fs";import{fileURLToPath as ge}from"url";import{dirname as N,join as he,resolve as L}from"path";function c(o,e,r=__ACTIVE_COLOR){return r?`${o}${e}\x1B[0m`:e}import{SourceService as ye,formatErrorCode as ve,highlightCode as Se}from"@remotex-labs/xmap";var B=de(),A=N(ge(import.meta.url)),be=N(A),_=(()=>{let o;return{get service(){if(!o){let e=me(he(A,"index.js.map"));o=new ye(e.toString(),import.meta.url)}return o}}})();global.__ACTIVE_COLOR||(global.__ACTIVE_COLOR=!0);function xe(o,e,r,t){return`${o.replace(`${t}\\`,e).replace(/\\/g,"/")}#L${r}`}function R(o,e,r,t,i){if(i.isPromiseAll())return`at async Promise.all (index: ${i.getPromiseIndex()})`;let n=i.isAsync()?"async":"",s=o?`${n} ${o}`:n,a=r>=0&&t>=0?c("\x1B[38;5;243m",`[${r}:${t}]`):"";return`at ${s} ${c("\x1B[38;5;238m",e)} ${a}`.replace(/\s{2,}/g," ").trim()}function Ce(o){let e=o.getLineNumber()||-1,r=o.getColumnNumber()||-1,t=o.getFileName()||"<anonymous>",i=o.getTypeName()||"",n=o.getFunctionName()||"",s=o.isNative()?"<native>":n;return i&&(s=`${i}.${s}`),{functionName:s,source:t,line:e,column:r}}function we(o,e){let r=__ACTIVE_COLOR?Se(o.code):o.code;return o.name&&e.name=="TypeError"&&(e.message=e.message.replace(/^\S+/,o.name)),ve({...o,code:r},{color:__ACTIVE_COLOR?"\x1B[38;5;197m":"",reset:__ACTIVE_COLOR?"\x1B[0m":""})}function Ee(o,e){let{functionName:r,source:t,line:i,column:n}=Ce(o);if(o.isPromiseAll()||o.isEval()||o.isNative())return R(r,t,i,n,o);let s=null,a=t===_.service.file;if(a?s=_.service.getPositionWithCode(i,n):e.error.sourceMap&&(s=e.error.sourceMap.getPositionWithCode(i,n)),s){let l=a?A:B,{line:g,column:h,name:O}=s,I=L(l,s.source);return e.blockCode||(e.blockCode=we(s,e.error)),s.sourceRoot&&(I=xe(L(l,s.source),s.sourceRoot,s.line,a?be:B)),R(O||r,I,g,h,o)}return t==="evalmachine.<anonymous>"?"":R(r,t,i,n,o)}function ke(o,e){return e.map(r=>Ee(r,o)).filter(Boolean)}function M(o,e){let r={error:o,blockCode:null,formattedError:global.__ACTIVE_COLOR?"\x1B[0m":""},t=ke(r,e);return r.formattedError+=`
2
+ import{cwd as me}from"process";import{readFileSync as ge}from"fs";import{fileURLToPath as he}from"url";import{dirname as N,join as ye,resolve as I}from"path";function c(o,e,t=__ACTIVE_COLOR){return t?`${o}${e}\x1B[0m`:e}import{SourceService as ve,formatErrorCode as Se,highlightCode as be}from"@remotex-labs/xmap";var L=me(),D=N(he(import.meta.url)),Ce=N(D),_=(()=>{let o;return{get service(){if(!o){let e=ge(ye(D,"index.js.map"));o=new ve(e.toString(),import.meta.url)}return o}}})();global.__ACTIVE_COLOR||(global.__ACTIVE_COLOR=!0);function xe(o,e,t,r){return`${o.replace(`${r}\\`,e).replace(/\\/g,"/")}#L${t}`}function R(o,e,t,r,i){if(i.isPromiseAll())return`at async Promise.all (index: ${i.getPromiseIndex()})`;let n=i.isAsync()?"async":"",s=o?`${n} ${o}`:n,a=t>=0&&r>=0?c("\x1B[38;5;243m",`[${t}:${r}]`):"";return`at ${s} ${c("\x1B[38;5;238m",e)} ${a}`.replace(/\s{2,}/g," ").trim()}function we(o){let e=o.getLineNumber()||-1,t=o.getColumnNumber()||-1,r=o.getFileName()||"<anonymous>",i=o.getTypeName()||"",n=o.getFunctionName()||"",s=o.isNative()?"<native>":n;return i&&(s=`${i}.${s}`),{functionName:s,source:r,line:e,column:t}}function Ee(o,e){let t=__ACTIVE_COLOR?be(o.code):o.code;return o.name&&e.name=="TypeError"&&(e.message=e.message.replace(/^\S+/,o.name)),Se({...o,code:t},{color:__ACTIVE_COLOR?"\x1B[38;5;197m":"",reset:__ACTIVE_COLOR?"\x1B[0m":""})}function ke(o,e){let{functionName:t,source:r,line:i,column:n}=we(o);if(o.isPromiseAll()||o.isEval()||o.isNative())return R(t,r,i,n,o);let s=null,a=r===_.service.file;if(a?s=_.service.getPositionWithCode(i,n):e.error.sourceMap&&(s=e.error.sourceMap.getPositionWithCode(i,n)),s){let l=a?D:L,{line:g,column:h,name:O}=s,B=I(l,s.source);return e.blockCode||(e.blockCode=Ee(s,e.error)),s.sourceRoot&&(B=xe(I(l,s.source),s.sourceRoot,s.line,a?Ce:L)),R(O||t,B,g,h,o)}return r==="evalmachine.<anonymous>"?"":R(t,r,i,n,o)}function Pe(o,e){return e.map(t=>ke(t,o)).filter(Boolean)}function M(o,e){let t={error:o,blockCode:null,formattedError:global.__ACTIVE_COLOR?"\x1B[0m":""},r=Pe(t,e);return t.formattedError+=`
3
3
  ${o.name}:
4
4
  ${c("\x1B[38;5;203m",o.message)}
5
5
 
6
- `,r.blockCode&&(r.formattedError+=`${r.blockCode}
6
+ `,t.blockCode&&(t.formattedError+=`${t.blockCode}
7
7
 
8
- `),t.length>0&&(r.formattedError+=`Enhanced Stack Trace:
9
- ${t.join(`
8
+ `),r.length>0&&(t.formattedError+=`Enhanced Stack Trace:
9
+ ${r.join(`
10
10
  `)}
11
- `),r.formattedError}var $=Error.prepareStackTrace;Error.prepareStackTrace=(o,e)=>(o.callStacks=e,$?$(o,e):"");process.on("uncaughtException",o=>{console.error(o.stack)});process.on("unhandledRejection",o=>{console.error(o.stack)});import Pe from"yargs";import{hideBin as Te}from"yargs/helpers";function F(o){let e=Pe(Te(o)).command("$0 [file]","A versatile JavaScript and TypeScript toolchain build system.",r=>{r.positional("entryPoints",{describe:"The file entryPoints to build",type:"string"}).option("typeCheck",{describe:"Perform type checking",alias:"tc",type:"boolean"}).option("node",{alias:"n",describe:"Build for node platform",type:"boolean"}).option("dev",{alias:"d",describe:"Array entryPoints to run as development in Node.js",type:"array"}).option("debug",{alias:"db",describe:"Array entryPoints to run in Node.js with debug state",type:"array"}).option("serve",{alias:"s",describe:"Serve the build folder over HTTP",type:"boolean"}).option("outdir",{alias:"o",describe:"Output directory",type:"string"}).option("declaration",{alias:"de",describe:"Add TypeScript declarations",type:"boolean"}).option("watch",{alias:"w",describe:"Watch for file changes",type:"boolean"}).option("config",{alias:"c",describe:"Build configuration file (js/ts)",type:"string",default:"xbuild.config.ts"}).option("tsconfig",{alias:"tsc",describe:"Set TypeScript configuration file to use",type:"string",default:"tsconfig.json"}).option("minify",{alias:"m",describe:"Minify the code",type:"boolean"}).option("bundle",{alias:"b",describe:"Bundle the code",type:"boolean"}).option("noTypeChecker",{alias:"ntc",describe:"Skip TypeScript type checking",type:"boolean"}).option("buildOnError",{alias:"boe",describe:"Continue building even if there are TypeScript type errors",type:"boolean"}).option("format",{alias:"f",describe:"Defines the format for the build output ('cjs' | 'esm' | 'iif').",type:"string"}).option("version",{alias:"v",describe:"Show version number",type:"boolean",default:!1,conflicts:"help"})}).help().alias("help","h").version(!1).middleware(r=>{r.version&&process.exit(0)});return e.showHelp(r=>{(process.argv.includes("--help")||process.argv.includes("-h"))&&(console.log(r+`
11
+ `),t.formattedError}var $=Error.prepareStackTrace;Error.prepareStackTrace=(o,e)=>(o.callStacks=e,$?$(o,e):"");process.on("uncaughtException",o=>{console.error(o.stack)});process.on("unhandledRejection",o=>{console.error(o.stack)});import Te from"yargs";import{hideBin as Oe}from"yargs/helpers";function F(o){let e=Te(Oe(o)).command("$0 [file]","A versatile JavaScript and TypeScript toolchain build system.",t=>{t.positional("entryPoints",{describe:"The file entryPoints to build",type:"string"}).option("typeCheck",{describe:"Perform type checking",alias:"tc",type:"boolean"}).option("node",{alias:"n",describe:"Build for node platform",type:"boolean"}).option("dev",{alias:"d",describe:"Array entryPoints to run as development in Node.js",type:"array"}).option("debug",{alias:"db",describe:"Array entryPoints to run in Node.js with debug state",type:"array"}).option("serve",{alias:"s",describe:"Serve the build folder over HTTP",type:"boolean"}).option("outdir",{alias:"o",describe:"Output directory",type:"string"}).option("declaration",{alias:"de",describe:"Add TypeScript declarations",type:"boolean"}).option("watch",{alias:"w",describe:"Watch for file changes",type:"boolean"}).option("config",{alias:"c",describe:"Build configuration file (js/ts)",type:"string",default:"xbuild.config.ts"}).option("tsconfig",{alias:"tsc",describe:"Set TypeScript configuration file to use",type:"string",default:"tsconfig.json"}).option("minify",{alias:"m",describe:"Minify the code",type:"boolean"}).option("bundle",{alias:"b",describe:"Bundle the code",type:"boolean"}).option("noTypeChecker",{alias:"ntc",describe:"Skip TypeScript type checking",type:"boolean"}).option("buildOnError",{alias:"boe",describe:"Continue building even if there are TypeScript type errors",type:"boolean"}).option("format",{alias:"f",describe:"Defines the format for the build output ('cjs' | 'esm' | 'iif').",type:"string"}).option("version",{alias:"v",describe:"Show version number",type:"boolean",default:!1,conflicts:"help"})}).help().alias("help","h").version(!1).middleware(t=>{t.version&&process.exit(0)});return e.showHelp(t=>{(process.argv.includes("--help")||process.argv.includes("-h"))&&(console.log(t+`
12
12
 
13
- `),process.exit(0))}),e}import{dirname as lr,resolve as y}from"path";import{build as fr,context as pr}from"esbuild";import{spawn as Oe}from"child_process";function j(o,e=!1){let r=["--enable-source-maps",o];e&&r.unshift("--inspect-brk=0.0.0.0:0");let t=Oe("node",r);return t.stdout.on("data",i=>{console.log(i.toString())}),t.stderr.on("data",i=>{console.error(i.toString())}),t}var d=class o extends Error{constructor(r,t){super(r);this.sourceMap=t;Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="xBuildBaseError"}callStacks=[];reformatStack(r){return r.callStacks?M(this,r.callStacks):r.stack??""}};var S=class o extends d{constructor(e){super(e.text),Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="EsbuildError",e.location}};var Re=`
13
+ `),process.exit(0))}),e}import{dirname as ft,resolve as y}from"path";import{build as pt,context as ut}from"esbuild";import{spawn as Re}from"child_process";function j(o,e=!1){let t=["--enable-source-maps",o];e&&t.unshift("--inspect-brk=0.0.0.0:0");let r=Re("node",t);return r.stdout.on("data",i=>{console.log(i.toString())}),r.stderr.on("data",i=>{console.error(i.toString())}),r}var d=class o extends Error{constructor(t,r){super(t);this.sourceMap=r;Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="xBuildBaseError"}callStacks=[];reformatStack(t){return t.callStacks?M(this,t.callStacks):t.stack??""}};var S=class o extends d{constructor(e){super(e.text),Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="EsbuildError",e.location}};var De=`
14
14
  ______ _ _ _
15
15
  | ___ \\ (_) | | |
16
16
  __ _| |_/ /_ _ _| | __| |
@@ -18,9 +18,9 @@ __ _| |_/ /_ _ _| | __| |
18
18
  > <| |_/ / |_| | | | (_| |
19
19
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
20
20
  `;function H(o=!0){return`
21
- \r${c("\x1B[38;5;208m",Re,o)}
22
- \rVersion: ${c("\x1B[38;5;197m","1.3.0",o)}
23
- \r`}function f(){return c("\x1B[38;5;203m","[xBuild]")}var m=class o extends d{originalError;originalErrorStack;constructor(e,r){super(e.message,r),Error.captureStackTrace&&Error.captureStackTrace(this,o),this.originalError=e,this.originalErrorStack=e.stack,this.name="VMRuntimeError",this.stack=this.reformatStack(e)}};import*as z from"http";import*as Y from"https";var W=`<!DOCTYPE html>
21
+ \r${c("\x1B[38;5;208m",De,o)}
22
+ \rVersion: ${c("\x1B[38;5;197m","1.3.2",o)}
23
+ \r`}function f(){return c("\x1B[38;5;203m","[xBuild]")}var m=class o extends d{originalError;originalErrorStack;constructor(e,t){super(e.message,t),Error.captureStackTrace&&Error.captureStackTrace(this,o),this.originalError=e,this.originalErrorStack=e.stack,this.name="VMRuntimeError",this.stack=this.reformatStack(e)}};import*as z from"http";import*as Y from"https";var W=`<!DOCTYPE html>
24
24
  <html>
25
25
  <head>
26
26
  <meta charset="UTF-8">
@@ -77,10 +77,10 @@ __ _| |_/ /_ _ _| | __| |
77
77
  <ul>\${ fileList }</ul>
78
78
  </body>
79
79
  </html>
80
- `;import{extname as V,join as J,resolve as De}from"path";import{existsSync as U,readdir as Ie,readFile as Le,readFileSync as q,stat as Be}from"fs";var G={html:{icon:"fa-file-code",color:"#d1a65f"},css:{icon:"fa-file-css",color:"#264de4"},js:{icon:"fa-file-code",color:"#f7df1e"},json:{icon:"fa-file-json",color:"#b41717"},png:{icon:"fa-file-image",color:"#53a8e4"},jpg:{icon:"fa-file-image",color:"#53a8e4"},jpeg:{icon:"fa-file-image",color:"#53a8e4"},gif:{icon:"fa-file-image",color:"#53a8e4"},txt:{icon:"fa-file-alt",color:"#8e8e8e"},folder:{icon:"fa-folder",color:"#ffb800"}},b=class{rootDir;isHttps;config;constructor(e,r){this.rootDir=De(r),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?U(this.config.keyfile)&&U(this.config.certfile):!1}start(){if(this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){z.createServer((r,t)=>{this.handleRequest(r,t,()=>this.defaultResponse(r,t))}).listen(this.config.port,this.config.host,()=>{console.log(`${f()} HTTP/S server is running at http://${this.config.host}:${this.config.port}`)})}startHttpsServer(){let e={key:q(this.config.keyfile),cert:q(this.config.certfile)};Y.createServer(e,(t,i)=>{this.handleRequest(t,i,()=>this.defaultResponse(t,i))}).listen(this.config.port,this.config.host,()=>{let t=c("\x1B[38;5;227m",`https://${this.config.host}:${this.config.port}`);console.log(`${f()} HTTPS server is running at ${t}`)})}handleRequest(e,r,t){try{this.config.onRequest?this.config.onRequest(e,r,t):t()}catch(i){this.sendError(r,i)}}getContentType(e){return{html:"text/html",css:"text/css",js:"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,r){let t=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",i=J(this.rootDir,t);if(!i.startsWith(this.rootDir)){r.statusCode=403,r.end();return}try{let n=await this.promisifyStat(i);n.isDirectory()?this.handleDirectory(i,t,r):n.isFile()&&this.handleFile(i,r)}catch(n){let s=n.message;s.includes("favicon")||console.log(f(),s),this.sendNotFound(r)}}promisifyStat(e){return new Promise((r,t)=>{Be(e,(i,n)=>i?t(i):r(n))})}handleDirectory(e,r,t){Ie(e,(i,n)=>{if(i)return this.sendError(t,i);let s=n.map(a=>{if(a.match(/[^A-Za-z0-9_\/\\.-]/))return;let l=J(r,a);if(l.match(/[^A-Za-z0-9_\/\\.-]/))return;let g=V(a).slice(1)||"folder",{icon:h,color:O}=G[g]||G.folder;return`<li><i class="fas ${h}" style="color: ${O};"></i> <a href="/${l}">${a}</a></li>`}).join("");t.writeHead(200,{"Content-Type":"text/html"}),t.end(W.replace("${ fileList }",s))})}handleFile(e,r){let t=V(e).slice(1)||"txt",i=this.getContentType(t);Le(e,(n,s)=>{if(n)return this.sendError(r,n);r.writeHead(200,{"Content-Type":i}),r.end(s)})}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,r){console.error(`${f()}`,r.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{promises as _e}from"fs";import{resolve as $e}from"path";var x=class{onEndHooks=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.push(e)}registerOnResolve(e){e&&this.onResolveHooks.push(e)}registerOnLoad(e){e&&this.onLoadHooks.push(e)}setup(){return{name:"middleware-plugin",setup:e=>{e.initialOptions.metafile=!0,e.onEnd(this.handleOnEnd.bind(this)),e.onStart(this.handleOnStart.bind(this,e)),e.onLoad({filter:/.*/},this.handleOnLoad.bind(this)),e.onResolve({filter:/.*/},this.handleOnResolve.bind(this))}}}async handleOnStart(e){let r={errors:[],warnings:[]};for(let t of this.onStartHooks){let i=await t(e);i&&(i.errors?.length&&r.errors.push(...i.errors),i.warnings?.length&&r.warnings.push(...i.warnings))}return r}async handleOnEnd(e){let r={errors:e.errors??[],warnings:e.warnings??[]};for(let t of this.onEndHooks){e.errors=r.errors,e.warnings=r.warnings;let i=await t(e);i&&(i.errors?.length&&r.errors.push(...i.errors),i.warnings?.length&&r.warnings.push(...i.warnings))}return r}async handleOnResolve(e){let r={};for(let t of this.onResolveHooks){let i=await t(e);i&&(r={...r,...i,path:i.path||r.path})}return r.path?r:null}async handleOnLoad(e){let r={contents:void 0,loader:"default"},t=$e(e.path);r.contents||(r.contents=await _e.readFile(t,"utf8"));for(let i of this.onLoadHooks){let n=await i(r.contents??"",r.loader,e);n&&(r={...r,...n,contents:n.contents||r.contents,loader:n.loader||r.loader})}return r.contents?r:null}};function Z(o,e){return o.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(r,t,i)=>e[t]?i:"")}import{relative as Ne}from"path";function K(o,e,r,t){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in r){let s=Ne(e,r[n]).replace(/\\/g,"/");s.startsWith("..")||(s=`./${s}`),o=o.replaceAll(n,`${s}/`),t&&(o=o.replace(i,(a,l)=>(l.startsWith("../")||l.startsWith("./"))&&!l.endsWith(".js")?a.replace(l,`${l}.js`):a))}return o}import{cwd as Me}from"process";import{build as X}from"esbuild";var p=class o extends d{originalErrorStack;constructor(e,r){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,o),r&&Object.assign(this,r),this.name="xBuildError",this.originalErrorStack=this.stack,this.stack=this.reformatStack(this)}};var Fe={write:!1,bundle:!0,minify:!1,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function je(o){let e=/\/\/# sourceMappingURL=data:application\/json;base64,([^'"\s]+)/,r=o.match(e);if(!r||!r[1])throw new p("Source map URL not found in the output.");let t=r[1];return{code:o.replace(e,""),sourceMap:t}}async function Q(o,e={}){let r={absWorkingDir:Me(),...Fe,...e,entryPoints:[o]},i=(await X(r)).outputFiles?.pop()?.text??"";return je(i)}async function ee(o,e="browser"){return(await X({entryPoints:o,bundle:!0,write:!1,metafile:!0,platform:e,packages:"external",logLevel:"silent",outdir:"dist"})).metafile}var C=class o extends Error{constructor(e,r){super(e),this.name="TypesError",Object.setPrototypeOf(this,o.prototype),r?.cause&&(this.cause=r.cause)}};import{resolve as E,relative as We,dirname as Ve,parse as Je}from"path";function He(o){let e={};return o.forEach(r=>{let t=r.substring(0,r.lastIndexOf("."));e[t]=r}),e}function w(o){if(Array.isArray(o)){let e={};return o.length>0&&typeof o[0]=="object"?o.forEach(r=>{e[r.out]=r.in}):typeof o[0]=="string"&&(e=He(o)),e}else if(o&&typeof o=="object")return o;throw new p("Unsupported entry points format")}import{sys as Ue,factory as D,createProgram as re,visitEachChild as te,isStringLiteral as qe,resolveModuleName as Ge,isImportDeclaration as oe,isExportDeclaration as ie,getPreEmitDiagnostics as ze,flattenDiagnosticMessageText as ne}from"typescript";var k=class{constructor(e,r,t=!0){this.tsConfig=e;this.outDir=r;this.activeColor=t;this.options={...this.tsConfig.options,outDir:this.outDir}}options;typeCheck(e=!1){let r=re(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0});this.handleDiagnostics(ze(r),e)}generateDeclarations(e){let r=Object.values(w(e));re(r,{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}).emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return oe(e)||ie(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&qe(e.moduleSpecifier)}resolveModuleFileName(e,r){let t,i=Ge(e,r.baseUrl,r,Ue);if(i.resolvedModule&&r.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return t;t=E(i.resolvedModule.resolvedFileName).replace(E(r.baseUrl),".")}return t}getRelativePathToOutDir(e,r){e=E(e).replace(E(this.options.baseUrl??""),".");let t=We(Ve(e),r).replace(/\\/g,"/"),i=Je(t);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,r){let t=D.createStringLiteral(r);return oe(e)?D.updateImportDeclaration(e,e.modifiers,e.importClause,t,void 0):ie(e)?D.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,t,void 0):e}createVisitor(e,r){let t=i=>{if(this.isImportOrExportDeclaration(i)&&this.hasStringLiteralModuleSpecifier(i)){let n=i.moduleSpecifier.text,s=this.resolveModuleFileName(n,this.options);if(s){let a=this.getRelativePathToOutDir(e.fileName,s);return this.updateModuleSpecifier(i,a)}}return te(i,t,r)};return t}createTransformerFactory(){return e=>({transformSourceFile:r=>te(r,this.createVisitor(r,e),e),transformBundle:r=>r})}handleDiagnostics(e,r=!1){if(e.length!==0&&(e.forEach(t=>{if(t.file&&t.start!==void 0){let{line:i,character:n}=t.file.getLineAndCharacterOfPosition(t.start),s=ne(t.messageText,`
81
- `),a=c("\x1B[38;5;81m",t.file.fileName,this.activeColor),l=c("\x1B[38;5;230m",`${i+1}:${n+1}`,this.activeColor),g=c("\x1B[38;5;9m","error",this.activeColor),h=c("\x1B[38;5;243m",`TS${t.code}`,this.activeColor);console.error(`${f()} ${a}:${l} - ${g} ${h}:${s}`)}else console.error(ne(t.messageText,`
80
+ `;import{extname as V,join as J,resolve as Be}from"path";import{existsSync as U,readdir as Ie,readFile as Le,readFileSync as q,stat as _e}from"fs";var G={html:{icon:"fa-file-code",color:"#d1a65f"},css:{icon:"fa-file-css",color:"#264de4"},js:{icon:"fa-file-code",color:"#f7df1e"},json:{icon:"fa-file-json",color:"#b41717"},png:{icon:"fa-file-image",color:"#53a8e4"},jpg:{icon:"fa-file-image",color:"#53a8e4"},jpeg:{icon:"fa-file-image",color:"#53a8e4"},gif:{icon:"fa-file-image",color:"#53a8e4"},txt:{icon:"fa-file-alt",color:"#8e8e8e"},folder:{icon:"fa-folder",color:"#ffb800"}},b=class{rootDir;isHttps;config;constructor(e,t){this.rootDir=Be(t),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?U(this.config.keyfile)&&U(this.config.certfile):!1}start(){if(this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){z.createServer((t,r)=>{this.handleRequest(t,r,()=>this.defaultResponse(t,r))}).listen(this.config.port,this.config.host,()=>{console.log(`${f()} HTTP/S server is running at http://${this.config.host}:${this.config.port}`)})}startHttpsServer(){let e={key:q(this.config.keyfile),cert:q(this.config.certfile)};Y.createServer(e,(r,i)=>{this.handleRequest(r,i,()=>this.defaultResponse(r,i))}).listen(this.config.port,this.config.host,()=>{let r=c("\x1B[38;5;227m",`https://${this.config.host}:${this.config.port}`);console.log(`${f()} HTTPS server is running at ${r}`)})}handleRequest(e,t,r){try{this.config.onRequest?this.config.onRequest(e,t,r):r()}catch(i){this.sendError(t,i)}}getContentType(e){return{html:"text/html",css:"text/css",js:"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 r=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",i=J(this.rootDir,r);if(!i.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await this.promisifyStat(i);n.isDirectory()?this.handleDirectory(i,r,t):n.isFile()&&this.handleFile(i,t)}catch(n){let s=n.message;s.includes("favicon")||console.log(f(),s),this.sendNotFound(t)}}promisifyStat(e){return new Promise((t,r)=>{_e(e,(i,n)=>i?r(i):t(n))})}handleDirectory(e,t,r){Ie(e,(i,n)=>{if(i)return this.sendError(r,i);let s=n.map(a=>{if(a.match(/[^A-Za-z0-9_\/\\.-]/))return;let l=J(t,a);if(l.match(/[^A-Za-z0-9_\/\\.-]/))return;let g=V(a).slice(1)||"folder",{icon:h,color:O}=G[g]||G.folder;return`<li><i class="fas ${h}" style="color: ${O};"></i> <a href="/${l}">${a}</a></li>`}).join("");r.writeHead(200,{"Content-Type":"text/html"}),r.end(W.replace("${ fileList }",s))})}handleFile(e,t){let r=V(e).slice(1)||"txt",i=this.getContentType(r);Le(e,(n,s)=>{if(n)return this.sendError(t,n);t.writeHead(200,{"Content-Type":i}),t.end(s)})}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(`${f()}`,t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{promises as $e}from"fs";import{resolve as Ne}from"path";var C=class{buildState={};onEndHooks=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.push(e)}registerOnResolve(e){e&&this.onResolveHooks.push(e)}registerOnLoad(e){e&&this.onLoadHooks.push(e)}setup(){return{name:"middleware-plugin",setup:e=>{e.initialOptions.metafile=!0,e.onEnd(this.handleOnEnd.bind(this)),e.onStart(this.handleOnStart.bind(this,e)),e.onLoad({filter:/.*/},this.handleOnLoad.bind(this)),e.onResolve({filter:/.*/},this.handleOnResolve.bind(this))}}}async handleOnStart(e){this.buildState={};let t={errors:[],warnings:[]};for(let r of this.onStartHooks){let i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}return t}async handleOnEnd(e){let t={errors:e.errors??[],warnings:e.warnings??[]};for(let r of this.onEndHooks){e.errors=t.errors,e.warnings=t.warnings;let i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}return t}async handleOnResolve(e){let t={};for(let r of this.onResolveHooks){let i=await r(e,this.buildState);i&&(t={...t,...i,path:i.path||t.path})}return t.path?t:null}async handleOnLoad(e){let t={contents:void 0,loader:"default"},r=Ne(e.path);t.contents||(t.contents=await $e.readFile(r,"utf8"));for(let i of this.onLoadHooks){let n=await i(t.contents??"",t.loader,e,this.buildState);n&&(t={...t,...n,contents:n.contents||t.contents,loader:n.loader||t.loader})}return t.contents?t:null}};function Z(o,e){return o.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(t,r,i)=>e[r]?i:"")}import{relative as Me}from"path";function K(o,e,t,r){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in t){let s=Me(e,t[n]).replace(/\\/g,"/");s.startsWith("..")||(s=`./${s}`),o=o.replaceAll(n,`${s}/`),r&&(o=o.replace(i,(a,l)=>(l.startsWith("../")||l.startsWith("./"))&&!l.endsWith(".js")?a.replace(l,`${l}.js`):a))}return o}import{cwd as Fe}from"process";import{build as X}from"esbuild";var p=class o extends d{originalErrorStack;constructor(e,t){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,o),t&&Object.assign(this,t),this.name="xBuildError",this.originalErrorStack=this.stack,this.stack=this.reformatStack(this)}};var je={write:!1,bundle:!0,minify:!1,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function He(o){let e=/\/\/# sourceMappingURL=data:application\/json;base64,([^'"\s]+)/,t=o.match(e);if(!t||!t[1])throw new p("Source map URL not found in the output.");let r=t[1];return{code:o.replace(e,""),sourceMap:r}}async function Q(o,e={}){let t={absWorkingDir:Fe(),...je,...e,entryPoints:[o]},i=(await X(t)).outputFiles?.pop()?.text??"";return He(i)}async function ee(o,e="browser"){return(await X({entryPoints:o,bundle:!0,write:!1,metafile:!0,platform:e,packages:"external",logLevel:"silent",outdir:"dist"})).metafile}var x=class o extends Error{constructor(e,t){super(e),this.name="TypesError",Object.setPrototypeOf(this,o.prototype),t?.cause&&(this.cause=t.cause)}};import{resolve as E,relative as Ve,dirname as Je,parse as Ue}from"path";function We(o){let e={};return o.forEach(t=>{let r=t.substring(0,t.lastIndexOf("."));e[r]=t}),e}function w(o){if(Array.isArray(o)){let e={};return o.length>0&&typeof o[0]=="object"?o.forEach(t=>{e[t.out]=t.in}):typeof o[0]=="string"&&(e=We(o)),e}else if(o&&typeof o=="object")return o;throw new p("Unsupported entry points format")}import{sys as qe,factory as A,createProgram as te,visitEachChild as re,isStringLiteral as Ge,resolveModuleName as ze,DiagnosticCategory as Ye,isImportDeclaration as oe,isExportDeclaration as ie,getPreEmitDiagnostics as ne,flattenDiagnosticMessageText as se}from"typescript";var k=class{constructor(e,t,r=!0){this.tsConfig=e;this.outDir=t;this.activeColor=r;this.options={...this.tsConfig.options,outDir:this.outDir}}options;typeCheck(e=!1){let t=te(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0});this.handleDiagnostics(ne(t),e)}generateDeclarations(e,t=!1,r=!1){let i=Object.values(w(e)),n=te(i,{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}),s=ne(n);if(!t&&s.some(a=>a.category===Ye.Error))return this.handleDiagnostics(s,r);n.emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return oe(e)||ie(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&Ge(e.moduleSpecifier)}resolveModuleFileName(e,t){let r,i=ze(e,t.baseUrl,t,qe);if(i.resolvedModule&&t.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return r;r=E(i.resolvedModule.resolvedFileName).replace(E(t.baseUrl),".")}return r}getRelativePathToOutDir(e,t){e=E(e).replace(E(this.options.baseUrl??""),".");let r=Ve(Je(e),t).replace(/\\/g,"/"),i=Ue(r);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,t){let r=A.createStringLiteral(t);return oe(e)?A.updateImportDeclaration(e,e.modifiers,e.importClause,r,void 0):ie(e)?A.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,r,void 0):e}createVisitor(e,t){let r=i=>{if(this.isImportOrExportDeclaration(i)&&this.hasStringLiteralModuleSpecifier(i)){let n=i.moduleSpecifier.text,s=this.resolveModuleFileName(n,this.options);if(s){let a=this.getRelativePathToOutDir(e.fileName,s);return this.updateModuleSpecifier(i,a)}}return re(i,r,t)};return r}createTransformerFactory(){return e=>({transformSourceFile:t=>re(t,this.createVisitor(t,e),e),transformBundle:t=>t})}handleDiagnostics(e,t=!1){if(e.length!==0&&(e.forEach(r=>{if(r.file&&r.start!==void 0){let{line:i,character:n}=r.file.getLineAndCharacterOfPosition(r.start),s=se(r.messageText,`
81
+ `),a=c("\x1B[38;5;81m",r.file.fileName,this.activeColor),l=c("\x1B[38;5;230m",`${i+1}:${n+1}`,this.activeColor),g=c("\x1B[38;5;9m","error",this.activeColor),h=c("\x1B[38;5;243m",`TS${r.code}`,this.activeColor);console.error(`${f()} ${a}:${l} - ${g} ${h}:${s}`)}else console.error(se(r.messageText,`
82
82
  `))}),console.log(`
83
- `),!r))throw new C("Type checking failed due to errors.")}};import u from"typescript";import{dirname as tr}from"path";import{existsSync as le,readFileSync as or}from"fs";import{cwd as Ye}from"process";var P={dev:!1,watch:!1,declaration:!1,buildOnError:!1,noTypeChecker:!1,define:{},esbuild:{write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:Ye(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};import{createRequire as Xe}from"module";import{SourceService as Qe}from"@remotex-labs/xmap";import{Script as Ze,createContext as Ke}from"vm";function se(o,e={}){e.console=console;let r=new Ze(o),t=Ke(e);return r.runInContext(t,{breakOnSigint:!0})}function ae(o,e){for(let r in o)if(Object.prototype.hasOwnProperty.call(o,r)){let t=o[r];typeof t=="function"?o[r]=er(t,e):typeof t=="object"&&t!==null&&ae(t,e)}return o}function er(o,e){return(...r)=>{try{return o(...r)}catch(t){throw new m(t,e)}}}function rr(o,e){return ae(o,e)}async function ce(o){let{code:e,sourceMap:r}=await Q(o,{banner:{js:"(function(module, exports) {"},footer:{js:"})(module, module.exports);"}}),t={exports:{}},i=Xe(import.meta.url),n=new Qe(JSON.parse(atob(r)));try{await se(e,{require:i,module:t})}catch(s){throw new m(s,n)}return rr(t.exports.default,n)}var ir=JSON.stringify({compilerOptions:{strict:!0,target:"ESNext",module:"ESNext",outDir:"dist",skipLibCheck:!0,isolatedModules:!1,esModuleInterop:!1,moduleDetection:"force",moduleResolution:"node",resolveJsonModule:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0}});function nr(o){let e=o.argv,r=i=>Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0)),t=r({bundle:e.bundle,minify:e.minify,outdir:e.outdir,tsconfig:e.tsconfig,entryPoints:e.file?[e.file]:void 0,target:e.node?[`node${process.version.slice(1)}`]:void 0,platform:e.node?"node":void 0,format:e.format});return{...r({dev:e.dev,watch:e.watch,declaration:e.declaration,serve:e.serve?{active:e.serve}:{undefined:void 0}}),esbuild:t}}function fe(o){let e=o.tsconfig??"",r=le(e)?or(e,"utf8"):JSON.stringify(ir),t=u.parseConfigFileTextToJson(e,r);if(t.error)throw new p(u.formatDiagnosticsWithColorAndContext([t.error],{getCurrentDirectory:u.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>u.sys.newLine}));let i=u.parseJsonConfigFileContent(t.config,u.sys,tr(e));if(i.errors.length>0)throw new p(u.formatDiagnosticsWithColorAndContext(i.errors,{getCurrentDirectory:u.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>u.sys.newLine}));return i}async function pe(o,e){let r=nr(e),t=le(o)?await ce(o):{},i=Array.isArray(t)?t:[t],n=i[0];return i.flatMap(s=>{let a={...P,...n,...s,...r,esbuild:{...P.esbuild,...n?.esbuild,...s?.esbuild,...r.esbuild},serve:{...P.serve,...n.serve,...s.serve,...r.serve}};if(!a.esbuild.entryPoints)throw new p("entryPoints cannot be undefined.");return a})}import{join as sr}from"path";import{mkdirSync as ar,writeFileSync as cr}from"fs";function ue(o){let e=o.esbuild.outdir??"",r=o.esbuild.format==="esm"?"module":"commonjs";ar(e,{recursive:!0}),cr(sr(e,"package.json"),`{"type": "${r}"}`)}var T=class{constructor(e){this.config=e;this.config.esbuild.logLevel="silent",this.pluginsProvider=new x,this.typeScriptProvider=new k(fe(this.config.esbuild),this.config.esbuild.outdir??"dist"),this.configureDevelopmentMode(),this.setupPlugins()}typeScriptProvider;activePossess=[];pluginsProvider;async run(){return await this.execute(async()=>{let e=await this.build();(this.config.watch||this.config.dev)&&await e.watch()})}async runDebug(e){return await this.execute(async()=>{this.config.dev=!1,this.config.watch=!1;let r=await this.build();this.spawnDev(r.metafile,e,!0)})}async serve(){let e=new b(this.config.serve,this.config.esbuild.outdir??"");return await this.execute(async()=>{e.start(),await(await this.build()).watch()})}async execute(e){try{await e()}catch(r){let t=r;Array.isArray(t.errors)||console.error(new m(r).stack)}}configureDevelopmentMode(){this.config.dev!==!1&&(!Array.isArray(this.config.dev)||this.config.dev.length<1)&&(this.config.dev=["index"])}setupPlugins(){let e=y(this.typeScriptProvider.options.baseUrl??""),r=this.generatePathAlias(e);this.registerPluginHooks(r,e)}registerPluginHooks(e,r){this.pluginsProvider.registerOnEnd(this.end.bind(this)),this.pluginsProvider.registerOnStart(this.start.bind(this)),this.pluginsProvider.registerOnLoad((t,i,n)=>{if(n.path.endsWith(".ts")){if(!this.config.esbuild.bundle){let s=lr(y(n.path).replace(r,"."));t=K(t.toString(),s,e,this.config.esbuild.format==="esm")}return{loader:"ts",contents:Z(t.toString(),this.config.define)}}})}generatePathAlias(e){let r=this.typeScriptProvider.options.paths,t={};for(let i in r){let n=r[i];if(n.length>0){let s=i.replace(/\*/g,"");t[s]=y(n[0].replace(/\*/g,"")).replace(e,".")}}return t}handleErrors(e){let r=e.errors??[];for(let t of r){if(!t.detail){console.error(new S(t).stack);continue}if(t.detail.name!=="TypesError"){if(t.detail.name){if(t.detail.name==="VMRuntimeError"){console.error(t.detail.stack);continue}if(t.detail instanceof Error){console.error(new m(t.detail).originalErrorStack);continue}}return console.error(t.text)}}}async build(){ue(this.config);let e=this.config.esbuild;this.config.hooks&&(this.pluginsProvider.registerOnEnd(this.config.hooks.onEnd),this.pluginsProvider.registerOnLoad(this.config.hooks.onLoad),this.pluginsProvider.registerOnStart(this.config.hooks.onStart),this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve)),e.define||(e.define={});for(let r in this.config.define)e.define[r]=JSON.stringify(this.config.define[r]);return this.config.esbuild.bundle||await this.processEntryPoints(),e.plugins=[this.pluginsProvider.setup()],this.config.watch||this.config.dev||this.config.serve.active?await pr(e):await fr(e)}spawnDev(e,r,t=!1){if(Array.isArray(r))for(let i in e.outputs)i.includes("map")||!r.some(n=>i.includes(`/${n}.`))||this.activePossess.push(j(i,t))}async start(e){try{console.log(`${f()} StartBuild ${e.initialOptions.outdir}`),this.config.noTypeChecker||this.typeScriptProvider.typeCheck(this.config.buildOnError),this.config.declaration&&this.typeScriptProvider.generateDeclarations(this.config.esbuild.entryPoints)}finally{for(;this.activePossess.length>0;){let r=this.activePossess.pop();r&&r.kill("SIGTERM")}}}async end(e){if(e.errors.length>0)return this.handleErrors(e);console.log(`
84
- ${f()} ${c("\x1B[38;5;166m","Build completed!")}`),console.log(`${f()} ${Object.keys(e.metafile.outputs).length} Modules:`),Object.keys(e.metafile.outputs).forEach(r=>{let t=e.metafile.outputs[r].bytes;console.log(`${f()} ${c("\x1B[38;5;227m",r)}: ${c("\x1B[38;5;208m",t.toString())} bytes`)}),console.log(`
85
- `),this.config.dev&&this.spawnDev(e.metafile,this.config.dev)}async processEntryPoints(){let e=this.config.esbuild,r=await ee(e.entryPoints,e.platform),t=y(this.typeScriptProvider.options.baseUrl??""),i=w(e.entryPoints),n=Object.values(i);Array.isArray(e.entryPoints)&&typeof e.entryPoints[0]=="string"&&(i={},n=[]);for(let s in r.inputs){if(n.includes(s))continue;let a=y(s).replace(t,"."),l=a.substring(0,a.lastIndexOf("."));i[l]=s}e.entryPoints=i}};global.__ACTIVE_COLOR=!0;console.log(H());async function ur(){let o=F(process.argv),e=o.argv,t=(await pe(e.config,o)).map(async i=>{let n=new T(i);if(e.typeCheck)return n.typeScriptProvider.typeCheck(!0);if(e.serve||i.serve.active)return await n.serve();if(Array.isArray(e.debug))return e.debug.length<1&&(e.debug=["index"]),await n.runDebug(e.debug);await n.run()});await Promise.all(t)}ur().catch(o=>{console.error(o.stack)});
83
+ `),!t))throw new x("Type checking failed due to errors.")}};import u from"typescript";import{dirname as ot}from"path";import{existsSync as fe,readFileSync as it}from"fs";import{cwd as Ze}from"process";var P={dev:!1,watch:!1,declaration:!1,buildOnError:!1,noTypeChecker:!1,define:{},esbuild:{write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:Ze(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};import{createRequire as Qe}from"module";import{SourceService as et}from"@remotex-labs/xmap";import{Script as Ke,createContext as Xe}from"vm";function ae(o,e={}){e.console=console;let t=new Ke(o),r=Xe(e);return t.runInContext(r,{breakOnSigint:!0})}function ce(o,e){for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let r=o[t];typeof r=="function"?o[t]=tt(r,e):typeof r=="object"&&r!==null&&ce(r,e)}return o}function tt(o,e){return(...t)=>{try{return o(...t)}catch(r){throw new m(r,e)}}}function rt(o,e){return ce(o,e)}async function le(o){let{code:e,sourceMap:t}=await Q(o,{banner:{js:"(function(module, exports) {"},footer:{js:"})(module, module.exports);"}}),r={exports:{}},i=Qe(import.meta.url),n=new et(JSON.parse(atob(t)));try{await ae(e,{require:i,module:r})}catch(s){throw new m(s,n)}return rt(r.exports.default,n)}var nt=JSON.stringify({compilerOptions:{strict:!0,target:"ESNext",module:"ESNext",outDir:"dist",skipLibCheck:!0,isolatedModules:!1,esModuleInterop:!1,moduleDetection:"force",moduleResolution:"node",resolveJsonModule:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0}});function st(o){let e=o.argv,t=i=>Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0)),r=t({bundle:e.bundle,minify:e.minify,outdir:e.outdir,tsconfig:e.tsconfig,entryPoints:e.file?[e.file]:void 0,target:e.node?[`node${process.version.slice(1)}`]:void 0,platform:e.node?"node":void 0,format:e.format});return{...t({dev:e.dev,watch:e.watch,declaration:e.declaration,serve:e.serve?{active:e.serve}:{undefined:void 0}}),esbuild:r}}function pe(o){let e=o.tsconfig??"",t=fe(e)?it(e,"utf8"):JSON.stringify(nt),r=u.parseConfigFileTextToJson(e,t);if(r.error)throw new p(u.formatDiagnosticsWithColorAndContext([r.error],{getCurrentDirectory:u.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>u.sys.newLine}));let i=u.parseJsonConfigFileContent(r.config,u.sys,ot(e));if(i.errors.length>0)throw new p(u.formatDiagnosticsWithColorAndContext(i.errors,{getCurrentDirectory:u.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>u.sys.newLine}));return i}async function ue(o,e){let t=st(e),r=fe(o)?await le(o):{},i=Array.isArray(r)?r:[r],n=i[0];return i.flatMap(s=>{let a={...P,...n,...s,...t,esbuild:{...P.esbuild,...n?.esbuild,...s?.esbuild,...t.esbuild},serve:{...P.serve,...n.serve,...s.serve,...t.serve}};if(!a.esbuild.entryPoints)throw new p("entryPoints cannot be undefined.");return a})}import{join as at}from"path";import{mkdirSync as ct,writeFileSync as lt}from"fs";function de(o){let e=o.moduleTypeOutDir??o.esbuild.outdir??"dist",t=o.esbuild.format==="esm"?"module":"commonjs";ct(e,{recursive:!0}),lt(at(e,"package.json"),`{"type": "${t}"}`)}var T=class{constructor(e){this.config=e;let t=pe(this.config.esbuild);this.config.esbuild.logLevel="silent",this.pluginsProvider=new C,this.typeScriptProvider=new k(t,this.config.declarationOutDir??t.options.outDir??this.config.esbuild.outdir),this.configureDevelopmentMode(),this.setupPlugins()}typeScriptProvider;activePossess=[];pluginsProvider;async run(){return await this.execute(async()=>{let e=await this.build();(this.config.watch||this.config.dev)&&await e.watch()})}async runDebug(e){return await this.execute(async()=>{this.config.dev=!1,this.config.watch=!1;let t=await this.build();this.spawnDev(t.metafile,e,!0)})}async serve(){let e=new b(this.config.serve,this.config.esbuild.outdir??"");return await this.execute(async()=>{e.start(),await(await this.build()).watch()})}async execute(e){try{await e()}catch(t){let r=t;Array.isArray(r.errors)||console.error(new m(t).stack)}}configureDevelopmentMode(){this.config.dev!==!1&&(!Array.isArray(this.config.dev)||this.config.dev.length<1)&&(this.config.dev=["index"])}setupPlugins(){let e=y(this.typeScriptProvider.options.baseUrl??""),t=this.generatePathAlias(e);this.registerPluginHooks(t,e)}registerPluginHooks(e,t){this.pluginsProvider.registerOnEnd(this.end.bind(this)),this.pluginsProvider.registerOnStart(this.start.bind(this)),this.pluginsProvider.registerOnLoad((r,i,n)=>{if(n.path.endsWith(".ts")){if(!this.config.esbuild.bundle){let s=ft(y(n.path).replace(t,"."));r=K(r.toString(),s,e,this.config.esbuild.format==="esm")}return{loader:"ts",contents:Z(r.toString(),this.config.define)}}})}generatePathAlias(e){let t=this.typeScriptProvider.options.paths,r={};for(let i in t){let n=t[i];if(n.length>0){let s=i.replace(/\*/g,"");r[s]=y(n[0].replace(/\*/g,"")).replace(e,".")}}return r}handleErrors(e){let t=e.errors??[];for(let r of t){if(!r.detail){console.error(new S(r).stack);continue}if(r.detail.name!=="TypesError"){if(r.detail.name){if(r.detail.name==="VMRuntimeError"){console.error(r.detail.stack);continue}if(r.detail instanceof Error){console.error(new m(r.detail).originalErrorStack);continue}}return console.error(r.text)}}}async build(){de(this.config);let e=this.config.esbuild;this.config.hooks&&(this.pluginsProvider.registerOnEnd(this.config.hooks.onEnd),this.pluginsProvider.registerOnLoad(this.config.hooks.onLoad),this.pluginsProvider.registerOnStart(this.config.hooks.onStart),this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve)),e.define||(e.define={});for(let t in this.config.define)e.define[t]=JSON.stringify(this.config.define[t]);return this.config.esbuild.bundle||await this.processEntryPoints(),e.plugins=[this.pluginsProvider.setup()],this.config.watch||this.config.dev||this.config.serve.active?await ut(e):await pt(e)}spawnDev(e,t,r=!1){if(Array.isArray(t))for(let i in e.outputs)i.includes("map")||!t.some(n=>i.includes(`/${n}.`))||this.activePossess.push(j(i,r))}async start(e,t){try{t.startTime=Date.now(),console.log(`${f()} StartBuild ${e.initialOptions.outdir}`),this.config.declaration?this.typeScriptProvider.generateDeclarations(this.config.esbuild.entryPoints,this.config.noTypeChecker,this.config.buildOnError):this.config.noTypeChecker||this.typeScriptProvider.typeCheck(this.config.buildOnError)}finally{for(;this.activePossess.length>0;){let r=this.activePossess.pop();r&&r.kill("SIGTERM")}}}async end(e,t){if(e.errors.length>0)return this.handleErrors(e);let r=Date.now()-t.startTime;console.log(`
84
+ ${f()} ${c("\x1B[38;5;166m",`Build completed! in ${r} ms`)}`),console.log(`${f()} ${Object.keys(e.metafile.outputs).length} Modules:`),Object.keys(e.metafile.outputs).forEach(i=>{let n=e.metafile.outputs[i].bytes;console.log(`${f()} ${c("\x1B[38;5;227m",i)}: ${c("\x1B[38;5;208m",n.toString())} bytes`)}),console.log(`
85
+ `),this.config.dev&&this.spawnDev(e.metafile,this.config.dev)}async processEntryPoints(){let e=this.config.esbuild,t=await ee(e.entryPoints,e.platform),r=y(this.typeScriptProvider.options.baseUrl??""),i=w(e.entryPoints),n=Object.values(i);Array.isArray(e.entryPoints)&&typeof e.entryPoints[0]=="string"&&(i={},n=[]);for(let s in t.inputs){if(n.includes(s))continue;let a=y(s).replace(r,"."),l=a.substring(0,a.lastIndexOf("."));i[l]=s}e.entryPoints=i}};global.__ACTIVE_COLOR=!0;console.log(H());async function dt(){let o=F(process.argv),e=o.argv,r=(await ue(e.config,o)).map(async i=>{let n=new T(i);if(e.typeCheck)return n.typeScriptProvider.typeCheck(!0);if(e.serve||i.serve.active)return await n.serve();if(Array.isArray(e.debug))return e.debug.length<1&&(e.debug=["index"]),await n.runDebug(e.debug);await n.run()});await Promise.all(r)}dt().catch(o=>{console.error(o.stack)});
86
86
  //# sourceMappingURL=index.js.map