@remotex-labs/xbuild 2.2.3 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- var Ot=Object.create;var Se=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var ze=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),te=r=>{throw TypeError(r)};var At=(r,e,t)=>e in r?Se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var He=(r,e)=>Se(r,"name",{value:e,configurable:!0});var A=r=>[,,,Ot(r?.[ze("metadata")]??null)],Ue=["class","method","getter","setter","accessor","field","value","get","set"],ee=r=>r!==void 0&&typeof r!="function"?te("Function expected"):r,Rt=(r,e,t,i,n)=>({kind:Ue[r],name:e,metadata:i,addInitializer:o=>t._?te("Already initialized"):n.push(ee(o||null))}),Mt=(r,e)=>At(e,ze("metadata"),r[3]),R=(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},M=(r,e,t,i,n,o)=>{var s,a,c,l,f,p=e&7,u=!!(e&8),g=!!(e&16),P=p>3?r.length+1:p?u?1:2:0,B=Ue[p+5],$=p>3&&(r[P-1]=[]),xe=r[P]||(r[P]=[]),b=p&&(!g&&!u&&(n=n.prototype),p<5&&(p>3||!g)&&Pt(p<4?n:{get[t](){return Ve(this,o)},set[t](w){return _e(this,o,w)}},t));p?g&&p<4&&He(o,(p>2?"set ":p>1?"get ":"")+t):He(n,t);for(var Z=i.length-1;Z>=0;Z--)l=Rt(p,t,c={},r[3],xe),p&&(l.static=u,l.private=g,f=l.access={has:g?w=>Nt(n,w):w=>t in w},p^3&&(f.get=g?w=>(p^1?Ve:Dt)(w,n,p^4?o:b.get):w=>w[t]),p>2&&(f.set=g?(w,be)=>_e(w,n,be,p^4?o:b.set):(w,be)=>w[t]=be)),a=(0,i[Z])(p?p<4?g?o:b[B]:p>4?void 0:{get:b.get,set:b.set}:n,l),c._=1,p^4||a===void 0?ee(a)&&(p>4?$.unshift(a):p?g?o=a:b[B]=a:n=a):typeof a!="object"||a===null?te("Object expected"):(ee(s=a.get)&&(b.get=s),ee(s=a.set)&&(b.set=s),ee(s=a.init)&&$.unshift(s));return p||Mt(r,n),b&&Se(n,t,b),g?p^4?o:b:n};var we=(r,e,t)=>e.has(r)||te("Cannot "+t),Nt=(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 _e=(r,e,t,i)=>(we(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),Dt=(r,e,t)=>(we(r,e,"access private method"),t);var Ce=new Map,Ke=new Map;function jt(r){return typeof r=="object"&&r!==null&&"useClass"in r}function $t(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Bt(r){return typeof r=="object"&&r!==null&&"useValue"in r}function N(r){return function(e){Ke.set(e,r||{})}}function Ie(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(jt(i))t.push(d(i.useClass,...Ie(i.providers)));else if($t(i))t.push(i.useFactory(...Ie(i.providers)));else if(Bt(i))t.push(i.useValue);else if(typeof i=="function")t.push(d(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function d(r,...e){if(Ce.has(r))return Ce.get(r);let t=Ke.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 We(r){return e=>new L(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 qe(r=(e,t)=>e===t){return e=>new L(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 L=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 L{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 H(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]:H(se(o)?o:{},n)}):Object.assign(r,{[i]:n})}return H(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"?Ht(r,e,t):!1}function Lt(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function Ht(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(!Lt(e,o)||!ae(r[o],e[o],t))return!1;return!0}var 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",absWorkingDir:process.cwd()})})});var Xe,Ee;Xe=[N({scope:"singleton"})];var S=class{constructor(e=Ge){this.initialConfig=e;this.config$=new ie(H({},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(We(e),qe((t,i)=>ae(t,i)))}patch(e){let t=H({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(H({},this.initialConfig,e))}};Ee=A(null),S=M(Ee,0,"ConfigurationService",Xe,S),R(Ee,1,S);import{cwd as zt}from"process";import{readdirSync as Ut}from"fs";import{matchesGlob as Te}from"path";import*as ne from"path";import*as q from"path/posix";var Vt=/\\/g,_t=/\/+/g;function T(r){if(!r)return"";let e=String(r);return e=e.replace(Vt,"/"),e=e.replace(_t,"/"),e}function Je(r){return q.normalize(T(r))}function y(...r){return q.join(...r.map(T))}function I(...r){return T(ne.resolve(...r))}function v(r){return T(ne.dirname(r))}function F(r,e){return q.relative(T(r),T(e))||"."}function Kt(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(t.endsWith(r)||Te(r,t))return!0;return!1}function Wt(r,e){let t=r+"/**";for(let i of e)if(Te(r,i)||Te(t,i))return!0;return!1}function Bi(r,e,t){return ce(r,e)?!ce(r,t):!1}function Ye(r,e){let{include:t,exclude:i}=Kt(e),n=Object.create(null),s=zt().length+1,a=r.length+1,c=i.length>0;function l(f){let p;try{p=Ut(f,{withFileTypes:!0})}catch{return}let u=p.length;for(let g=0;g<u;g++){let P=p[g],B=y(f,P.name),$=B.slice(a);if(P.isDirectory()){(!c||!Wt($,i))&&l(B);continue}if(!(c&&ce($,i))&&ce($,t)){let xe=B.slice(s),b=$.lastIndexOf("."),Z=b>0?$.slice(0,b):$;n[Z]=xe}}}return l(r),n}var V=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{closeSync as Gt,fstatSync as Xt,openSync as Jt,readFileSync as Yt}from"fs";var Qe,Fe;Qe=[N({scope:"singleton"})];var x=class{resolvedPathCache=new Map;snapshotsByPath=new Map;clear(){this.snapshotsByPath.clear(),this.resolvedPathCache.clear()}getSnapshot(e){return this.snapshotsByPath.get(this.resolve(e))}getOrTouchFile(e){return this.snapshotsByPath.get(this.resolve(e))??this.touchFile(e)}getTrackedFilePaths(){return[...this.snapshotsByPath.keys()]}touchFile(e){let t=this.resolve(e),i=this.snapshotsByPath.get(t)??this.createEntry(t);try{this.syncEntry(t,i)}catch{(i.contentSnapshot!==void 0||i.version>0)&&(i.version++,i.mtimeMs=0,i.contentSnapshot=void 0)}return{...i}}resolve(e){let t=this.resolvedPathCache.get(e);if(t)return t;let i=I(e);return this.resolvedPathCache.set(e,i),i}createEntry(e){let t={version:0,mtimeMs:0,contentSnapshot:void 0};return this.snapshotsByPath.set(e,t),t}syncEntry(e,t){let i=Jt(e,"r");try{let{mtimeMs:n}=Xt(i);if(n===t.mtimeMs)return;let o=Yt(i,"utf-8");t.version++,t.mtimeMs=n,t.contentSnapshot=o?qt.ScriptSnapshot.fromString(o):void 0}finally{Gt(i)}}};Fe=A(null),x=M(Fe,0,"FilesModel",Qe,x),R(Fe,1,x);import{readFileSync as Qt}from"fs";import{SourceService as Zt}from"@remotex-labs/xmap";var Ze,ke;Ze=[N({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=Qt(i,"utf-8");return this.initializeSourceMap(n,t)}catch(n){throw new Error(`Failed to initialize SourceService: ${t}
3
- ${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return T(process.cwd())}getDistDir(){return T(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Zt(e,t);this.sourceMaps.set(t,i)}};ke=A(null),C=M(ke,0,"FrameworkService",Ze,C),R(ke,1,C);import{parseErrorStack as et}from"@remotex-labs/xmap/parser.component";import{highlightCode as er}from"@remotex-labs/xmap/highlighter.component";import{Bias as tr}from"@remotex-labs/xmap";import{formatErrorCode as rr}from"@remotex-labs/xmap/formatter.component";var ir=/\s{2,}/g,nr=/^https?:\/\//,or=/^file:\/\//;function sr(r){return r instanceof Error?et(r):r.detail instanceof Error?et(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 ar(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,u=Math.max(s-f,0),g=Math.min(s+p,o.length);return{line:s,column:a+1,code:o.slice(u,g).join(`
5
- `),source:e,name:null,startLine:u,endLine:g,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function cr(r){return rr({...r,code:er(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(ir," ").trim()}function lr(r,e){let{source:t,sourceRoot:i,line:n}=e;if(!t)return r.fileName?r.fileName.replace(or,""):"";let o=Math.max(t.lastIndexOf("http://"),t.lastIndexOf("https://"));if(o>0)return`${t.substring(o)}#L${n}`;if(nr.test(t))return`${t}#L${n}`;if(i){let s=F(v(this.framework.distPath),y(this.framework.distPath,t));return`${i}${s}#L${n}`}return`${t}#L${n}`}function pr(r,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=cr(e)),Oe.call(this,{...r,line:e.line,column:e.column,functionName:e.name??r.functionName,fileName:lr.call(this,r,e)})}function fr(r,e){if(!this.withNativeFrames&&r.native||!r.line&&!r.column&&!r.fileName&&!r.functionName)return"";let t=ar.call(this,r);if(!t)return Oe.call(this,r);let i=t.getPositionWithCode(r.line??0,r.column??0,tr.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,pr.call(this,r,i)):Oe.call(this,r)}function G(r,e,t=0){let i=d(S).getValue(a=>a.verbose)??!1,n={code:"",line:0,column:0,source:"",formatCode:"",lineOffset:t,files:d(x),framework:d(C),withNativeFrames:i,withFrameworkFrames:i,...e};return{stacks:sr(r).stack.map(a=>fr.call(n,a,e)).filter(Boolean),code:n.code,line:n.line??0,column:n.column??0,source:n.source,formatCode:n.formatCode}}function X(r,e,t,i=[]){let n=[`
6
- ${e}: ${oe.lightCoral(t)}`];for(let o of i??[])o.text&&n.push(`
7
- `+oe.gray(o.text));return r.formatCode&&n.push(`
1
+ var It=Object.create;var me=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var Be=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),J=r=>{throw TypeError(r)};var Ft=(r,e,t)=>e in r?me(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ne=(r,e)=>me(r,"name",{value:e,configurable:!0});var T=r=>[,,,It(r?.[Be("metadata")]??null)],$e=["class","method","getter","setter","accessor","field","value","get","set"],X=r=>r!==void 0&&typeof r!="function"?J("Function expected"):r,Ot=(r,e,t,i,n)=>({kind:$e[r],name:e,metadata:i,addInitializer:o=>t._?J("Already initialized"):n.push(X(o||null))}),kt=(r,e)=>Ft(e,Be("metadata"),r[3]),F=(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},O=(r,e,t,i,n,o)=>{var s,a,c,l,f,p=e&7,d=!!(e&8),g=!!(e&16),I=p>3?r.length+1:p?d?1:2:0,A=$e[p+5],R=p>3&&(r[I-1]=[]),ue=r[I]||(r[I]=[]),y=p&&(!g&&!d&&(n=n.prototype),p<5&&(p>3||!g)&&Tt(p<4?n:{get[t](){return De(this,o)},set[t](S){return je(this,o,S)}},t));p?g&&p<4&&Ne(o,(p>2?"set ":p>1?"get ":"")+t):Ne(n,t);for(var G=i.length-1;G>=0;G--)l=Ot(p,t,c={},r[3],ue),p&&(l.static=d,l.private=g,f=l.access={has:g?S=>Pt(n,S):S=>t in S},p^3&&(f.get=g?S=>(p^1?De:Mt)(S,n,p^4?o:y.get):S=>S[t]),p>2&&(f.set=g?(S,de)=>je(S,n,de,p^4?o:y.set):(S,de)=>S[t]=de)),a=(0,i[G])(p?p<4?g?o:y[A]:p>4?void 0:{get:y.get,set:y.set}:n,l),c._=1,p^4||a===void 0?X(a)&&(p>4?R.unshift(a):p?g?o=a:y[A]=a:n=a):typeof a!="object"||a===null?J("Object expected"):(X(s=a.get)&&(y.get=s),X(s=a.set)&&(y.set=s),X(s=a.init)&&R.unshift(s));return p||kt(r,n),y&&me(n,t,y),g?p^4?o:y:n};var ge=(r,e,t)=>e.has(r)||J("Cannot "+t),Pt=(r,e)=>Object(e)!==e?J('Cannot use the "in" operator on this value'):r.has(e),De=(r,e,t)=>(ge(r,e,"read from private field"),t?t.call(r):e.get(r));var je=(r,e,t,i)=>(ge(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),Mt=(r,e,t)=>(ge(r,e,"access private method"),t);var he=new Map,Le=new Map;function Rt(r){return typeof r=="object"&&r!==null&&"useClass"in r}function At(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Nt(r){return typeof r=="object"&&r!==null&&"useValue"in r}function k(r){return function(e){Le.set(e,r||{})}}function ve(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Rt(i))t.push(u(i.useClass,...ve(i.providers)));else if(At(i))t.push(i.useFactory(...ve(i.providers)));else if(Nt(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(he.has(r))return he.get(r);let t=Le.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=ve(t.providers,e),n=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&he.set(r,n),n}function He(r){return e=>new N(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 Ve(r=(e,t)=>e===t){return e=>new N(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 N=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 Y=class extends N{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 Q=class extends Y{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 Z(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function D(r,...e){if(!e.length)return r;let t=e.shift();if(Z(r)&&Z(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]}):Z(n)?Object.assign(r,{[i]:D(Z(o)?o:{},n)}):Object.assign(r,{[i]:n})}return D(r,...e)}return r}function ee(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"?jt(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 jt(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((o,s)=>ee(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)||!ee(r[o],e[o],t))return!1;return!0}var _e=Object.freeze({verbose:!1,common:Object.freeze({types:!0,declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:process.cwd()})})});var ze,ye;ze=[k({scope:"singleton"})];var x=class{constructor(e=_e){this.initialConfig=e;this.config$=new Q(D({},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(He(e),Ve((t,i)=>ee(t,i)))}patch(e){let t=D({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(D({},this.initialConfig,e))}};ye=T(null),x=O(ye,0,"ConfigurationService",ze,x),F(ye,1,x);import{cwd as Bt}from"process";import{readdirSync as $t}from"fs";import{matchesGlob as xe}from"path";import{join as Lt}from"@remotex-labs/xmap";function Ht(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 te(r,e){for(let t of e)if(t.endsWith(r)||xe(r,t))return!0;return!1}function Vt(r,e){let t=r+"/**";for(let i of e)if(xe(r,i)||xe(t,i))return!0;return!1}function _i(r,e,t){return te(r,e)?!te(r,t):!1}function Ue(r,e){let{include:t,exclude:i}=Ht(e),n=Object.create(null),s=Bt().length+1,a=r.length+1,c=i.length>0;function l(f){let p;try{p=$t(f,{withFileTypes:!0})}catch{return}let d=p.length;for(let g=0;g<d;g++){let I=p[g],A=Lt(f,I.name),R=A.slice(a);if(I.isDirectory()){(!c||!Vt(R,i))&&l(A);continue}if(!(c&&te(R,i))&&te(R,t)){let ue=A.slice(s),y=R.lastIndexOf("."),G=y>0?R.slice(0,y):R;n[G]=ue}}}return l(r),n}var j=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};import{resolveError as Jt}from"@remotex-labs/xmap";import{xterm as Ce}from"@remotex-labs/xansi/xterm.component";import _t from"typescript";import{resolve as zt}from"@remotex-labs/xmap";import{closeSync as Ut,fstatSync as Kt,openSync as qt,readFileSync as Wt}from"fs";var Ke,be;Ke=[k({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)??this.createEntry(t);try{this.syncEntry(t,i)}catch{(i.contentSnapshot!==void 0||i.version>0)&&(i.version++,i.mtimeMs=0,i.contentSnapshot=void 0)}return{...i}}resolve(e){let t=this.resolvedPathCache.get(e);if(t)return t;let i=zt(e);return this.resolvedPathCache.set(e,i),i}createEntry(e){let t={version:0,mtimeMs:0,contentSnapshot:void 0};return this.snapshotsByPath.set(e,t),t}syncEntry(e,t){let i=qt(e,"r");try{let{mtimeMs:n}=Kt(i);if(n===t.mtimeMs)return;let o=Wt(i,"utf-8");t.version++,t.mtimeMs=n,t.contentSnapshot=o?_t.ScriptSnapshot.fromString(o):void 0}finally{Ut(i)}}};be=T(null),v=O(be,0,"FilesModel",Ke,v),F(be,1,v);import{readFileSync as Gt}from"fs";import{SourceService as Xt}from"@remotex-labs/xmap";import{resolve as Se,toPosix as qe}from"@remotex-labs/xmap";var We,we;We=[k({scope:"singleton"})];var b=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=Se(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=Se(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=Se(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
+ ${n instanceof Error?n.message:String(n)}`)}}getRootDir(){return qe(process.cwd())}getDistDir(){return qe(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Xt(e,t);this.sourceMaps.set(t,i)}};we=T(null),b=O(we,0,"FrameworkService",We,b),F(we,1,b);import{parseErrorStack as Ge}from"@remotex-labs/xmap/parser.component";import{formatErrorCode as Yt}from"@remotex-labs/xmap/formatter.component";import{highlightCode as Qt}from"@remotex-labs/xmap/highlighter.component";function Zt(r=""){let t=u(b).getSourceMap(r);if(t)return t;let i=u(v).getOrTouchFile(r),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,d=Math.max(s-f,0),g=Math.min(s+p,o.length);return{line:s,column:a+1,code:o.slice(d,g).join(`
5
+ `),source:r,name:null,startLine:d,endLine:g,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function er(r){return r instanceof Error?Ge(r):r.detail instanceof Error?Ge(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 _(r,e){let t=u(b),i=u(x).getValue(s=>s.verbose)??!1,n=er(r),o=Jt(n,{...e,withNativeFrames:i||(e?.withFrameworkFrames??!1),getSource(s){return Zt(s)}});return o.stack.filter(s=>{if(!(e?.withFrameworkFrames??!1)&&t.isFrameworkFile(s))return!1;!o.formatCode&&s.code&&(o.formatCode=Yt({code:Qt(s.code),line:s.line??0,column:s.column??0,startLine:s.stratLine??0},{color:Ce.brightPink}))}),o}function z(r,e,t,i=[]){let n=[`
6
+ ${e}: ${Ce.lightCoral(t)}`];for(let o of i??[])o.text&&n.push(`
7
+ `+Ce.gray(o.text));return r.formatCode&&n.push(`
8
8
 
9
- ${r.formatCode}`),r.stacks.length&&n.push(`
9
+ ${r.formatCode}`),r.stack.length&&n.push(`
10
10
 
11
11
  Enhanced Stack Trace:
12
- ${r.stacks.join(`
12
+ ${r.stack.map(o=>o.format).join(`
13
13
  `)}
14
- `),n.join("")}var k=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=X(this.errorMetadata,e.name,e.message)}};var E=class extends k{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};var _=class extends k{id;constructor(e,t){super(e.text??"","esBuildError"),this.id=e.id??"",e.detail instanceof Error?(this.stack=e.detail.stack,this.message=e.detail.message,this.reformatStack(e.detail,t)):(this.errorMetadata=G(e,{withFrameworkFrames:!0}),this.stack=X(this.errorMetadata,this.name,this.message,e.notes))}};function ur(r){if(r instanceof k)return r;if(r.detail instanceof k||r.detail instanceof V)return r.detail;if(r.detail instanceof Error)return new _(r,{withFrameworkFrames:!0});if(r.location)return new _(r);if(r.text)return new E(r.text)}function le(r=[],e){for(let t of r){let i=ur(t);i&&e.push(i)}}function Pe(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return le(r.errors,e.errors),le(r.warnings,e.warnings),e}function J(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as nt from"http";import*as ot from"https";import{extname as rt}from"path";import{readFileSync as it}from"fs";var tt=`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Dark File Browser \u2014 FTP-like</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="logo">F</div><div><h1>xBuildFTP</h1><div class="muted">Browse & serve files</div></div></div><div class="search"><input placeholder="Search files & folders..."/></div><div class="quick-list"><a href="/">\u{1F3E0} Home</a><a href="\${ up }">\u2B06\uFE0F Up</a></div></aside><main class="main"><div class="topbar"><div class="topbar"><ul class="breadcrumbs"> \${ paths } </ul></div></div> \${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>`;import{xterm as mr}from"@remotex-labs/xansi/xterm.component";function K(){return mr.lightCoral("[xBuild]")}import{readdir as gr,stat as hr,readFile as yr}from"fs/promises";import{xterm as pe}from"@remotex-labs/xansi/xterm.component";var Ae=class{constructor(e,t){this.config=e;this.rootDir=I(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=d(C);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(K(),pe.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(K(),pe.dim("Server stopped.")),this.server=void 0}async restart(){console.log(K(),pe.burntOrange("Restarting server...")),await this.stop(),await this.start()}setActualPort(){if(this.config.port===0){let e=this.server.address();e&&typeof e=="object"&&e.port&&(this.config.port=e.port)}}startHttpServer(){return new Promise(e=>{this.server=nt.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:it(this.config.key??y(this.framework.distPath,"..","certs","server.key")),cert:it(this.config.cert??y(this.framework.distPath,"..","certs","server.crt"))};this.server=ot.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(`${K()} Request ${pe.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=y(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await hr(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(K(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await gr(e)).map(l=>{let f=y(t,l),p=rt(l).slice(1)||"folder";return p==="folder"?`
14
+ `),n.join("")}var C=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=_(e,t),this.formattedStack=z(this.errorMetadata,e.name,e.message)}};var w=class extends C{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};var B=class extends C{id;constructor(e,t){super(e.text??"","esBuildError"),this.id=e.id??"",e.detail instanceof Error?(this.stack=e.detail.stack,this.message=e.detail.message,this.reformatStack(e.detail,t)):(this.errorMetadata=_(e,{withFrameworkFrames:!0}),this.stack=z(this.errorMetadata,this.name,this.message,e.notes))}};function tr(r){if(r instanceof C)return r;if(r.detail instanceof C||r.detail instanceof j)return r.detail;if(r.detail instanceof Error)return new B(r,{withFrameworkFrames:!0});if(r.location)return new B(r);if(r.text)return new w(r.text)}function re(r=[],e){for(let t of r){let i=tr(t);i&&e.push(i)}}function Ee(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return re(r.errors,e.errors),re(r.warnings,e.warnings),e}function U(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Qe from"http";import*as Ze from"https";import{extname as Je}from"path";import{readFileSync as Ye}from"fs";var Xe=`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Dark File Browser \u2014 FTP-like</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" /><style>:root{--bg:#0b0f14;--panel:#0f1720;--muted:#9aa4b2;--accent:#E5C07B;--glass:rgba(255,255,255,0.03);--card:#0c1116;--radius:12px;--gap:12px;--shadow:0 6px 18px rgba(0,0,0,0.4);--file-icon-size:40px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial}*{box-sizing:border-box;font-style:normal !important}html,body{height:100%;margin:0;font-size:14px;color:#dce7ef;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:radial-gradient(1200px 600px at 10% 10%,rgba(110,231,183,0.04),transparent 8%),linear-gradient(180deg,rgba(255,255,255,0.01),transparent 20%),var(--bg);padding:28px;display:flex;gap:20px;align-items:flex-start;justify-content:center}.app{width:1100px;max-width:98vw;display:flex;gap:18px;padding:18px;border-radius:16px;box-shadow:var(--shadow);border:1px solid rgba(255,255,255,0.03);background:linear-gradient(180deg,rgba(255,255,255,0.02),rgba(255,255,255,0));overflow:hidden}.sidebar{width:260px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border-radius:var(--radius);padding:14px}.brand{display:flex;gap:12px;align-items:center;margin-bottom:10px}.logo{width:46px;height:46px;border-radius:10px;background:linear-gradient(135deg,#b65b9f 0%,#804b8f 100%);display:flex;align-items:center;justify-content:center;font-weight:700}.brand h1{font-size:16px;margin:0}.muted{color:var(--muted);font-size:13px}.search{margin:12px 0}.search input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.03);background:var(--glass);color:inherit}.quick-list{margin-top:12px}.quick-list a{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;background:transparent;color:var(--muted);text-decoration:none;cursor:pointer;transition:color 0.15s ease}.quick-list a:hover{color:var(--accent)}.main{flex:1;display:flex;flex-direction:column}.topbar{display:flex;align-items:center;gap:12px;padding-bottom:12px}.breadcrumbs{list-style:none;display:flex;gap:8px;align-items:center;background:var(--glass);padding:8px 12px;border-radius:var(--radius);margin:0}.breadcrumbs li{display:flex;align-items:center}.breadcrumbs li:not(:last-child)::after{content:'>';margin-left:8px;color:var(--muted)}.breadcrumbs a{color:var(--muted);text-decoration:none;transition:color 0.15s ease}.breadcrumbs a:hover{color:var(--accent)}.list{margin-top:14px;display:grid;grid-template-columns:1fr;gap:10px}.list a{display:flex;text-decoration:none;color:inherit}.folder-row,.file-row{display:flex;gap:12px;align-items:center;padding:10px;border-radius:10px;background:linear-gradient(180deg,rgba(255,255,255,0.01),transparent);border:1px solid rgba(255,255,255,0.02);transition:color 0.25s ease}.icon{width:var(--file-icon-size);height:var(--file-icon-size);border-radius:10px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.02);flex-shrink:0;transition:background 0.25s ease,color 0.25s ease}.folder-row:hover,.file-row:hover{color:var(--accent)}.folder-row:hover .icon{background:rgba(152,195,121,0.2)}.file-row:hover .icon{background:rgba(224,108,117,0.2)}.folder-row:hover .icon i{color:#98C379}.file-row:hover .icon i{color:#e09c6c}.meta{display:flex;flex-direction:column}.name{font-weight:600}.sub{color:var(--muted);font-size:13px}.empty{padding:40px;text-align:center;color:var(--muted)}@media (max-width:880px){.app{flex-direction:column;padding:12px}.sidebar,.main{width:100%}}</style></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="logo">F</div><div><h1>xBuildFTP</h1><div class="muted">Browse & serve files</div></div></div><div class="search"><input placeholder="Search files & folders..."/></div><div class="quick-list"><a href="/">\u{1F3E0} Home</a><a href="\${ up }">\u2B06\uFE0F Up</a></div></aside><main class="main"><div class="topbar"><div class="topbar"><ul class="breadcrumbs"> \${ paths } </ul></div></div> \${ fileList } </main></div></body><script> const searchInput = document.querySelector('.search input'); const listItems = document.querySelectorAll('.list > .folder-row, .list > .file-row'); const emptyMessage = document.querySelector('.empty'); searchInput.addEventListener('input', () => { const query = searchInput.value.toLowerCase(); let anyVisible = false; listItems.forEach(item => { const name = item.querySelector('.name').textContent.toLowerCase(); if (name.includes(query)) { item.style.display = 'flex'; anyVisible = true; } else { item.style.display = 'none'; } }); emptyMessage.style.display = anyVisible ? 'none' : 'block'; }); </script></html>`;import{resolve as nr,join as ie}from"@remotex-labs/xmap";import{xterm as ir}from"@remotex-labs/xansi/xterm.component";function H(){return ir.lightCoral("[xBuild]")}import{readdir as or,stat as sr,readFile as ar}from"fs/promises";import{xterm as ne}from"@remotex-labs/xansi/xterm.component";var Ie=class{constructor(e,t){this.config=e;this.rootDir=nr(t),this.config.port||=0,this.config.host||="localhost"}server;rootDir;framework=u(b);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(H(),ne.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(H(),ne.dim("Server stopped.")),this.server=void 0}async restart(){console.log(H(),ne.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=Qe.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:Ye(this.config.key??ie(this.framework.distPath,"..","certs","server.key")),cert:Ye(this.config.cert??ie(this.framework.distPath,"..","certs","server.crt"))};this.server=Ze.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(`${H()} Request ${ne.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=ie(this.rootDir,i);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await sr(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(H(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let o=(await or(e)).map(l=>{let f=ie(t,l),p=Je(l).slice(1)||"folder";return p==="folder"?`
15
15
  <a href="/${f}" class="folder-row">
16
16
  <div class="icon"><i class="fa-solid fa-folder"></i></div>
17
17
  <div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div>
@@ -21,18 +21,18 @@ Enhanced Stack Trace:
21
21
  <div class="icon"><i class="fa-solid fa-file-code"></i></div>
22
22
  <div class="meta"><div class="name">${l}</div><div class="sub">${p}</div></div>
23
23
  </a>
24
- `}).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=tt.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=rt(e).slice(1)||"txt",n=this.getContentType(i),o=await yr(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(K(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as st}from"path";import{stat as vr,watch as xr}from"fs/promises";var Re=class{excludes;include;debounceTimer=null;framework=d(C);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=xr(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=Je(n);if(o.endsWith("~")||!this.include.some(a=>st(o,a))||this.excludes.some(a=>st(o,a)))continue;let s=y(this.framework.rootPath,o);try{if(!(await vr(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)}};import jr from"typescript";import{build as $r}from"esbuild";import{writeFile as gt,mkdir as Br,readFile as Lr}from"fs/promises";import m from"typescript";import br from"typescript";var Sr=/^#!.*(\r?\n)?/,wr=/export {};\n?/g,Cr=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,Ir=/^export\s+(?:default\s+)?/gm,Er=/(?<=[:;,{}\[\]()\w"'`])[ \t]*\/\*\*[^\r\n]*?\*\/[ \t]*$/gm;function Tr(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(Sr,""):r}function Fr(r){return r.includes("export {}")?r.replace(wr,""):r}function kr(r){return r=r.replace(Er,""),r.replace(Cr,"$1")}function at(r){return r.replace(Ir,"")}function Or(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function fe(r){return Or(r)&&(r=Tr(r),r=Fr(r),r=kr(r)),r}function Me(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||v(r),s=i||v(r),c=F(s,r).replace(/\.tsx?$/,".d.ts"),l=br.sys.resolvePath(`${o}/${c}`);return T(l)}var ct,Ne;ct=[N({scope:"singleton"})];var W=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=d(x);constructor(){this.printer=m.createPrinter({newLine:m.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),o=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===o)return s;let a=this.initDeclaration(e.fileName,o),c=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!m.isStringLiteral(e))return null;let i=e.text,n=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!n||n.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:n,isExternal:!1}}addNamedElements(e,t){for(let i of t){let n=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(n)}}hasExportModifier(e){return m.canHaveModifiers(e)?m.getModifiers(e)?.some(i=>i.kind===m.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return m.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,m.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(m.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(m.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=m.factory.createNodeArray(n),s=this.printer.printList(m.ListFormat.MultiLine,o,e),a=at(fe(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;m.isNamespaceImport(f)?i.push(f.name.text):m.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&&(m.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:m.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:n}=e;if(!i)return;let o=this.resolveModule(i,t.fileName);if(!o)return;let{fileName:s,isExternal:a}=o;if(a||t.internalDeps.add(s),!n){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(m.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}m.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(m.isVariableStatement(e)){for(let i of e.declarationList.declarations)m.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(m.isEnumDeclaration(e)||m.isClassDeclaration(e)||m.isFunctionDeclaration(e)||m.isInterfaceDeclaration(e)||m.isTypeAliasDeclaration(e))&&e.name&&m.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};Ne=A(null),W=M(Ne,0,"GraphModel",ct,W),R(Ne,1,W);import z from"typescript";import{mkdir as Pr,writeFile as Ar}from"fs/promises";var lt=`/**
24
+ `}).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=Xe.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=Je(e).slice(1)||"txt",n=this.getContentType(i),o=await ar(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(H(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as et}from"path";import{stat as cr,watch as lr}from"fs/promises";import{normalize as pr,join as fr}from"@remotex-labs/xmap";var Te=class{excludes;include;debounceTimer=null;framework=u(b);constructor(e=[],t=["**/*"]){this.include=t,this.excludes=e}async start(e){let t=new Set,i=lr(this.framework.rootPath,{recursive:!0});for await(let{filename:n}of i){if(!n)continue;let o=pr(n);if(o.endsWith("~")||!this.include.some(a=>et(o,a))||this.excludes.some(a=>et(o,a)))continue;let s=fr(this.framework.rootPath,o);try{if(!(await cr(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)}};import Dr from"typescript";import{build as jr}from"esbuild";import{writeFile as pt,mkdir as Br,readFile as $r}from"fs/promises";import m from"typescript";import ur from"typescript";import{dirname as tt,relative as dr,toPosix as mr}from"@remotex-labs/xmap";var gr=/^#!.*(\r?\n)?/,hr=/export {};\n?/g,vr=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,yr=/^export\s+(?:default\s+)?/gm,xr=/(?<=[:;,{}\[\]()\w"'`])[ \t]*\/\*\*[^\r\n]*?\*\/[ \t]*$/gm;function br(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(gr,""):r}function Sr(r){return r.includes("export {}")?r.replace(hr,""):r}function wr(r){return r=r.replace(xr,""),r.replace(vr,"$1")}function rt(r){return r.replace(yr,"")}function Cr(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function oe(r){return Cr(r)&&(r=br(r),r=Sr(r),r=wr(r)),r}function Fe(r,e){let{outDir:t,rootDir:i,declarationDir:n}=e,o=n||t||tt(r),s=i||tt(r),c=dr(s,r).replace(/\.tsx?$/,".d.ts"),l=ur.sys.resolvePath(`${o}/${c}`);return mr(l)}var it,Oe;it=[k({scope:"singleton"})];var V=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(v);constructor(){this.printer=m.createPrinter({newLine:m.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let n=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),o=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===o)return s;let a=this.initDeclaration(e.fileName,o),c=this.emitDeclaration.call(n,e);return a.content=this.stripImportsExports.call(n,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!m.isStringLiteral(e))return null;let i=e.text,n=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!n||n.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:n,isExternal:!1}}addNamedElements(e,t){for(let i of t){let n=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(n)}}hasExportModifier(e){return m.canHaveModifiers(e)?m.getModifiers(e)?.some(i=>i.kind===m.SyntaxKind.ExportKeyword)??!1:!1}emitDeclaration(e){let i=this.languageService.getEmitOutput(e.fileName,!0,!0).outputFiles[0]?.text;if(!i)throw new Error(`Failed to emit declaration: ${e.fileName}`);return m.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,m.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],n=[];for(let c of e.statements){if(m.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(m.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),n.push(c)}let o=m.factory.createNodeArray(n),s=this.printer.printList(m.ListFormat.MultiLine,o,e),a=rt(oe(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;m.isNamespaceImport(f)?i.push(f.name.text):m.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&&(m.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:m.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:n}=e;if(!i)return;let o=this.resolveModule(i,t.fileName);if(!o)return;let{fileName:s,isExternal:a}=o;if(a||t.internalDeps.add(s),!n){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(m.isNamespaceExport(n)){a?t.externalExports.namespace[n.name.text]=s:t.internalExports.namespace[n.name.text]=s;return}m.isNamedExports(n)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],n.elements):this.addNamedElements(t.internalExports.exports,n.elements))}extractExportName(e,t){if(m.isVariableStatement(e)){for(let i of e.declarationList.declarations)m.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(m.isEnumDeclaration(e)||m.isClassDeclaration(e)||m.isFunctionDeclaration(e)||m.isInterfaceDeclaration(e)||m.isTypeAliasDeclaration(e))&&e.name&&m.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};Oe=T(null),V=O(Oe,0,"GraphModel",it,V),F(Oe,1,V);import $ from"typescript";import{mkdir as Er,writeFile as Ir}from"fs/promises";import{join as Tr,dirname as Fr}from"@remotex-labs/xmap";var nt=`/**
25
25
  * This file was automatically generated by xBuild.
26
26
  * DO NOT EDIT MANUALLY.
27
27
  */
28
- `;var ue=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=d(W);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=y(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Pr(v(i),{recursive:!0}),await Ar(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 u of p.internalExports.star)a.add(u)}for(let u of p.internalDeps)i.has(u)||s.push(u);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(`,
29
- `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[lt],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 {
28
+ `;var se=class{constructor(e,t){this.languageService=e;this.languageHostService=t}graphModel=u(V);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=Tr(n.outDir,`${o}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}async bundleCollectDeclarations(e,t,i){let n=this.graphModel.scan(e,this.languageService,this.languageHostService),o=await this.getBundleContent(n,t);await Er(Fr(i),{recursive:!0}),await Ir(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 d of p.internalExports.star)a.add(d)}for(let d of p.internalDeps)i.has(d)||s.push(d);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(`,
29
+ `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:n}}parseContent(e,t,i){let n=[nt],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 {
30
30
  ${f.join(`,
31
31
  `)}
32
32
  };`)}return l.length>0&&n.push(...l),n.join(`
33
- `)}};import{mkdir as Rr,writeFile as Mr}from"fs/promises";import{xterm as Nr}from"@remotex-labs/xansi/xterm.component";var de=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(`${Nr.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=fe(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await Rr(v(o),{recursive:!0}),await Mr(o,n,"utf8")}};import Y from"typescript";var me=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=d(x);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(v(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 pt,De;pt=[N({providers:[{useValue:"tsconfig.json"}]})];var D=class D{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 de(n,i),this.bundlerService=new ue(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=D.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=D.serviceCache.get(e);t&&(t.refCount--,D.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=D.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new me(e.options),i=z.createLanguageService(t,z.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return D.serviceCache.set(this.configPath,n),n}parseConfig(){let e=z.getParsedCommandLineOfConfigFile(this.configPath,{skipLibCheck:!0,stripInternal:!0,emitDeclarationOnly:!0},{...z.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:z.ScriptTarget.ESNext,module:z.ModuleKind.NodeNext,declaration:!0,skipLibCheck:!0,moduleResolution:z.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:z.flattenDiagnosticMessageText(e.messageText,`
34
- `),category:e.category};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};De=A(null),D=M(De,0,"TypescriptService",pt,D),R(De,1,D);var Q=D;import{cwd as je}from"process";import{build as ft}from"esbuild";var Dr={write:!1,bundle:!0,minify:!0,outdir:`${je()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function ut(r,e,t={}){return await ft({absWorkingDir:je(),...Dr,...t,stdin:{loader:"ts",contents:r,resolveDir:je(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function dt(r,e={}){try{return await ft({...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 le(t.errors,i.errors),i}throw t}}function mt(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=Ye(r,e)),t}else if(e&&typeof e=="object")return e;throw new E("Unsupported entry points format")}var ge=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new E(`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=d(S);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(!this.active)return;this.applyInjections();let e=Object.assign({},this.buildConfig.esbuild);this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&Object.assign(e,{entryPoints:this.dependenciesFile});try{let t=await $r(e);return await this.packageTypeComponent(),t}catch(t){if(J(t)){if(t.errors.filter(n=>n.location).length>0)throw t;return{errors:t?.errors??[],warnings:t?.warnings??[]}}}}getConfig(e,t={}){return e?H({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;if(typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError){let n=new V("Type checking failed",t);e.warnings?.push({detail:n,location:void 0})}else{let n=[],o=[],s=new V("Type checking failed",n),a=new V("Type checking failed",o);for(let c of t)(c.category===jr.DiagnosticCategory.Error?n:o).push(c);n.length&&e.errors?.push({detail:s,location:void 0}),o.length&&e.warnings?.push({detail:a,location:void 0})}return e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(typeof e.buildResult.metafile?.outputs=="object"){let s=Object.keys(e.buildResult.metafile?.outputs);for(let a of s){if(!a.endsWith(".map"))continue;let c=v(a);Lr(a,"utf8").then(l=>{let f=JSON.parse(l);f.sources=f.sources.map(p=>p.startsWith("http")?p:y(c,p)),gt(a,JSON.stringify(f),"utf8")})}}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 Br(e,{recursive:!0}),await gt(y(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new E(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new E("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=mt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.outdir&&i.esbuild.outfile&&(this.buildConfig.esbuild.outdir=void 0),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new 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 dt(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 Hr}from"fs/promises";var he=class{constructor(e,t){this.variantName=e;this.argv=t}filesModel=d(x);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,options:e.initialOptions,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(this.executeStartHooks.bind(this,t,e)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(this.executeEndHooks.bind(this,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},this.executeResolveHooks.bind(this,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},this.executeLoadHooks.bind(this,t))}}}pushError(e,t,i,n=this.variantName){e.push({id:t,detail:i,location:null,pluginName:n})}async executeStartHooks(e,t){e.stage.startTime=new Date;let i=[],n=[],o={build:t,...e};for(let[s,a]of this.startHooks.entries())try{let c=await a(o);c?.errors&&i.push(...c.errors),c?.warnings&&n.push(...c.warnings)}catch(c){this.pushError(i,"startHook",c,s)}return{errors:i,warnings:n}}async executeEndHooks(e,t){let{errors:i,warnings:n}=t,o=Date.now()-e.stage.startTime.getTime(),s={buildResult:t,duration:o,...e};for(let[a,c]of this.endHooks.entries())try{let l=await c(s);l?.errors&&i.push(...l.errors),l?.warnings&&n.push(...l.warnings)}catch(l){this.pushError(i,"endHook",l,a)}if(t.errors.length===0)for(let[a,c]of this.successHooks.entries())try{await c(s)}catch(l){this.pushError(i,"endHook",l,a)}}async executeResolveHooks(e,t){let i={errors:[]},n={args:t,...e};for(let[o,s]of this.resolveHooks.entries())try{let a=await s(n);if(!a)continue;i={...i,...a}}catch(a){this.pushError(i.errors,"endResolve",a,o)}return i}async executeLoadHooks(e,t){let i=[],n=[],o="default",s=I(t.path),a=this.filesModel.getSnapshot(s),c=a?.contentSnapshot?a.contentSnapshot.text:await Hr(s,"utf8");for(let[l,f]of this.loadHooks.entries())try{let p=await f({contents:c,loader:o,args:t,...e});if(!p)continue;p.contents!==void 0&&(c=p.contents),p.loader&&(o=p.loader),p.errors&&i.push(...p.errors),p.warnings&&n.push(...p.warnings)}catch(p){this.pushError(i,"loadHook",p,l)}return{contents:c,loader:o,errors:i,warnings:n}}};import h from"typescript";import{highlightCode as Ct}from"@remotex-labs/xmap/highlighter.component";import j from"typescript";var Vr="$$ifdef";function _r(r,e,t,i=!1){let n=i?"export function ":"function ";return j.isArrowFunction(e)||j.isFunctionExpression(e)?zr(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function zr(r,e,t,i){let o=e.modifiers?.some(l=>l.kind===j.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=Ur(e,t);return`${o}${i}${r}(${s})${a} ${c}`}function Ur(r,e){let t=r.body.getText(e);return j.isArrowFunction(r)&&!j.isBlock(r.body)?`{ return ${t}; }`:t}function Kr(r,e,t="",i="();"){return j.isArrowFunction(r)||j.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===j.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function ht(r,e,t){let i=r in t&&!!t[r];return e===Vr===i}function yt(r,e,t,i){let[n,o]=e.arguments;if(!j.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!ht(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return _r(c,o,i.sourceFile,t)}function ye(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!j.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!ht(a,c,e.defines))return"";let l="",f=t?.name.getText(e.sourceFile);return f&&(l=i?`export const ${f} = `:`const ${f} = `),Kr(s,e.sourceFile,l,n)}import O from"typescript";import{createRequire as Gr}from"module";var ve=class extends k{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=G(e,{},t),this.stack=X(this.errorMetadata,this.name,this.message)}};import{Script as Wr,createContext as qr}from"vm";async function vt(r,e={},t={}){let i=new Wr(r,t),n=qr(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}async function xt(r,e,t){let[i,n]=(await ut(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=Gr(e.sourceFile.fileName),a=Xr(e.sourceFile.fileName,o,s);a.context=e.context;let c=await vt(n.text,a,{filename:e.sourceFile.fileName});return c===null?"undefined":typeof c=="number"||typeof c=="boolean"?String(c):JSON.stringify(c)}catch(o){Jr(o,e,i.text,t)}return"undefined"}function Xr(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:v(r),__filename:r}}function Jr(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);d(C).setSource(t,e.sourceFile.fileName);let s=new ve(r,o);e.errors.push({text:s.message,detail:s})}function Yr(r,e){let t=null,i=n=>{if(!t){if(O.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}O.isVariableStatement(n)&&(t=Qr(n,r),t)||O.forEachChild(n,i)}};return i(e),t}function Qr(r,e){for(let t of r.declarationList.declarations)if(O.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(O.isArrowFunction(t.initializer)||O.isFunctionExpression(t.initializer)))return t.initializer;return null}function bt(r){return`module.exports = (${r})();`}function Zr(r){return r&O.NodeFlags.Const?"const":r&O.NodeFlags.Let?"let":"var"}function St(r,e){return r?O.isIdentifier(r)?ei(r,e):O.isArrowFunction(r)||O.isFunctionExpression(r)?{node:r,data:bt(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function ei(r,e){let t=Yr(r.text,e.sourceFile);return t?{node:t,data:bt(t.getText(e.sourceFile))}:(ti(r.text,e,r),{data:"",node:r})}function ti(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 wt(r,e,t,i,n){let o=t.arguments[0],s=St(o,n);if(!s)return!1;let a=await xt(s.data,n,s.node),c=Zr(e.declarationList.flags),l=i?"export ":"",f=r.name.getText(n.sourceFile);return`${l}${c} ${f} = ${a};`}async function $e(r,e){let t=r[0],i=St(t,e);return i?xt(i.data,e,i.node):!1}var ri=/\.(ts|js)$/,U=["$$ifdef","$$ifndef","$$inline"];function Be(r,e){return U.some(t=>r.getText(e).includes(t))}function It(r){return r===U[2]?1:2}async function ii(r,e,t){let i=!1;for(let n of r.declarationList.declarations){let o="",s,a=n.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,o=`(${a.arguments.map(p=>p.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(!U.includes(c))continue;if(s.arguments.length!==It(c)){let{line:f,character:p}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new _({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:f+1,column:p}})}let l=r.modifiers?.some(f=>f.kind===h.SyntaxKind.ExportKeyword)??!1;c===U[2]?i=await wt(n,r,s,l,t):o?i=ye(s,t,n,l,o):i=yt(n,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function ni(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!U.includes(n))return!1;if(i.arguments.length!==It(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new _({text:`Invalid macro call: ${n} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let o=!1;return n==U[2]?(await $e(i.arguments,t),o="undefined"):o=ye(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),o!==!1}async function oi(r,e,t){if(!h.isCallExpression(r)||!Be(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===U[2]){let s=await $e(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=ye(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function si(r,e="unknow"){let t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let n=[r.sourceFile],o=new Set;for(;n.length>0;){let c=n.pop(),l=c?.kind;if(!c||!l||i&&(l===h.SyntaxKind.VariableStatement&&await ii(c,o,r)||l===h.SyntaxKind.ExpressionStatement&&Be(c,r.sourceFile)&&await ni(c,o,r)||l===h.SyntaxKind.CallExpression&&Be(c,r.sourceFile)&&await oi(c,o,r)))continue;if(t.size>0){if(l===h.SyntaxKind.CallExpression){let p=c;h.isIdentifier(p.expression)&&t.has(p.expression.text)&&o.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}else if(l===h.SyntaxKind.Identifier){let p=c;if(t.has(p.text)){let u=c.parent??c;if(u&&!h.isImportSpecifier(u)&&!h.isExportSpecifier(u)){let g=u?.getText(r.sourceFile);(!h.isCallExpression(u)||u.expression!==c)&&(!g||U.every(P=>!g.includes(P)))&&o.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}}}}let f=c.getChildren(r.sourceFile);for(let p=f.length-1;p>=0;p--)n.push(f[p])}if(o.size===0)return r.contents;let s=Array.from(o);s.sort((c,l)=>l.start-c.start),r.stage.replacementInfo??={},r.stage.replacementInfo[e]??=[];let a=r.stage.replacementInfo[e];for(let{start:c,end:l,replacement:f}of s)a.push({source:Ct(r.contents.slice(c,l)),replacement:Ct(f)}),r.contents=r.contents.slice(0,c)+f+r.contents.slice(l);return r.contents}async function Et(r,e){let{args:t,loader:i,stage:n,contents:o,variantName:s,options:a,argv:c}=e;if(t.path.includes("node_modules")||o.length<1||!ri.test(t.path))return;let f=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!f)return;let p={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:f,context:{argv:c,options:a,variantName:s}},u=await si(p,r.name);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(u=r.typescript.languageHostService.resolveAliases(u,t.path,".js")),{loader:i,contents:u,warnings:p.warnings,errors:p.errors}}var Tt="$$",Ft=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function ai(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
33
+ `)}};import{dirname as Or}from"@remotex-labs/xmap";import{mkdir as kr,writeFile as Pr}from"fs/promises";import{xterm as Mr}from"@remotex-labs/xansi/xterm.component";var ae=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(`${Mr.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=Fe(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=Fe(e.fileName,t);n=oe(n),n=this.languageHostService.resolveAliases(n,e.fileName,".d.ts"),await kr(Or(o),{recursive:!0}),await Pr(o,n,"utf8")}};import K from"typescript";import{relative as Rr,dirname as Ar}from"@remotex-labs/xmap";var q=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=K.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static sys=K.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=K.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static reload(){let e=u(v);e.getTrackedFilePaths().map(t=>{e.touchFile(t)})}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,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 K.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 K.resolveModuleName(e,t,this.compilerOptions,K.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=Rr(Ar(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 ot,ke;ot=[k({providers:[{useValue:"tsconfig.json"}]})];var P=class P{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 ae(n,i),this.bundlerService=new se(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=P.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=P.serviceCache.get(e);t&&(t.refCount--,P.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=P.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new q(e.options),i=$.createLanguageService(t,$.createDocumentRegistry()),n={config:e,host:t,service:i,refCount:1};return P.serviceCache.set(this.configPath,n),n}parseConfig(){let e=$.getParsedCommandLineOfConfigFile(this.configPath,{sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0},{...$.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:$.ScriptTarget.ESNext,module:$.ModuleKind.NodeNext,sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0,moduleResolution:$.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:$.flattenDiagnosticMessageText(e.messageText,`
34
+ `),category:e.category};if(e.file&&e.start!==void 0){let{line:i,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=n+1,t.code=e.code}return t}};ke=T(null),P=O(ke,0,"TypescriptService",ot,P),F(ke,1,P);var W=P;import{cwd as Pe}from"process";import{build as st}from"esbuild";var Nr={write:!1,bundle:!0,minify:!0,outdir:`${Pe()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function at(r,e,t={}){return await st({absWorkingDir:Pe(),...Nr,...t,stdin:{loader:"ts",contents:r,resolveDir:Pe(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function ct(r,e={}){try{return await st({...e,outdir:"tmp",write:!1,bundle:!0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(U(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw re(t.errors,i.errors),i}throw t}}import{relative as Lr,resolve as Hr,join as ft,dirname as Vr}from"@remotex-labs/xmap";function lt(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=Ue(r,e)),t}else if(e&&typeof e=="object")return e;throw new w("Unsupported entry points format")}var ce=class{constructor(e,t,i,n={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=n;if(!this.buildConfig?.esbuild)throw new w(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new W(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(x);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(!this.active)return;this.applyInjections();let e=Object.assign({},this.buildConfig.esbuild);this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&Object.assign(e,{entryPoints:this.dependenciesFile});try{let t=await jr(e);return await this.packageTypeComponent(),t}catch(t){if(U(t)){if(t.errors.filter(n=>n.location).length>0)throw t;return{errors:t?.errors??[],warnings:t?.warnings??[]}}}}getConfig(e,t={}){return e?D({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;if(typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError){let n=new j("Type checking failed",t);e.warnings?.push({detail:n,location:void 0})}else{let n=[],o=[],s=new j("Type checking failed",n),a=new j("Type checking failed",o);for(let c of t)(c.category===Dr.DiagnosticCategory.Error?n:o).push(c);n.length&&e.errors?.push({detail:s,location:void 0}),o.length&&e.warnings?.push({detail:a,location:void 0})}return e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(typeof e.buildResult.metafile?.outputs=="object"){let s=Object.keys(e.buildResult.metafile?.outputs);for(let a of s){if(!a.endsWith(".map"))continue;let c=Vr(a);$r(a,"utf8").then(l=>{let f=JSON.parse(l);f.sources=f.sources.map(p=>p.startsWith("http")?p:ft(c,p)),pt(a,JSON.stringify(f),"utf8")})}}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 Br(e,{recursive:!0}),await pt(ft(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new w(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints)throw new w("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,JSON.stringify(o)])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=lt(this.typescriptModule.config.options.rootDir??process.cwd(),e.esbuild.entryPoints),e.esbuild=Object.assign({},e.esbuild,{define:i,logLevel:"silent",plugins:[this.lifecycle.create()]}),e}async handleConfigChange({variantConfig:e,commonConfig:t}){this.active=!1;let i=this.getConfig(e,t);i&&(this.active=!0,this.buildConfig=this.initializeConfig(i),i.esbuild.outdir&&i.esbuild.outfile&&(this.buildConfig.esbuild.outdir=void 0),i.esbuild.tsconfig&&i.esbuild.tsconfig!==this.tsConfigPath&&(this.typescriptModule.dispose(this.tsConfigPath),this.tsConfigPath=i.esbuild.tsconfig,this.typescriptModule=new W(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 ct(e.entryPoints,{loader:e.loader,platform:e.platform}),i={};for(let n of Object.keys(t.inputs)){let o=Lr(this.typescriptModule.config.options.rootDir,Hr(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 _r}from"fs/promises";import{resolve as zr}from"@remotex-labs/xmap";var le=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,options:e.initialOptions,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(this.executeStartHooks.bind(this,t,e)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(this.executeEndHooks.bind(this,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},this.executeResolveHooks.bind(this,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},this.executeLoadHooks.bind(this,t))}}}pushError(e,t,i,n=this.variantName){e.push({id:t,detail:i,location:null,pluginName:n})}async executeStartHooks(e,t){e.stage.startTime=new Date;let i=[],n=[],o={build:t,...e};for(let[s,a]of this.startHooks.entries())try{let c=await a(o);c?.errors&&i.push(...c.errors),c?.warnings&&n.push(...c.warnings)}catch(c){this.pushError(i,"startHook",c,s)}return{errors:i,warnings:n}}async executeEndHooks(e,t){let{errors:i,warnings:n}=t,o=Date.now()-e.stage.startTime.getTime(),s={buildResult:t,duration:o,...e};for(let[a,c]of this.endHooks.entries())try{let l=await c(s);l?.errors&&i.push(...l.errors),l?.warnings&&n.push(...l.warnings)}catch(l){this.pushError(i,"endHook",l,a)}if(t.errors.length===0)for(let[a,c]of this.successHooks.entries())try{await c(s)}catch(l){this.pushError(i,"endHook",l,a)}}async executeResolveHooks(e,t){let i={errors:[]},n={args:t,...e};for(let[o,s]of this.resolveHooks.entries())try{let a=await s(n);if(!a)continue;i={...i,...a}}catch(a){this.pushError(i.errors,"endResolve",a,o)}return i}async executeLoadHooks(e,t){let i=[],n=[],o="default",s=zr(t.path),a=this.filesModel.getSnapshot(s),c=a?.contentSnapshot?a.contentSnapshot.text:await _r(s,"utf8");for(let[l,f]of this.loadHooks.entries())try{let p=await f({contents:c,loader:o,args:t,...e});if(!p)continue;p.contents!==void 0&&(c=p.contents),p.loader&&(o=p.loader),p.errors&&i.push(...p.errors),p.warnings&&n.push(...p.warnings)}catch(p){this.pushError(i,"loadHook",p,l)}return{contents:c,loader:o,errors:i,warnings:n}}};import h from"typescript";import{highlightCode as xt}from"@remotex-labs/xmap/highlighter.component";import M from"typescript";var Ur="$$ifdef";function Kr(r,e,t,i=!1){let n=i?"export function ":"function ";return M.isArrowFunction(e)||M.isFunctionExpression(e)?qr(r,e,t,n):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function qr(r,e,t,i){let o=e.modifiers?.some(l=>l.kind===M.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=Wr(e,t);return`${o}${i}${r}(${s})${a} ${c}`}function Wr(r,e){let t=r.body.getText(e);return M.isArrowFunction(r)&&!M.isBlock(r.body)?`{ return ${t}; }`:t}function Gr(r,e,t="",i="();"){return M.isArrowFunction(r)||M.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===M.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function ut(r,e,t){let i=r in t&&!!t[r];return e===Ur===i}function dt(r,e,t,i){let[n,o]=e.arguments;if(!M.isStringLiteral(n))return!1;let s=e.expression.text,a=n.text;if(!ut(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Kr(c,o,i.sourceFile,t)}function pe(r,e,t,i=!1,n){let[o,s]=r.arguments;if(!M.isStringLiteral(o))return!1;let a=o.text,c=r.expression.text;if(!ut(a,c,e.defines))return"";let l="",f=t?.name.getText(e.sourceFile);return f&&(l=i?`export const ${f} = `:`const ${f} = `),Gr(s,e.sourceFile,l,n)}import E from"typescript";import{createRequire as Yr}from"module";var fe=class extends C{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=_(e,{lineOffset:t}),this.stack=z(this.errorMetadata,this.name,this.message)}};import{Script as Xr,createContext as Jr}from"vm";async function mt(r,e={},t={}){let i=new Xr(r,t),n=Jr(e);return await i.runInContext(n,{breakOnSigint:!0,displayErrors:!1})}import{dirname as Qr,relative as Zr}from"@remotex-labs/xmap";async function gt(r,e,t){let[i,n]=(await at(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let o={exports:{}},s=Yr(e.sourceFile.fileName),a=ei(e.sourceFile.fileName,o,s);a.context=e.context;let c=await mt(n.text,a,{filename:e.sourceFile.fileName});return c===null?"undefined":typeof c=="number"||typeof c=="boolean"?String(c):JSON.stringify(c)}catch(o){ti(o,e,i.text,t)}return"undefined"}function ei(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:Qr(r),__filename:r}}function ti(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(b).setSource(t,e.sourceFile.fileName);let s=new fe(r,o);e.errors.push({text:s.message,detail:s})}function ri(r,e){let t=null,i=n=>{if(!t){if(E.isFunctionDeclaration(n)&&n.name?.text===r){t=n;return}E.isVariableStatement(n)&&(t=ii(n,r),t)||E.forEachChild(n,i)}};return i(e),t}function ii(r,e){for(let t of r.declarationList.declarations)if(E.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(E.isArrowFunction(t.initializer)||E.isFunctionExpression(t.initializer)))return t.initializer;return null}function ht(r){return`module.exports = (${r})();`}function ni(r){return r&E.NodeFlags.Const?"const":r&E.NodeFlags.Let?"let":"var"}function vt(r,e){return r?E.isIdentifier(r)?oi(r,e):E.isArrowFunction(r)||E.isFunctionExpression(r)?{node:r,data:ht(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function oi(r,e){let t=ri(r.text,e.sourceFile);return t?{node:t,data:ht(t.getText(e.sourceFile))}:(si(r.text,e,r),{data:"",node:r})}function si(r,e,t){let i=t.getStart(e.sourceFile),{line:n,character:o}=e.sourceFile.getLineAndCharacterOfPosition(i),s=Zr(".",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 yt(r,e,t,i,n){let o=t.arguments[0],s=vt(o,n);if(!s)return!1;let a=await gt(s.data,n,s.node),c=ni(e.declarationList.flags),l=i?"export ":"",f=r.name.getText(n.sourceFile);return`${l}${c} ${f} = ${a};`}async function Me(r,e){let t=r[0],i=vt(t,e);return i?gt(i.data,e,i.node):!1}var ai=/\.(ts|js)$/,L=["$$ifdef","$$ifndef","$$inline"];function Re(r,e){return L.some(t=>r.getText(e).includes(t))}function bt(r){return r===L[2]?1:2}async function ci(r,e,t){let i=!1;for(let n of r.declarationList.declarations){let o="",s,a=n.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,o=`(${a.arguments.map(p=>p.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(!L.includes(c))continue;if(s.arguments.length!==bt(c)){let{line:f,character:p}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new B({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:f+1,column:p}})}let l=r.modifiers?.some(f=>f.kind===h.SyntaxKind.ExportKeyword)??!1;c===L[2]?i=await yt(n,r,s,l,t):o?i=pe(s,t,n,l,o):i=dt(n,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function li(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let n=i.expression.text;if(!L.includes(n))return!1;if(i.arguments.length!==bt(n)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new B({text:`Invalid macro call: ${n} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let o=!1;return n==L[2]?(await Me(i.arguments,t),o="undefined"):o=pe(i,t),o!==!1&&e.add({replacement:o,end:i.getEnd(),start:i.getStart(t.sourceFile)}),o!==!1}async function pi(r,e,t){if(!h.isCallExpression(r)||!Re(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===L[2]){let s=await Me(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let o=pe(i,t);return o===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:o}),!0)}async function fi(r,e="unknow"){let t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let n=[r.sourceFile],o=new Set;for(;n.length>0;){let c=n.pop(),l=c?.kind;if(!c||!l||i&&(l===h.SyntaxKind.VariableStatement&&await ci(c,o,r)||l===h.SyntaxKind.ExpressionStatement&&Re(c,r.sourceFile)&&await li(c,o,r)||l===h.SyntaxKind.CallExpression&&Re(c,r.sourceFile)&&await pi(c,o,r)))continue;if(t.size>0){if(l===h.SyntaxKind.CallExpression){let p=c;h.isIdentifier(p.expression)&&t.has(p.expression.text)&&o.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}else if(l===h.SyntaxKind.Identifier){let p=c;if(t.has(p.text)){let d=c.parent??c;if(d&&!h.isImportSpecifier(d)&&!h.isExportSpecifier(d)){let g=d?.getText(r.sourceFile);(!h.isCallExpression(d)||d.expression!==c)&&(!g||L.every(I=>!g.includes(I)))&&o.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}}}}let f=c.getChildren(r.sourceFile);for(let p=f.length-1;p>=0;p--)n.push(f[p])}if(o.size===0)return r.contents;let s=Array.from(o);s.sort((c,l)=>l.start-c.start),r.stage.replacementInfo??={},r.stage.replacementInfo[e]??=[];let a=r.stage.replacementInfo[e];for(let{start:c,end:l,replacement:f}of s)a.push({source:xt(r.contents.slice(c,l)),replacement:xt(f)}),r.contents=r.contents.slice(0,c)+f+r.contents.slice(l);return r.contents}async function St(r,e){let{args:t,loader:i,stage:n,contents:o,variantName:s,options:a,argv:c}=e;if(t.path.includes("node_modules")||o.length<1||!ai.test(t.path))return;let f=r.typescript.languageService.getProgram()?.getSourceFile(t.path);if(!f)return;let p={stage:n,errors:[],contents:o.toString(),warnings:[],defines:r.config.define??{},sourceFile:f,context:{argv:c,options:a,variantName:s}},d=await fi(p,r.name);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(d=r.typescript.languageHostService.resolveAliases(d,t.path,".js")),{loader:i,contents:d,warnings:p.warnings,errors:p.errors}}var wt="$$",Ct=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function ui(r,e,t,i){let n=1;for(let s=0;s<i;s++)r[s]===`
35
35
  `&&n++;let o=r.lastIndexOf(`
36
- `,i-1)+1;return{file:t,line:n,column:r.indexOf(e,o)-o}}function ci(r,e){let t=r.lastIndexOf(`
37
- `,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 kt(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],n=d(x),o=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=n.resolve(a);Ft.lastIndex=0;for(let f of c.matchAll(Ft)){let p=f.index;if(ci(c,p))continue;let[,u,g,P]=f;if(t.filesWithMacros.add(l),!u||(u.startsWith(Tt)||i.push({text:`Macro function '${u}' not start with '${Tt}' prefix to avoid conflicts`,location:ai(c,u,a,p)}),g==="inline"))continue;let B=!!o[P];g==="ifndef"===B&&t.disabledMacroNames.add(u)}}return{warnings:i}}var Le=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=d(S);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 kt(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 E("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new he(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new ge(e,t,this.config.variants[e],this.argv),t.onLoad(Et.bind({},this.variants[e]),"build-service")}}};function Bs(r){d(S).reload(r)}function Ls(r){d(S).patch(r)}export{Le as BuildService,Ae as ServerModule,Re as WatchService,Ye as collectFilesFromGlob,Pe as enhancedBuildResult,J as isBuildResultError,Wt as isDirectoryExcluded,ce as matchesAny,ur as normalizeMessageToError,Bs as overwriteConfig,Kt as parseGlobs,Ls as patchConfig,le as processEsbuildMessages,Bi as shouldIncludeFile};
36
+ `,i-1)+1;return{file:t,line:n,column:r.indexOf(e,o)-o}}function di(r,e){let t=r.lastIndexOf(`
37
+ `,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.values(r.dependencies??{});for(let a of s){let c=n.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=n.resolve(a);Ct.lastIndex=0;for(let f of c.matchAll(Ct)){let p=f.index;if(di(c,p))continue;let[,d,g,I]=f;if(t.filesWithMacros.add(l),!d||(d.startsWith(wt)||i.push({text:`Macro function '${d}' not start with '${wt}' prefix to avoid conflicts`,location:ui(c,d,a,p)}),g==="inline"))continue;let A=!!o[I];g==="ifndef"===A&&t.disabledMacroNames.add(d)}}return{warnings:i}}var Ae=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}onEndCallback;onStartCallback;variants={};configuration=u(x);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload({config:e,clearCache:t=!1}={}){t&&q.reload(),e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t=[],i={},n=Object.entries(this.variants).map(async([o,s])=>{if(!(e&&!e.includes(o)))try{let a=await s.build();a&&(i[o]=Ee(a))}catch(a){if(U(a)||a instanceof AggregateError){let c=Ee({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 w("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new le(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new ce(e,t,this.config.variants[e],this.argv),t.onLoad(St.bind({},this.variants[e]),"build-service")}}};function _s(r){u(x).reload(r)}function zs(r){u(x).patch(r)}export{Ae as BuildService,Ie as ServerModule,Te as WatchService,Ue as collectFilesFromGlob,Ee as enhancedBuildResult,U as isBuildResultError,Vt as isDirectoryExcluded,te as matchesAny,tr as normalizeMessageToError,_s as overwriteConfig,Ht as parseGlobs,zs as patchConfig,re as processEsbuildMessages,_i as shouldIncludeFile};
38
38
  //# sourceMappingURL=index.js.map