@remotex-labs/xbuild 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -286,7 +286,7 @@ declare global {
286
286
  * @see {@link DefineType} for valid definition names
287
287
  * @since 2.0.0
288
288
  */
289
- function $$ifdef<T>(define: DefineType, callback: T): T;
289
+ function $$ifdef<T>(define: DefineType, callback: T): T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;
290
290
  /**
291
291
  * Conditional inclusion macro that includes code when a definition is falsy or undefined.
292
292
  *
@@ -347,7 +347,7 @@ declare global {
347
347
  * @see {@link DefineType} for valid definition names
348
348
  * @since 2.0.0
349
349
  */
350
- function $$ifndef<T>(define: DefineType, callback: T): T;
350
+ function $$ifndef<T>(define: DefineType, callback: T): T extends (...args: infer A) => infer R ? (...args: A) => R | undefined : T | undefined;
351
351
  /**
352
352
  * Inline evaluation macro that executes code at build time and replaces it with the result.
353
353
  *
@@ -419,7 +419,7 @@ declare global {
419
419
  *
420
420
  * @since 2.0.0
421
421
  */
422
- function $$inline(callback: unknown): string;
422
+ function $$inline(callback: unknown): string | undefined;
423
423
  /**
424
424
  * Pre-configuration CLI arguments snapshot (bootstrap argv).
425
425
  *
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- var Tt=Object.create;var Se=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var _e=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),te=r=>{throw TypeError(r)};var kt=(r,e,t)=>e in r?Se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Le=(r,e)=>Se(r,"name",{value:e,configurable:!0});var O=r=>[,,,Tt(r?.[_e("metadata")]??null)],ze=["class","method","getter","setter","accessor","field","value","get","set"],ee=r=>r!==void 0&&typeof r!="function"?te("Function expected"):r,Ot=(r,e,t,i,n)=>({kind:ze[r],name:e,metadata:i,addInitializer:o=>t._?te("Already initialized"):n.push(ee(o||null))}),Pt=(r,e)=>kt(e,_e("metadata"),r[3]),P=(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},R=(r,e,t,i,n,o)=>{var s,a,c,l,f,p=e&7,g=!!(e&8),m=!!(e&16),B=p>3?r.length+1:p?g?1:2:0,U=ze[p+5],j=p>3&&(r[B-1]=[]),xe=r[B]||(r[B]=[]),x=p&&(!m&&!g&&(n=n.prototype),p<5&&(p>3||!m)&&Ft(p<4?n:{get[t](){return Ve(this,o)},set[t](w){return He(this,o,w)}},t));p?m&&p<4&&Le(o,(p>2?"set ":p>1?"get ":"")+t):Le(n,t);for(var Z=i.length-1;Z>=0;Z--)l=Ot(p,t,c={},r[3],xe),p&&(l.static=g,l.private=m,f=l.access={has:m?w=>Rt(n,w):w=>t in w},p^3&&(f.get=m?w=>(p^1?Ve:At)(w,n,p^4?o:x.get):w=>w[t]),p>2&&(f.set=m?(w,be)=>He(w,n,be,p^4?o:x.set):(w,be)=>w[t]=be)),a=(0,i[Z])(p?p<4?m?o:x[U]:p>4?void 0:{get:x.get,set:x.set}:n,l),c._=1,p^4||a===void 0?ee(a)&&(p>4?j.unshift(a):p?m?o=a:x[U]=a:n=a):typeof a!="object"||a===null?te("Object expected"):(ee(s=a.get)&&(x.get=s),ee(s=a.set)&&(x.set=s),ee(s=a.init)&&j.unshift(s));return p||Pt(r,n),x&&Se(n,t,x),m?p^4?o:x:n};var we=(r,e,t)=>e.has(r)||te("Cannot "+t),Rt=(r,e)=>Object(e)!==e?te('Cannot use the "in" operator on this value'):r.has(e),Ve=(r,e,t)=>(we(r,e,"read from private field"),t?t.call(r):e.get(r));var He=(r,e,t,i)=>(we(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),At=(r,e,t)=>(we(r,e,"access private method"),t);var Ce=new Map,Ue=new Map;function Mt(r){return typeof r=="object"&&r!==null&&"useClass"in r}function Nt(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function jt(r){return typeof r=="object"&&r!==null&&"useValue"in r}function A(r){return function(e){Ue.set(e,r||{})}}function Ie(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Mt(i))t.push(u(i.useClass,...Ie(i.providers)));else if(Nt(i))t.push(i.useFactory(...Ie(i.providers)));else if(jt(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(Ce.has(r))return Ce.get(r);let t=Ue.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=Ie(t.providers,e),n=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Ce.set(r,n),n}function qe(r){return e=>new $(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 We(r=(e,t)=>e===t){return e=>new $(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 $=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 re=class extends ${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 ie=class extends re{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 se(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function L(r,...e){if(!e.length)return r;let t=e.shift();if(se(r)&&se(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]}):se(n)?Object.assign(r,{[i]:L(se(o)?o:{},n)}):Object.assign(r,{[i]:n})}return L(r,...e)}return r}function ae(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"?Bt(r,e,t):!1}function Dt(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function Bt(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((o,s)=>ae(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(!Dt(e,o)||!ae(r[o],e[o],t))return!1;return!0}var $t="tsconfig.json",Ge=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",tsconfig:$t,absWorkingDir:process.cwd()})})});var Ke,Ee;Ke=[A({scope:"singleton"})];var b=class{constructor(e=Ge){this.initialConfig=e;this.config$=new ie(L({},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(qe(e),We((t,i)=>ae(t,i)))}patch(e){let t=L({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(L({},this.initialConfig,e))}};Ee=O(null),b=R(Ee,0,"ConfigurationService",Ke,b),P(Ee,1,b);import{cwd as Ht}from"process";import{readdirSync as _t}from"fs";import{matchesGlob as Te}from"path";import*as ne from"path";import*as q from"path/posix";var Lt=/\\/g,Vt=/\/+/g;function E(r){if(!r)return"";let e=String(r);return e=e.replace(Lt,"/"),e=e.replace(Vt,"/"),e}function Xe(r){return q.normalize(E(r))}function h(...r){return q.join(...r.map(E))}function I(...r){return E(ne.resolve(...r))}function T(r){return E(ne.dirname(r))}function F(r,e){return q.relative(E(r),E(e))||"."}function zt(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 ce(r,e){for(let t of e)if(Te(r,t))return!0;return!1}function Ut(r,e){let t=r+"/**";for(let i of e)if(Te(r,i)||Te(t,i))return!0;return!1}function Ai(r,e,t){return ce(r,e)?!ce(r,t):!1}function Je(r,e){let{include:t,exclude:i}=zt(e),n=Object.create(null),s=Ht().length+1,a=r.length+1,c=i.length>0;function l(f){let p;try{p=_t(f,{withFileTypes:!0})}catch{return}let g=p.length;for(let m=0;m<g;m++){let B=p[m],U=h(f,B.name),j=U.slice(a);if(B.isDirectory()){(!c||!Ut(j,i))&&l(U);continue}if(!(c&&ce(j,i))&&ce(j,t)){let xe=U.slice(s),x=j.lastIndexOf("."),Z=x>0?j.slice(0,x):j;n[Z]=xe}}}return l(r),n}var W=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};import{xterm as oe}from"@remotex-labs/xansi/xterm.component";import qt from"typescript";import{readFileSync as Wt,statSync as Gt}from"fs";var Ye,Fe;Ye=[A({scope:"singleton"})];var v=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=Gt(t).mtimeMs;if(o===i.mtimeMs)return{...i};let s=Wt(t,"utf-8"),a=s?qt.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=I(e);return this.resolvedPathCache.set(e,i),i}};Fe=O(null),v=R(Fe,0,"FilesModel",Ye,v),P(Fe,1,v);import{readFileSync as Kt}from"fs";import{SourceService as Xt}from"@remotex-labs/xmap";var Qe,ke;Qe=[A({scope:"singleton"})];var C=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=I(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=I(t);try{return this.initializeSourceMap(e,i)}catch(n){throw new Error(`Failed to initialize SourceService: ${i}
2
- ${n instanceof Error?n.message:String(n)}`)}}setSourceFile(e){if(!e)return;let t=I(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let n=Kt(i,"utf-8");return this.initializeSourceMap(n,t)}catch(n){throw new Error(`Failed to initialize SourceService: ${t}
1
+ var Tt=Object.create;var Se=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var _e=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),te=r=>{throw TypeError(r)};var kt=(r,e,t)=>e in r?Se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Le=(r,e)=>Se(r,"name",{value:e,configurable:!0});var O=r=>[,,,Tt(r?.[_e("metadata")]??null)],ze=["class","method","getter","setter","accessor","field","value","get","set"],ee=r=>r!==void 0&&typeof r!="function"?te("Function expected"):r,Ot=(r,e,t,i,n)=>({kind:ze[r],name:e,metadata:i,addInitializer:o=>t._?te("Already initialized"):n.push(ee(o||null))}),Pt=(r,e)=>kt(e,_e("metadata"),r[3]),P=(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},R=(r,e,t,i,n,o)=>{var s,a,l,c,f,p=e&7,g=!!(e&8),m=!!(e&16),B=p>3?r.length+1:p?g?1:2:0,U=ze[p+5],j=p>3&&(r[B-1]=[]),xe=r[B]||(r[B]=[]),x=p&&(!m&&!g&&(n=n.prototype),p<5&&(p>3||!m)&&Ft(p<4?n:{get[t](){return Ve(this,o)},set[t](w){return He(this,o,w)}},t));p?m&&p<4&&Le(o,(p>2?"set ":p>1?"get ":"")+t):Le(n,t);for(var Z=i.length-1;Z>=0;Z--)c=Ot(p,t,l={},r[3],xe),p&&(c.static=g,c.private=m,f=c.access={has:m?w=>Rt(n,w):w=>t in w},p^3&&(f.get=m?w=>(p^1?Ve:At)(w,n,p^4?o:x.get):w=>w[t]),p>2&&(f.set=m?(w,be)=>He(w,n,be,p^4?o:x.set):(w,be)=>w[t]=be)),a=(0,i[Z])(p?p<4?m?o:x[U]:p>4?void 0:{get:x.get,set:x.set}:n,c),l._=1,p^4||a===void 0?ee(a)&&(p>4?j.unshift(a):p?m?o=a:x[U]=a:n=a):typeof a!="object"||a===null?te("Object expected"):(ee(s=a.get)&&(x.get=s),ee(s=a.set)&&(x.set=s),ee(s=a.init)&&j.unshift(s));return p||Pt(r,n),x&&Se(n,t,x),m?p^4?o:x:n};var we=(r,e,t)=>e.has(r)||te("Cannot "+t),Rt=(r,e)=>Object(e)!==e?te('Cannot use the "in" operator on this value'):r.has(e),Ve=(r,e,t)=>(we(r,e,"read from private field"),t?t.call(r):e.get(r));var He=(r,e,t,i)=>(we(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),At=(r,e,t)=>(we(r,e,"access private method"),t);var Ce=new Map,Ue=new Map;function Mt(r){return typeof r=="object"&&r!==null&&"useClass"in r}function Nt(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function jt(r){return typeof r=="object"&&r!==null&&"useValue"in r}function A(r){return function(e){Ue.set(e,r||{})}}function Ie(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Mt(i))t.push(u(i.useClass,...Ie(i.providers)));else if(Nt(i))t.push(i.useFactory(...Ie(i.providers)));else if(jt(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(Ce.has(r))return Ce.get(r);let t=Ue.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=Ie(t.providers,e),n=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Ce.set(r,n),n}function qe(r){return e=>new $(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 We(r=(e,t)=>e===t){return e=>new $(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 $=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 re=class extends ${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 ie=class extends re{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 se(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function L(r,...e){if(!e.length)return r;let t=e.shift();if(se(r)&&se(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]}):se(n)?Object.assign(r,{[i]:L(se(o)?o:{},n)}):Object.assign(r,{[i]:n})}return L(r,...e)}return r}function ae(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"?Bt(r,e,t):!1}function Dt(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function Bt(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((o,s)=>ae(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(!Dt(e,o)||!ae(r[o],e[o],t))return!1;return!0}var $t="tsconfig.json",Ke=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",tsconfig:$t,absWorkingDir:process.cwd()})})});var Ge,Ee;Ge=[A({scope:"singleton"})];var b=class{constructor(e=Ke){this.initialConfig=e;this.config$=new ie(L({},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(qe(e),We((t,i)=>ae(t,i)))}patch(e){let t=L({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(L({},this.initialConfig,e))}};Ee=O(null),b=R(Ee,0,"ConfigurationService",Ge,b),P(Ee,1,b);import{cwd as Ht}from"process";import{readdirSync as _t}from"fs";import{matchesGlob as Te}from"path";import*as ne from"path";import*as q from"path/posix";var Lt=/\\/g,Vt=/\/+/g;function E(r){if(!r)return"";let e=String(r);return e=e.replace(Lt,"/"),e=e.replace(Vt,"/"),e}function Xe(r){return q.normalize(E(r))}function v(...r){return q.join(...r.map(E))}function I(...r){return E(ne.resolve(...r))}function T(r){return E(ne.dirname(r))}function F(r,e){return q.relative(E(r),E(e))||"."}function zt(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 ce(r,e){for(let t of e)if(Te(r,t))return!0;return!1}function Ut(r,e){let t=r+"/**";for(let i of e)if(Te(r,i)||Te(t,i))return!0;return!1}function Ai(r,e,t){return ce(r,e)?!ce(r,t):!1}function Je(r,e){let{include:t,exclude:i}=zt(e),n=Object.create(null),s=Ht().length+1,a=r.length+1,l=i.length>0;function c(f){let p;try{p=_t(f,{withFileTypes:!0})}catch{return}let g=p.length;for(let m=0;m<g;m++){let B=p[m],U=v(f,B.name),j=U.slice(a);if(B.isDirectory()){(!l||!Ut(j,i))&&c(U);continue}if(!(l&&ce(j,i))&&ce(j,t)){let xe=U.slice(s),x=j.lastIndexOf("."),Z=x>0?j.slice(0,x):j;n[Z]=xe}}}return c(r),n}var W=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};import{xterm as oe}from"@remotex-labs/xansi/xterm.component";import qt from"typescript";import{readFileSync as Wt,statSync as Kt}from"fs";var Ye,Fe;Ye=[A({scope:"singleton"})];var y=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=Kt(t).mtimeMs;if(o===i.mtimeMs)return{...i};let s=Wt(t,"utf-8"),a=s?qt.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=I(e);return this.resolvedPathCache.set(e,i),i}};Fe=O(null),y=R(Fe,0,"FilesModel",Ye,y),P(Fe,1,y);import{readFileSync as Gt}from"fs";import{SourceService as Xt}from"@remotex-labs/xmap";var Qe,ke;Qe=[A({scope:"singleton"})];var C=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=I(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=I(t);try{return this.initializeSourceMap(e,i)}catch(n){throw new Error(`Failed to initialize SourceService: ${i}
2
+ ${n instanceof Error?n.message:String(n)}`)}}setSourceFile(e){if(!e)return;let t=I(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let n=Gt(i,"utf-8");return this.initializeSourceMap(n,t)}catch(n){throw new Error(`Failed to initialize SourceService: ${t}
3
3
  ${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return E(process.cwd())}getDistDir(){return E(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Xt(e,t);this.sourceMaps.set(t,i)}};ke=O(null),C=R(ke,0,"FrameworkService",Qe,C),P(ke,1,C);import{parseErrorStack as Ze}from"@remotex-labs/xmap/parser.component";import{highlightCode as Jt}from"@remotex-labs/xmap/highlighter.component";import{Bias as Yt}from"@remotex-labs/xmap";import{formatErrorCode as Qt}from"@remotex-labs/xmap/formatter.component";var Zt=/\s{2,}/g,er=/^https?:\/\//,tr=/^file:\/\//;function rr(r){return r instanceof Error?Ze(r):r.detail instanceof Error?Ze(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 ir(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(`
4
- `);return{getPositionWithCode:(s,a,c,l)=>{let f=l?.linesBefore??3,p=l?.linesAfter??3,g=Math.max(s-f,0),m=Math.min(s+p,o.length);return{line:s,column:a+1,code:o.slice(g,m).join(`
5
- `),source:e,name:null,startLine:g,endLine:m,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function nr(r){return Qt({...r,code:Jt(r.code)},{color:oe.brightPink})}function Oe(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?oe.gray(`[${r.line}:${r.column}]`):"";return`at ${r.functionName??""} ${oe.darkGray(e)} ${t}`.replace(Zt," ").trim()}function or(r,e){let{source:t,sourceRoot:i,line:n}=e;if(!t)return r.fileName?r.fileName.replace(tr,""):"";let o=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(o>0)return`${t.substring(o)}#L${n}`;if(er.test(t))return`${t}#L${n}`;if(i){let s=F(T(this.framework.distPath),h(this.framework.distPath,t));return`${i}${s}#L${n}`}return`${t}#L${n}`}function sr(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=nr(e)),Oe.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:or.call(this,r,e)})}function ar(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=ir.call(this,r);if(!t)return Oe.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,Yt.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,sr.call(this,r,i)):Oe.call(this,r)}function G(r,e,t=0){let i=u(b).getValue(a=>a.verbose)??!1,n={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:u(v),framework:u(C),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:rr(r).stack.map(a=>ar.call(n,a,e)).filter(Boolean),code:n.code,line:n.line??0,column:n.column??0,source:n.source,formatCode:n.formatCode}}function K(r,e,t,i=[]){let n=[`
4
+ `);return{getPositionWithCode:(s,a,l,c)=>{let f=c?.linesBefore??3,p=c?.linesAfter??3,g=Math.max(s-f,0),m=Math.min(s+p,o.length);return{line:s,column:a+1,code:o.slice(g,m).join(`
5
+ `),source:e,name:null,startLine:g,endLine:m,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function nr(r){return Qt({...r,code:Jt(r.code)},{color:oe.brightPink})}function Oe(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?oe.gray(`[${r.line}:${r.column}]`):"";return`at ${r.functionName??""} ${oe.darkGray(e)} ${t}`.replace(Zt," ").trim()}function or(r,e){let{source:t,sourceRoot:i,line:n}=e;if(!t)return r.fileName?r.fileName.replace(tr,""):"";let o=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(o>0)return`${t.substring(o)}#L${n}`;if(er.test(t))return`${t}#L${n}`;if(i){let s=F(T(this.framework.distPath),v(this.framework.distPath,t));return`${i}${s}#L${n}`}return`${t}#L${n}`}function sr(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=nr(e)),Oe.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:or.call(this,r,e)})}function ar(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=ir.call(this,r);if(!t)return Oe.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,Yt.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,sr.call(this,r,i)):Oe.call(this,r)}function K(r,e,t=0){let i=u(b).getValue(a=>a.verbose)??!1,n={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:u(y),framework:u(C),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:rr(r).stack.map(a=>ar.call(n,a,e)).filter(Boolean),code:n.code,line:n.line??0,column:n.column??0,source:n.source,formatCode:n.formatCode}}function G(r,e,t,i=[]){let n=[`
6
6
  ${e}: ${oe.lightCoral(t)}`];for(let o of i??[])o.text&&n.push(`
7
7
  `+oe.gray(o.text));return r.formatCode&&n.push(`
8
8
 
@@ -11,7 +11,7 @@ ${r.formatCode}`),r.stacks.length&&n.push(`
11
11
  Enhanced Stack Trace:
12
12
  ${r.stacks.join(`
13
13
  `)}
14
- `),n.join("")}var S=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=G(e,t),this.formattedStack=K(this.errorMetadata,e.name,e.message)}};var le=class extends S{constructor(e){super(e.text,"esBuildError"),this.errorMetadata=G(e,{withFrameworkFrames:!0}),this.stack=K(this.errorMetadata,this.name,this.message,e.notes)}};var X=class r extends S{constructor(t,i){if(t instanceof S)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(n=>new r(n,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,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:
14
+ `),n.join("")}var S=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=K(e,t),this.formattedStack=G(this.errorMetadata,e.name,e.message)}};var le=class extends S{constructor(e){super(e.text,"esBuildError"),this.errorMetadata=K(e,{withFrameworkFrames:!0}),this.stack=G(this.errorMetadata,this.name,this.message,e.notes)}};var X=class r extends S{constructor(t,i){if(t instanceof S)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(n=>new r(n,i))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,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:
15
15
  ${t}
16
16
  `}return this.formattedStack||this.stack}};function cr(r){return r instanceof S?r:r.detail instanceof S||r.detail instanceof W?r.detail:r.detail&&("errors"in r.detail||r.detail instanceof AggregateError)?new X(r.detail,{withFrameworkFrames:!0}):r.detail instanceof Error?new X(r.detail,{withFrameworkFrames:!0}):r.location?new le(r):new X(new Error(r.text))}function pe(r=[],e){for(let t of r)e.push(cr(t))}function Pe(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return pe(r.errors,e.errors),pe(r.warnings,e.warnings),e}function J(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as it from"http";import*as nt from"https";import{extname as tt}from"path";import{readFileSync as rt}from"fs";var et=`<!doctype html>
17
17
  <html lang="en">
@@ -331,27 +331,27 @@ ${t}
331
331
  });
332
332
  </script>
333
333
  </html>
334
- `;import{xterm as pr}from"@remotex-labs/xansi/xterm.component";function _(){return pr.lightCoral("[xBuild]")}import{readdir as fr,stat as ur,readFile as dr}from"fs/promises";import{xterm as fe}from"@remotex-labs/xansi/xterm.component";var Re=class{constructor(e,t){this.config=e;this.rootDir=I(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(C);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(_(),fe.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(_(),fe.dim("Server stopped.")),this.server=void 0}async restart(){console.log(_(),fe.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=it.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:rt(this.config.key??h(this.framework.distPath,"..","certs","server.key")),cert:rt(this.config.cert??h(this.framework.distPath,"..","certs","server.crt"))};this.server=nt.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(`${_()} Request ${fe.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=h(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await ur(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(_(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await fr(e)).map(l=>{let f=h(t,l),p=tt(l).slice(1)||"folder";return p==="folder"?`
334
+ `;import{xterm as pr}from"@remotex-labs/xansi/xterm.component";function _(){return pr.lightCoral("[xBuild]")}import{readdir as fr,stat as ur,readFile as dr}from"fs/promises";import{xterm as fe}from"@remotex-labs/xansi/xterm.component";var Re=class{constructor(e,t){this.config=e;this.rootDir=I(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(C);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(_(),fe.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(_(),fe.dim("Server stopped.")),this.server=void 0}async restart(){console.log(_(),fe.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=it.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:rt(this.config.key??v(this.framework.distPath,"..","certs","server.key")),cert:rt(this.config.cert??v(this.framework.distPath,"..","certs","server.crt"))};this.server=nt.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(`${_()} Request ${fe.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=v(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await ur(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(_(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await fr(e)).map(c=>{let f=v(t,c),p=tt(c).slice(1)||"folder";return p==="folder"?`
335
335
  <a href="/${f}" class="folder-row">
336
336
  <div class="icon"><i class="fa-solid fa-folder"></i></div>
337
- <div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div>
337
+ <div class="meta"><div class="name">${c}</div><div class="sub">Folder</div></div>
338
338
  </a>
339
339
  `:`
340
340
  <a href="/${f}" class="file-row">
341
341
  <div class="icon"><i class="fa-solid fa-file-code"></i></div>
342
- <div class="meta"><div class="name">${l}</div><div class="sub">${p}</div></div>
342
+ <div class="meta"><div class="name">${c}</div><div class="sub">${p}</div></div>
343
343
  </a>
344
- `}).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=et.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=tt(e).slice(1)||"txt",n=this.getContentType(i),o=await dr(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(_(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as ot}from"path";import{stat as mr,watch as gr}from"fs/promises";var Ae=class{excludes;include;debounceTimer=null;framework=u(C);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=gr(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=Xe(n);if(o.endsWith("~")||!this.include.some(a=>ot(o,a))||this.excludes.some(a=>ot(o,a)))continue;let s=h(this.framework.rootPath,o);try{if(!(await mr(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 M=class extends S{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{build as Ar}from"esbuild";import{writeFile as Mr,mkdir as Nr}from"fs/promises";import d from"typescript";import hr from"typescript";var vr=/^#!.*(\r?\n)?/,yr=/export {};\n?/g,xr=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,br=/^export\s+(?:default\s+)?/gm,Sr=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function wr(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(vr,""):r}function Cr(r){return r.includes("export {}")?r.replace(yr,""):r}function Ir(r){return r=r.replace(Sr,""),r.replace(xr,"$1")}function st(r){return r.replace(br,"")}function Er(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function ue(r){return Er(r)&&(r=wr(r),r=Cr(r),r=Ir(r)),r}function Me(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||T(r),s=i||T(r),c=F(s,r).replace(/\.tsx?$/,".d.ts"),l=hr.sys.resolvePath(`${o}/${c}`);return E(l)}var at,Ne;at=[A({scope:"singleton"})];var z=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(v);constructor(){this.printer=d.createPrinter({newLine:d.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(!d.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 d.canHaveModifiers(e)?d.getModifiers(e)?.some(i=>i.kind===d.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 d.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,d.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(d.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(d.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=d.factory.createNodeArray(n),s=this.printer.printList(d.ListFormat.MultiLine,o,e),a=st(ue(s));for(let c of i)if(c.includes(" as ")){let[l,f]=c.split(" as ");a=a.replace(new RegExp(`\\b${f}\\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:f}=n;if(!f)return;d.isNamespaceImport(f)?i.push(f.name.text):d.isNamedImports(f)&&this.addNamedElements(i,f.elements);return}if(!n){t.externalImports.namespace[a]="";return}n.name&&(t.externalImports.default[a]=n.name.text);let{namedBindings:l}=n;l&&(d.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:d.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(d.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}d.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(d.isVariableStatement(e)){for(let i of e.declarationList.declarations)d.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(d.isEnumDeclaration(e)||d.isClassDeclaration(e)||d.isFunctionDeclaration(e)||d.isInterfaceDeclaration(e)||d.isTypeAliasDeclaration(e))&&e.name&&d.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};Ne=O(null),z=R(Ne,0,"GraphModel",at,z),P(Ne,1,z);import V from"typescript";import{mkdir as Tr,writeFile as Fr}from"fs/promises";var ct=`/**
344
+ `}).join("");o?o=`<div class="list">${o}</div>`:o='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(c=>(s+=`${c}/`,`<li><a href="${s}">${c}</a></li>`)).join(""),l=et.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(l)}async handleFile(e,t){let i=tt(e).slice(1)||"txt",n=this.getContentType(i),o=await dr(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(_(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as ot}from"path";import{stat as mr,watch as gr}from"fs/promises";var Ae=class{excludes;include;debounceTimer=null;framework=u(C);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=gr(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=Xe(n);if(o.endsWith("~")||!this.include.some(a=>ot(o,a))||this.excludes.some(a=>ot(o,a)))continue;let s=v(this.framework.rootPath,o);try{if(!(await mr(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 M=class extends S{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{build as Ar}from"esbuild";import{writeFile as Mr,mkdir as Nr}from"fs/promises";import d from"typescript";import hr from"typescript";var vr=/^#!.*(\r?\n)?/,yr=/export {};\n?/g,xr=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,br=/^export\s+(?:default\s+)?/gm,Sr=/\s*\/\*\*[\s\S]*?\*\/\s*$/g;function wr(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(vr,""):r}function Cr(r){return r.includes("export {}")?r.replace(yr,""):r}function Ir(r){return r=r.replace(Sr,""),r.replace(xr,"$1")}function st(r){return r.replace(br,"")}function Er(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function ue(r){return Er(r)&&(r=wr(r),r=Cr(r),r=Ir(r)),r}function Me(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||T(r),s=i||T(r),l=F(s,r).replace(/\.tsx?$/,".d.ts"),c=hr.sys.resolvePath(`${o}/${l}`);return E(c)}var at,Ne;at=[A({scope:"singleton"})];var z=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(y);constructor(){this.printer=d.createPrinter({newLine:d.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),l=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,l,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(!d.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 d.canHaveModifiers(e)?d.getModifiers(e)?.some(i=>i.kind===d.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 d.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,d.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let l of e.statements){if(d.isImportDeclaration(l)){this.handleImport(l,t,i);continue}if(d.isExportDeclaration(l)){this.handleExport(l,t);continue}this.hasExportModifier(l)&&this.extractExportName(l,t),n.push(l)}let o=d.factory.createNodeArray(n),s=this.printer.printList(d.ListFormat.MultiLine,o,e),a=st(ue(s));for(let l of i)if(l.includes(" as ")){let[c,f]=l.split(" as ");a=a.replace(new RegExp(`\\b${f}\\b`,"g"),c)}else a=a.replace(new RegExp(`\\b${l}\\.`,"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:l}=s;if(!l){t.internalDeps.add(a);let{namedBindings:f}=n;if(!f)return;d.isNamespaceImport(f)?i.push(f.name.text):d.isNamedImports(f)&&this.addNamedElements(i,f.elements);return}if(!n){t.externalImports.namespace[a]="";return}n.name&&(t.externalImports.default[a]=n.name.text);let{namedBindings:c}=n;c&&(d.isNamespaceImport(c)?t.externalImports.namespace[c.name.text]=a:d.isNamedImports(c)&&this.addNamedElements(t.externalImports.named[a]??=[],c.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(d.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}d.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(d.isVariableStatement(e)){for(let i of e.declarationList.declarations)d.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(d.isEnumDeclaration(e)||d.isClassDeclaration(e)||d.isFunctionDeclaration(e)||d.isInterfaceDeclaration(e)||d.isTypeAliasDeclaration(e))&&e.name&&d.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};Ne=O(null),z=R(Ne,0,"GraphModel",at,z),P(Ne,1,z);import V from"typescript";import{mkdir as Tr,writeFile as Fr}from"fs/promises";var ct=`/**
345
345
  * This file was automatically generated by xBuild.
346
346
  * DO NOT EDIT MANUALLY.
347
347
  */
348
- `;var de=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(z);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=h(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}generateRandomName(e){let t="abcdefghijklmnopqrstuvwxyz",i;do i=Array.from({length:3},()=>t[Math.floor(Math.random()*t.length)]).join("");while(e.has(i));return e.add(i),i}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Tr(T(i),{recursive:!0}),await Fr(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 f=t.getSourceFile(l);if(!f)continue;let p=this.graphModel.scan(f,this.languageService,this.languageHostService);if(o.add(p),a.has(l)){n.add(p);for(let g of p.internalExports.star)a.add(g)}for(let g of p.internalDeps)i.has(g)||s.push(g);c+=p.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(`,
349
- `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[ct],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 f=Array.from(new Set(a)).sort();n.push(`export {
348
+ `;var de=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(z);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 l=v(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,l)}))}generateRandomName(e){let t="abcdefghijklmnopqrstuvwxyz",i;do i=Array.from({length:3},()=>t[Math.floor(Math.random()*t.length)]).join("");while(e.has(i));return e.add(i),i}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Tr(T(i),{recursive:!0}),await Fr(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),l="";for(;s.length>0;){let c=s.pop();if(i.has(c))continue;i.add(c);let f=t.getSourceFile(c);if(!f)continue;let p=this.graphModel.scan(f,this.languageService,this.languageHostService);if(o.add(p),a.has(c)){n.add(p);for(let g of p.internalExports.star)a.add(g)}for(let g of p.internalDeps)i.has(g)||s.push(g);l+=p.content}return l+=e.content,this.parseContent(l,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[l]of s)t.push(`import * as ${l} 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 l=this.collectNamespaceExports(a,t);l.exports.length>0&&(o.push(...l.declarations),o.push(`const ${s} = { ${l.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 l=this.collectNamespaceExports(a);l.exports.length>0&&(i.push(...l.declarations),i.push(`const ${s} = { ${l.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(`,
349
+ `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[ct],o=this.collectExternalImports(t),s=this.generateImportStatements(o);n.push(...s),s.length>0&&n.push("");let{exports:a,declarations:l,externalExports:c}=this.collectBundleExports(i);if(l.length>0&&(n.push(...l),n.push("")),n.push(e),a.length>0){let f=Array.from(new Set(a)).sort();n.push(`export {
350
350
  ${f.join(`,
351
351
  `)}
352
- };`)}return l.length>0&&n.push(...l),n.join(`
353
- `)}};import{mkdir as kr,writeFile as Or}from"fs/promises";import{xterm as Pr}from"@remotex-labs/xansi/xterm.component";var me=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Pr.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let n=[],o=t.getSourceFiles();for(let s=0;s<o.length;s++){let a=o[s];this.shouldEmitFile(a,t,i)&&n.push(a)}n.length!==0&&await Promise.all(n.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let n=Me(e.fileName,i),o=r.emittedVersions.get(n),s=this.languageHostService.getScriptVersion(e.fileName);return!o||o!==s?(r.emittedVersions.set(n,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let n=i.outputFiles[0].text,o=Me(e.fileName,t);n=ue(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await kr(T(o),{recursive:!0}),await Or(o,n,"utf8")}};import Y from"typescript";var ge=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Y.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=Y.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(v);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Y.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,n,o){return r.sys.readDirectory(e,t,i,n,o)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return Y.getDefaultLibFilePath(e)}getScriptVersion(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.version.toString():"0"}hasScriptSnapshot(e){return this.trackFiles.has(this.filesCache.resolve(e))}getScriptSnapshot(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.contentSnapshot:this.touchFile(e).contentSnapshot}resolveModuleName(e,t){return Y.resolveModuleName(e,t,this.compilerOptions,Y.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let n=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,n),n}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(n,o)=>{let s=this.resolveModuleFileName(o,t);if(!s)return n;let a=s.replace(/\.tsx?$/,i),c=F(t,a);return n.replace(o,c.startsWith(".")?c:"./"+c)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(n=>n.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var lt,je;lt=[A({providers:[{useValue:"tsconfig.json"}]})];var N=class N{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:n}=this.acquireLanguageService();this.config=t,this.languageService=n,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new me(n,i),this.bundlerService=new de(n,i)}config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(n=>t.getSourceFile(n)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(n=>this.shouldCheckFile(n)).flatMap(n=>this.collectDiagnostics(n)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=N.serviceCache.get(this.configPath);i.config=this.parseConfig(),i.host.options=i.config.options}}async emitBundle(e,t){await this.bundlerService.emit(e,t)}async emit(e){await this.emitterService.emit(e)}dispose(e){let t=N.serviceCache.get(e);t&&(t.refCount--,N.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=N.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new ge(e.options),i=V.createLanguageService(t,V.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return N.serviceCache.set(this.configPath,n),n}parseConfig(){let e=V.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...V.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:V.ScriptTarget.ESNext,module:V.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:V.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:V.flattenDiagnosticMessageText(e.messageText,`
354
- `)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};je=O(null),N=R(je,0,"TypescriptService",lt,N),P(je,1,N);var Q=N;import{cwd as De}from"process";import{build as pt}from"esbuild";var Rr={write:!1,bundle:!0,minify:!0,outdir:`${De()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function ft(r,e,t={}){return await pt({absWorkingDir:De(),...Rr,...t,stdin:{loader:"ts",contents:r,resolveDir:De(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function ut(r,e={}){try{return await pt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(J(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw pe(t.errors,i.errors),i}throw t}}function dt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Je(r,e)),t}else if(e&&typeof e=="object")return e;throw new M("Unsupported entry points format")}var he=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new M(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new Q(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(b);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ar(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(J(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?L({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new W("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Nr(e,{recursive:!0}),await Mr(h(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new M(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new M("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=dt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new Q(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await ut(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=F(this.typescriptModule.config.options.rootDir,I(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as jr}from"fs/promises";var ve=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(v);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=I(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await jr(s,"utf8");for(let c of this.loadHooks.values()){let l=await c({contents:i,loader:n,args:e,...t});l&&(l.contents!==void 0&&(i=l.contents),l.loader&&(n=l.loader),l.errors&&o.errors.push(...l.errors),l.warnings&&o.warnings.push(...l.warnings))}return{contents:i,loader:n,...o}}};import y from"typescript";import H from"typescript";var Dr="$$ifdef";function Br(r,e,t,i=!1){let n=i?"export function ":"function ";return H.isArrowFunction(e)||H.isFunctionExpression(e)?$r(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function $r(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Lr(e,t);return`${i}${r}(${n})${o} ${s}`}function Lr(r,e){let t=r.body.getText(e);return H.isArrowFunction(r)&&!H.isBlock(r.body)?`{ return ${t}; }`:t}function Vr(r,e){return H.isArrowFunction(r)||H.isFunctionExpression(r)?`(${r.getText(e)})()`:`(() => { return ${r.getText(e)}; })()`}function mt(r,e,t){let i=r in t&&!!t[r];return e===Dr===i}function gt(r,e,t,i){let[n,o]=e.arguments;if(!H.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!mt(a,s,i.defines))return"";let c=r.name.getText(i.sourceFile);return Br(c,o,i.sourceFile,t)}function ht(r,e,t){let[i,n]=r;if(!H.isStringLiteral(i))return!1;let o=i.text;return mt(o,e,t.defines)?Vr(n,t.sourceFile):""}import k from"typescript";import{createRequire as zr}from"module";var ye=class extends S{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=G(e,{},t),this.stack=K(this.errorMetadata,this.name,this.message)}};import{Script as Hr,createContext as _r}from"vm";async function vt(r,e={},t={}){let i=new Hr(r,t),n=_r(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function yt(r,e,t){let[i,n]=(await ft(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=zr(e.sourceFile.fileName),a=await vt(n.text,Ur(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){qr(o,e,i.text,t)}return"undefined"}function Ur(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:T(r),__filename:r}}function qr(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(C).setSource(t,e.sourceFile.fileName);let s=new ye(r,o);e.errors.push({text:s.message,detail:s})}function Wr(r,e){let t=null,i=n=>{if(!t){if(k.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}k.isVariableStatement(n)&&(t=Gr(n,r),t)||k.forEachChild(n,i)}};return i(e),t}function Gr(r,e){for(let t of r.declarationList.declarations)if(k.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(k.isArrowFunction(t.initializer)||k.isFunctionExpression(t.initializer)))return t.initializer;return null}function xt(r){return`module.exports = (${r})();`}function Kr(r){return r&k.NodeFlags.Const?"const":r&k.NodeFlags.Let?"let":"var"}function bt(r,e){return r?k.isIdentifier(r)?Xr(r,e):k.isArrowFunction(r)||k.isFunctionExpression(r)?{node:r,data:xt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xr(r,e){let t=Wr(r.text,e.sourceFile);return t?{node:t,data:xt(t.getText(e.sourceFile))}:(Jr(r.text,e,r),{data:"",node:r})}function Jr(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=F(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function St(r,e,t,i,n){let o=t.arguments[0],s=bt(o,n);if(!s)return!1;let a=await yt(s.data,n,s.node),c=Kr(e.declarationList.flags),l=i?"export ":"",f=r.name.getText(n.sourceFile);return`${l}${c} ${f} = ${a};`}async function Be(r,e){let t=r[0],i=bt(t,e);return i?yt(i.data,e,i.node):!1}var Yr=/\.(ts|js)$/,D=["$$ifdef","$$ifndef","$$inline"];async function Qr(r,e,t){for(let i of r.declarationList.declarations){let n=i.initializer;if(!n||!y.isCallExpression(n)||!y.isIdentifier(n.expression))continue;let o=n.expression.text;if(!D.includes(o))continue;let s=o==D[2]?1:2;if(!D.includes(o))return;if(n.arguments.length<s||n.arguments.length>s)throw new Error(`Invalid macro call: ${o} with ${n.arguments.length} arguments`);let a=r.modifiers?.some(l=>l.kind===y.SyntaxKind.ExportKeyword)??!1,c=!1;o===D[2]?c=await St(i,r,n,a,t):c=gt(i,n,a,t),c!==!1&&e.add({replacement:c,end:r.getEnd(),start:r.getStart(t.sourceFile)})}}async function Zr(r,e,t){let i=r.expression;if(!y.isIdentifier(i.expression))return;let n=i.expression.text,o=n==D[2]?1:2;if(!D.includes(n))return;if(i.arguments.length<o||i.arguments.length>o)throw new Error(`Invalid macro call: ${n} with ${i.arguments.length} arguments`);let s=!1;n==D[2]?s=await Be(i.arguments,t):s=ht(i.arguments,n,t),s!==!1&&e.add({replacement:s,end:r.getEnd(),start:r.getStart(t.sourceFile)})}async function ei(r){let e=new Set,t=r.stage.defineMetadata.disabledMacroNames,i=async o=>{if(y.isVariableStatement(o))await Qr(o,e,r);else if(y.isExpressionStatement(o)&&y.isCallExpression(o.expression))await Zr(o,e,r);else if(y.isCallExpression(o)&&y.isIdentifier(o.expression)&&o.expression.text===D[2]){let a=o.parent;if(!a||!y.isVariableDeclaration(a)&&!y.isExpressionStatement(a)){let c=await Be(o.arguments,r);c!==!1&&e.add({replacement:c,end:o.getEnd(),start:o.getStart(r.sourceFile)})}}else if(y.isCallExpression(o)&&y.isIdentifier(o.expression)&&t.has(o.expression.text))e.add({start:o.getStart(r.sourceFile),end:o.getEnd(),replacement:"undefined"});else if(y.isIdentifier(o)&&t.has(o.text)){let a=o.parent,c=a?.getText(r.sourceFile);(!a||!y.isCallExpression(a)||a.expression!==o)&&(!c||D.every(l=>!c.includes(l)))&&e.add({start:o.getStart(r.sourceFile),end:o.getEnd(),replacement:"undefined"})}let s=o.getChildren(r.sourceFile);for(let a of s)await i(a)};if(await i(r.sourceFile),e.size===0)return r.contents;let n=Array.from(e);n.sort((o,s)=>s.start-o.start);for(let{start:o,end:s,replacement:a}of n)r.contents=r.contents.slice(0,o)+a+r.contents.slice(s);return r.contents}async function wt(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Yr.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let c=o.toString(),l={stage:n,errors:[],contents:c,warnings:[],defines:r.config.define??{},sourceFile:a};return a&&(c=await ei(l)),r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(c=r.typescript.languageHostService.resolveAliases(c,t.path,".js")),{loader:i,contents:c,warnings:l.warnings,errors:l.errors}}var Ct="$$",It=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef)\s*\(\s*['"]([^'"]+)['"]/g;function ti(r,e,t,i){let n=1;for(let o=0;o<i;o++)r[o]===`
352
+ };`)}return c.length>0&&n.push(...c),n.join(`
353
+ `)}};import{mkdir as kr,writeFile as Or}from"fs/promises";import{xterm as Pr}from"@remotex-labs/xansi/xterm.component";var me=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Pr.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let n=[],o=t.getSourceFiles();for(let s=0;s<o.length;s++){let a=o[s];this.shouldEmitFile(a,t,i)&&n.push(a)}n.length!==0&&await Promise.all(n.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let n=Me(e.fileName,i),o=r.emittedVersions.get(n),s=this.languageHostService.getScriptVersion(e.fileName);return!o||o!==s?(r.emittedVersions.set(n,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let n=i.outputFiles[0].text,o=Me(e.fileName,t);n=ue(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await kr(T(o),{recursive:!0}),await Or(o,n,"utf8")}};import Y from"typescript";var ge=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Y.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=Y.sys;alias;aliasCache=new Map;moduleResolutionCache;trackFiles=new Set;filesCache=u(y);get aliasRegex(){return this.alias}set options(e){this.compilerOptions=e,this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=Y.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,n,o){return r.sys.readDirectory(e,t,i,n,o)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return Y.getDefaultLibFilePath(e)}getScriptVersion(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.version.toString():"0"}hasScriptSnapshot(e){return this.trackFiles.has(this.filesCache.resolve(e))}getScriptSnapshot(e){let t=this.filesCache.getSnapshot(e);return this.trackFiles.add(this.filesCache.resolve(e)),t?t.contentSnapshot:this.touchFile(e).contentSnapshot}resolveModuleName(e,t){return Y.resolveModuleName(e,t,this.compilerOptions,Y.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let n=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,n),n}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(n,o)=>{let s=this.resolveModuleFileName(o,t);if(!s)return n;let a=s.replace(/\.tsx?$/,i),l=F(t,a);return n.replace(o,l.startsWith(".")?l:"./"+l)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(n=>n.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var lt,je;lt=[A({providers:[{useValue:"tsconfig.json"}]})];var N=class N{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:n}=this.acquireLanguageService();this.config=t,this.languageService=n,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new me(n,i),this.bundlerService=new de(n,i)}config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(n=>t.getSourceFile(n)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(n=>this.shouldCheckFile(n)).flatMap(n=>this.collectDiagnostics(n)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=N.serviceCache.get(this.configPath);i.config=this.parseConfig(),i.host.options=i.config.options}}async emitBundle(e,t){await this.bundlerService.emit(e,t)}async emit(e){await this.emitterService.emit(e)}dispose(e){let t=N.serviceCache.get(e);t&&(t.refCount--,N.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){return e&&!e.fileName.includes("node_modules")&&!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=N.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new ge(e.options),i=V.createLanguageService(t,V.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return N.serviceCache.set(this.configPath,n),n}parseConfig(){let e=V.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...V.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:V.ScriptTarget.ESNext,module:V.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:V.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:V.flattenDiagnosticMessageText(e.messageText,`
354
+ `)};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};je=O(null),N=R(je,0,"TypescriptService",lt,N),P(je,1,N);var Q=N;import{cwd as De}from"process";import{build as pt}from"esbuild";var Rr={write:!1,bundle:!0,minify:!0,outdir:`${De()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function ft(r,e,t={}){return await pt({absWorkingDir:De(),...Rr,...t,stdin:{loader:"ts",contents:r,resolveDir:De(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function ut(r,e={}){try{return await pt({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(J(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw pe(t.errors,i.errors),i}throw t}}function dt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=Je(r,e)),t}else if(e&&typeof e=="object")return e;throw new M("Unsupported entry points format")}var he=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new M(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new Q(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.typescriptModule.languageHostService.touchFiles(Object.values(this.buildConfig.esbuild.entryPoints)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(o=>({variantConfig:o.variants?.[this.name],commonConfig:o.common})).subscribe(this.handleConfigChange.bind(this),o=>{throw o})}dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(b);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(this.active){this.applyInjections(),this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&(this.buildConfig.esbuild.entryPoints=this.dependenciesFile);try{let e=await Ar(this.buildConfig.esbuild);return await this.packageTypeComponent(),e}catch(e){if(J(e)){if(e.errors.filter(i=>i.pluginName==="").length>0)throw e;return{errors:e.errors,warnings:e.warnings}}throw e}}}getConfig(e,t={}){return e?L({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;let i=new W("Type checking failed",t);return typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError?e.warnings?.push({detail:i,location:void 0}):e.errors?.push({detail:i,location:void 0}),e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,n=typeof i=="object"?i.bundle!==!1:!0,o=typeof i=="object"?i.outDir:void 0;try{n?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,o):await this.typescriptModule.emit(o)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:n,onEnd:o,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),n&&this.lifecycle.onLoad(n),o&&this.lifecycle.onEnd(o),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await Nr(e,{recursive:!0}),await Mr(v(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new M(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new M("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.tsconfig??="tsconfig.json",e.esbuild.entryPoints=dt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new Q(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,{metafile:t}=await ut(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=F(this.typescriptModule.config.options.rootDir,I(n)),s=this.stripExtension(o);i[s]=n}return i}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[n,o]of Object.entries(t))i[e][n]=typeof o=="function"?o(this.name,this.argv):o}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as jr}from"fs/promises";var ve=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=u(y);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(async()=>this.executeStartHooks(e,t)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(async i=>this.executeEndHooks(i,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},async i=>this.executeResolveHooks(i,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},async i=>this.executeLoadHooks(i,t))}}}async executeStartHooks(e,t){t.stage.startTime=new Date;let i={errors:[],warnings:[]};for(let n of this.startHooks.values()){let o=await n({build:e,...t});o&&(o.errors&&i.errors.push(...o.errors),o.warnings&&i.warnings.push(...o.warnings))}return i}async executeEndHooks(e,t){let i={errors:[],warnings:[]},n=Date.now()-t.stage.startTime.getTime();for(let o of this.endHooks.values()){let s=await o({buildResult:e,duration:n,...t});s&&(s.errors&&i.errors.push(...s.errors),s.warnings&&i.warnings.push(...s.warnings))}if(e.errors.length===0)for(let o of this.successHooks.values())await o({buildResult:e,duration:n,...t});return i}async executeResolveHooks(e,t){let i;for(let n of this.resolveHooks.values()){let o=await n({args:e,...t});o&&(i?i={...i,...o}:i=o)}return i??null}async executeLoadHooks(e,t){let i,n="default",o={errors:[],warnings:[]},s=I(e.path),a=this.filesModel.getSnapshot(s);a&&a.contentSnapshot?i=a.contentSnapshot.text:i=await jr(s,"utf8");for(let l of this.loadHooks.values()){let c=await l({contents:i,loader:n,args:e,...t});c&&(c.contents!==void 0&&(i=c.contents),c.loader&&(n=c.loader),c.errors&&o.errors.push(...c.errors),c.warnings&&o.warnings.push(...c.warnings))}return{contents:i,loader:n,...o}}};import h from"typescript";import H from"typescript";var Dr="$$ifdef";function Br(r,e,t,i=!1){let n=i?"export function ":"function ";return H.isArrowFunction(e)||H.isFunctionExpression(e)?$r(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function $r(r,e,t,i){let n=e.parameters.map(a=>a.getText(t)).join(", "),o=e.type?`: ${e.type.getText(t)}`:"",s=Lr(e,t);return`${i}${r}(${n})${o} ${s}`}function Lr(r,e){let t=r.body.getText(e);return H.isArrowFunction(r)&&!H.isBlock(r.body)?`{ return ${t}; }`:t}function Vr(r,e){return H.isArrowFunction(r)||H.isFunctionExpression(r)?`(${r.getText(e)})()`:`(() => { return ${r.getText(e)}; })()`}function mt(r,e,t){let i=r in t&&!!t[r];return e===Dr===i}function gt(r,e,t,i){let[n,o]=e.arguments;if(!H.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!mt(a,s,i.defines))return"";let l=r.name.getText(i.sourceFile);return Br(l,o,i.sourceFile,t)}function ht(r,e,t){let[i,n]=r;if(!H.isStringLiteral(i))return!1;let o=i.text;return mt(o,e,t.defines)?Vr(n,t.sourceFile):""}import k from"typescript";import{createRequire as zr}from"module";var ye=class extends S{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=K(e,{},t),this.stack=G(this.errorMetadata,this.name,this.message)}};import{Script as Hr,createContext as _r}from"vm";async function vt(r,e={},t={}){let i=new Hr(r,t),n=_r(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function yt(r,e,t){let[i,n]=(await ft(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=zr(e.sourceFile.fileName),a=await vt(n.text,Ur(e.sourceFile.fileName,o,s),{filename:e.sourceFile.fileName});if(a==null)return"undefined";if(typeof a=="string")return JSON.stringify(a);if(typeof a=="number"||typeof a=="boolean")return String(a)}catch(o){qr(o,e,i.text,t)}return"undefined"}function Ur(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:T(r),__filename:r}}function qr(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let n=i.getStart(e.sourceFile),{line:o}=e.sourceFile.getLineAndCharacterOfPosition(n);u(C).setSource(t,e.sourceFile.fileName);let s=new ye(r,o);e.errors.push({text:s.message,detail:s})}function Wr(r,e){let t=null,i=n=>{if(!t){if(k.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}k.isVariableStatement(n)&&(t=Kr(n,r),t)||k.forEachChild(n,i)}};return i(e),t}function Kr(r,e){for(let t of r.declarationList.declarations)if(k.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(k.isArrowFunction(t.initializer)||k.isFunctionExpression(t.initializer)))return t.initializer;return null}function xt(r){return`module.exports = (${r})();`}function Gr(r){return r&k.NodeFlags.Const?"const":r&k.NodeFlags.Let?"let":"var"}function bt(r,e){return r?k.isIdentifier(r)?Xr(r,e):k.isArrowFunction(r)||k.isFunctionExpression(r)?{node:r,data:xt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function Xr(r,e){let t=Wr(r.text,e.sourceFile);return t?{node:t,data:xt(t.getText(e.sourceFile))}:(Jr(r.text,e,r),{data:"",node:r})}function Jr(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=F(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:n+1,column:o,file:e.sourceFile.fileName,lineText:"asd"}})}async function St(r,e,t,i,n){let o=t.arguments[0],s=bt(o,n);if(!s)return!1;let a=await yt(s.data,n,s.node),l=Gr(e.declarationList.flags),c=i?"export ":"",f=r.name.getText(n.sourceFile);return`${c}${l} ${f} = ${a};`}async function Be(r,e){let t=r[0],i=bt(t,e);return i?yt(i.data,e,i.node):!1}var Yr=/\.(ts|js)$/,D=["$$ifdef","$$ifndef","$$inline"];async function Qr(r,e,t){for(let i of r.declarationList.declarations){let n=i.initializer;if(!n||!h.isCallExpression(n)||!h.isIdentifier(n.expression))continue;let o=n.expression.text;if(!D.includes(o))continue;let s=o==D[2]?1:2;if(!D.includes(o))continue;if(n.arguments.length<s||n.arguments.length>s)throw new Error(`Invalid macro call: ${o} with ${n.arguments.length} arguments`);let a=r.modifiers?.some(c=>c.kind===h.SyntaxKind.ExportKeyword)??!1,l=!1;o===D[2]?l=await St(i,r,n,a,t):l=gt(i,n,a,t),l!==!1&&e.add({replacement:l,end:r.getEnd(),start:r.getStart(t.sourceFile)})}}async function Zr(r,e,t){let i=r.expression;if(!h.isIdentifier(i.expression))return;let n=i.expression.text,o=n==D[2]?1:2;if(!D.includes(n))return;if(i.arguments.length<o||i.arguments.length>o)throw new Error(`Invalid macro call: ${n} with ${i.arguments.length} arguments`);let s=!1;n==D[2]?s=await Be(i.arguments,t):s=ht(i.arguments,n,t),s!==!1&&e.add({replacement:s,end:r.getEnd(),start:r.getStart(t.sourceFile)})}async function ei(r){let e=new Set,t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let n=[r.sourceFile];for(;n.length>0;){let s=n.pop(),a=s?.kind;if(!a)continue;if(t.size>0){if(a===h.SyntaxKind.CallExpression){let c=s;h.isIdentifier(c.expression)&&t.has(c.expression.text)&&e.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}else if(a===h.SyntaxKind.Identifier){let c=s;if(t.has(c.text)){let f=s.parent??s;if(f&&!h.isImportSpecifier(f)&&!h.isExportSpecifier(f)){let p=f?.getText(r.sourceFile);(!h.isCallExpression(f)||f.expression!==s)&&(!p||D.every(g=>!p.includes(g)))&&e.add({start:s.getStart(r.sourceFile),end:s.getEnd(),replacement:"undefined"})}}}}if(i){if(a===h.SyntaxKind.VariableStatement)await Qr(s,e,r);else if(a===h.SyntaxKind.ExpressionStatement){let c=s;h.isCallExpression(c.expression)&&await Zr(c,e,r)}else if(a===h.SyntaxKind.CallExpression){let c=s;if(h.isIdentifier(c.expression)&&c.expression.text===D[2]){let f=s.parent;if(!f||!h.isVariableDeclaration(f)&&!h.isExpressionStatement(f)){let p=await Be(c.arguments,r);p!==!1&&e.add({replacement:p,end:s.getEnd(),start:s.getStart(r.sourceFile)})}}}}let l=s.getChildren(r.sourceFile);for(let c=l.length-1;c>=0;c--)n.push(l[c])}if(e.size===0)return r.contents;let o=Array.from(e);o.sort((s,a)=>a.start-s.start);for(let{start:s,end:a,replacement:l}of o)r.contents=r.contents.slice(0,s)+l+r.contents.slice(a);return r.contents}async function wt(r,e){let{args:t,loader:i,stage:n,contents:o}=e;if(t.path.includes("node_modules")||o.length<1||!Yr.test(t.path))return;let a=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!a)return;let l=o.toString(),c={stage:n,errors:[],contents:l,warnings:[],defines:r.config.define??{},sourceFile:a};return a&&(l=await ei(c)),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 Ct="$$",It=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*['"]([^'"]+)['"]/g;function ti(r,e,t,i){let n=1;for(let o=0;o<i;o++)r[o]===`
355
355
  `&&n++;return{file:t,line:n,column:r.indexOf(e,i)-i}}function ri(r,e){let t=r.lastIndexOf(`
356
- `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function Et(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(v),o=r.config.define??{},s=Object.keys(r.dependencies);if(!s)return Promise.resolve({warnings:i});for(let a of s){let l=n.getOrTouchFile(a)?.contentSnapshot?.text;if(l){It.lastIndex=0;for(let f of l.matchAll(It)){if(ri(l,f.index))continue;t.filesWithMacros.add(n.resolve(a));let[,p,g,m]=f;if(!p)continue;let B=m in o&&!!o[m];g==="ifndef"===B&&t.disabledMacroNames.add(p),p.startsWith(Ct)||i.push({text:`Macro function '${p}' not start with '${Ct}' prefix to avoid conflicts`,location:ti(l,p,a,f.index)})}}}return{warnings:i}}var $e=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(b);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=Pe(a))}catch(a){if(J(a)||a instanceof AggregateError){let c=Pe({errors:a.errors});t.push(...c.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await Et(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new M("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new ve(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new he(e,t,this.config.variants[e],this.argv),t.onLoad(wt.bind({},this.variants[e]),"build-service")}}};function Rs(r){u(b).reload(r)}function As(r){u(b).patch(r)}export{$e as BuildService,Re as ServerModule,Ae as WatchService,Je as collectFilesFromGlob,Pe as enhancedBuildResult,J as isBuildResultError,Ut as isDirectoryExcluded,ce as matchesAny,cr as normalizeMessageToError,Rs as overwriteConfig,zt as parseGlobs,As as patchConfig,pe as processEsbuildMessages,Ai as shouldIncludeFile};
356
+ `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],n=r[t+1];return i==="/"&&(n==="/"||n==="*")||i==="*"}async function Et(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=u(y),o=r.config.define??{},s=Object.values(r.dependencies??{});if(!s)return Promise.resolve({warnings:i});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(c){It.lastIndex=0;for(let f of c.matchAll(It)){if(ri(c,f.index))continue;t.filesWithMacros.add(n.resolve(a));let[,p,g,m]=f;if(!p)continue;let B=m in o&&!!o[m];g==="ifndef"===B&&t.disabledMacroNames.add(p),p.startsWith(Ct)||i.push({text:`Macro function '${p}' not start with '${Ct}' prefix to avoid conflicts`,location:ti(c,p,a,f.index)})}}}return{warnings:i}}var $e=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(b);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload(e){e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=Pe(a))}catch(a){if(J(a)||a instanceof AggregateError){let l=Pe({errors:a.errors});t.push(...l.errors)}else a instanceof Error?t.push(a):t.push(new Error(String(a)))}});if(await Promise.allSettled(n),t.length)throw new AggregateError(t,"Build failed");return i}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await Et(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let n of t.errors)i.push({detail:n,text:n.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(o=>!(o in e))]}parseVariants(){if(!this.config.variants)throw new M("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new ve(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new he(e,t,this.config.variants[e],this.argv),t.onLoad(wt.bind({},this.variants[e]),"build-service")}}};function Rs(r){u(b).reload(r)}function As(r){u(b).patch(r)}export{$e as BuildService,Re as ServerModule,Ae as WatchService,Je as collectFilesFromGlob,Pe as enhancedBuildResult,J as isBuildResultError,Ut as isDirectoryExcluded,ce as matchesAny,cr as normalizeMessageToError,Rs as overwriteConfig,zt as parseGlobs,As as patchConfig,pe as processEsbuildMessages,Ai as shouldIncludeFile};
357
357
  //# sourceMappingURL=index.js.map