@remotex-labs/xbuild 2.1.5 → 2.2.0

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/README.md CHANGED
@@ -2,8 +2,9 @@
2
2
 
3
3
  [![Documentation](https://img.shields.io/badge/Documentation-orange?logo=typescript&logoColor=f5f5f5)](https://remotex-labs.github.io/xBuild/)
4
4
  [![npm version](https://img.shields.io/npm/v/@remotex-labs/xbuild.svg)](https://www.npmjs.com/package/@remotex-labs/xbuild)
5
+ [![downloads](https://img.shields.io/npm/dm/@remotex-labs/xbuild?label=npm%20downloads)](https://www.npmjs.com/package/@remotex-labs/xbuild)
5
6
  [![License: MPL 2.0](https://img.shields.io/badge/License-MPL_2.0-brightgreen.svg)](https://opensource.org/licenses/MPL-2.0)
6
- [![Node.js CI](https://github.com/remotex-labs/xbuild/actions/workflows/test.yml/badge.svg)](https://github.com/remotex-labs/xBuild/actions/workflows/test.yml)
7
+ [![Test CI](https://github.com/remotex-labs/xbuild/actions/workflows/test.yml/badge.svg)](https://github.com/remotex-labs/xBuild/actions/workflows/test.yml)
7
8
  [![Discord](https://img.shields.io/discord/1364348850696884234?logo=Discord&label=Discord)](https://discord.gg/psV9grS9th)
8
9
  [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/remotex-labs/xBuild)
9
10
 
@@ -12,11 +13,13 @@
12
13
  ## Installation
13
14
 
14
15
  Install `@remotex-labs/xbuild` globally using npm:
16
+
15
17
  ```bash
16
18
  npm install -g @remotex-labs/xbuild
17
19
  ```
18
20
 
19
21
  Or using Yarn:
22
+
20
23
  ```bash
21
24
  yarn global add @remotex-labs/xbuild
22
25
  ```
@@ -98,6 +101,7 @@ The `xBuild` configuration file allows you to customize various settings for the
98
101
  By default, xbuild uses `config.xbuild.ts` (`--config` change it). Here's how you can configure it:
99
102
 
100
103
  ### Example Configuration
104
+
101
105
  ```ts
102
106
  /**
103
107
  * Import will remove at compile time
@@ -130,7 +134,7 @@ export const config: xBuildConfig = {
130
134
  packages: 'external',
131
135
  sourcemap: true,
132
136
  external: [ './index.js' ],
133
- sourceRoot: `https://github.com/remotex-lab/xBuild/tree/v${ pkg.version }/`,
137
+ sourceRoot: `https://github.com/remotex-labs/xBuild/tree/v${ pkg.version }/`,
134
138
  loader: {
135
139
  '.html': 'text'
136
140
  }
@@ -161,6 +165,7 @@ export const config: xBuildConfig = {
161
165
  ```
162
166
 
163
167
  ## Using the ifdef Plugin
168
+
164
169
  The `ifdef` in `xBuild` allows to conditionally include or exclude code based on defined variables. Here's an example:
165
170
 
166
171
  ```ts
@@ -188,6 +193,7 @@ console.log(result);
188
193
  ```
189
194
 
190
195
  ### Setting Conditions in Configuration
196
+
191
197
  To enable these blocks during the build, define your conditions in the `xBuild` configuration file:
192
198
 
193
199
  ```ts
@@ -222,7 +228,7 @@ export const config: xBuildConfig = {
222
228
  packages: 'external',
223
229
  sourcemap: true,
224
230
  external: [ './index.js' ],
225
- sourceRoot: `https://github.com/remotex-lab/xBuild/tree/v${ pkg.version }/`,
231
+ sourceRoot: `https://github.com/remotex-labs/xBuild/tree/v${ pkg.version }/`,
226
232
  loader: {
227
233
  '.html': 'text'
228
234
  }
@@ -257,6 +263,7 @@ export const config: xBuildConfig = {
257
263
  ```
258
264
 
259
265
  ## Hooks
266
+
260
267
  The `LifecycleHooksInterface` interface provides a structure for lifecycle hooks to customize the build process.
261
268
 
262
269
  ```ts
@@ -270,6 +277,7 @@ export interface LifecycleHooksInterface {
270
277
  ```
271
278
 
272
279
  ## Links
280
+
273
281
  - [Documentation](https://remotex-labs.github.io/xBuild/)
274
282
  - [GitHub Repository](https://github.com/remotex-labs/xBuild)
275
283
  - [Issue Tracker](https://github.com/remotex-labs/xBuild/issues)
package/dist/bash.js CHANGED
@@ -1,20 +1,18 @@
1
1
  #!/usr/bin/env node
2
- var wr=Object.create;var Ke=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var St=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),ge=r=>{throw TypeError(r)};var Tr=(r,e,t)=>e in r?Ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var vt=(r,e)=>Ke(r,"name",{value:e,configurable:!0});var O=r=>[,,,wr(r?.[St("metadata")]??null)],Ct=["class","method","getter","setter","accessor","field","value","get","set"],me=r=>r!==void 0&&typeof r!="function"?ge("Function expected"):r,Fr=(r,e,t,i,n)=>({kind:Ct[r],name:e,metadata:i,addInitializer:o=>t._?ge("Already initialized"):n.push(me(o||null))}),kr=(r,e)=>Tr(e,St("metadata"),r[3]),A=(r,e,t,i)=>{for(var n=0,o=r[e>>1],s=o&&o.length;n<s;n++)e&1?o[n].call(t):i=o[n].call(t,i);return i},P=(r,e,t,i,n,o)=>{var s,a,c,l,p,f=e&7,d=!!(e&8),g=!!(e&16),L=f>3?r.length+1:f?d?1:2:0,W=Ct[f+5],_=f>3&&(r[L-1]=[]),We=r[L]||(r[L]=[]),C=f&&(!g&&!d&&(n=n.prototype),f<5&&(f>3||!g)&&Ir(f<4?n:{get[t](){return xt(this,o)},set[t](I){return bt(this,o,I)}},t));f?g&&f<4&&vt(o,(f>2?"set ":f>1?"get ":"")+t):vt(n,t);for(var de=i.length-1;de>=0;de--)l=Fr(f,t,c={},r[3],We),f&&(l.static=d,l.private=g,p=l.access={has:g?I=>Or(n,I):I=>t in I},f^3&&(p.get=g?I=>(f^1?xt:Ar)(I,n,f^4?o:C.get):I=>I[t]),f>2&&(p.set=g?(I,Ge)=>bt(I,n,Ge,f^4?o:C.set):(I,Ge)=>I[t]=Ge)),a=(0,i[de])(f?f<4?g?o:C[W]:f>4?void 0:{get:C.get,set:C.set}:n,l),c._=1,f^4||a===void 0?me(a)&&(f>4?_.unshift(a):f?g?o=a:C[W]=a:n=a):typeof a!="object"||a===null?ge("Object expected"):(me(s=a.get)&&(C.get=s),me(s=a.set)&&(C.set=s),me(s=a.init)&&_.unshift(s));return f||kr(r,n),C&&Ke(n,t,C),g?f^4?o:C:n};var qe=(r,e,t)=>e.has(r)||ge("Cannot "+t),Or=(r,e)=>Object(e)!==e?ge('Cannot use the "in" operator on this value'):r.has(e),xt=(r,e,t)=>(qe(r,e,"read from private field"),t?t.call(r):e.get(r));var bt=(r,e,t,i)=>(qe(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),Ar=(r,e,t)=>(qe(r,e,"access private method"),t);import{rmSync as In}from"fs";import{cwd as Tn}from"process";import Oe from"node:process";var Xe=new Map,Et=new Map;function Pr(r){return typeof r=="object"&&r!==null&&"useClass"in r}function $r(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Rr(r){return typeof r=="object"&&r!==null&&"useValue"in r}function $(r){return function(e){Et.set(e,r||{})}}function Ye(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Pr(i))t.push(u(i.useClass,...Ye(i.providers)));else if($r(i))t.push(i.useFactory(...Ye(i.providers)));else if(Rr(i))t.push(i.useValue);else if(typeof i=="function")t.push(u(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function u(r,...e){if(Xe.has(r))return Xe.get(r);let t=Et.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=Ye(t.providers,e),n=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Xe.set(r,n),n}import{xterm as xe}from"@remotex-labs/xansi/xterm.component";import Nr from"typescript";import{readFileSync as Dr,statSync as Lr}from"fs";import*as he from"path";import*as ne from"path/posix";var Mr=/\\/g,Br=/\/+/g;function R(r){if(!r)return"";let e=String(r);return e=e.replace(Mr,"/"),e=e.replace(Br,"/"),e}function wt(r){return ne.normalize(R(r))}function x(...r){return ne.join(...r.map(R))}function E(...r){return R(he.resolve(...r))}function M(r){return R(he.dirname(r))}function T(r,e){return ne.relative(R(r),R(e))||"."}var It,Je;It=[$({scope:"singleton"})];var b=class{resolvedPathCache=new Map;snapshotsByPath=new Map;clear(){this.snapshotsByPath.clear(),this.resolvedPathCache.clear()}getSnapshot(e){return this.snapshotsByPath.get(this.resolve(e))}getOrTouchFile(e){return this.snapshotsByPath.get(this.resolve(e))??this.touchFile(e)}getTrackedFilePaths(){return[...this.snapshotsByPath.keys()]}touchFile(e){let t=this.resolve(e),i=this.snapshotsByPath.get(t);i||(i={version:0,mtimeMs:0,contentSnapshot:void 0},this.snapshotsByPath.set(t,i));try{let o=Lr(t).mtimeMs;if(o===i.mtimeMs)return{...i};let s=Dr(t,"utf-8"),a=s?Nr.ScriptSnapshot.fromString(s):void 0;i.version++,i.mtimeMs=o,i.contentSnapshot=a}catch{(i.contentSnapshot!==void 0||i.version>0)&&(i.version++,i.mtimeMs=0,i.contentSnapshot=void 0)}return{...i}}resolve(e){let t=this.resolvedPathCache.get(e);if(t)return t;let i=E(e);return this.resolvedPathCache.set(e,i),i}};Je=O(null),b=P(Je,0,"FilesModel",It,b),A(Je,1,b);import{readFileSync as jr}from"fs";import{SourceService as Hr}from"@remotex-labs/xmap";var Tt,Qe;Tt=[$({scope:"singleton"})];var S=class{filePath;distPath;rootPath;sourceMaps=new Map;constructor(){this.filePath=import.meta.filename,this.setSourceFile(this.filePath),this.rootPath=this.getRootDir(),this.distPath=this.getDistDir()}isFrameworkFile(e){let{source:t,sourceRoot:i}=e,n=t?.toLowerCase();return!!(t&&n.includes("xbuild")&&!n.includes("xbuild.config")||i&&i.includes("xBuild"))}getSourceMap(e){if(e=E(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=E(t);try{return this.initializeSourceMap(e,i)}catch(n){throw new Error(`Failed to initialize SourceService: ${i}
3
- ${n instanceof Error?n.message:String(n)}`)}}setSourceFile(e){if(!e)return;let t=E(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let n=jr(i,"utf-8");return this.initializeSourceMap(n,t)}catch(n){throw new Error(`Failed to initialize SourceService: ${t}
4
- ${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return R(process.cwd())}getDistDir(){return R(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Hr(e,t);this.sourceMaps.set(t,i)}};Qe=O(null),S=P(Qe,0,"FrameworkService",Tt,S),A(Qe,1,S);import{parseErrorStack as Pt}from"@remotex-labs/xmap/parser.component";function Ft(r){return e=>new G(t=>e.subscribe({next:i=>{try{let n=r(i);t.next?.(n)}catch(n){t.error?.(n)}},error:i=>t.error?.(i),complete:()=>t.complete?.()}))}function kt(r=(e,t)=>e===t){return e=>new G(t=>{let i=!1,n;return e.subscribe({next:o=>{try{if(!i){n=o,i=!0,t.next?.(o);return}r(n,o)||(n=o,t.next?.(o))}catch(s){t.error?.(s)}},error:o=>t.error?.(o),complete:()=>t.complete?.()})})}var G=class{constructor(e){this.handler=e}subscribe(e,t,i){let n=this.createSafeObserver(e,t,i),o;try{o=this.handler(n)}catch(s){return n.error?.(s),()=>{}}return()=>{try{o?.()}catch(s){n.error?.(s)}}}pipe(...e){return e.length===0?this:e.reduce((t,i)=>i(t),this)}createSafeObserver(e,t,i){return typeof e=="function"?{next:e,error:t,complete:i}:e||{}}};var ye=class extends G{isCompleted=!1;observers=new Set;constructor(){super(e=>{if(this.isCompleted){e.complete?.();return}return this.observers.add(e),()=>this.observers.delete(e)})}next(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.next?.(e)}catch(n){t.push(n);try{i.error?.(n)}catch{}}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in next()`)}error(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.error?.(e)}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in error()`)}complete(){if(this.isCompleted)return;let e=[];for(let t of[...this.observers])try{t.complete?.()}catch(i){e.push(i)}if(this.observers.clear(),this.isCompleted=!0,e.length>0)throw new AggregateError(e,`${e.length} observer(s) failed in complete()`)}};var ve=class extends ye{lastValue;constructor(e){super(),this.lastValue=typeof e=="function"?e():e}get value(){return this.lastValue}subscribe(e,t,i){if(this.isCompleted)return()=>{};let n=this.createSafeObserver(e,t,i),o=super.subscribe(n);return n.next?.(this.lastValue),o}next(e){this.isCompleted||(this.lastValue=e,super.next(e))}};function Fe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function K(r,...e){if(!e.length)return r;let t=e.shift();if(Fe(r)&&Fe(t)){for(let i in t){let n=t[i],o=r[i];Array.isArray(n)&&Array.isArray(o)?Object.assign(r,{[i]:[...o,...n]}):Fe(n)?Object.assign(r,{[i]:K(Fe(o)?o:{},n)}):Object.assign(r,{[i]:n})}return K(r,...e)}return r}function ke(r,e,t=!0){return r===e||Object.is(r,e)?!0:r===null||e===null?!1:r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.source===e.source&&r.flags===e.flags:URL&&r instanceof URL&&e instanceof URL?r.href===e.href:typeof r=="object"&&typeof e=="object"?_r(r,e,t):!1}function Vr(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function _r(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((o,s)=>ke(o,e[s],t));let i=Object.keys(r),n=Object.keys(e);if(t&&i.length!==n.length)return!1;for(let o of i)if(!Vr(e,o)||!ke(r[o],e[o],t))return!1;return!0}var Ot=Object.freeze({verbose:!1,common:Object.freeze({types:!0,declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:process.cwd()})})});var At,Ze;At=[$({scope:"singleton"})];var v=class{constructor(e=Ot){this.initialConfig=e;this.config$=new ve(K({},e))}config$;getValue(e){return e?e(this.config$.value):this.config$.value}subscribe(e){return this.config$.subscribe(e)}select(e){return this.config$.pipe(Ft(e),kt((t,i)=>ke(t,i)))}patch(e){let t=K({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(K({},this.initialConfig,e))}};Ze=O(null),v=P(Ze,0,"ConfigurationService",At,v),A(Ze,1,v);import{highlightCode as Ur}from"@remotex-labs/xmap/highlighter.component";import{Bias as zr}from"@remotex-labs/xmap";import{formatErrorCode as Wr}from"@remotex-labs/xmap/formatter.component";var Gr=/\s{2,}/g,Kr=/^https?:\/\//,qr=/^file:\/\//;function Xr(r){return r instanceof Error?Pt(r):r.detail instanceof Error?Pt(r.detail):r.location?{name:"esBuildMessage",message:r.text??"",rawStack:"",stack:[{source:`@${r.location.file}`,line:r.location.line,column:r.location.column,fileName:r.location.file,eval:!1,async:!1,native:!1,constructor:!1}]}:{stack:[],name:"esBuildMessage",message:r.text??"",rawStack:""}}function Yr(r){let e=r.fileName??"",t=this.framework.getSourceMap(e);if(t)return t;let i=this.files.getOrTouchFile(e),n=i?.contentSnapshot?.text;if(!i||!n)return null;let o=n.split(`
5
- `);return{getPositionWithCode:(s,a,c,l)=>{let p=l?.linesBefore??3,f=l?.linesAfter??3,d=Math.max(s-p,0),g=Math.min(s+f,o.length);return{line:s,column:a+1,code:o.slice(d,g).join(`
6
- `),source:e,name:null,startLine:d,endLine:g,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function Jr(r){return Wr({...r,code:Ur(r.code)},{color:xe.brightPink})}function et(r){let e=r.fileName;if(e?.includes(this.framework.rootPath)&&(e=T(this.framework.rootPath,e)),!e)return r.source??"";let t=r.line&&r.column?xe.gray(`[${r.line}:${r.column}]`):"";return`at ${r.functionName??""} ${xe.darkGray(e)} ${t}`.replace(Gr," ").trim()}function Qr(r,e){let{source:t,sourceRoot:i,line:n}=e;if(!t)return r.fileName?r.fileName.replace(qr,""):"";let o=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(o>0)return`${t.substring(o)}#L${n}`;if(Kr.test(t))return`${t}#L${n}`;if(i){let s=T(M(this.framework.distPath),x(this.framework.distPath,t));return`${i}${s}#L${n}`}return`${t}#L${n}`}function Zr(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=Jr(e)),et.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:Qr.call(this,r,e)})}function ei(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=Yr.call(this,r);if(!t)return et.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,zr.LOWER_BOUND,e);return i?!this.withFrameworkFrames&&this.framework.isFrameworkFile(i)?"":(this.lineOffset&&(i.line+=this.lineOffset,i.startLine+=this.lineOffset,i.endLine+=this.lineOffset),this.line=i.line,this.column=i.column,Zr.call(this,r,i)):et.call(this,r)}function U(r,e,t=0){let i=u(v).getValue(a=>a.verbose)??!1,n={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:u(b),framework:u(S),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:Xr(r).stack.map(a=>ei.call(n,a,e)).filter(Boolean),code:n.code,line:n.line??0,column:n.column??0,source:n.source,formatCode:n.formatCode}}function z(r,e,t,i=[]){let n=[`
7
- ${e}: ${xe.lightCoral(t)}`];for(let o of i??[])o.text&&n.push(`
8
- `+xe.gray(o.text));return r.formatCode&&n.push(`
2
+ var Ir=Object.create;var Ke=Object.defineProperty;var wr=Object.getOwnPropertyDescriptor;var St=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),ge=r=>{throw TypeError(r)};var Tr=(r,e,t)=>e in r?Ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var vt=(r,e)=>Ke(r,"name",{value:e,configurable:!0});var P=r=>[,,,Ir(r?.[St("metadata")]??null)],Et=["class","method","getter","setter","accessor","field","value","get","set"],me=r=>r!==void 0&&typeof r!="function"?ge("Function expected"):r,kr=(r,e,t,i,o)=>({kind:Et[r],name:e,metadata:i,addInitializer:n=>t._?ge("Already initialized"):o.push(me(n||null))}),Fr=(r,e)=>Tr(e,St("metadata"),r[3]),$=(r,e,t,i)=>{for(var o=0,n=r[e>>1],s=n&&n.length;o<s;o++)e&1?n[o].call(t):i=n[o].call(t,i);return i},R=(r,e,t,i,o,n)=>{var s,a,c,l,p,f=e&7,d=!!(e&8),g=!!(e&16),H=f>3?r.length+1:f?d?1:2:0,K=Et[f+5],U=f>3&&(r[H-1]=[]),We=r[H]||(r[H]=[]),E=f&&(!g&&!d&&(o=o.prototype),f<5&&(f>3||!g)&&wr(f<4?o:{get[t](){return xt(this,n)},set[t](T){return bt(this,n,T)}},t));f?g&&f<4&&vt(n,(f>2?"set ":f>1?"get ":"")+t):vt(o,t);for(var de=i.length-1;de>=0;de--)l=kr(f,t,c={},r[3],We),f&&(l.static=d,l.private=g,p=l.access={has:g?T=>Or(o,T):T=>t in T},f^3&&(p.get=g?T=>(f^1?xt:Ar)(T,o,f^4?n:E.get):T=>T[t]),f>2&&(p.set=g?(T,Ge)=>bt(T,o,Ge,f^4?n:E.set):(T,Ge)=>T[t]=Ge)),a=(0,i[de])(f?f<4?g?n:E[K]:f>4?void 0:{get:E.get,set:E.set}:o,l),c._=1,f^4||a===void 0?me(a)&&(f>4?U.unshift(a):f?g?n=a:E[K]=a:o=a):typeof a!="object"||a===null?ge("Object expected"):(me(s=a.get)&&(E.get=s),me(s=a.set)&&(E.set=s),me(s=a.init)&&U.unshift(s));return f||Fr(r,o),E&&Ke(o,t,E),g?f^4?n:E:o};var qe=(r,e,t)=>e.has(r)||ge("Cannot "+t),Or=(r,e)=>Object(e)!==e?ge('Cannot use the "in" operator on this value'):r.has(e),xt=(r,e,t)=>(qe(r,e,"read from private field"),t?t.call(r):e.get(r));var bt=(r,e,t,i)=>(qe(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),Ar=(r,e,t)=>(qe(r,e,"access private method"),t);import{rmSync as ko}from"fs";import{cwd as Fo}from"process";import Fe from"node:process";var Ye=new Map,Ct=new Map;function Pr(r){return typeof r=="object"&&r!==null&&"useClass"in r}function $r(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Rr(r){return typeof r=="object"&&r!==null&&"useValue"in r}function M(r){return function(e){Ct.set(e,r||{})}}function Xe(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Pr(i))t.push(u(i.useClass,...Xe(i.providers)));else if($r(i))t.push(i.useFactory(...Xe(i.providers)));else if(Rr(i))t.push(i.useValue);else if(typeof i=="function")t.push(u(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function u(r,...e){if(Ye.has(r))return Ye.get(r);let t=Ct.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=Xe(t.providers,e),o=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Ye.set(r,o),o}import{xterm as xe}from"@remotex-labs/xansi/xterm.component";import Nr from"typescript";import*as he from"path";import*as ne from"path/posix";var Mr=/\\/g,Br=/\/+/g;function B(r){if(!r)return"";let e=String(r);return e=e.replace(Mr,"/"),e=e.replace(Br,"/"),e}function It(r){return ne.normalize(B(r))}function x(...r){return ne.join(...r.map(B))}function C(...r){return B(he.resolve(...r))}function k(r){return B(he.dirname(r))}function F(r,e){return ne.relative(B(r),B(e))||"."}import{closeSync as Dr,fstatSync as jr,openSync as Lr,readFileSync as Hr}from"fs";var wt,Je;wt=[M({scope:"singleton"})];var b=class{resolvedPathCache=new Map;snapshotsByPath=new Map;clear(){this.snapshotsByPath.clear(),this.resolvedPathCache.clear()}getSnapshot(e){return this.snapshotsByPath.get(this.resolve(e))}getOrTouchFile(e){return this.snapshotsByPath.get(this.resolve(e))??this.touchFile(e)}getTrackedFilePaths(){return[...this.snapshotsByPath.keys()]}touchFile(e){let t=this.resolve(e),i=this.snapshotsByPath.get(t)??this.createEntry(t);try{this.syncEntry(t,i)}catch{(i.contentSnapshot!==void 0||i.version>0)&&(i.version++,i.mtimeMs=0,i.contentSnapshot=void 0)}return{...i}}resolve(e){let t=this.resolvedPathCache.get(e);if(t)return t;let i=C(e);return this.resolvedPathCache.set(e,i),i}createEntry(e){let t={version:0,mtimeMs:0,contentSnapshot:void 0};return this.snapshotsByPath.set(e,t),t}syncEntry(e,t){let i=Lr(e,"r");try{let{mtimeMs:o}=jr(i);if(o===t.mtimeMs)return;let n=Hr(i,"utf-8");t.version++,t.mtimeMs=o,t.contentSnapshot=n?Nr.ScriptSnapshot.fromString(n):void 0}finally{Dr(i)}}};Je=P(null),b=R(Je,0,"FilesModel",wt,b),$(Je,1,b);import{readFileSync as _r}from"fs";import{SourceService as Vr}from"@remotex-labs/xmap";var Tt,Qe;Tt=[M({scope:"singleton"})];var S=class{filePath;distPath;rootPath;sourceMaps=new Map;constructor(){this.filePath=import.meta.filename,this.setSourceFile(this.filePath),this.rootPath=this.getRootDir(),this.distPath=this.getDistDir()}isFrameworkFile(e){let{source:t,sourceRoot:i}=e,o=t?.toLowerCase();return!!(t&&o.includes("xbuild")&&!o.includes("xbuild.config")||i&&i.includes("xBuild"))}getSourceMap(e){if(e=C(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=C(t);try{return this.initializeSourceMap(e,i)}catch(o){throw new Error(`Failed to initialize SourceService: ${i}
3
+ ${o instanceof Error?o.message:String(o)}`)}}setSourceFile(e){if(!e)return;let t=C(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let o=_r(i,"utf-8");return this.initializeSourceMap(o,t)}catch(o){throw new Error(`Failed to initialize SourceService: ${t}
4
+ ${o instanceof Error?o.message:String(o)}`)}}getRootDir(){return B(process.cwd())}getDistDir(){return B(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Vr(e,t);this.sourceMaps.set(t,i)}};Qe=P(null),S=R(Qe,0,"FrameworkService",Tt,S),$(Qe,1,S);import{parseErrorStack as Pt}from"@remotex-labs/xmap/parser.component";function kt(r){return e=>new q(t=>e.subscribe({next:i=>{try{let o=r(i);t.next?.(o)}catch(o){t.error?.(o)}},error:i=>t.error?.(i),complete:()=>t.complete?.()}))}function Ft(r=(e,t)=>e===t){return e=>new q(t=>{let i=!1,o;return e.subscribe({next:n=>{try{if(!i){o=n,i=!0,t.next?.(n);return}r(o,n)||(o=n,t.next?.(n))}catch(s){t.error?.(s)}},error:n=>t.error?.(n),complete:()=>t.complete?.()})})}var q=class{constructor(e){this.handler=e}subscribe(e,t,i){let o=this.createSafeObserver(e,t,i),n;try{n=this.handler(o)}catch(s){return o.error?.(s),()=>{}}return()=>{try{n?.()}catch(s){o.error?.(s)}}}pipe(...e){return e.length===0?this:e.reduce((t,i)=>i(t),this)}createSafeObserver(e,t,i){return typeof e=="function"?{next:e,error:t,complete:i}:e||{}}};var ye=class extends q{isCompleted=!1;observers=new Set;constructor(){super(e=>{if(this.isCompleted){e.complete?.();return}return this.observers.add(e),()=>this.observers.delete(e)})}next(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.next?.(e)}catch(o){t.push(o);try{i.error?.(o)}catch{}}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in next()`)}error(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.error?.(e)}catch(o){t.push(o)}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in error()`)}complete(){if(this.isCompleted)return;let e=[];for(let t of[...this.observers])try{t.complete?.()}catch(i){e.push(i)}if(this.observers.clear(),this.isCompleted=!0,e.length>0)throw new AggregateError(e,`${e.length} observer(s) failed in complete()`)}};var ve=class extends ye{lastValue;constructor(e){super(),this.lastValue=typeof e=="function"?e():e}get value(){return this.lastValue}subscribe(e,t,i){if(this.isCompleted)return()=>{};let o=this.createSafeObserver(e,t,i),n=super.subscribe(o);return o.next?.(this.lastValue),n}next(e){this.isCompleted||(this.lastValue=e,super.next(e))}};function Te(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Y(r,...e){if(!e.length)return r;let t=e.shift();if(Te(r)&&Te(t)){for(let i in t){let o=t[i],n=r[i];Array.isArray(o)&&Array.isArray(n)?Object.assign(r,{[i]:[...n,...o]}):Te(o)?Object.assign(r,{[i]:Y(Te(n)?n:{},o)}):Object.assign(r,{[i]:o})}return Y(r,...e)}return r}function ke(r,e,t=!0){return r===e||Object.is(r,e)?!0:r===null||e===null?!1:r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.source===e.source&&r.flags===e.flags:URL&&r instanceof URL&&e instanceof URL?r.href===e.href:typeof r=="object"&&typeof e=="object"?zr(r,e,t):!1}function Ur(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function zr(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((n,s)=>ke(n,e[s],t));let i=Object.keys(r),o=Object.keys(e);if(t&&i.length!==o.length)return!1;for(let n of i)if(!Ur(e,n)||!ke(r[n],e[n],t))return!1;return!0}var Ot=Object.freeze({verbose:!1,common:Object.freeze({types:!0,declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:process.cwd()})})});var At,Ze;At=[M({scope:"singleton"})];var v=class{constructor(e=Ot){this.initialConfig=e;this.config$=new ve(Y({},e))}config$;getValue(e){return e?e(this.config$.value):this.config$.value}subscribe(e){return this.config$.subscribe(e)}select(e){return this.config$.pipe(kt(e),Ft((t,i)=>ke(t,i)))}patch(e){let t=Y({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(Y({},this.initialConfig,e))}};Ze=P(null),v=R(Ze,0,"ConfigurationService",At,v),$(Ze,1,v);import{highlightCode as Wr}from"@remotex-labs/xmap/highlighter.component";import{Bias as Gr}from"@remotex-labs/xmap";import{formatErrorCode as Kr}from"@remotex-labs/xmap/formatter.component";var qr=/\s{2,}/g,Yr=/^https?:\/\//,Xr=/^file:\/\//;function Jr(r){return r instanceof Error?Pt(r):r.detail instanceof Error?Pt(r.detail):r.location?{name:"esBuildMessage",message:r.text??"",rawStack:"",stack:[{source:`@${r.location.file}`,line:r.location.line,column:r.location.column,fileName:r.location.file,eval:!1,async:!1,native:!1,constructor:!1}]}:{stack:[],name:"esBuildMessage",message:r.text??"",rawStack:""}}function Qr(r){let e=r.fileName??"",t=this.framework.getSourceMap(e);if(t)return t;let i=this.files.getOrTouchFile(e),o=i?.contentSnapshot?.text;if(!i||!o)return null;let n=o.split(`
5
+ `);return{getPositionWithCode:(s,a,c,l)=>{let p=l?.linesBefore??3,f=l?.linesAfter??3,d=Math.max(s-p,0),g=Math.min(s+f,n.length);return{line:s,column:a+1,code:n.slice(d,g).join(`
6
+ `),source:e,name:null,startLine:d,endLine:g,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function Zr(r){return Kr({...r,code:Wr(r.code)},{color:xe.brightPink})}function et(r){let e=r.fileName;if(e?.includes(this.framework.rootPath)&&(e=F(this.framework.rootPath,e)),!e)return r.source??"";let t=r.line&&r.column?xe.gray(`[${r.line}:${r.column}]`):"";return`at ${r.functionName??""} ${xe.darkGray(e)} ${t}`.replace(qr," ").trim()}function ei(r,e){let{source:t,sourceRoot:i,line:o}=e;if(!t)return r.fileName?r.fileName.replace(Xr,""):"";let n=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(n>0)return`${t.substring(n)}#L${o}`;if(Yr.test(t))return`${t}#L${o}`;if(i){let s=F(k(this.framework.distPath),x(this.framework.distPath,t));return`${i}${s}#L${o}`}return`${t}#L${o}`}function ti(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=Zr(e)),et.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:ei.call(this,r,e)})}function ri(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=Qr.call(this,r);if(!t)return et.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,Gr.LOWER_BOUND,e);return i?!this.withFrameworkFrames&&this.framework.isFrameworkFile(i)?"":(this.lineOffset&&(i.line+=this.lineOffset,i.startLine+=this.lineOffset,i.endLine+=this.lineOffset),this.line=i.line,this.column=i.column,ti.call(this,r,i)):et.call(this,r)}function z(r,e,t=0){let i=u(v).getValue(a=>a.verbose)??!1,o={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:u(b),framework:u(S),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:Jr(r).stack.map(a=>ri.call(o,a,e)).filter(Boolean),code:o.code,line:o.line??0,column:o.column??0,source:o.source,formatCode:o.formatCode}}function W(r,e,t,i=[]){let o=[`
7
+ ${e}: ${xe.lightCoral(t)}`];for(let n of i??[])n.text&&o.push(`
8
+ `+xe.gray(n.text));return r.formatCode&&o.push(`
9
9
 
10
- ${r.formatCode}`),r.stacks.length&&n.push(`
10
+ ${r.formatCode}`),r.stacks.length&&o.push(`
11
11
 
12
12
  Enhanced Stack Trace:
13
13
  ${r.stacks.join(`
14
14
  `)}
15
- `),n.join("")}var y=class extends Error{errorMetadata;formattedStack;constructor(e,t="xBuildBaseError"){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=t,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}get metadata(){return this.errorMetadata}[Symbol.for("nodejs.util.inspect.custom")](){return this.formattedStack||this.stack}reformatStack(e,t){this.errorMetadata=U(e,t),this.formattedStack=z(this.errorMetadata,e.name,e.message)}};function $t(r){if(r instanceof AggregateError){console.error("AggregateError:",r.message);for(let e of r.errors)if(e instanceof Error&&!(e instanceof y)){let t=U(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(z(t,e.name,e.message))}else console.error(e);return}if(r instanceof Error&&!(r instanceof y)){let e=U(r,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(z(e,r.name,r.message))}else console.error(r)}Oe.on("uncaughtException",r=>{$t(r),Oe.exit(2)});Oe.on("unhandledRejection",r=>{$t(r),Oe.exit(2)});import tt from"yargs";import{hideBin as ri}from"yargs/helpers";var ti="config.xbuild.ts",Ae={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:ti},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string"},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},Rt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var Mt,rt;Mt=[$({scope:"singleton"})];var Z=class{parseConfigFile(e){return tt(e).help(!1).version(!1).options({config:Ae.config}).parseSync()}parseUserArgv(e,t){return t?tt(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=tt(ri(e)).locale("en"),n=i.showHelp;return i.showHelp=function(o){return this.group(Object.keys(Ae),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",o=>o.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Ae).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),Rt.forEach(([o,s])=>{i.example(o,s)}),i.parseSync()}};rt=O(null),Z=P(rt,0,"ArgvModule",Mt,Z),A(rt,1,Z);import mt from"readline";import{exec as nn}from"child_process";import{cwd as ii}from"process";import{readdirSync as ni}from"fs";import{matchesGlob as it}from"path";function oi(r){let e=[],t=[];for(let i of r)i.startsWith("!")?t.push(i.slice(1)):e.push(i);return{include:e,exclude:t}}function Bt(r,e){for(let t of e)if(it(r,t))return!0;return!1}function si(r,e){let t=r+"/**";for(let i of e)if(it(r,i)||it(t,i))return!0;return!1}function Pe(r,e){let{include:t,exclude:i}=oi(e),n=Object.create(null),s=ii().length+1,a=r.length+1,c=i.length>0;function l(p){let f;try{f=ni(p,{withFileTypes:!0})}catch{return}let d=f.length;for(let g=0;g<d;g++){let L=f[g],W=x(p,L.name),_=W.slice(a);if(L.isDirectory()){(!c||!si(_,i))&&l(W);continue}if(!(c&&Bt(_,i))&&Bt(_,t)){let We=W.slice(s),C=_.lastIndexOf("."),de=C>0?_.slice(0,C):_;n[de]=We}}}return l(r),n}var B=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var ee=class extends y{constructor(e){super(e.text??"","esBuildError"),this.errorMetadata=U(e,{withFrameworkFrames:!0}),this.stack=z(this.errorMetadata,this.name,this.message,e.notes)}};var q=class r extends y{constructor(t,i){if(t instanceof y)return t;super(t.message,"VMRuntimeError");this.originalError=t;this.originalError instanceof AggregateError&&Array.isArray(this.originalError.errors)&&(this.errors=this.originalError.errors.map(n=>new r(n,i))),this.stack=this.originalError.stack,this.message=this.originalError.message,this.reformatStack(this.originalError,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
16
- ${t}
17
- `}return this.formattedStack||this.stack}};function ai(r){return r instanceof y?r:r.detail instanceof y||r.detail instanceof B?r.detail:r.detail instanceof Error?new q(r.detail,{withFrameworkFrames:!0}):r.location?new ee(r):new q(new Error(r.text))}function be(r=[],e){for(let t of r)e.push(ai(t))}function Se(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return be(r.errors,e.errors),be(r.warnings,e.warnings),e}function te(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Ht from"http";import*as Vt from"https";import{extname as Lt}from"path";import{readFileSync as jt}from"fs";var Nt=`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Dark File Browser \u2014 FTP-like</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="logo">F</div><div><h1>xBuildFTP</h1><div class="muted">Browse & serve files</div></div></div><div class="search"><input placeholder="Search files & folders..."/></div><div class="quick-list"><a href="/">\u{1F3E0} Home</a><a href="\${ up }">\u2B06\uFE0F Up</a></div></aside><main class="main"><div class="topbar"><div class="topbar"><ul class="breadcrumbs"> \${ paths } </ul></div></div> \${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>`;import{xterm as nt}from"@remotex-labs/xansi/xterm.component";var li=`
15
+ `),o.join("")}var y=class extends Error{errorMetadata;formattedStack;constructor(e,t="xBuildBaseError"){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=t,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}get metadata(){return this.errorMetadata}[Symbol.for("nodejs.util.inspect.custom")](){return this.formattedStack||this.stack}reformatStack(e,t){this.errorMetadata=z(e,t),this.formattedStack=W(this.errorMetadata,e.name,e.message)}};function $t(r){if(r instanceof AggregateError){console.error("AggregateError:",r.message);for(let e of r.errors)if(e instanceof Error&&!(e instanceof y)){let t=z(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(W(t,e.name,e.message))}else console.error(e);return}if(r instanceof Error&&!(r instanceof y)){let e=z(r,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(W(e,r.name,r.message))}else console.error(r)}Fe.on("uncaughtException",r=>{$t(r),Fe.exit(2)});Fe.on("unhandledRejection",r=>{$t(r),Fe.exit(2)});import tt from"yargs";import{hideBin as oi}from"yargs/helpers";var ii="config.xbuild.ts",Oe={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:ii},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string"},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},Rt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var Mt,rt;Mt=[M({scope:"singleton"})];var te=class{parseConfigFile(e){return tt(e).help(!1).version(!1).options({config:Oe.config}).parseSync()}parseUserArgv(e,t){return t?tt(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=tt(oi(e)).locale("en"),o=i.showHelp;return i.showHelp=function(n){return this.group(Object.keys(Oe),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),o.call(this,n)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",n=>n.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Oe).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),Rt.forEach(([n,s])=>{i.example(n,s)}),i.parseSync()}};rt=P(null),te=R(rt,0,"ArgvModule",Mt,te),$(rt,1,te);import mt from"readline";import{exec as no}from"child_process";import{cwd as ni}from"process";import{readdirSync as si}from"fs";import{matchesGlob as it}from"path";function ai(r){let e=[],t=[];for(let i of r)i.startsWith("!")?t.push(i.slice(1)):e.push(i);return{include:e,exclude:t}}function Bt(r,e){for(let t of e)if(t.endsWith(r)||it(r,t))return!0;return!1}function ci(r,e){let t=r+"/**";for(let i of e)if(it(r,i)||it(t,i))return!0;return!1}function Ae(r,e){let{include:t,exclude:i}=ai(e),o=Object.create(null),s=ni().length+1,a=r.length+1,c=i.length>0;function l(p){let f;try{f=si(p,{withFileTypes:!0})}catch{return}let d=f.length;for(let g=0;g<d;g++){let H=f[g],K=x(p,H.name),U=K.slice(a);if(H.isDirectory()){(!c||!ci(U,i))&&l(K);continue}if(!(c&&Bt(U,i))&&Bt(U,t)){let We=K.slice(s),E=U.lastIndexOf("."),de=E>0?U.slice(0,E):U;o[de]=We}}}return l(r),o}var N=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var I=class extends y{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};var X=class extends y{id;constructor(e,t){super(e.text??"","esBuildError"),this.id=e.id??"",e.detail instanceof Error?(this.stack=e.detail.stack,this.message=e.detail.message,this.reformatStack(e.detail,t)):(this.errorMetadata=z(e,{withFrameworkFrames:!0}),this.stack=W(this.errorMetadata,this.name,this.message,e.notes))}};function li(r){if(r instanceof y)return r;if(r.detail instanceof y||r.detail instanceof N)return r.detail;if(r.detail instanceof Error)return new X(r,{withFrameworkFrames:!0});if(r.location)return new X(r);if(r.text)return new I(r.text)}function be(r=[],e){for(let t of r){let i=li(t);i&&e.push(i)}}function Se(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return be(r.errors,e.errors),be(r.warnings,e.warnings),e}function G(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Ht from"http";import*as _t from"https";import{extname as jt}from"path";import{readFileSync as Lt}from"fs";var Nt=`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Dark File Browser \u2014 FTP-like</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="logo">F</div><div><h1>xBuildFTP</h1><div class="muted">Browse & serve files</div></div></div><div class="search"><input placeholder="Search files & folders..."/></div><div class="quick-list"><a href="/">\u{1F3E0} Home</a><a href="\${ up }">\u2B06\uFE0F Up</a></div></aside><main class="main"><div class="topbar"><div class="topbar"><ul class="breadcrumbs"> \${ paths } </ul></div></div> \${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>`;import{xterm as ot}from"@remotex-labs/xansi/xterm.component";var pi=`
18
16
  ______ _ _ _
19
17
  | ___ \\ (_) | | |
20
18
  __ _| |_/ /_ _ _| | __| |
@@ -22,9 +20,9 @@ __ _| |_/ /_ _ _| | __| |
22
20
  > <| |_/ / |_| | | | (_| |
23
21
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
24
22
  `;function Dt(){return`
25
- \r${nt.burntOrange(li)}
26
- \rVersion: ${nt.brightPink("2.1.5")}
27
- \r`}function F(){return nt.lightCoral("[xBuild]")}import{readdir as fi,stat as pi,readFile as ui}from"fs/promises";import{xterm as $e}from"@remotex-labs/xansi/xterm.component";var Ce=class{constructor(e,t){this.config=e;this.rootDir=E(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(S);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(F(),$e.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(F(),$e.dim("Server stopped.")),this.server=void 0}async restart(){console.log(F(),$e.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=Ht.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:jt(this.config.key??x(this.framework.distPath,"..","certs","server.key")),cert:jt(this.config.cert??x(this.framework.distPath,"..","certs","server.crt"))};this.server=Vt.createServer(t,(i,n)=>{this.handleRequest(i,n,()=>this.defaultResponse(i,n))}),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(`${F()} Request ${$e.lightCoral(e.url?.toString()??"")}`),this.config.onRequest?this.config.onRequest(e,t,i):i()}catch(n){this.sendError(t,n)}}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(/^\/+/,"")||"",n=x(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await pi(n);o.isDirectory()?await this.handleDirectory(n,i,t):o.isFile()&&await this.handleFile(n,t)}catch(o){let s=o.message;s.includes("favicon")||console.log(F(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await fi(e)).map(l=>{let p=x(t,l),f=Lt(l).slice(1)||"folder";return f==="folder"?`
23
+ \r${ot.burntOrange(pi)}
24
+ \rVersion: ${ot.brightPink("2.2.0")}
25
+ \r`}function O(){return ot.lightCoral("[xBuild]")}import{readdir as ui,stat as di,readFile as mi}from"fs/promises";import{xterm as Pe}from"@remotex-labs/xansi/xterm.component";var Ee=class{constructor(e,t){this.config=e;this.rootDir=C(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(S);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(O(),Pe.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(O(),Pe.dim("Server stopped.")),this.server=void 0}async restart(){console.log(O(),Pe.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=Ht.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:Lt(this.config.key??x(this.framework.distPath,"..","certs","server.key")),cert:Lt(this.config.cert??x(this.framework.distPath,"..","certs","server.crt"))};this.server=_t.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(`${O()} Request ${Pe.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=x(this.rootDir,i);if(!o.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await di(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(O(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let n=(await ui(e)).map(l=>{let p=x(t,l),f=jt(l).slice(1)||"folder";return f==="folder"?`
28
26
  <a href="/${p}" class="folder-row">
29
27
  <div class="icon"><i class="fa-solid fa-folder"></i></div>
30
28
  <div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div>
@@ -34,47 +32,49 @@ __ _| |_/ /_ _ _| | __| |
34
32
  <div class="icon"><i class="fa-solid fa-file-code"></i></div>
35
33
  <div class="meta"><div class="name">${l}</div><div class="sub">${f}</div></div>
36
34
  </a>
37
- `}).join("");o?o=`<div class="list">${o}</div>`:o='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(l=>(s+=`${l}/`,`<li><a href="${s}">${l}</a></li>`)).join(""),c=Nt.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));i.writeHead(200,{"Content-Type":"text/html"}),i.end(c)}async handleFile(e,t){let i=Lt(e).slice(1)||"txt",n=this.getContentType(i),o=await ui(e);t.writeHead(200,{"Content-Type":n}),t.end(o)}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{matchesGlob as _t}from"path";import{stat as di,watch as mi}from"fs/promises";var Ee=class{excludes;include;debounceTimer=null;framework=u(S);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=mi(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=wt(n);if(o.endsWith("~")||!this.include.some(a=>_t(o,a))||this.excludes.some(a=>_t(o,a)))continue;let s=x(this.framework.rootPath,o);try{if(!(await di(s)).isFile())continue}catch{}t.add(o),this.debounce(()=>this.handleChangedFiles(e,t))}}async handleChangedFiles(e,t){e?.([...t]),t.clear()}debounce(e,t=150){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}};var j=class extends y{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import Ai from"typescript";import{build as Pi}from"esbuild";import{writeFile as $i,mkdir as Ri}from"fs/promises";import m from"typescript";import gi from"typescript";var hi=/^#!.*(\r?\n)?/,yi=/export {};\n?/g,vi=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,xi=/^export\s+(?:default\s+)?/gm,bi=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function Si(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(hi,""):r}function Ci(r){return r.includes("export {}")?r.replace(yi,""):r}function Ei(r){return r=r.replace(bi,""),r.replace(vi,"$1")}function Ut(r){return r.replace(xi,"")}function wi(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function Re(r){return wi(r)&&(r=Si(r),r=Ci(r),r=Ei(r)),r}function ot(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||M(r),s=i||M(r),c=T(s,r).replace(/\.tsx?$/,".d.ts"),l=gi.sys.resolvePath(`${o}/${c}`);return R(l)}var zt,st;zt=[$({scope:"singleton"})];var re=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(b);constructor(){this.printer=m.createPrinter({newLine:m.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),o=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===o)return s;let a=this.initDeclaration(e.fileName,o),c=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!m.isStringLiteral(e))return null;let i=e.text,n=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!n||n.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:n,isExternal:!1}}addNamedElements(e,t){for(let i of t){let n=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(n)}}hasExportModifier(e){return m.canHaveModifiers(e)?m.getModifiers(e)?.some(i=>i.kind===m.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return m.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,m.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(m.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(m.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=m.factory.createNodeArray(n),s=this.printer.printList(m.ListFormat.MultiLine,o,e),a=Ut(Re(s));for(let c of i)if(c.includes(" as ")){let[l,p]=c.split(" as ");a=a.replace(new RegExp(`\\b${p}\\b`,"g"),l)}else a=a.replace(new RegExp(`\\b${c}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:n,moduleSpecifier:o}=e;if(!n||!o)return;let s=this.resolveModule(o,t.fileName);if(!s)return;let{fileName:a,isExternal:c}=s;if(!c){t.internalDeps.add(a);let{namedBindings:p}=n;if(!p)return;m.isNamespaceImport(p)?i.push(p.name.text):m.isNamedImports(p)&&this.addNamedElements(i,p.elements);return}if(!n){t.externalImports.namespace[a]="";return}n.name&&(t.externalImports.default[a]=n.name.text);let{namedBindings:l}=n;l&&(m.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:m.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:n}=e;if(!i)return;let o=this.resolveModule(i,t.fileName);if(!o)return;let{fileName:s,isExternal:a}=o;if(a||t.internalDeps.add(s),!n){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(m.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}m.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(m.isVariableStatement(e)){for(let i of e.declarationList.declarations)m.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(m.isEnumDeclaration(e)||m.isClassDeclaration(e)||m.isFunctionDeclaration(e)||m.isInterfaceDeclaration(e)||m.isTypeAliasDeclaration(e))&&e.name&&m.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};st=O(null),re=P(st,0,"GraphModel",zt,re),A(st,1,re);import X from"typescript";import{mkdir as Ii,writeFile as Ti}from"fs/promises";var Wt=`/**
35
+ `}).join("");n?n=`<div class="list">${n}</div>`:n='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(l=>(s+=`${l}/`,`<li><a href="${s}">${l}</a></li>`)).join(""),c=Nt.replace("${ fileList }",n).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));i.writeHead(200,{"Content-Type":"text/html"}),i.end(c)}async handleFile(e,t){let i=jt(e).slice(1)||"txt",o=this.getContentType(i),n=await mi(e);t.writeHead(200,{"Content-Type":o}),t.end(n)}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(O(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as Vt}from"path";import{stat as gi,watch as hi}from"fs/promises";var Ce=class{excludes;include;debounceTimer=null;framework=u(S);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=hi(this.framework.rootPath,{recursive:!0});for await(let{filename:o}of i){if(!o)continue;let n=It(o);if(n.endsWith("~")||!this.include.some(a=>Vt(n,a))||this.excludes.some(a=>Vt(n,a)))continue;let s=x(this.framework.rootPath,n);try{if(!(await gi(s)).isFile())continue}catch{}t.add(n),this.debounce(()=>this.handleChangedFiles(e,t))}}async handleChangedFiles(e,t){e?.([...t]),t.clear()}debounce(e,t=150){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}};import $i from"typescript";import{build as Ri}from"esbuild";import{writeFile as Mi,mkdir as Bi}from"fs/promises";import m from"typescript";import yi from"typescript";var vi=/^#!.*(\r?\n)?/,xi=/export {};\n?/g,bi=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,Si=/^export\s+(?:default\s+)?/gm,Ei=/(?<=[:;,{}\[\]()\w"'`])[ \t]*\/\*\*[^\r\n]*?\*\/[ \t]*$/gm;function Ci(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(vi,""):r}function Ii(r){return r.includes("export {}")?r.replace(xi,""):r}function wi(r){return r=r.replace(Ei,""),r.replace(bi,"$1")}function Ut(r){return r.replace(Si,"")}function Ti(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function $e(r){return Ti(r)&&(r=Ci(r),r=Ii(r),r=wi(r)),r}function nt(r,e){let{outDir:t,rootDir:i,declarationDir:o}=e,n=o||t||k(r),s=i||k(r),c=F(s,r).replace(/\.tsx?$/,".d.ts"),l=yi.sys.resolvePath(`${n}/${c}`);return B(l)}var zt,st;zt=[M({scope:"singleton"})];var re=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(b);constructor(){this.printer=m.createPrinter({newLine:m.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let o=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),n=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===n)return s;let a=this.initDeclaration(e.fileName,n),c=this.emitDeclaration.call(o,e);return a.content=this.stripImportsExports.call(o,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!m.isStringLiteral(e))return null;let i=e.text,o=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!o||o.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:o,isExternal:!1}}addNamedElements(e,t){for(let i of t){let o=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(o)}}hasExportModifier(e){return m.canHaveModifiers(e)?m.getModifiers(e)?.some(i=>i.kind===m.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return m.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,m.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],o=[];for(let c of e.statements){if(m.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(m.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),o.push(c)}let n=m.factory.createNodeArray(o),s=this.printer.printList(m.ListFormat.MultiLine,n,e),a=Ut($e(s));for(let c of i)if(c.includes(" as ")){let[l,p]=c.split(" as ");a=a.replace(new RegExp(`\\b${p}\\b`,"g"),l)}else a=a.replace(new RegExp(`\\b${c}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:o,moduleSpecifier:n}=e;if(!o||!n)return;let s=this.resolveModule(n,t.fileName);if(!s)return;let{fileName:a,isExternal:c}=s;if(!c){t.internalDeps.add(a);let{namedBindings:p}=o;if(!p)return;m.isNamespaceImport(p)?i.push(p.name.text):m.isNamedImports(p)&&this.addNamedElements(i,p.elements);return}if(!o){t.externalImports.namespace[a]="";return}o.name&&(t.externalImports.default[a]=o.name.text);let{namedBindings:l}=o;l&&(m.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:m.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:o}=e;if(!i)return;let n=this.resolveModule(i,t.fileName);if(!n)return;let{fileName:s,isExternal:a}=n;if(a||t.internalDeps.add(s),!o){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(m.isNamespaceExport(o)){a?t.externalExports.namespace[o.name.text]=s:t.internalExports.namespace[o.name.text]=s;return}m.isNamedExports(o)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],o.elements):this.addNamedElements(t.internalExports.exports,o.elements))}extractExportName(e,t){if(m.isVariableStatement(e)){for(let i of e.declarationList.declarations)m.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(m.isEnumDeclaration(e)||m.isClassDeclaration(e)||m.isFunctionDeclaration(e)||m.isInterfaceDeclaration(e)||m.isTypeAliasDeclaration(e))&&e.name&&m.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};st=P(null),re=R(st,0,"GraphModel",zt,re),$(st,1,re);import J from"typescript";import{mkdir as ki,writeFile as Fi}from"fs/promises";var Wt=`/**
38
36
  * This file was automatically generated by xBuild.
39
37
  * DO NOT EDIT MANUALLY.
40
38
  */
41
- `;var Me=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(re);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let n=this.languageHostService.getCompilationSettings();t&&(n={...n,outDir:t}),await Promise.all(Object.entries(e).map(async([o,s])=>{let a=i.getSourceFile(s);if(!a)return;let c=x(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Ii(M(i),{recursive:!0}),await Ti(i,o,"utf-8")}async getBundleContent(e,t){let i=new Set,n=new Set([e]),o=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),c="";for(;s.length>0;){let l=s.pop();if(i.has(l))continue;i.add(l);let p=t.getSourceFile(l);if(!p)continue;let f=this.graphModel.scan(p,this.languageService,this.languageHostService);if(o.add(f),a.has(l)){n.add(f);for(let d of f.internalExports.star)a.add(d)}for(let d of f.internalDeps)i.has(d)||s.push(d);c+=f.content}return c+=e.content,this.parseContent(c,o,n)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[n,o]of Object.entries(i.externalImports.default)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});let s=t.get(n);s.default||(s.default=o)}for(let[n,o]of Object.entries(i.externalImports.named)){t.has(n)||t.set(n,{named:new Set,namespace:new Map});for(let s of o)t.get(n).named.add(s)}for(let[n,o]of Object.entries(i.externalImports.namespace))t.has(o)||t.set(o,{named:new Set,namespace:new Map}),t.get(o).namespace.set(n,o)}return t}generateImportStatements(e){let t=[];for(let[i,{default:n,named:o,namespace:s}]of e){let a=[];if(n&&a.push(n),o.size>0&&a.push(`{ ${Array.from(o).sort().join(", ")} }`),s.size>0)for(let[c]of s)t.push(`import * as ${c} from '${i}';`);a.length>0&&t.push(`import ${a.join(", ")} from '${i}';`)}return t}collectNamespaceExports(e,t=new Set){if(t.has(e))return{exports:[],declarations:[]};t.add(e);let i=this.graphModel.get(e);if(!i)return{exports:[],declarations:[]};let n=[...i.internalExports.exports],o=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let c=this.collectNamespaceExports(a,t);c.exports.length>0&&(o.push(...c.declarations),o.push(`const ${s} = { ${c.exports.join(", ")} };`),n.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);n.push(...a.exports),o.push(...a.declarations)}return{exports:n,declarations:o}}collectBundleExports(e){let t=[],i=[],n=[];for(let o of e){t.push(...o.internalExports.exports);for(let[s,a]of Object.entries(o.internalExports.namespace)){let c=this.collectNamespaceExports(a);c.exports.length>0&&(i.push(...c.declarations),i.push(`const ${s} = { ${c.exports.join(", ")} };`),t.push(s))}for(let s of o.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(o.externalExports.namespace))n.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(o.externalExports.exports))n.push(`export { ${a.join(`,
42
- `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[Wt],o=this.collectExternalImports(t),s=this.generateImportStatements(o);n.push(...s),s.length>0&&n.push("");let{exports:a,declarations:c,externalExports:l}=this.collectBundleExports(i);if(c.length>0&&(n.push(...c),n.push("")),n.push(e),a.length>0){let p=Array.from(new Set(a)).sort();n.push(`export {
39
+ `;var Re=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(re);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let o=this.languageHostService.getCompilationSettings();t&&(o={...o,outDir:t}),await Promise.all(Object.entries(e).map(async([n,s])=>{let a=i.getSourceFile(s);if(!a)return;let c=x(o.outDir,`${n}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}async bundleCollectDeclarations(e,t,i){let o=this.graphModel.scan(e,this.languageService,this.languageHostService),n=await this.getBundleContent(o,t);await ki(k(i),{recursive:!0}),await Fi(i,n,"utf-8")}async getBundleContent(e,t){let i=new Set,o=new Set([e]),n=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),c="";for(;s.length>0;){let l=s.pop();if(i.has(l))continue;i.add(l);let p=t.getSourceFile(l);if(!p)continue;let f=this.graphModel.scan(p,this.languageService,this.languageHostService);if(n.add(f),a.has(l)){o.add(f);for(let d of f.internalExports.star)a.add(d)}for(let d of f.internalDeps)i.has(d)||s.push(d);c+=f.content}return c+=e.content,this.parseContent(c,n,o)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[o,n]of Object.entries(i.externalImports.default)){t.has(o)||t.set(o,{named:new Set,namespace:new Map});let s=t.get(o);s.default||(s.default=n)}for(let[o,n]of Object.entries(i.externalImports.named)){t.has(o)||t.set(o,{named:new Set,namespace:new Map});for(let s of n)t.get(o).named.add(s)}for(let[o,n]of Object.entries(i.externalImports.namespace))t.has(n)||t.set(n,{named:new Set,namespace:new Map}),t.get(n).namespace.set(o,n)}return t}generateImportStatements(e){let t=[];for(let[i,{default:o,named:n,namespace:s}]of e){let a=[];if(o&&a.push(o),n.size>0&&a.push(`{ ${Array.from(n).sort().join(", ")} }`),s.size>0)for(let[c]of s)t.push(`import * as ${c} from '${i}';`);a.length>0&&t.push(`import ${a.join(", ")} from '${i}';`)}return t}collectNamespaceExports(e,t=new Set){if(t.has(e))return{exports:[],declarations:[]};t.add(e);let i=this.graphModel.get(e);if(!i)return{exports:[],declarations:[]};let o=[...i.internalExports.exports],n=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let c=this.collectNamespaceExports(a,t);c.exports.length>0&&(n.push(...c.declarations),n.push(`const ${s} = { ${c.exports.join(", ")} };`),o.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);o.push(...a.exports),n.push(...a.declarations)}return{exports:o,declarations:n}}collectBundleExports(e){let t=[],i=[],o=[];for(let n of e){t.push(...n.internalExports.exports);for(let[s,a]of Object.entries(n.internalExports.namespace)){let c=this.collectNamespaceExports(a);c.exports.length>0&&(i.push(...c.declarations),i.push(`const ${s} = { ${c.exports.join(", ")} };`),t.push(s))}for(let s of n.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(n.externalExports.namespace))o.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(n.externalExports.exports))o.push(`export { ${a.join(`,
40
+ `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:o}}parseContent(e,t,i){let o=[Wt],n=this.collectExternalImports(t),s=this.generateImportStatements(n);o.push(...s),s.length>0&&o.push("");let{exports:a,declarations:c,externalExports:l}=this.collectBundleExports(i);if(c.length>0&&(o.push(...c),o.push("")),o.push(e),a.length>0){let p=Array.from(new Set(a)).sort();o.push(`export {
43
41
  ${p.join(`,
44
42
  `)}
45
- };`)}return l.length>0&&n.push(...l),n.join(`
46
- `)}};import{mkdir as Fi,writeFile as ki}from"fs/promises";import{xterm as Oi}from"@remotex-labs/xansi/xterm.component";var Be=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Oi.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let n=[],o=t.getSourceFiles();for(let s=0;s<o.length;s++){let a=o[s];this.shouldEmitFile(a,t,i)&&n.push(a)}n.length!==0&&await Promise.all(n.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let n=ot(e.fileName,i),o=r.emittedVersions.get(n),s=this.languageHostService.getScriptVersion(e.fileName);return!o||o!==s?(r.emittedVersions.set(n,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let n=i.outputFiles[0].text,o=ot(e.fileName,t);n=Re(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await Fi(M(o),{recursive:!0}),await ki(o,n,"utf8")}};import oe from"typescript";var Ne=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=oe.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=oe.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(b);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=oe.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,n,o){return r.sys.readDirectory(e,t,i,n,o)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return oe.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 oe.resolveModuleName(e,t,this.compilerOptions,oe.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let n=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,n),n}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(n,o)=>{let s=this.resolveModuleFileName(o,t);if(!s)return n;let a=s.replace(/\.tsx?$/,i),c=T(t,a);return n.replace(o,c.startsWith(".")?c:"./"+c)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(n=>n.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var Gt,at;Gt=[$({providers:[{useValue:"tsconfig.json"}]})];var H=class H{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:n}=this.acquireLanguageService();this.config=t,this.languageService=n,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new Be(n,i),this.bundlerService=new Me(n,i)}config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(n=>t.getSourceFile(n)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(n=>this.shouldCheckFile(n)).flatMap(n=>this.collectDiagnostics(n)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=H.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=H.serviceCache.get(e);t&&(t.refCount--,H.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=H.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new Ne(e.options),i=X.createLanguageService(t,X.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return H.serviceCache.set(this.configPath,n),n}parseConfig(){let e=X.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...X.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:X.ScriptTarget.ESNext,module:X.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:X.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:X.flattenDiagnosticMessageText(e.messageText,`
47
- `),category:e.category};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};at=O(null),H=P(at,0,"TypescriptService",Gt,H),A(at,1,H);var se=H;import{cwd as De}from"process";import{build as ct}from"esbuild";var Kt={write:!1,bundle:!0,minify:!0,outdir:`${De()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function qt(r,e={}){try{return await ct({absWorkingDir:De(),...Kt,...e,metafile:!0,entryPoints:r})}catch(t){if(te(t)){let i=new AggregateError([],"Failed to build entryPoints");throw be(t.errors,i.errors),i}throw t}}async function Xt(r,e,t={}){return await ct({absWorkingDir:De(),...Kt,...t,stdin:{loader:"ts",contents:r,resolveDir:De(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Yt(r,e={}){try{return await ct({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(te(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw be(t.errors,i.errors),i}throw t}}function Jt(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=Pe(r,e)),t}else if(e&&typeof e=="object")return e;throw new j("Unsupported entry points format")}var Le=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new j(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new se(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(v);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Pi(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(te(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?K({},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 n=new B("Type checking failed",t);e.warnings?.push({detail:n,location:void 0})}else{let n=[],o=[],s=new B("Type checking failed",n),a=new B("Type checking failed",o);for(let c of t)(c.category===Ai.DiagnosticCategory.Error?n:o).push(c);n.length&&e.errors?.push({detail:s,location:void 0}),o.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(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Ri(e,{recursive:!0}),await $i(x(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new j(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new j("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=Jt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new se(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await Yt(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=T(this.typescriptModule.config.options.rootDir,E(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Mi}from"fs/promises";var je=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(b);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(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=this.variantName){e.push({detail:t,pluginName:i})}async executeStartHooks(e,t){e.stage.startTime=new Date;let i=[],n=[],o={build:t,...e};for(let[s,a]of this.startHooks.entries())try{let c=await a(o);c?.errors&&i.push(...c.errors),c?.warnings&&n.push(...c.warnings)}catch(c){this.pushError(i,c,s)}return{errors:i,warnings:n}}async executeEndHooks(e,t){let i=t.errors,n=t.warnings,o=Date.now()-e.stage.startTime.getTime(),s={buildResult:t,duration:o,...e};for(let[a,c]of this.endHooks.entries())try{let l=await c(s);l?.errors&&i.push(...l.errors),l?.warnings&&n.push(...l.warnings)}catch(l){this.pushError(i,l,a)}if(t.errors.length===0)for(let[a,c]of this.successHooks.entries())try{await c(s)}catch(l){this.pushError(i,l,a)}return{errors:i,warnings:n}}async executeResolveHooks(e,t){let i,n={args:t,...e};for(let o of this.resolveHooks.values()){let s=await o(n);s&&(i=i?{...i,...s}:s)}return i??null}async executeLoadHooks(e,t){let i=[],n=[],o="default",s=E(t.path),a=this.filesModel.getSnapshot(s),c=a?.contentSnapshot?a.contentSnapshot.text:await Mi(s,"utf8");for(let[l,p]of this.loadHooks.entries())try{let f=await p({contents:c,loader:o,args:t,...e});if(!f)continue;f.contents!==void 0&&(c=f.contents),f.loader&&(o=f.loader),f.errors&&i.push(...f.errors),f.warnings&&n.push(...f.warnings)}catch(f){this.pushError(i,f,l)}return{contents:c,loader:o,errors:i,warnings:n}}};import h from"typescript";import{highlightCode as or}from"@remotex-labs/xmap/highlighter.component";import V from"typescript";var Bi="$$ifdef";function Ni(r,e,t,i=!1){let n=i?"export function ":"function ";return V.isArrowFunction(e)||V.isFunctionExpression(e)?Di(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Di(r,e,t,i){let o=e.modifiers?.some(l=>l.kind===V.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=Li(e,t);return`${o}${i}${r}(${s})${a} ${c}`}function Li(r,e){let t=r.body.getText(e);return V.isArrowFunction(r)&&!V.isBlock(r.body)?`{ return ${t}; }`:t}function ji(r,e,t="",i="();"){return V.isArrowFunction(r)||V.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===V.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Qt(r,e,t){let i=r in t&&!!t[r];return e===Bi===i}function Zt(r,e,t,i){let[n,o]=e.arguments;if(!V.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!Qt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Ni(c,o,i.sourceFile,t)}function He(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!V.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!Qt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),ji(s,e.sourceFile,l,n)}import N from"typescript";import{createRequire as _i}from"module";var Ve=class extends y{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=U(e,{},t),this.stack=z(this.errorMetadata,this.name,this.message)}};import{Script as Hi,createContext as Vi}from"vm";async function er(r,e={},t={}){let i=new Hi(r,t),n=Vi(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function tr(r,e,t){let[i,n]=(await Xt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=_i(e.sourceFile.fileName),a=await er(n.text,Ui(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});return a===null?"undefined":typeof a=="number"||typeof a=="boolean"?String(a):JSON.stringify(a)}catch(o){zi(o,e,i.text,t)}return"undefined"}function Ui(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:M(r),__filename:r}}function zi(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(S).setSource(t,e.sourceFile.fileName);let s=new Ve(r,o);e.errors.push({text:s.message,detail:s})}function Wi(r,e){let t=null,i=n=>{if(!t){if(N.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}N.isVariableStatement(n)&&(t=Gi(n,r),t)||N.forEachChild(n,i)}};return i(e),t}function Gi(r,e){for(let t of r.declarationList.declarations)if(N.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(N.isArrowFunction(t.initializer)||N.isFunctionExpression(t.initializer)))return t.initializer;return null}function rr(r){return`module.exports = (${r})();`}function Ki(r){return r&N.NodeFlags.Const?"const":r&N.NodeFlags.Let?"let":"var"}function ir(r,e){return r?N.isIdentifier(r)?qi(r,e):N.isArrowFunction(r)||N.isFunctionExpression(r)?{node:r,data:rr(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function qi(r,e){let t=Wi(r.text,e.sourceFile);return t?{node:t,data:rr(t.getText(e.sourceFile))}:(Xi(r.text,e,r),{data:"",node:r})}function Xi(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=T(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function nr(r,e,t,i,n){let o=t.arguments[0],s=ir(o,n);if(!s)return!1;let a=await tr(s.data,n,s.node),c=Ki(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(n.sourceFile);return`${l}${c} ${p} = ${a};`}async function lt(r,e){let t=r[0],i=ir(t,e);return i?tr(i.data,e,i.node):!1}var Yi=/\.(ts|js)$/,Y=["$$ifdef","$$ifndef","$$inline"];function ft(r,e){return Y.some(t=>r.getText(e).includes(t))}function sr(r){return r===Y[2]?1:2}async function Ji(r,e,t){let i=!1;for(let n of r.declarationList.declarations){let o="",s,a=n.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,o=`(${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(!Y.includes(c))continue;if(s.arguments.length!==sr(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new ee({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===Y[2]?i=await nr(n,r,s,l,t):o?i=He(s,t,n,l,o):i=Zt(n,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function Qi(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!Y.includes(n))return!1;if(i.arguments.length!==sr(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new ee({text:`Invalid macro call: ${n} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let o=!1;return n==Y[2]?(await lt(i.arguments,t),o="undefined"):o=He(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),o!==!1}async function Zi(r,e,t){if(!h.isCallExpression(r)||!ft(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===Y[2]){let s=await lt(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=He(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function en(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 n=[r.sourceFile],o=new Set;for(;n.length>0;){let c=n.pop(),l=c?.kind;if(!c||!l||i&&(l===h.SyntaxKind.VariableStatement&&await Ji(c,o,r)||l===h.SyntaxKind.ExpressionStatement&&ft(c,r.sourceFile)&&await Qi(c,o,r)||l===h.SyntaxKind.CallExpression&&ft(c,r.sourceFile)&&await Zi(c,o,r)))continue;if(t.size>0){if(l===h.SyntaxKind.CallExpression){let f=c;h.isIdentifier(f.expression)&&t.has(f.expression.text)&&o.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 g=d?.getText(r.sourceFile);(!h.isCallExpression(d)||d.expression!==c)&&(!g||Y.every(L=>!g.includes(L)))&&o.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--)n.push(p[f])}if(o.size===0)return r.contents;let s=Array.from(o);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:or(r.contents.slice(c,l)),replacement:or(p)}),r.contents=r.contents.slice(0,c)+p+r.contents.slice(l);return r.contents}async function ar(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Yi.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:a},l=await en(c,r.name);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(l=r.typescript.languageHostService.resolveAliases(l,t.path,".js")),{loader:i,contents:l,warnings:c.warnings,errors:c.errors}}var cr="$$",lr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function tn(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
48
- `&&n++;let o=r.lastIndexOf(`
49
- `,i-1)+1;return{file:t,line:n,column:r.indexOf(e,o)-o}}function rn(r,e){let t=r.lastIndexOf(`
50
- `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function fr(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(b),o=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=n.resolve(a);lr.lastIndex=0;for(let p of c.matchAll(lr)){let f=p.index;if(rn(c,f))continue;let[,d,g,L]=p;if(t.filesWithMacros.add(l),!d||(d.startsWith(cr)||i.push({text:`Macro function '${d}' not start with '${cr}' prefix to avoid conflicts`,location:tn(c,d,a,f)}),g==="inline"))continue;let W=!!o[L];g==="ifndef"===W&&t.disabledMacroNames.add(d)}}return{warnings:i}}var we=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(v);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=Se(a))}catch(a){if(te(a)||a instanceof AggregateError){let c=Se({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await fr(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new j("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new je(e,this.argv);t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new Le(e,t,this.config.variants[e],this.argv),t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onLoad(ar.bind({},this.variants[e]),"build-service")}}};function pr(r){u(v).reload(r)}function ur(r){u(v).patch(r)}import{platform as on,exit as sn,stdin as _e,stdout as ut}from"process";import{xterm as Ue}from"@remotex-labs/xansi/xterm.component";var pt={SIGINT:"",SIGQUIT:""},w={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},dr={win32:"start",darwin:"open",linux:"xdg-open"};function an(r=!1){let e=["\u{1F680} Shortcuts"],t=Ue.dim(" press "),i=(n,o)=>{e.push(`${t}${Ue.bold(n)}${Ue.dim(o)}`)};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
43
+ };`)}return l.length>0&&o.push(...l),o.join(`
44
+ `)}};import{mkdir as Oi,writeFile as Ai}from"fs/promises";import{xterm as Pi}from"@remotex-labs/xansi/xterm.component";var Me=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Pi.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=nt(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=nt(e.fileName,t);o=$e(o),o=this.languageHostService.resolveAliases(o,e.fileName,".d.ts"),await Oi(k(n),{recursive:!0}),await Ai(n,o,"utf8")}};import se from"typescript";var Be=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=se.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=se.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(b);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=se.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,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 se.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 se.resolveModuleName(e,t,this.compilerOptions,se.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=F(k(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 Gt,at;Gt=[M({providers:[{useValue:"tsconfig.json"}]})];var _=class _{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 Me(o,i),this.bundlerService=new Re(o,i)}config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(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=_.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=_.serviceCache.get(e);t&&(t.refCount--,_.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=_.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new Be(e.options),i=J.createLanguageService(t,J.createDocumentRegistry()),o={config:e,host:t,service:i,refCount:1};return _.serviceCache.set(this.configPath,o),o}parseConfig(){let e=J.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...J.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:J.ScriptTarget.ESNext,module:J.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:J.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:J.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}};at=P(null),_=R(at,0,"TypescriptService",Gt,_),$(at,1,_);var ae=_;import{cwd as Ne}from"process";import{build as ct}from"esbuild";var Kt={write:!1,bundle:!0,minify:!0,outdir:`${Ne()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function qt(r,e={}){try{return await ct({absWorkingDir:Ne(),...Kt,...e,metafile:!0,entryPoints:r})}catch(t){if(G(t)){let i=new AggregateError([],"Failed to build entryPoints");throw be(t.errors,i.errors),i}throw t}}async function Yt(r,e,t={}){return await ct({absWorkingDir:Ne(),...Kt,...t,stdin:{loader:"ts",contents:r,resolveDir:Ne(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Xt(r,e={}){try{return await ct({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(G(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw be(t.errors,i.errors),i}throw t}}function Jt(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=Ae(r,e)),t}else if(e&&typeof e=="object")return e;throw new I("Unsupported entry points format")}var De=class{constructor(e,t,i,o={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=o;if(!this.buildConfig?.esbuild)throw new I(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new ae(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(n=>({variantConfig:n.variants?.[this.name],commonConfig:n.common})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(v);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);this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&Object.assign(e,{entryPoints:this.dependenciesFile});try{let t=await Ri(e);return await this.packageTypeComponent(),t}catch(t){if(G(t)){if(t.errors.filter(o=>o.location).length>0)throw t;return{errors:t?.errors??[],warnings:t?.warnings??[]}}}}getConfig(e,t={}){return e?Y({},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 N("Type checking failed",t);e.warnings?.push({detail:o,location:void 0})}else{let o=[],n=[],s=new N("Type checking failed",o),a=new N("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(!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 Bi(e,{recursive:!0}),await Mi(x(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new I(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new I("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([o,n])=>[o,JSON.stringify(n)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=Jt(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 ae(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await Xt(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let o of Object.keys(t.inputs)){let n=F(this.typescriptModule.config.options.rootDir,C(o)),s=this.stripExtension(n);i[s]=o}return i}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 Ni}from"fs/promises";var je=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(b);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=C(t.path),a=this.filesModel.getSnapshot(s),c=a?.contentSnapshot?a.contentSnapshot.text:await Ni(s,"utf8");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 nr}from"@remotex-labs/xmap/highlighter.component";import V from"typescript";var Di="$$ifdef";function ji(r,e,t,i=!1){let o=i?"export function ":"function ";return V.isArrowFunction(e)||V.isFunctionExpression(e)?Li(r,e,t,o):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Li(r,e,t,i){let n=e.modifiers?.some(l=>l.kind===V.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=Hi(e,t);return`${n}${i}${r}(${s})${a} ${c}`}function Hi(r,e){let t=r.body.getText(e);return V.isArrowFunction(r)&&!V.isBlock(r.body)?`{ return ${t}; }`:t}function _i(r,e,t="",i="();"){return V.isArrowFunction(r)||V.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===V.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Qt(r,e,t){let i=r in t&&!!t[r];return e===Di===i}function Zt(r,e,t,i){let[o,n]=e.arguments;if(!V.isStringLiteral(o))return!1;let s=e.expression.text,a=o.text;if(!Qt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return ji(c,n,i.sourceFile,t)}function Le(r,e,t,i=!1,o){let[n,s]=r.arguments;if(!V.isStringLiteral(n))return!1;let a=n.text,c=r.expression.text;if(!Qt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),_i(s,e.sourceFile,l,o)}import D from"typescript";import{createRequire as zi}from"module";var He=class extends y{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=z(e,{},t),this.stack=W(this.errorMetadata,this.name,this.message)}};import{Script as Vi,createContext as Ui}from"vm";async function er(r,e={},t={}){let i=new Vi(r,t),o=Ui(e);return await i.runInContext(o,{breakOnSigint:!0,displayErrors:!1})}async function tr(r,e,t){let[i,o]=(await Yt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let n={exports:{}},s=zi(e.sourceFile.fileName),a=Wi(e.sourceFile.fileName,n,s);a.context=e.context;let c=await er(o.text,a,{filename:e.sourceFile.fileName});return c===null?"undefined":typeof c=="number"||typeof c=="boolean"?String(c):JSON.stringify(c)}catch(n){Gi(n,e,i.text,t)}return"undefined"}function Wi(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:k(r),__filename:r}}function Gi(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(S).setSource(t,e.sourceFile.fileName);let s=new He(r,n);e.errors.push({text:s.message,detail:s})}function Ki(r,e){let t=null,i=o=>{if(!t){if(D.isFunctionDeclaration(o)&&o.name?.text===r){t=o;return}D.isVariableStatement(o)&&(t=qi(o,r),t)||D.forEachChild(o,i)}};return i(e),t}function qi(r,e){for(let t of r.declarationList.declarations)if(D.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(D.isArrowFunction(t.initializer)||D.isFunctionExpression(t.initializer)))return t.initializer;return null}function rr(r){return`module.exports = (${r})();`}function Yi(r){return r&D.NodeFlags.Const?"const":r&D.NodeFlags.Let?"let":"var"}function ir(r,e){return r?D.isIdentifier(r)?Xi(r,e):D.isArrowFunction(r)||D.isFunctionExpression(r)?{node:r,data:rr(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xi(r,e){let t=Ki(r.text,e.sourceFile);return t?{node:t,data:rr(t.getText(e.sourceFile))}:(Ji(r.text,e,r),{data:"",node:r})}function Ji(r,e,t){let i=t.getStart(e.sourceFile),{line:o,character:n}=e.sourceFile.getLineAndCharacterOfPosition(i),s=F(".",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 or(r,e,t,i,o){let n=t.arguments[0],s=ir(n,o);if(!s)return!1;let a=await tr(s.data,o,s.node),c=Yi(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(o.sourceFile);return`${l}${c} ${p} = ${a};`}async function lt(r,e){let t=r[0],i=ir(t,e);return i?tr(i.data,e,i.node):!1}var Qi=/\.(ts|js)$/,Q=["$$ifdef","$$ifndef","$$inline"];function ft(r,e){return Q.some(t=>r.getText(e).includes(t))}function sr(r){return r===Q[2]?1:2}async function Zi(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(!Q.includes(c))continue;if(s.arguments.length!==sr(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new X({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===Q[2]?i=await or(o,r,s,l,t):n?i=Le(s,t,o,l,n):i=Zt(o,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function eo(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let o=i.expression.text;if(!Q.includes(o))return!1;if(i.arguments.length!==sr(o)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new X({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==Q[2]?(await lt(i.arguments,t),n="undefined"):n=Le(i,t),n!==!1&&e.add({replacement:n,end:i.getEnd(),start:i.getStart(t.sourceFile)}),n!==!1}async function to(r,e,t){if(!h.isCallExpression(r)||!ft(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===Q[2]){let s=await lt(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let n=Le(i,t);return n===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:n}),!0)}async function ro(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 Zi(c,n,r)||l===h.SyntaxKind.ExpressionStatement&&ft(c,r.sourceFile)&&await eo(c,n,r)||l===h.SyntaxKind.CallExpression&&ft(c,r.sourceFile)&&await to(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 g=d?.getText(r.sourceFile);(!h.isCallExpression(d)||d.expression!==c)&&(!g||Q.every(H=>!g.includes(H)))&&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:nr(r.contents.slice(c,l)),replacement:nr(p)}),r.contents=r.contents.slice(0,c)+p+r.contents.slice(l);return r.contents}async function ar(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||!Qi.test(t.path))return;let p=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!p)return;let f={stage:o,errors:[],contents:n.toString(),warnings:[],defines:r.config.define??{},sourceFile:p,context:{argv:c,options:a,variantName:s}},d=await ro(f,r.name);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(d=r.typescript.languageHostService.resolveAliases(d,t.path,".js")),{loader:i,contents:d,warnings:f.warnings,errors:f.errors}}var cr="$$",lr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function io(r,e,t,i){let o=1;for(let s=0;s<i;s++)r[s]===`
46
+ `&&o++;let n=r.lastIndexOf(`
47
+ `,i-1)+1;return{file:t,line:o,column:r.indexOf(e,n)-n}}function oo(r,e){let t=r.lastIndexOf(`
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 fr(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],o=u(b),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);lr.lastIndex=0;for(let p of c.matchAll(lr)){let f=p.index;if(oo(c,f))continue;let[,d,g,H]=p;if(t.filesWithMacros.add(l),!d||(d.startsWith(cr)||i.push({text:`Macro function '${d}' not start with '${cr}' prefix to avoid conflicts`,location:io(c,d,a,f)}),g==="inline"))continue;let K=!!n[H];g==="ifndef"===K&&t.disabledMacroNames.add(d)}}return{warnings:i}}var Ie=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(v);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},o=Object.entries(this.variants).map(async([n,s])=>{if(!(e&&!e.includes(n)))try{let a=await s.build();a&&(i[n]=Se(a))}catch(a){if(G(a)||a instanceof AggregateError){let c=Se({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(o),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await fr(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 I("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new je(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new De(e,t,this.config.variants[e],this.argv),t.onLoad(ar.bind({},this.variants[e]),"build-service")}}};function pr(r){u(v).reload(r)}function ur(r){u(v).patch(r)}import{platform as so,exit as ao,stdin as _e,stdout as ut}from"process";import{xterm as Ve}from"@remotex-labs/xansi/xterm.component";var pt={SIGINT:"",SIGQUIT:""},w={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},dr={win32:"start",darwin:"open",linux:"xdg-open"};function co(r=!1){let e=["\u{1F680} Shortcuts"],t=Ve.dim(" press "),i=(o,n)=>{e.push(`${t}${Ve.bold(o)}${Ve.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
51
49
  `),e.join(`
52
50
  `)}function dt(){let r=Math.max(0,ut.rows-2);r>0&&console.log(`
53
- `.repeat(r)),mt.cursorTo(ut,0,0),mt.clearScreenDown(ut)}function cn(r){let e=dr[on]??"xdg-open";nn(`${e} ${r}`)}function ln(r,e,t,i,n){if(e?.name)switch((e.sequence===w.QUIT||r===pt.SIGINT||r===pt.SIGQUIT)&&(console.log(`
54
- \u{1F44B} Exiting...`),sn(1)),e.name){case w.CLEAR:dt();break;case w.VERBOSE:let o=u(v).getValue(s=>s.verbose);console.log(`\u{1F41E} Debug mode: ${o?"DISABLED":"ENABLED"}`),ur({verbose:!o});break;case w.RELOAD:dt(),t();break;case w.HELP:dt(),console.log(i);break;case w.SHOW_URL:n&&console.log(`${F()} ${Ue.canaryYellow(n)}`);break;case w.OPEN_BROWSER:n&&cn(n);break}}function mr(r,e){if(!_e.isTTY)return;let t=an(!!e);console.log(t),_e.setRawMode(!0),mt.emitKeypressEvents(_e),_e.on("keypress",(i,n)=>{ln(i,n,r,t,e)})}import{existsSync as fn}from"fs";import{runInThisContext as pn}from"vm";import{createRequire as un}from"module";var dn={minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1};async function gt(r){if(!r||!fn(r))return{};u(b).touchFile(r);let[e,t]=(await qt([r],{...dn,outdir:"tmp"})).outputFiles;u(S).setSource(e.text,r),globalThis.module={exports:{}},globalThis.require=un(E(r)),await pn(t.text,{filename:r});let i=module.exports.config??module.exports.default;return i||{}}import{xterm as J}from"@remotex-labs/xansi/xterm.component";var gr=J.hex("#80a36b"),Ie=J.hex("#dcdfe4"),ae=J.hex("#5798cd"),D=J.hex("#e5c07b"),ce=J.hex("#56b6c2"),Q=J.hex("#e06c75"),le=J.hex("#c678dd"),fe=J.hex("#a5a7ab");import{xterm as yt}from"@remotex-labs/xansi/xterm.component";var k=" ",ht=1024,hr=ht*1024,vr="\u2014",ie="\u2192",pe="\xD7",mn="\u2022";function ue(r,e=ae.dim(ie)){return`${F()} ${e} ${ae(r)}`}function gn(r){return r<ht?`${r} B`:r<hr?`${(r/ht).toFixed(2)} KB`:`${(r/hr).toFixed(2)} MB`}function xr(r){let e=r.file?T(process.cwd(),r.file):"(unknown)",t=D(String((r.line??0)+1)),i=D(String((r.column??0)+1));return`${ce(e)}:${t}:${i}`}function hn(r,e){if(!e.metadata?.formatCode)return;let t=e.metadata.formatCode.split(`
51
+ `.repeat(r)),mt.cursorTo(ut,0,0),mt.clearScreenDown(ut)}function lo(r){let e=dr[so]??"xdg-open";no(`${e} ${r}`)}function fo(r,e,t,i,o){if(e?.name)switch((e.sequence===w.QUIT||r===pt.SIGINT||r===pt.SIGQUIT)&&(console.log(`
52
+ \u{1F44B} Exiting...`),ao(1)),e.name){case w.CLEAR:dt();break;case w.VERBOSE:let n=u(v).getValue(s=>s.verbose);console.log(`\u{1F41E} Debug mode: ${n?"DISABLED":"ENABLED"}`),ur({verbose:!n});break;case w.RELOAD:dt(),t();break;case w.HELP:dt(),console.log(i);break;case w.SHOW_URL:o&&console.log(`${O()} ${Ve.canaryYellow(o)}`);break;case w.OPEN_BROWSER:o&&lo(o);break}}function mr(r,e){if(!_e.isTTY)return;let t=co(!!e);console.log(t),_e.setRawMode(!0),mt.emitKeypressEvents(_e),_e.on("keypress",(i,o)=>{fo(i,o,r,t,e)})}import{existsSync as po}from"fs";import{runInThisContext as uo}from"vm";import{createRequire as mo}from"module";var go={minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1};async function gt(r){if(!r||!po(r))return{};u(b).touchFile(r);let[e,t]=(await qt([r],{...go,outdir:"tmp"})).outputFiles;u(S).setSource(e.text,r),globalThis.module={exports:{}},globalThis.require=mo(C(r)),await uo(t.text,{filename:r});let i=module.exports.config??module.exports.default;return i||{}}var Ue=class r extends y{constructor(t,i){if(t instanceof y)return t;super(t.message,"VMRuntimeError");this.originalError=t;this.originalError instanceof AggregateError&&Array.isArray(this.originalError.errors)&&(this.errors=this.originalError.errors.map(o=>new r(o,i))),this.stack=this.originalError.stack,this.message=this.originalError.message,this.reformatStack(this.originalError,i)}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
53
+ ${t}
54
+ `}return this.formattedStack||this.stack}};import{xterm as yt}from"@remotex-labs/xansi/xterm.component";import{xterm as Z}from"@remotex-labs/xansi/xterm.component";var gr=Z.hex("#80a36b"),we=Z.hex("#dcdfe4"),ce=Z.hex("#5798cd"),j=Z.hex("#e5c07b"),le=Z.hex("#56b6c2"),L=Z.hex("#e06c75"),fe=Z.hex("#c678dd"),pe=Z.hex("#a5a7ab");var A=" ",ht=1024,hr=ht*1024,vr="\u2014",ie="\u2192",ee="\xD7",ho="\u2022";function oe(r,e=ce.dim(ie)){return`${O()} ${e} ${ce(r)}`}function yo(r){return r<ht?`${r} B`:r<hr?`${(r/ht).toFixed(2)} KB`:`${(r/hr).toFixed(2)} MB`}function xr(r){let e=r.file?F(process.cwd(),r.file):"(unknown)",t=j(String((r.line??0)+1)),i=j(String((r.column??0)+1));return`${le(e)}:${t}:${i}`}function vo(r,e){if(!e.metadata?.formatCode)return;let t=e.metadata.formatCode.split(`
55
55
  `),i=e.metadata.stacks.join(`
56
- `);r.push("");for(let n of t)r.push(`${k}${n}`);r.push(""),r.push(`${k}Enhanced Stack Trace:`),r.push(` ${i}`)}function yn(r){if(!r.metadata?.formatCode)return;let e=r.metadata.formatCode.split(`
57
- `).map(i=>`${k}${i}`).join(`
56
+ `);r.push("");for(let o of t)r.push(`${A}${o}`);r.push(""),r.push(`${A}Enhanced Stack Trace:`),r.push(` ${i}`)}function xo(r){if(!r.metadata?.formatCode)return;let e=r.metadata.formatCode.split(`
57
+ `).map(i=>`${A}${i}`).join(`
58
58
  `),t=r.metadata.stacks.join(`
59
59
  `);console.log(`
60
60
  ${e}
61
61
 
62
- ${k}Enhanced Stack Trace:
63
- ${t}`)}function vn(r,e,t){let i=xr(r),n=t(`TS${r.code}`),o=fe(r.message);return`${k}${e} ${i} ${Ie(ie)} ${n} ${Ie(vr)} ${o}`}function br(r,e,t=Q){let i=xr(r),n=t(`TS${r.code}`),o=fe(r.message);console.log(`${k}${e} ${i}`,Ie(ie),`${n} ${Ie(vr)} ${o}`)}function xn(r,e,t){let i=e.diagnostics.length;if(i===0)return r.push(`${k}${D(t)} ${D("TypesError")}: ${fe(e.message||"Type checking warning")}`),1;r.push("");for(let n of e.diagnostics)r.push(vn(n,D(t),yt.deepOrange));return i}function bn(r,e,t,i){r.push(`
64
- ${k}${i(t)} ${i.dim(e.toString())}`),e instanceof y&&hn(r,e)}function Sn(r,e,t,i){return e instanceof B?xn(r,e,t):(bn(r,e,t,i),1)}function yr(r,e){if(r.length===0)return;let t=e==="Errors",i=t?pe:mn,n=t?Q:D,o=0,s=[""];for(let a of r)o+=Sn(s,a,i,n);s[0]=`
65
- ${n(e)} (${o})`,console.log(s.join(`
66
- `))}function Cn(r){let e=Object.entries(r.outputs),t=e.length,i=[];i.push(`
67
- ${gr("Outputs")} (${t})`);for(let[n,o]of e){let s=D.dim(gn(o.bytes));i.push(`${k}${ae(ie)} ${ce(n)}: ${s}`)}i.push(""),console.log(i.join(`
68
- `))}function Te(r){if(r instanceof AggregateError)for(let e of r.errors)Te(e);else if(r instanceof B)for(let e of r.diagnostics)br(e,Q(pe));else r instanceof y?(console.log(`
69
- ${k}${Q(pe)} ${r}`),yn(r)):r instanceof Error?Te(new q(r)):Te(new q(new Error(String(r))))}function En(r,e){let t=e.length>0,i=t?D(r):le(r),n=t?Q(pe):ae.dim(ie),o=ue("completed",n);if(console.log(`${o} ${i}`),t){console.log("");for(let s of e)br(s,Q(pe));console.log("")}}function Sr(r){for(let[e,t]of Object.entries(r))En(e,t)}function Cr({variantName:r}){console.log(`${ue("build")} ${le(r)}`)}function wn(r,e){if(!u(v).getValue().verbose)return;let t=e?.replacementInfo?.[r];if(!t||!Array.isArray(t)||t.length===0)return;let i=k+ce(ie),n=[ue(`macro ${D("replacement")}`)];for(let{source:o,replacement:s}of t){let a=yt.dim("// "+o).replaceAll(`
62
+ ${A}Enhanced Stack Trace:
63
+ ${t}`)}function bo(r,e,t){let i=xr(r),o=t(`TS${r.code}`),n=pe(r.message);return`${A}${e} ${i} ${we(ie)} ${o} ${we(vr)} ${n}`}function br(r,e,t=L){let i=xr(r),o=t(`TS${r.code}`),n=pe(r.message);console.log(`${A}${e} ${i}`,we(ie),`${o} ${we(vr)} ${n}`)}function So(r,e,t){let i=e.diagnostics.length;if(i===0)return r.push(`${A}${j(t)} ${j("TypesError")}: ${pe(e.message||"Type checking warning")}`),1;r.push("");for(let o of e.diagnostics)r.push(bo(o,j(t),yt.deepOrange));return i}function Eo(r,e,t,i){let o=`${i(e.name)}: ${e.message.slice(e.name.length+1)}`;r.push(`
64
+ ${A}${i(t)} ${o}`),e instanceof y&&vo(r,e)}function Co(r,e,t,i){return e instanceof N?So(r,e,t):(Eo(r,e,t,i),1)}function yr(r,e){if(r.length===0)return;let t=e==="Errors",i=t?ee:ho,o=t?L:j,n=0,s=[""];for(let a of r)n+=Co(s,a,i,o);s[0]=`
65
+ ${o(e)} (${n})`,console.log(s.join(`
66
+ `))}function Io(r){let e=Object.entries(r.outputs),t=e.length,i=[];i.push(`
67
+ ${gr("Outputs")} (${t})`);for(let[o,n]of e){let s=j.dim(yo(n.bytes));i.push(`${A}${ce(ie)} ${le(o)}: ${s}`)}i.push(""),console.log(i.join(`
68
+ `))}function ue(r){if(r instanceof y){let e=`${L(r.name)}: ${r.message.slice(r.name.length+1)}`;console.log(`
69
+ ${A}${L(ee)} ${e}`),xo(r)}else if(G(r))for(let e of r.errors)ue(e);else if(r instanceof N)for(let e of r.diagnostics)br(e,L(ee));else r instanceof Error?ue(new Ue(r)):ue(new I(String(r)))}function wo(r,e){let t=e.length>0,i=t?j(r):fe(r),o=t?L(ee):ce.dim(ie),n=oe("completed",o);if(console.log(`${n} ${i}`),t){console.log("");for(let s of e)br(s,L(ee));console.log("")}}function Sr(r){for(let[e,t]of Object.entries(r))wo(e,t)}function Er({variantName:r}){console.log(`${oe("build")} ${fe(r)}`)}function To(r,e){if(!u(v).getValue().verbose)return;let t=e?.replacementInfo?.[r];if(!t||!Array.isArray(t)||t.length===0)return;let i=A+le(ie),o=[oe(`macro ${j("replacement")}`)];for(let{source:n,replacement:s}of t){let a=yt.dim("// "+n).replaceAll(`
70
70
  `,`
71
- ${k}`);if(s&&s!=="undefined"){let c=s.replaceAll(`
71
+ ${A}`);if(s&&s!=="undefined"){let c=s.replaceAll(`
72
72
  `,`
73
- ${k}`);n.push(`
74
- ${i} ${c} ${a}`)}else n.push(`
75
- ${i} ${a}`)}console.log(n.join(`
76
- `))}function Er({variantName:r,duration:e,buildResult:t,stage:i}){let{errors:n,warnings:o,metafile:s}=Se(t),a=!!s,c=a?le(r):D(r),l=a?ae.dim(ie):Q(pe),p=ue("completed",l);console.log(`${p} ${c} ${yt.dim(`in ${e} ms`)}`),yr(n,"Errors"),yr(o,"Warnings"),(n.length||o.length)&&console.log(""),wn(r,i),a?Cn(s):console.log("")}var Fn=["!node_modules/**","!dist/**","!bundle/**","!**/*.d.ts"],kn=["dist","dist/**",".git/**",".idea/**","node_modules/**"];function On(r,e){if(!e.entryPoints)return;let t=[...e.entryPoints,...Fn];e.outdir&&t.push(`!${e.outdir}/**`,`!${e.outdir}`),r.common?.esbuild?.outdir&&t.push(`!${r.common.esbuild.outdir}/**`,`!${r.common.esbuild.outdir}`),r.variants={argv:{esbuild:{entryPoints:Pe(Tn(),t)}}}}function An(r,e){e.verbose!==void 0&&(r.verbose=e.verbose);let t=Object.values(r.variants??{});for(let i of t)e.types!==void 0&&(i.types=e.types),e.outdir!==void 0&&(i.esbuild.outdir=e.outdir),e.bundle!==void 0&&(i.esbuild.minify=e.bundle),e.minify!==void 0&&(i.esbuild.minify=e.minify),e.tsconfig!==void 0&&(i.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(i.esbuild.platform=e.platform),e.declaration!==void 0&&(i.declaration=e.declaration),e.failOnError!==void 0&&(i.types={failOnError:e.failOnError})}function Pn(r){let e=[...kn];r.common?.esbuild?.outdir&&e.push(r.common.esbuild.outdir,`${r.common.esbuild.outdir}/**`);let t=Object.values(r.variants??{});for(let i of t)i.esbuild.outdir&&e.push(i.esbuild.outdir,`${i.esbuild.outdir}/**`);return e}async function $n(r,e){if(!((e.serve??!1)!==!1||r.serve?.start))return;let i,n=r.serve?.dir||e.serve||"dist",o={...r.serve,onStart({host:a,port:c,url:l}){i=l,console.log(`${ue("serve")} ${le(n)} ${ce(l)}
77
- `),r.serve?.onStart?.({host:a,port:c,url:l})}};return await new Ce(o,n).start(),i}async function ze(r,e){try{let t=x(process.cwd(),"dist");if(In(t,{recursive:!0,force:!0}),e.typeCheck){let i=await r.typeChack();Sr(i)}else await r.build(e.build)}catch(t){Te(t)}}async function Rn(r,e,t,i){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let o=Pn(e),s=new Ee(o);mr(async()=>{await ze(r,t)},i),await ze(r,t),await s.start(async a=>{if(r.touchFiles(a),a.includes(t.config)){let c=await gt(t.config);r.reload(c)}console.log(`
78
- ${F()} ${fe("Rebuilding")}: files (${a.length})
79
- `),await ze(r,t)})}async function Mn(){console.log(Dt());let r=u(Z),e=r.parseConfigFile(process.argv);globalThis.$argv=e;let t=await gt(e.config),i=r.enhancedParse(process.argv,t.userArgv),n=r.parseUserArgv(process.argv,t.userArgv);On(t,i),An(t,i),pr(t);let o=new we(n);o.onEnd=Er,o.onStart=Cr;let s=await $n(t,i);await Rn(o,t,i,s),await ze(o,i)}Mn();
73
+ ${A}`);o.push(`
74
+ ${i} ${c} ${a}`)}else o.push(`
75
+ ${i} ${a}`)}console.log(o.join(`
76
+ `))}function Cr({variantName:r,duration:e,buildResult:t,stage:i}){let{errors:o,warnings:n,metafile:s}=Se(t),a=!!s,c=a?fe(r):j(r),l=a?ce.dim(ie):L(ee),p=oe("completed",l);console.log(`${p} ${c} ${yt.dim(`in ${e} ms`)}`),yr(o,"Errors"),yr(n,"Warnings"),(o.length||n.length)&&console.log(""),To(r,i),a?Io(s):console.log("")}var Oo=["!node_modules/**","!dist/**","!bundle/**","!**/*.d.ts"],Ao=["dist","dist/**",".git/**",".idea/**","node_modules/**"];function Po(r,e){if(!e.entryPoints)return;let t=[...e.entryPoints,...Oo];e.outdir&&t.push(`!${e.outdir}/**`,`!${e.outdir}`),r.common?.esbuild?.outdir&&t.push(`!${r.common.esbuild.outdir}/**`,`!${r.common.esbuild.outdir}`),r.variants={argv:{esbuild:{entryPoints:Ae(Fo(),t)}}}}function $o(r,e){e.verbose!==void 0&&(r.verbose=e.verbose);let t=Object.values(r.variants??{});for(let i of t)e.types!==void 0&&(i.types=e.types),e.outdir!==void 0&&(i.esbuild.outdir=e.outdir),e.bundle!==void 0&&(i.esbuild.minify=e.bundle),e.minify!==void 0&&(i.esbuild.minify=e.minify),e.tsconfig!==void 0&&(i.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(i.esbuild.platform=e.platform),e.declaration!==void 0&&(i.declaration=e.declaration),e.failOnError!==void 0&&(i.types={failOnError:e.failOnError})}function Ro(r){let e=[...Ao];r.common?.esbuild?.outdir&&e.push(r.common.esbuild.outdir,`${r.common.esbuild.outdir}/**`);let t=Object.values(r.variants??{});for(let i of t)i.esbuild.outdir&&e.push(i.esbuild.outdir,`${i.esbuild.outdir}/**`);return e}async function Mo(r,e){if(!((e.serve??!1)!==!1||r.serve?.start))return;let i,o=r.serve?.dir||e.serve||"dist",n={...r.serve,onStart({host:a,port:c,url:l}){i=l,console.log(`${oe("serve")} ${fe(o)} ${le(l)}
77
+ `),r.serve?.onStart?.({host:a,port:c,url:l})}};return await new Ee(n,o).start(),i}async function ze(r,e){try{let t=x(process.cwd(),"dist");if(ko(t,{recursive:!0,force:!0}),e.typeCheck){let i=await r.typeChack();Sr(i)}else{let i=await r.build(e.build);Object.entries(i).forEach(([o,n])=>{let s=n.errors.filter(c=>c?.id==="endHook");if(!s.length)return;let a=oe("onEnd-hook",L(ee));console.log(a,o),s.forEach(c=>ue(c)),console.log("")})}}catch(t){ue(t)}}async function Bo(r,e,t,i){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let n=Ro(e),s=new Ce(n);mr(async()=>{await ze(r,t)},i),await ze(r,t),await s.start(async a=>{if(r.touchFiles(a),a.includes(t.config)){let c=await gt(t.config);r.reload(c)}console.log(`
78
+ ${O()} ${pe("Rebuilding")}: files (${a.length})
79
+ `),await ze(r,t)})}async function No(){console.log(Dt());let r=u(te),e=r.parseConfigFile(process.argv);globalThis.$argv=e;let t=await gt(e.config),i=r.enhancedParse(process.argv,t.userArgv),o=r.parseUserArgv(process.argv,t.userArgv);Po(t,i),$o(t,i),pr(t);let n=new Ie(o);n.onEnd=Cr,n.onStart=Er;let s=await Mo(t,i);await Bo(n,t,i,s),await ze(n,i)}No();
80
80
  //# sourceMappingURL=bash.js.map