@remotex-labs/xbuild 2.5.0 → 3.0.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/bash.js CHANGED
@@ -1,83 +1,58 @@
1
- #!/usr/bin/env node
2
- var wr=Object.create;var Ve=Object.defineProperty;var Cr=Object.getOwnPropertyDescriptor;var yt=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),fe=r=>{throw TypeError(r)};var Ir=(r,e,t)=>e in r?Ve(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var mt=(r,e)=>Ve(r,"name",{value:e,configurable:!0});var F=r=>[,,,wr(r?.[yt("metadata")]??null)],vt=["class","method","getter","setter","accessor","field","value","get","set"],le=r=>r!==void 0&&typeof r!="function"?fe("Function expected"):r,Tr=(r,e,t,i,o)=>({kind:vt[r],name:e,metadata:i,addInitializer:n=>t._?fe("Already initialized"):o.push(le(n||null))}),Or=(r,e)=>Ir(e,yt("metadata"),r[3]),k=(r,e,t,i)=>{for(var o=0,n=r[e>>1],s=n&&n.length;o<s;o++)e&1?n[o].call(t):i=n[o].call(t,i);return i},A=(r,e,t,i,o,n)=>{var s,a,c,l,p,f=e&7,d=!!(e&8),m=!!(e&16),$=f>3?r.length+1:f?d?1:2:0,_=vt[f+5],j=f>3&&(r[$-1]=[]),Le=r[$]||(r[$]=[]),E=f&&(!m&&!d&&(o=o.prototype),f<5&&(f>3||!m)&&Cr(f<4?o:{get[t](){return gt(this,n)},set[t](C){return ht(this,n,C)}},t));f?m&&f<4&&mt(n,(f>2?"set ":f>1?"get ":"")+t):mt(o,t);for(var ce=i.length-1;ce>=0;ce--)l=Tr(f,t,c={},r[3],Le),f&&(l.static=d,l.private=m,p=l.access={has:m?C=>Fr(o,C):C=>t in C},f^3&&(p.get=m?C=>(f^1?gt:kr)(C,o,f^4?n:E.get):C=>C[t]),f>2&&(p.set=m?(C,He)=>ht(C,o,He,f^4?n:E.set):(C,He)=>C[t]=He)),a=(0,i[ce])(f?f<4?m?n:E[_]:f>4?void 0:{get:E.get,set:E.set}:o,l),c._=1,f^4||a===void 0?le(a)&&(f>4?j.unshift(a):f?m?n=a:E[_]=a:o=a):typeof a!="object"||a===null?fe("Object expected"):(le(s=a.get)&&(E.get=s),le(s=a.set)&&(E.set=s),le(s=a.init)&&j.unshift(s));return f||Or(r,o),E&&Ve(o,t,E),m?f^4?n:E:o};var _e=(r,e,t)=>e.has(r)||fe("Cannot "+t),Fr=(r,e)=>Object(e)!==e?fe('Cannot use the "in" operator on this value'):r.has(e),gt=(r,e,t)=>(_e(r,e,"read from private field"),t?t.call(r):e.get(r));var ht=(r,e,t,i)=>(_e(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),kr=(r,e,t)=>(_e(r,e,"access private method"),t);import{rmSync as jo}from"fs";import{cwd as Lo}from"process";import Se from"node:process";import{resolveError as Ur}from"@remotex-labs/xmap";var Ue=new Map,xt=new Map;function Ar(r){return typeof r=="object"&&r!==null&&"useClass"in r}function Pr(r){return typeof r=="object"&&r!==null&&"useFactory"in r}function Rr(r){return typeof r=="object"&&r!==null&&"useValue"in r}function P(r){return function(e){xt.set(e,r||{})}}function ze(r,e=[]){if(!r)return e;let t=e;for(let i of r.slice(t.length))if(Ar(i))t.push(u(i.useClass,...ze(i.providers)));else if(Pr(i))t.push(i.useFactory(...ze(i.providers)));else if(Rr(i))t.push(i.useValue);else if(typeof i=="function")t.push(u(i));else throw new Error(`Unknown provider type: ${typeof i}`);return t}function u(r,...e){if(Ue.has(r))return Ue.get(r);let t=xt.get(r);if(!t)throw new Error(`Cannot inject ${r.name} \u2013 not marked @Injectable`);let i=ze(t.providers,e),o=t.factory?t.factory(...i):new r(...i);return t?.scope==="singleton"&&Ue.set(r,o),o}import{xterm as Ye}from"@remotex-labs/xansi/xterm.component";import $r from"typescript";import{resolve as Mr}from"@remotex-labs/xmap";import{closeSync as Br,fstatSync as Nr,openSync as Dr,readFileSync as jr}from"fs";var bt,We;bt=[P({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=Mr(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=Dr(e,"r");try{let{mtimeMs:o}=Nr(i);if(o===t.mtimeMs)return;let n=jr(i,"utf-8");t.version++,t.mtimeMs=o,t.contentSnapshot=n?$r.ScriptSnapshot.fromString(n):void 0}finally{Br(i)}}};We=F(null),v=A(We,0,"FilesModel",bt,v),k(We,1,v);import{readFileSync as Lr}from"fs";import{SourceService as Hr}from"@remotex-labs/xmap";import{resolve as Ge,toPosix as St}from"@remotex-labs/xmap";var Et,Ke;Et=[P({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,o=t?.toLowerCase();return!!(t&&o.includes("xbuild")&&!o.includes("xbuild.config")||i&&i.includes("xBuild"))}getSourceMap(e){if(e=Ge(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let i=Ge(t);try{return this.initializeSourceMap(e,i)}catch(o){throw new Error(`Failed to initialize SourceService: ${i}
3
- ${o instanceof Error?o.message:String(o)}`)}}setSourceFile(e){if(!e)return;let t=Ge(e),i=`${e}.map`;if(!this.sourceMaps.has(t))try{let o=Lr(i,"utf-8");return this.initializeSourceMap(o,t)}catch(o){throw new Error(`Failed to initialize SourceService: ${t}
4
- ${o instanceof Error?o.message:String(o)}`)}}getRootDir(){return St(process.cwd())}getDistDir(){return St(import.meta.dirname)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let i=new Hr(e,t);this.sourceMaps.set(t,i)}};Ke=F(null),b=A(Ke,0,"FrameworkService",Et,b),k(Ke,1,b);import{parseErrorStack as Ot}from"@remotex-labs/xmap/parser.component";function wt(r){return e=>new U(t=>e.subscribe({next:i=>{try{let o=r(i);t.next?.(o)}catch(o){t.error?.(o)}},error:i=>t.error?.(i),complete:()=>t.complete?.()}))}function Ct(r=(e,t)=>e===t){return e=>new U(t=>{let i=!1,o;return e.subscribe({next:n=>{try{if(!i){o=n,i=!0,t.next?.(n);return}r(o,n)||(o=n,t.next?.(n))}catch(s){t.error?.(s)}},error:n=>t.error?.(n),complete:()=>t.complete?.()})})}var U=class{constructor(e){this.handler=e}handler;subscribe(e,t,i){let o=this.createSafeObserver(e,t,i),n;try{n=this.handler(o)}catch(s){return o.error?.(s),()=>{}}return()=>{try{n?.()}catch(s){o.error?.(s)}}}pipe(...e){return e.length===0?this:e.reduce((t,i)=>i(t),this)}createSafeObserver(e,t,i){return typeof e=="function"?{next:e,error:t,complete:i}:e||{}}};var pe=class extends U{isCompleted=!1;observers=new Set;constructor(){super(e=>{if(this.isCompleted){e.complete?.();return}return this.observers.add(e),()=>this.observers.delete(e)})}next(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.next?.(e)}catch(o){t.push(o);try{i.error?.(o)}catch{}}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in next()`)}error(e){if(this.isCompleted)return;let t=[];for(let i of[...this.observers])try{i.error?.(e)}catch(o){t.push(o)}if(t.length>0)throw new AggregateError(t,`${t.length} observer(s) failed in error()`)}complete(){if(this.isCompleted)return;let e=[];for(let t of[...this.observers])try{t.complete?.()}catch(i){e.push(i)}if(this.observers.clear(),this.isCompleted=!0,e.length>0)throw new AggregateError(e,`${e.length} observer(s) failed in complete()`)}};var ue=class extends pe{lastValue;constructor(e){super(),this.lastValue=typeof e=="function"?e():e}get value(){return this.lastValue}subscribe(e,t,i){if(this.isCompleted)return()=>{};let o=this.createSafeObserver(e,t,i),n=super.subscribe(o);return o.next?.(this.lastValue),n}next(e){this.isCompleted||(this.lastValue=e,super.next(e))}};function xe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function z(r,...e){if(!e.length)return r;let t=e.shift();if(xe(r)&&xe(t)){for(let i in t){let o=t[i],n=r[i];Array.isArray(o)&&Array.isArray(n)?Object.assign(r,{[i]:[...n,...o]}):xe(o)?Object.assign(r,{[i]:z(xe(n)?n:{},o)}):Object.assign(r,{[i]:o})}return z(r,...e)}return r}function be(r,e,t=!0){return r===e||Object.is(r,e)?!0:r===null||e===null?!1:r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.source===e.source&&r.flags===e.flags:URL&&r instanceof URL&&e instanceof URL?r.href===e.href:typeof r=="object"&&typeof e=="object"?_r(r,e,t):!1}function Vr(r,e){return r==null||typeof r!="object"&&typeof r!="function"?!1:e in r||Object.prototype.hasOwnProperty.call(r,e)}function _r(r,e,t=!0){if(Array.isArray(r)&&Array.isArray(e))return t&&r.length!==e.length?!1:r.every((n,s)=>be(n,e[s],t));let i=Object.keys(r),o=Object.keys(e);if(t&&i.length!==o.length)return!1;for(let n of i)if(!Vr(e,n)||!be(r[n],e[n],t))return!1;return!0}var It=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 Tt,qe;Tt=[P({scope:"singleton"})];var x=class{constructor(e=It){this.initialConfig=e;this.config$=new ue(z({},e))}initialConfig;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(wt(e),Ct((t,i)=>be(t,i)))}patch(e){let t=z({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(z({},this.initialConfig,e))}};qe=F(null),x=A(qe,0,"ConfigurationService",Tt,x),k(qe,1,x);import{formatErrorCode as zr}from"@remotex-labs/xmap/formatter.component";import{highlightCode as Wr}from"@remotex-labs/xmap/highlighter.component";function Gr(r=""){let t=u(b).getSourceMap(r);if(t)return t;let i=u(v).getOrTouchFile(r),o=i?.contentSnapshot?.text;if(!i||!o)return null;let n=o.split(`
5
- `);return{getPositionWithCode:(s,a,c,l)=>{let p=l?.linesBefore??3,f=l?.linesAfter??3,d=Math.max(s-p,0),m=Math.min(s+f,n.length);return{line:s,column:a+1,code:n.slice(d,m).join(`
6
- `),source:r,name:null,startLine:d,endLine:m,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function Kr(r){return r instanceof Error?Ot(r):r.detail instanceof Error?Ot(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 L(r,e){let t=u(b),i=u(x).getValue(s=>s.verbose)??!1,o=Kr(r),n=Ur(o,{...e,withNativeFrames:i||(e?.withFrameworkFrames??!1),getSource(s){return Gr(s)}});return n.stack.filter(s=>{if(!(e?.withFrameworkFrames??!1)&&t.isFrameworkFile(s))return!1;!n.formatCode&&s.code&&(n.formatCode=zr({code:Wr(s.code),line:s.line??0,column:s.column??0,startLine:s.stratLine??0},{color:Ye.brightPink}))}),n}function H(r,e,t,i=[]){let o=[`
7
- ${e}: ${Ye.lightCoral(t)}`];for(let n of i??[])n.text&&o.push(`
8
- `+Ye.gray(n.text));return r.formatCode&&o.push(`
1
+ var rt=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var or=(i,e,t)=>e in i?rt(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var b=(i,e,t,r)=>{for(var n=r>1?void 0:r?nr(e,t):e,o=i.length-1,s;o>=0;o--)(s=i[o])&&(n=(r?s(e,t,n):s(n))||n);return r&&n&&rt(e,t,n),n};var ce=(i,e,t)=>or(i,typeof e!="symbol"?e+"":e,t);import{rmSync as gn}from"fs";import le from"node:process";import{inject as Re}from"@remotex-labs/xinject";import{readFileSync as sr,statSync as ar}from"fs";import{resolve as cr}from"@remotex-labs/xmap";import{Injectable as lr}from"@remotex-labs/xinject";var h=class{resolved=new Map;cache=new Map;clear(){this.cache.clear(),this.resolved.clear()}getSnapshot(e){return this.cache.get(this.resolve(e))}touch(e,t){let r=this.resolve(e);return this.cache.get(r)??this.sync(r,this.stat(r),t)}refresh(e,t,r){let n=this.resolve(e);return this.sync(n,t??this.stat(n),r)}refreshAll(e){let t=e??this.cache.keys();for(let r of t)this.refresh(r)}resolve(e){let t=this.resolved.get(e);return t===void 0&&this.resolved.set(e,t=cr(e)),t}sync(e,t,r="utf-8"){let n=this.cache.get(e);return t?.isFile()?n?.mtimeMs===t.mtimeMs?n:this.store(e,{mtimeMs:t.mtimeMs,version:(n?.version??0)+1,snapshot:this.snapshot(sr(e,r))}):n&&!n.snapshot?n:this.store(e,{mtimeMs:0,snapshot:void 0,version:(n?.version??0)+1})}changeRange(e,t){let r=e.length,n=t.length,o=Math.min(r,n),s=0;for(;s<o&&e.charCodeAt(s)===t.charCodeAt(s);)s++;let a=0;for(;a<o-s&&e.charCodeAt(r-1-a)===t.charCodeAt(n-1-a);)a++;return{span:{start:s,length:r-s-a},newLength:n-s-a}}snapshot(e){return{text:e,getText:(t,r)=>e.slice(t,r),getLength:()=>e.length,getChangeRange:t=>this.changeRange(t.getText(0,t.getLength()),e)}}store(e,t){return this.cache.set(e,t),t}stat(e){return ar(e,{throwIfNoEntry:!1})}};h=b([lr({scope:"singleton"})],h);import{resolveError as hr}from"@remotex-labs/xmap";import{xterm as De}from"@remotex-labs/xansi/xterm.component";import{cwd as fr}from"process";import{readFileSync as pr}from"fs";import{inject as ur,Injectable as dr}from"@remotex-labs/xinject";import{normalize as Le,SourceService as mr}from"@remotex-labs/xmap";var it=/xbuild(?!\.config)/i,gr=/"mappings"\s*:\s*""/,u=class{frameworkFile;frameworkRoot;projectRoot;sourceMaps=new Map;constructor(){this.projectRoot=Le(fr()),this.frameworkFile=Le(import.meta.filename),this.frameworkRoot=Le(import.meta.dirname),this.loadSourceMap(this.frameworkFile)}static resolve(e){return(u.files??=ur(h)).resolve(e)}isFrameworkFile(e){return it.test(e.source??"")||it.test(e.sourceRoot??"")}getSourceMap(e){return this.sourceMaps.get(u.resolve(e))}addSourceMap(e,t,r=!1){let n=u.resolve(e);!r&&this.sourceMaps.has(n)||this.register(n,t)}loadSourceMap(e){if(!e)return;let t=u.resolve(e);if(this.sourceMaps.has(t))return;let r;try{r=pr(`${t}.map`,"utf-8")}catch(n){throw u.failure(t,n)}this.register(t,r)}static failure(e,t){return new Error(`Failed to load source map for: ${e}
2
+ ${t instanceof Error?t.message:String(t)}`)}register(e,t){if(!gr.test(t))try{this.sourceMaps.set(e,new mr(t,e))}catch(r){throw u.failure(e,r)}}};ce(u,"files"),u=b([dr({scope:"singleton"})],u);import{parseErrorStack as nt}from"@remotex-labs/xmap/parser.component";import{formatErrorCode as yr}from"@remotex-labs/xmap/formatter.component";import{highlightCode as vr}from"@remotex-labs/xmap/highlighter.component";function br(i=""){let t=Re(u).getSourceMap(i);if(t)return t;let r=Re(h).touch(i),n=r.snapshot?.text;if(!r||!n)return null;let o=n.split(`
3
+ `);return{getPositionWithCode:(s,a,c,l)=>{let f=l?.linesAfter??3,p=l?.linesBefore??3,S=Math.max(s-p,1),d=Math.min(s+f,o.length);return{line:s,name:null,code:o.slice(S-1,d).join(`
4
+ `),source:i,column:a,endLine:d,startLine:S,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1}}}}function xr(i){return i instanceof Error?nt(i):i.detail instanceof Error?nt(i.detail):i.location?{name:"esBuildMessage",message:i.text??"",rawStack:"",stack:[{source:`@${i.location.file}`,line:i.location.line,column:i.location.column||1,fileName:i.location.file,eval:!1,async:!1,native:!1,constructor:!1}]}:{stack:[],name:"esBuildMessage",message:i.text??"",rawStack:""}}function B(i,e,t=!1){let r=Re(u),n=xr(i),o=hr(n,{...e,withNativeFrames:t||(e?.withFrameworkFrames??!1),getSource(s){return br(s)}});return o.stack.filter(s=>{if(!(e?.withFrameworkFrames??!1)&&r.isFrameworkFile(s))return!1;!o.formatCode&&s.code&&(o.formatCode=yr({code:vr(s.code),line:s.line??1,column:s.column??1,startLine:s.stratLine??1},{color:De.brightPink}))}),o}function Q(i,e,t,r=[]){let n=[`
5
+ ${e}: ${De.lightCoral(t)}`];for(let o of r??[])o.text&&n.push(`
6
+ `+De.gray(o.text));return i.formatCode&&n.push(`
9
7
 
10
- ${r.formatCode}`),r.stack.length&&o.push(`
8
+ ${i.formatCode}`),i.stack.length&&n.push(`
11
9
 
12
10
  Enhanced Stack Trace:
13
- ${r.stack.map(n=>n.format).join(`
11
+ ${i.stack.map(o=>o.format).join(`
14
12
  `)}
15
- `),o.join("")}var y=class extends Error{errorMetadata;formattedStack;constructor(e,t="xBuildBaseError"){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=t,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}get metadata(){return this.errorMetadata}[Symbol.for("nodejs.util.inspect.custom")](){return this.formattedStack||this.stack}reformatStack(e,t){this.errorMetadata=L(e,t),this.formattedStack=H(this.errorMetadata,e.name,e.message)}};function Ft(r){if(r instanceof AggregateError){console.error("AggregateError:",r.message);for(let e of r.errors)if(e instanceof Error&&!(e instanceof y)){let t=L(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(H(t,e.name,e.message))}else console.error(e);return}if(r instanceof Error&&!(r instanceof y)){let e=L(r,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(H(e,r.name,r.message))}else console.error(r)}Se.on("uncaughtException",r=>{Ft(r),Se.exit(2)});Se.on("unhandledRejection",r=>{Ft(r),Se.exit(2)});import{join as Ho}from"@remotex-labs/xmap";import Xe from"yargs";import{hideBin as Yr}from"yargs/helpers";var qr="config.xbuild.ts",Ee={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:qr},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string"},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0}},kt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var At,Je;At=[P({scope:"singleton"})];var Q=class{parseConfigFile(e){return Xe(e).help(!1).version(!1).options({config:Ee.config}).parseSync()}parseUserArgv(e,t){return t?Xe(e).help(!1).version(!1).options(t).parseSync():{}}enhancedParse(e,t={}){let i=Xe(Yr(e)).locale("en"),o=i.showHelp;return i.showHelp=function(n){return this.group(Object.keys(Ee),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),o.call(this,n)},i.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",n=>n.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(Ee).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),kt.forEach(([n,s])=>{i.example(n,s)}),i.parseSync()}};Je=F(null),Q=A(Je,0,"ArgvModule",At,Q),k(Je,1,Q);import lt from"readline";import{exec as ho}from"child_process";import{cwd as Xr}from"process";import{readdirSync as Jr}from"fs";import{matchesGlob as Qe}from"path";import{join as Qr}from"@remotex-labs/xmap";function Zr(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 Pt(r,e){for(let t of e)if(t.endsWith(r)||Qe(r,t))return!0;return!1}function ei(r,e){let t=r+"/**";for(let i of e)if(Qe(r,i)||Qe(t,i))return!0;return!1}function we(r,e){let{include:t,exclude:i}=Zr(e),o=Object.create(null),s=Xr().length+1,a=r.length+1,c=i.length>0;function l(p){let f;try{f=Jr(p,{withFileTypes:!0})}catch{return}let d=f.length;for(let m=0;m<d;m++){let $=f[m],_=Qr(p,$.name),j=_.slice(a);if($.isDirectory()){(!c||!ei(j,i))&&l(_);continue}if(!(c&&Pt(j,i))&&Pt(j,t)){let Le=_.slice(s),E=j.lastIndexOf("."),ce=E>0?j.slice(0,E):j;o[ce]=Le}}}return l(r),o}var M=class r extends Error{diagnostics;constructor(e,t=[]){super(e),this.name="TypesError",this.diagnostics=t,Object.setPrototypeOf(this,r.prototype)}};var S=class extends y{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};var W=class extends y{id;constructor(e,t){super(e.text??"","esBuildError"),this.id=e.id??"",e.detail instanceof Error?(this.stack=e.detail.stack,this.message=e.detail.message,this.reformatStack(e.detail,t)):(this.errorMetadata=L(e,{withFrameworkFrames:!0}),this.stack=H(this.errorMetadata,this.name,this.message,e.notes))}};function ti(r){if(r instanceof y)return r;if(r.detail instanceof y||r.detail instanceof M)return r.detail;if(r.detail instanceof Error)return new W(r,{withFrameworkFrames:!0});if(r.location)return new W(r);if(r.text)return new S(r.text)}function de(r=[],e){for(let t of r){let i=ti(t);i&&e.push(i)}}function me(r){let e={errors:[],warnings:[],metafile:r.metafile,outputFiles:r.outputFiles,mangleCache:r.mangleCache};return de(r.errors,e.errors),de(r.warnings,e.warnings),e}function V(r){return typeof r=="object"&&r!==null&&"errors"in r}import*as Nt from"http";import*as Dt from"https";import{extname as Mt}from"path";import{readFileSync as Bt}from"fs";var Rt=`<!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 oi,join as Ce}from"@remotex-labs/xmap";import{xterm as Ze}from"@remotex-labs/xansi/xterm.component";var ii=`
13
+ `),n.join("")}var F=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=B(e,t),this.formattedStack=Q(this.errorMetadata,e.name,e.message)}};function ot(i){if(i instanceof AggregateError){console.error("AggregateError:",i.message);for(let e of i.errors)if(e instanceof Error&&!(e instanceof F)){let t=B(e,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(Q(t,e.name,e.message))}else console.error(e);return}if(i instanceof Error&&!(i instanceof F)){let e=B(i,{withFrameworkFrames:!0,withNativeFrames:!0});console.error(Q(e,i.name,i.message))}else console.error(i)}le.on("uncaughtException",i=>{ot(i),le.exit(2)});le.on("unhandledRejection",i=>{ot(i),le.exit(3)});import{exit as ki}from"process";import{exec as Fr}from"child_process";import*as dt from"node:readline";import{resolve as kr}from"path";import{stdout as ue}from"process";import{xterm as Pe}from"@remotex-labs/xansi/xterm.component";var Sr=`
16
14
  ______ _ _ _
17
15
  | ___ \\ (_) | | |
18
16
  __ _| |_/ /_ _ _| | __| |
19
17
  \\ \\/ / ___ \\ | | | | |/ _\` |
20
18
  > <| |_/ / |_| | | | (_| |
21
19
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
22
- `;function $t(){return`
23
- \r${Ze.burntOrange(ii)}
24
- \rVersion: ${Ze.brightPink("2.5.0")}
25
- \r`}function I(){return Ze.lightCoral("[xBuild]")}import{readdir as ni,stat as si,readFile as ai}from"fs/promises";import{xterm as Ie}from"@remotex-labs/xansi/xterm.component";var ge=class{constructor(e,t){this.config=e;this.rootDir=oi(t),this.config.port||=0,this.config.host||="localhost"}config;server;rootDir;framework=u(b);async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server){console.log(I(),Ie.gray("No server is currently running."));return}await new Promise((e,t)=>{this.server.close(i=>{i?t(i):e()})}),console.log(I(),Ie.dim("Server stopped.")),this.server=void 0}async restart(){console.log(I(),Ie.burntOrange("Restarting server...")),await this.stop(),await this.start()}setActualPort(){if(this.config.port===0){let e=this.server.address();e&&typeof e=="object"&&e.port&&(this.config.port=e.port)}}startHttpServer(){return new Promise(e=>{this.server=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:Bt(this.config.key??Ce(this.framework.distPath,"..","certs","server.key")),cert:Bt(this.config.cert??Ce(this.framework.distPath,"..","certs","server.crt"))};this.server=Dt.createServer(t,(i,o)=>{this.handleRequest(i,o,()=>this.defaultResponse(i,o))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort(),this.config.onStart?.({host:this.config.host,port:this.config.port,url:`https://${this.config.host}:${this.config.port}`}),e()})})}handleRequest(e,t,i){try{this.config.verbose&&console.log(`${I()} Request ${Ie.lightCoral(e.url?.toString()??"")}`),this.config.onRequest?this.config.onRequest(e,t,i):i()}catch(o){this.sendError(t,o)}}getContentType(e){return{html:"text/html",css:"text/css",js:"application/javascript",cjs:"application/javascript",mjs:"application/javascript",ts:"text/plain",map:"application/json",json:"application/json",png:"image/png",jpg:"image/jpeg",gif:"image/gif",txt:"text/plain"}[e]||"application/octet-stream"}async defaultResponse(e,t){let i=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",o=Ce(this.rootDir,i);if(!o.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await si(o);n.isDirectory()?await this.handleDirectory(o,i,t):n.isFile()&&await this.handleFile(o,t)}catch(n){let s=n.message;s.includes("favicon")||console.log(I(),s),this.sendNotFound(t)}}async handleDirectory(e,t,i){let n=(await ni(e)).map(l=>{let p=Ce(t,l),f=Mt(l).slice(1)||"folder";return f==="folder"?`
26
- <a href="/${p}" class="folder-row">
20
+ `;function st(){return`
21
+ \r${Pe.burntOrange(Sr)}
22
+ \rVersion: ${Pe.brightPink("3.0.0")}
23
+ \r`}function at(){return Pe.lightCoral("[xBuild]")}import{relative as Cr}from"@remotex-labs/xmap";import{inject as $r}from"@remotex-labs/xinject";import{stripAnsi as Er}from"@remotex-labs/xansi";import{cursorTo as Tr,clearScreenDown as Mr}from"readline";import{xterm as Lr}from"@remotex-labs/xansi/xterm.component";import{xterm as R}from"@remotex-labs/xansi/xterm.component";var fe=R.hex("#a6da95"),Qn=R.hex("#cad3f5"),w=R.hex("#91d7e3"),T=R.hex("#eed49f"),N=R.hex("#f5a97f"),pe=R.hex("#ed8796"),D=R.hex("#c6a0f6"),m=R.hex("#939ab7");var q={verbose:0,info:1,warning:2,error:3,silent:4};function M(i,e=w.dim("\u2192")){return`${at()} ${e} ${w(i)}`}function ft(i){return Er(i).length}function X(i,e){return i+" ".repeat(Math.max(0,e-ft(i)))}function Rr(i){if(i.includes("://"))return i;let e=i.startsWith(".")?kr($r(u).frameworkRoot,i):u.resolve(i);return Cr(process.cwd(),e)}function Dr(i,e=0,t=0){if(!i)return"";let r=m.dim(":");return`${N(Rr(i))}${r}${T(String(e))}${r}${T(String(t))}`}function Pr(i,e){let t=`${process.cwd()}/`,r=[];return i.formatCode&&r.push("",...i.formatCode.split(`
24
+ `).map(n=>`${e}${Lr.dim(n)}`)),i.stack.length>1&&r.push("",...i.stack.map(n=>`${e}${m.dim(n.format.replaceAll(t,""))}`)),r.length>0?[...r,""]:r}function Ar(i,e){let t=i.id?.startsWith("TS")??!1,r=t&&!e?void 0:B(i,{linesAfter:1,linesBefore:1,withFrameworkFrames:!0}),n=t?void 0:r?.stack[0],o=n??i.location;return{id:i.id??"",detail:e&&r?Pr(r," ".repeat(2)):[],location:Dr(n?.fileName??i.location?.file,o?.line,o?.column)}}function te(i,e,t,r,n=!1){if(i.length<1)return;let o=0,s=0,a=[];for(let l of i){let f=Ar(l,n);o=Math.max(o,ft(f.location)),s=Math.max(s,f.id.length),a.push(f)}let c=[`
25
+ ${t(e)} ${m.dim(`(${a.length})`)}`];for(let[l,{id:f,location:p,detail:S}]of a.entries()){let d=s>0?`${X(t(f),s)} `:"";c.push(`${" "}${t(r)} ${X(p,o)} ${d}${m(i[l].text??"")}`),c.push(...S)}console.log(c.join(`
26
+ `))}function me(){let i=Math.max(0,ue.rows-2);i>0&&console.log(`
27
+ `.repeat(i)),Tr(ue,0,0),Mr(ue)}function de(){return ue.columns||100}function Ae(i){return i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(2)} KB`:`${(i/1048576).toFixed(2)} MB`}function pt(i,e=6){let t=Object.entries(i.outputs).sort(([,f],[,p])=>p.bytes-f.bytes);if(t.length<1)return;let r=t.slice(0,e),n=r.map(([,{bytes:f}])=>Ae(f)),o=Math.max(...n.map(f=>f.length)),s=t.reduce((f,[,{bytes:p}])=>f+p,0),a=de()-" ".length-o-4,c=` ${fe("Outputs")} ${m.dim(`(${t.length})`)}`,l=[`
28
+ ${X(c,de()-o-1)}${T.dim(Ae(s))}`];for(let[f,[p]]of r.entries())l.push(`${" "}${w.dim("\u2192")} ${X(N(p),a+1)}`+T.dim(n[f].padStart(o)));if(t.length>e){let f=t.slice(e).reduce((S,[,{bytes:d}])=>S+d,0),p=m.dim(`${"\xB7"} ${t.length-e} more`);l.push(`${" "} ${X(p,a+1)}${T.dim(Ae(f).padStart(o))}`)}console.log(l.join(`
29
+ `))}import{platform as Nr,stdin as H,stdout as k,exit as Vr}from"process";import{xterm as Hr}from"@remotex-labs/xansi/xterm.component";import{ANSI as L,moveCursor as Oe,writeRaw as P}from"@remotex-labs/xansi";import{ShadowRenderer as _r}from"@remotex-labs/xansi/shadow.service";var Ur={darwin:"open",win32:"start"},Wr=[{key:"h",describe:"show this menu",server:!1},{key:"b",describe:"run the build",server:!1},{key:"r",describe:"reload and rebuild",server:!1},{key:"v",describe:"toggle verbose",server:!1},{key:"c",describe:"clear the screen",server:!1},{key:"o",describe:"open it in a browser",server:!0},{key:"q",describe:"quit",server:!1}],I,mt="",z,re;function qr(){return new Promise(i=>{let e=t=>{let r=/\[(\d+);\d+R/.exec(t.toString());r&&(H.off("data",e),i(Number(r[1])))};H.on("data",e),P("\x1B[6n"),setTimeout(()=>(H.off("data",e),i(k.rows)),100).unref()})}function zr(i){Fr(`${Ur[Nr]??"xdg-open"} ${i}`)}function Kr(){let i=[`
30
+ \u{1F680} ${D("Shortcuts")}`];for(let{key:e,describe:t,server:r}of Wr)(!r||I?.url)&&i.push(`${" "}${m.dim("press")} ${Hr.bold(e)} ${m.dim(`to ${t}`)}`);return`${i.join(`
31
+ `)}
32
+ `}function ie(i=!1){if(!z)return;let e=[mt||`${w.dim("\u21BB")} ${m("watching")}`];I?.url&&e.push(N(I.url)),I?.logLevel==="verbose"&&e.push(D("verbose")),e.push(m.dim("press h for shortcuts")),P(L.SAVE_CURSOR),z.writeText(0,0,` ${e.join(m.dim(` ${"\xB7"} `))}`,!0),z.render(i),P(L.RESTORE_CURSOR)}function gt(i){mt=i,ie()}async function ht(i){if(!H.isTTY||!k.isTTY||re)return;I=i,H.setRawMode(!0),P(L.HIDE_CURSOR);let e=await qr();e>=k.rows&&P(`
33
+ `),ut(Math.min(e,k.rows-1)),dt.emitKeypressEvents(H),H.on("keypress",(t,r)=>Gr(r)),k.on("resize",()=>ut()),re=setInterval(()=>ie(!0),300).unref(),process.on("exit",yt)}function yt(){re&&(clearInterval(re),re=void 0,z=void 0,P(`\x1B[r${Oe(k.rows,1)}${L.CLEAR_LINE}${L.SHOW_CURSOR}`))}function ut(i){if(k.rows<4)return z=void 0,P(`\x1B[r${L.CLEAR_LINE}`);let e=k.rows-1,t=i===void 0?L.RESTORE_CURSOR:Oe(i,1);z=new _r(1,de(),e,1),P(`${L.SAVE_CURSOR}\x1B[1;${e}r${Oe(k.rows,1)}${L.CLEAR_LINE}${t}`),ie(!0)}async function Gr(i){switch(i.ctrl&&(i.name==="c"||i.name==="d")&&(i.name="q"),i.name){case"q":yt(),k.write(`${m("Stopped.")}
34
+ `,()=>Vr(process.exitCode?Number(process.exitCode):0));return;case"c":return me(),ie(!0);case"h":return console.log(Kr());case"v":return I?.toggleVerbose(),ie(!0);case"o":I?.url&&zr(I.url);return;case"b":return I?.rebuild("rebuilding");case"r":return I?.rebuild("reloading",!0)}}import{Injectable as Ci,inject as $i}from"@remotex-labs/xinject";import{Injectable as Qr}from"@remotex-labs/xinject";import{BehaviorSubject as Xr}from"@remotex-labs/xobservable";function je(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}function vt(i){if(!je(i))return!1;let e=Object.getPrototypeOf(i);return e===null||Object.getPrototypeOf(e)===null}function C(i,...e){if(!e.length)return i;let t=e.shift();if(je(i)&&je(t)){for(let r in t){let n=t[r],o=i[r];Array.isArray(n)&&Array.isArray(o)?Object.assign(i,{[r]:[...o,...n]}):vt(n)?Object.assign(i,{[r]:C(vt(o)?o:{},n)}):Object.assign(i,{[r]:n})}return C(i,...e)}return i}function he(i,e,t=!0){return i===e||Object.is(i,e)?!0:i===null||e===null?!1:i instanceof Date&&e instanceof Date?i.getTime()===e.getTime():i instanceof RegExp&&e instanceof RegExp?i.source===e.source&&i.flags===e.flags:URL&&i instanceof URL&&e instanceof URL?i.href===e.href:typeof i=="object"&&typeof e=="object"?Jr(i,e,t):!1}function Yr(i,e){return i==null||typeof i!="object"&&typeof i!="function"?!1:e in i||Object.prototype.hasOwnProperty.call(i,e)}function Jr(i,e,t=!0){if(Array.isArray(i)&&Array.isArray(e))return t&&i.length!==e.length?!1:i.every((o,s)=>he(o,e[s],t));let r=Object.keys(i),n=Object.keys(e);if(t&&r.length!==n.length)return!1;for(let o of r)if(!Yr(e,o)||!he(i[o],e[o],t))return!1;return!0}function ye(i){return JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString()+"n":t)}import{map as Zr,distinctUntilChanged as ei}from"@remotex-labs/xobservable";var bt=Object.freeze({common:Object.freeze({types:!0,logOverride:{},declaration:!0,esbuild:Object.freeze({write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:process.cwd(),legalComments:"none"})})});var $=class{constructor(e=bt){this.initialConfig=e;this.config$=new Xr(C({},e))}initialConfig;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(Zr(e),ei((t,r)=>he(t,r)))}patch(e){let t=C({},this.config$.value,e);this.config$.next(t)}reload(e){this.config$.next(C({},this.initialConfig,e))}};$=b([Qr({scope:"singleton"})],$);import v from"typescript";import{Injectable as vi}from"@remotex-labs/xinject";import{normalize as bi,relative as xi,dirname as Si}from"@remotex-labs/xmap";import{existsSync as ti}from"fs";import{parseSync as ri}from"oxc-parser";import{inject as ii}from"@remotex-labs/xinject";import{mkdir as ni,writeFile as oi}from"fs/promises";import{isolatedDeclarationSync as si}from"oxc-transform";import{join as Fe,dirname as Ne,relative as ai}from"@remotex-labs/xmap";function A(i,e,t){let r=i.end;for(;r<e.length;){let n=e.charCodeAt(r);if(n!==32&&n!==9)break;r++}e.charCodeAt(r)===13&&r++,e.charCodeAt(r)===10&&r++,t.push({start:i.start,end:r})}function K(i,e){if(e.length<1)return i;e.sort((o,s)=>o.start-s.start);let t=new Array(e.length*2+1),r=0,n=0;for(let o=0;o<e.length;o++){let s=e[o];s.start<n||(t[r++]=i.slice(n,s.start),t[r++]=s.text??"",n=s.end)}return t[r++]=i.slice(n),t.length=r,t.join("")}function xt(i,e,t,r){if(!i)return;let n=r.resolve(i.value,e);if(!n||n.isExternalLibraryImport)return;let{extension:o,relativeFileName:s}=n,a=o?s.slice(0,-o.length):s;t.push({end:i.end,start:i.start,text:`'${a}.js'`})}function St(i,e,t="",r){if(!t)return t;let n=[];for(let o of i.program.body)switch(o.type){case"ImportDeclaration":case"ExportAllDeclaration":case"ExportNamedDeclaration":xt(o.source,e,n,r);break;case"TSImportEqualsDeclaration":o.moduleReference.type==="TSExternalModuleReference"&&xt(o.moduleReference.expression,e,n,r)}return K(t,n)}var wt=`/**
35
+ * This file was automatically generated by xBuild.
36
+ * DO NOT EDIT MANUALLY.
37
+ */
38
+ `;var ve=class{constructor(e){this.ts=e}ts;cache=new Map;filesCache=ii(h);emitted=new Map;clear(){this.cache.clear(),this.emitted.clear()}touch(e){let t=this.filesCache.resolve(e),r=this.filesCache.touch(t),n=this.cache.get(t);if(n?.version===r.version)return n;let o=this.build(t,r.snapshot?.text??"",r.version);return this.cache.set(t,o),o}async emit(e,t){let r=[],n=[],o=new Set,s=new Map;for(let[c,l]of Object.entries(e))s.set(this.filesCache.resolve(l),c);let a=[...s.keys()];for(;a.length>0;){let c=a.pop();if(o.has(c)||c.endsWith(".d.ts"))continue;o.add(c);let l=this.touch(c);for(let p of l.projectDependencies)o.has(p)||a.push(p);let f=this.outputPath(c,t,s.get(c));this.emitted.get(f)===l.version&&ti(f)||(this.emitted.set(f,l.version),r.push(f),n.push(l.declaration))}return this.write(r,n)}async emitBundle(e,t){let r=this.ts.config.options,n=this.filesCache.resolve(t??r.declarationDir??r.outDir??".");return this.write(Object.keys(e).map(o=>Fe(n,`${o}.d.ts`)),Object.values(e).map(o=>this.bundle(o)))}bundle(e){let t=this.filesCache.resolve(e),r=this.touch(t);return this.render(this.collectClosure(t,r),this.collectSurface(t,r))}async write(e,t){if(e.length<1)return e;let r=new Set(e.map(n=>Ne(n)));return await Promise.all([...r].map(n=>ni(n,{recursive:!0}))),await Promise.all(e.map((n,o)=>oi(n,t[o],"utf-8"))),e}outputPath(e,t,r){let{declarationDir:n,outDir:o,rootDir:s}=this.ts.config.options,a=t??n??o,c=a?this.filesCache.resolve(a):Ne(e);if(r)return Fe(c,`${r}.d.ts`);let l=s?this.filesCache.resolve(s):Ne(e);return Fe(c,ai(l,e).replace(/\.([cm]?)tsx?$/,".d.$1ts"))}collectClosure(e,t){let r=new Set([e]),n=[],o=[...t.projectDependencies];for(;o.length>0;){let s=o.pop();if(r.has(s))continue;r.add(s);let a=this.touch(s);n.push(a);for(let c of a.projectDependencies)r.has(c)||o.push(c)}return n.push(t),n}collectSurface(e,t){let r=new Set,n=new Set,o=new Set([e]),s=[t];for(;s.length>0;){let a=s.pop();for(let c of a.projectExports.exports)r.add(this.clause(c));for(let[c,l]of Object.entries(a.packageExports)){l.star&&n.add(`export * from '${c}';`),l.named?.length&&n.add(`export { ${l.named.map(f=>this.clause(f)).join(", ")} } from '${c}';`);for(let f of l.namespaces??[])n.add(`export * as ${f} from '${c}';`)}for(let c of a.projectExports.star)o.has(c)||(o.add(c),s.push(this.touch(c)))}return{exports:r,statements:n}}mergeImports(e){let t=new Map;for(let r of e)for(let[n,o]of Object.entries(r.packageImports)){let s=t.get(n);s||t.set(n,s={side:!1,named:new Set,namespaces:new Set}),o.side&&(s.side=!0),s.default??=o.default;for(let a of o.namespaces??[])s.namespaces.add(a);for(let a of o.named??[])s.named.add(this.clause(a))}return t}renderImports(e){let t=[];for(let[r,n]of e){n.side&&t.push(`import '${r}';`);for(let s of n.namespaces)t.push(`import * as ${s} from '${r}';`);let o=[];n.default&&o.push(n.default),n.named.size>0&&o.push(`{ ${[...n.named].sort().join(", ")} }`),o.length>0&&t.push(`import ${o.join(", ")} from '${r}';`)}return t}render(e,t){let r=[wt],n=this.renderImports(this.mergeImports(e));n.length>0&&r.push(...n,"");for(let o of e){let s=o.content.trim();s&&r.push(s,"")}return t.exports.size>0&&r.push(`export {
39
+ ${[...t.exports].sort().join(`,
40
+ `)}
41
+ };`),r.push(...t.statements),t.exports.size<1&&t.statements.size<1&&r.push("export {};"),`${r.join(`
42
+ `)}
43
+ `}clause(e){return e.alias?`${e.name} as ${e.alias}`:e.name}build(e,t,r){let n=si(e,t,{stripInternal:!0}).code,o={edits:[],target:e,parsed:ri(e,n,{sourceType:"module"}),content:n,bundleEdits:[],packageImports:Object.create(null),packageExports:Object.create(null),projectExports:{star:new Set,exports:[],namespace:Object.create(null)},projectDependencies:new Set},s=[],{body:a}=o.parsed.program;for(let c of a)this.strip(c,o)&&s.push(c.start);return this.pruneComments(o,a,s),{version:r,content:K(n,o.bundleEdits),declaration:K(n,o.edits),packageImports:o.packageImports,packageExports:o.packageExports,projectExports:o.projectExports,projectDependencies:o.projectDependencies}}strip(e,t){switch(e.type){case"ImportDeclaration":return this.stripImport(e,t),!1;case"ExportAllDeclaration":return this.stripStarExport(e,t),!1;case"ExportNamedDeclaration":return this.stripNamedExport(e,t);case"ExportDefaultDeclaration":return this.stripDefaultExport(e,t);case"TSImportEqualsDeclaration":return this.stripImportEquals(e,t);case"TSExportAssignment":case"TSNamespaceExportDeclaration":return A(e,t.content,t.bundleEdits),!1;default:return!0}}stripImport(e,t){if(A(e,t.content,t.bundleEdits),this.link(e.source,t))return;let r=t.packageImports[e.source.value]??={};if(e.specifiers.length<1){r.side=!0;return}for(let n of e.specifiers)switch(n.type){case"ImportDefaultSpecifier":r.default??=n.local.name;break;case"ImportNamespaceSpecifier":(r.namespaces??=[]).push(n.local.name);break;default:(r.named??=[]).push(this.binding(this.nameOf(n.imported),n.local.name))}}stripImportEquals(e,t){let{moduleReference:r}=e;if(r.type!=="TSExternalModuleReference")return!0;A(e,t.content,t.bundleEdits);let n=r.expression;return this.link(n,t)||((t.packageImports[n.value]??={}).namespaces??=[]).push(e.id.name),!1}stripNamedExport(e,t){let{exports:r}=t.projectExports;if(e.declaration)return this.collectDeclared(e.declaration,r),t.bundleEdits.push({start:e.start,end:e.declaration.start}),!0;A(e,t.content,t.bundleEdits);let n=e.source&&!this.link(e.source,t)?(t.packageExports[e.source.value]??={}).named??=[]:r;for(let o of e.specifiers)n.push(this.binding(this.nameOf(o.local),this.nameOf(o.exported)));return!1}stripStarExport(e,t){A(e,t.content,t.bundleEdits);let r=this.link(e.source,t),n=e.exported?this.nameOf(e.exported):null;if(r){n?t.projectExports.namespace[n]=r:t.projectExports.star.add(r);return}let o=t.packageExports[e.source.value]??={};n?(o.namespaces??=[]).push(n):o.star=!0}stripDefaultExport(e,t){let{declaration:r}=e,n=this.defaultBinding(r);return n&&t.projectExports.exports.push({name:n,alias:"default"}),n&&r.type!=="Identifier"?(t.bundleEdits.push({start:e.start,end:r.start,text:"declare "}),!0):(A(e,t.content,t.bundleEdits),!1)}pruneComments(e,t,r){let{content:n,bundleEdits:o}=e,s=0,a=0;for(let c of e.parsed.comments)if(!(c.type!=="Block"||c.value.charCodeAt(0)!==42)){for(;s<t.length&&t[s].end<=c.start;)s++;if(!(s<t.length&&t[s].start<c.start)){for(;a<r.length&&r[a]<c.end;)a++;a<r.length&&this.blank(n,c.end,r[a])||A(c,n,o)}}}link(e,t){let r=this.ts.resolve(e.value,t.target);if(!r||r.isExternalLibraryImport)return null;let{extension:n,relativeFileName:o,resolvedFileName:s}=r,a=this.filesCache.resolve(s);return t.projectDependencies.add(a),t.edits.push({end:e.end,start:e.start,text:`'${n?o.slice(0,-n.length):o}.d.ts'`}),a}collectDeclared(e,t){if(e.type==="VariableDeclaration"){for(let r of e.declarations)r.id.type==="Identifier"&&t.push({name:r.id.name});return}"id"in e&&e.id&&"name"in e.id&&t.push({name:e.id.name})}defaultBinding(e){return e.type==="Identifier"?e.name:"id"in e?e.id?.name:void 0}nameOf(e){return"name"in e?e.name:JSON.stringify(e.value)}binding(e,t){return e===t?{name:e}:{name:e,alias:t}}blank(e,t,r){for(let n=t;n<r;n++){let o=e.charCodeAt(n);if(o!==32&&o!==9&&o!==10&&o!==13)return!1}return!0}};import G from"typescript";import{relative as hi}from"@remotex-labs/xmap";import{inject as yi}from"@remotex-labs/xinject";import{readdirSync as ci}from"fs";import{join as li}from"@remotex-labs/xmap";var Ve={64:")",43:")+",42:")*",63:")?"};function He(i){return".+^$()|\\{}[]*?".includes(i)?"\\"+i:i}function g(i,e){return i.charCodeAt(e)}function fi(i,e){return(e===0||g(i,e-1)===47)&&(e+2===i.length||g(i,e+2)===47)}function ne(i){return`(?:${i})`}function _e(i,e){let t=e+1,r=g(i,t);for((r===33||r===94)&&t++,g(i,t)===93&&t++;t<i.length&&g(i,t)!==93;)t+=g(i,t)===92?2:1;return t}function pi(i,e){for(let t=e,r=0;t<i.length;t++){let n=g(i,t);if(n===92)t++;else if(n===40)r++;else{if(n===41&&--r===0)return t;n===91&&(t=_e(i,t))}}return-1}function ui(i,e){let t=!1;for(let r=e+1,n=0;r<i.length;r++){let o=g(i,r);if(o===92)r++;else if(o===123)n++;else if(o===125){if(n===0)return t?r:-1;n--}else o===44&&n===0?t=!0:o===91&&(r=_e(i,r))}return-1}function di(i,e){let t=_e(i,e);if(t>=i.length)return["\\[",e+1];let r=e+1,n="[",o=g(i,r);for((o===33||o===94)&&(n+="^/",r++),g(i,r)===93&&(n+="\\]",r++);r<t;r++)g(i,r)===92?n+="\\"+i[++r]:g(i,r)===94?n+="\\^":n+=i[r];return[n+"]",t+1]}function mi(i,e){for(let t=e;t<i.length;t++){if(g(i,t)===47)return t;g(i,t)===92&&t++}return i.length}function oe(i,e=!1,t=0,r={}){let{dot:n=!1}=r,o="",s=0,a=e,c=n?"":"(?!\\.)",l=c+"[^/]"+"+",f=ne(l+"(?:/"+l+")*")+"?";for(;s<i.length;){let p=g(i,s),S=g(i,s+1);if(S===40&&(p===33||Ve[p])){let d=pi(i,s+1);if(p!==33){let W=d===-1?i.length:d,ae=oe(i.slice(s+2,W),a,124,r);o+="(?:"+ae+Ve[p],s=W+1;continue}if(d!==-1){let W=oe(i.slice(s+2,d),a,124,r),ae=mi(i,d+1),tt=oe(i.slice(d+1,ae),!1,0,r);o+=ne((a?c:"")+`(?!${ne(W)+tt+"(?:$|/)"})`+"[^/]*?"+tt),s=ae;continue}}switch(p){case 47:o+="/",s++,a=!0;break;case 92:o+=s+1<i.length?He(i[s+1]):"\\\\",s+=2;break;case 63:o+=a&&!n?"[^./]":"[^/]",s++;break;case 42:if(S===42&&t!==124&&(s>0||e)&&fi(i,s)){let d=s===0&&t===0?"(?:[A-Za-z]:)?/?":"";g(i,s+2)===47?(o+=d+ne(l+"/")+"*",s+=3,a=!0):(o+=d+f,s+=2)}else o+=(a?c:"")+"[^/]*",s++;break;case 123:{let d=ui(i,s);d===-1?(o+="\\{",s++):(o+=ne(oe(i.slice(s+1,d),a,44,r)),s=d+1);break}case 91:{let[d,W]=di(i,s);o+=(a&&!n&&d!=="\\["?"(?!\\.)":"")+d,s=W;break}case 124:case 44:t===p?(o+="|",a=e):o+=He(i[s]),s++;break;default:o+=He(i[s]),s++}}return o}function gi(i,e={}){return new RegExp("^"+oe(i,!0,0,e)+"$",e.flags)}function se(i,e={}){let t=[],r=[];for(let n of i){let o=!1;for(;g(n,0)===33&&g(n,1)!==40;)o=!o,n=n.slice(1);(o?r:t).push(gi(n,e))}return n=>(t.length===0||t.some(o=>o.test(n)))&&!r.some(o=>o.test(n))}function It(i,e,t={}){let r=u.resolve(i),n=se(e,t),o=t.dot||e.some(c=>g(c,0)===46||c.includes("/.")),s=[],a=[""];for(;a.length>0;){let c=a.pop(),l;try{l=ci(c?li(r,c):r,{withFileTypes:!0})}catch{continue}for(let f of l){if(!o&&g(f.name,0)===46)continue;let p=c?`${c}/${f.name}`:f.name;f.isDirectory()?a.push(p):n(p)&&s.push(p)}}return s}var be=class{constructor(e){this.config=e;this.reload()}config;filesCache=yi(h);trackedFiles=new Set;exclusions=new Map;matches;get tracked(){return this.trackedFiles}get ignoreSourceFile(){return e=>this.isExcluded(e.fileName)}set options(e){this.config=e,this.reload()}clearTracked(){this.trackedFiles.clear(),this.refreshFiles(this.config.fileNames)}reload(){this.matches=this.compileExclude(this.config.raw?.exclude),this.exclusions.clear(),this.clearTracked()}refresh(e){return this.filesCache.refresh(this.track(e))}refreshFiles(e=this.trackedFiles){for(let t of e)this.isExcluded(t)||this.refresh(t)}getCompilationSettings(){return this.config.options}fileExists(e){return G.sys.fileExists(e)}readFile(e,t){return this.filesCache.touch(e,t).snapshot?.text}readDirectory(e,t,r,n,o){return G.sys.readDirectory(e,t,r,n,o)}getDirectories(e){return G.sys.getDirectories(e)}directoryExists(e){return G.sys.directoryExists(e)}getCurrentDirectory(){return G.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackedFiles]}getDefaultLibFileName(e){return G.getDefaultLibFilePath(e)}getScriptVersion(e){return this.filesCache.touch(this.track(e)).version.toString()}getScriptSnapshot(e){return this.filesCache.touch(e).snapshot}realpath(e){return this.filesCache.resolve(e)}compileExclude(e){return e&&e.length>0?se(e):()=>!1}isExcluded(e){let t=this.filesCache.resolve(e),r=this.exclusions.get(t);return r===void 0&&this.exclusions.set(t,r=this.matches(hi(process.cwd(),t))),r}track(e){let t=this.filesCache.resolve(e);return this.trackedFiles.add(t),t}};var y=class{constructor(e="tsconfig.json"){this.configPath=e;this.parsedConfig=this.parseConfig(),this.languageHostService=new be(this.parsedConfig),this.configVersion=this.languageHostService.filesCache.touch(this.configPath).version,this.resolutionCache=this.createResolutionCache(),this.languageService=v.createLanguageService(this.languageHostService,v.createDocumentRegistry(!0)),this.declaration=new ve(this)}configPath;languageService;languageHostService;diagnosticsCache=new Map;builderHost={createHash:v.sys.createHash,readFile:(e,t)=>this.languageHostService.readFile(e,t),getCurrentDirectory:()=>v.sys.getCurrentDirectory(),useCaseSensitiveFileNames:()=>v.sys.useCaseSensitiveFileNames};declaration;parsedConfig;configVersion;resolutionCache;builder;static reload(e=!1){let t=[];for(let[r,n]of y.cache)n.instance.refresh(e)&&t.push(r);return t}get config(){return this.parsedConfig}check(e){let t=this.languageService.getProgram();if(!t)return[];let r=this.languageHostService.ignoreSourceFile,n=s=>s.fileName.includes("node_modules")?!0:r(s),o;for(this.builder=v.createEmitAndSemanticDiagnosticsBuilderProgram(t,this.builderHost,this.builder);o=this.builder.getSemanticDiagnosticsOfNextAffectedFile(void 0,n);)if("fileName"in o.affected){let s=o.affected;this.diagnosticsCache.set(s.fileName,[...o.result,...this.builder.getSyntacticDiagnostics(s),...this.languageService.getSuggestionDiagnostics(s.fileName)].map(a=>this.formatDiagnostic(a)))}return this.reconcileDiagnostics(t,e??this.diagnosticsCache.keys())}async emit(e,t){return t??=this.config.options.outDir??"dist",this.declaration.emit(e,t)}async emitBundle(e,t){return t??=this.config.options.outDir??"dist",this.declaration.emitBundle(e,t)}touchFiles(e){this.languageHostService.refreshFiles(e)}resolve(e,t){let r=t?this.languageHostService.filesCache.resolve(Si(t)):process.cwd(),o=this.resolutionCache.getOrCreateCacheForDirectory(r).get(e,void 0)?.resolvedModule;if(o)return o;let s=v.resolveModuleName(e,t??"",this.parsedConfig.options,this.languageHostService,this.resolutionCache).resolvedModule;if(s){let a=xi(r,s.resolvedFileName);s.container=r,s.relativeFileName=a.startsWith(".")?a:`./${a}`}return s}dispose(){let e=y.cache.get(this.configPath);e&&(e.refCount--,!(e.refCount>0)&&(this.languageService.dispose(),y.cache.delete(this.configPath)))}[Symbol.dispose??Symbol.for("Symbol.dispose")](){this.dispose()}static acquire(e="tsconfig.json"){let t=bi(e),r=y.cache.get(t);if(r)return r.refCount++,r.instance;let n=new y(t);return y.cache.set(t,{instance:n,refCount:1}),n}refresh(e=!1){let{version:t}=this.languageHostService.filesCache.touch(this.configPath);return!e&&t===this.configVersion?!1:(this.configVersion=t,this.parsedConfig=this.parseConfig(),this.languageHostService.options=this.parsedConfig,this.resolutionCache=this.createResolutionCache(),this.declaration.clear(),this.diagnosticsCache.clear(),this.builder=void 0,!0)}createResolutionCache(){return v.createModuleResolutionCache(v.sys.getCurrentDirectory(),e=>this.languageHostService.realpath(e),this.parsedConfig.options)}reconcileDiagnostics(e,t){let r=this.languageHostService.filesCache,n=[];for(let o of t){let s=r.resolve(o),a=this.diagnosticsCache.get(s);a&&(e.getSourceFile(s)?n.push(...a):this.diagnosticsCache.delete(s))}return n}formatDiagnostic(e){let t={message:v.flattenDiagnosticMessageText(e.messageText,`
44
+ `),category:e.category};if(e.file&&e.start!==void 0){let{line:r,character:n}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=r+1,t.column=n+1,t.code=e.code}return t}parseConfig(){let e=v.getParsedCommandLineOfConfigFile(this.configPath,{sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0},{...v.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:v.ScriptTarget.ESNext,module:v.ModuleKind.NodeNext,sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0,moduleResolution:v.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,noEmit:!0,rootDir:e.options?.rootDir??process.cwd(),isolatedModules:!1,useCaseSensitiveFileNames:!0},e}};ce(y,"cache",new Map),y=b([vi({factory(i){return y.acquire(i)}})],y);var Y=class{constructor(e){this.build=e;this.restoreLevel=this.logLevel!=="verbose"?this.logLevel:"info"}build;config$=$i($);serverUrl;restoreLevel;set logLevel(e){this.config$.patch({logLevel:e})}get logLevel(){return this.config$.getValue().logLevel??"info"}get url(){return this.serverUrl??""}set url(e){this.serverUrl=e}buildEvent(e){if(e.type==="start")return this.say(`${w.dim("\u2192")} ${m("building")} ${D(e.context.variantName)}`,`${M("build")} ${D(e.context.variantName)}`);let{errors:t,warnings:r,info:n,verbose:o,metafile:s}=e.buildResult,a=!s;a?process.exitCode=1:process.exitCode=0,this.groups({error:t,warning:r,info:n,verbose:o}),s&&pt(s,this.logLevel==="verbose"?1/0:void 0);let c=a?pe("\xD7"):fe("\u2713"),l=a?T(e.context.variantName):D(e.context.variantName);this.say(`${c} ${l} ${m.dim(`in ${e.duration} ms`)}`,`
45
+ ${M("build",c)} ${l} ${m.dim(`in ${e.duration} ms`)}`)}serverEvent(e){switch(e.type){case"start":return this.url=e.url,console.log(`${M("serve")} ${N(e.url)}`);case"stop":this.serverUrl=void 0,e.running&&console.log(`${M("serve")} ${m("stopped")}`);return;case"request":this.logLevel==="verbose"&&console.log(`${M("serve")} ${m.dim(e.url)}`);return;case"error":if(e.url?.includes("favicon"))return;console.log(`${M("serve",pe("\xD7"))} ${m(e.error.message)}`)}}diagnostics(e){let t=!1;for(let[r,n]of Object.entries(e)){let o=n.error.length+n.warning.length+n.info.length+n.verbose.length;t||=n.error.length>0,console.log(`${M("type-check")} ${D(r)} ${m.dim(`${o} to look at`)}`),this.groups(n),console.log("")}ki(t?1:0)}async rebuild(e,t=!1){me(),y.reload(t),this.say(`${w.dim("\u21BB")} ${m(e)}`,`${M("rebuild",w.dim("\u21BB"))} ${m(e)}`),await this.build()}toggleVerbose(){return this.logLevel==="verbose"?this.logLevel=this.restoreLevel:(this.restoreLevel=this.logLevel,this.logLevel="verbose"),this.logLevel}say(e,t){console.log(t),gt(e)}groups(e){let t=q[this.logLevel],r=this.logLevel==="verbose";q.error>=t&&te(e.error,"Errors",pe,"\xD7",!0),q.warning>=t&&te(e.warning,"Warnings",T,"\u2022",r),q.info>=t&&te(e.info,"Info",w,"\u2192",r),q.verbose>=t&&te(e.verbose,"Verbose",m,"\xB7",r)}};Y=b([Ci({scope:"singleton"})],Y);import Ct from"yargs";import{hideBin as Ti}from"yargs/helpers";import{Injectable as Mi}from"@remotex-labs/xinject";var Ei="config.xbuild.ts",xe={entryPoints:{describe:"Source files to build (supports glob patterns)",type:"string",array:!0},typeCheck:{describe:"Perform type checking without building output",alias:"tc",type:"boolean"},platform:{describe:"Target platform for the build output",alias:"p",type:"string",choices:["browser","node","neutral"]},serve:{describe:"Start server to the <folder>",alias:"s",type:"string"},outdir:{describe:"Directory for build output files",alias:"o",type:"string"},declaration:{describe:"Generate TypeScript declaration files (.d.ts)",alias:"de",type:"boolean"},watch:{describe:"Watch mode - rebuild on file changes",alias:"w",type:"boolean"},config:{describe:"Path to build configuration file",alias:"c",type:"string",default:Ei},tsconfig:{describe:"Path to TypeScript configuration file",alias:"tsc",type:"string"},minify:{describe:"Minify the build output",alias:"m",type:"boolean"},bundle:{describe:"Bundle dependencies into output files",alias:"b",type:"boolean"},types:{describe:"Enable type checking during build process",alias:"btc",type:"boolean"},failOnError:{describe:"Fail build when TypeScript errors are detected",alias:"foe",type:"boolean"},format:{describe:"Output module format",alias:"f",type:"string",choices:["cjs","esm","iife"]},verbose:{describe:"Verbose error stack traces",alias:"v",type:"boolean"},build:{describe:"Select an build configuration variant by names (as defined in your config file)",alias:"xb",type:"string",array:!0},clean:{describe:"Clean build artifacts",type:"boolean",default:!1}},kt=[["xBuild src/index.ts","Build a single file with default settings"],["xBuild src/**/*.ts --bundle --minify","Bundle and minify all TypeScript files"],["xBuild src/app.ts -s","Development mode with watch and dev server"],["xBuild src/app.ts -s dist","Development mode with watch and dev server from dist folder"],["xBuild src/lib.ts --format esm --declaration","Build ESM library with type definitions"],["xBuild src/server.ts --platform node --outdir dist","Build Node.js application to dist folder"],["xBuild --typeCheck","Type check only without generating output"],["xBuild --config custom.xbuild.ts","Use custom configuration file"]];var O=class{parseConfigFile(e){return Ct(e).help(!1).version(!1).options({config:xe.config}).parseSync()}enhancedParse(e,t={}){let r=Ct(Ti(e)).locale("en"),n=r.showHelp;return r.showHelp=function(o){return this.group(Object.keys(xe),"xBuild Options:"),this.group(Object.keys(t),"user Options:"),n.call(this,o)},r.usage("Usage: xBuild [files..] [options]").command("* [entryPoints..]","Specific files to build (supports glob patterns)",o=>o.positional("entryPoints",{describe:"Specific files to build (supports glob patterns)",type:"string",array:!0})).options(t).options(xe).epilogue("For more information, check the documentation https://remotex-labs.github.io/xBuild/").help().alias("help","h").strict().version(),kt.forEach(([o,s])=>{r.example(o,s)}),r.parseSync()}};O=b([Mi({scope:"singleton"})],O);import{inject as et}from"@remotex-labs/xinject";import*as Mt from"http";import*as Lt from"https";import{extname as Et}from"path";import{readFileSync as Tt}from"fs";var $t=`<!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{join as Se}from"@remotex-labs/xmap";import{inject as Ri}from"@remotex-labs/xinject";import{Subject as Di}from"@remotex-labs/xobservable";import{readdir as Pi,stat as Ai,readFile as Oi}from"fs/promises";var we=class{constructor(e,t){this.config=e;this.rootDir=u.resolve(t),this.config.port||=0,this.config.host||="localhost"}config;server;events$=new Di;rootDir;framework=Ri(u);get pipe(){return this.events$.pipe.bind(this.events$)}get subscribe(){return this.events$.subscribe.bind(this.events$)}async start(){if(this.config.https)return await this.startHttpsServer();await this.startHttpServer()}async stop(){if(!this.server)return this.events$.next({type:"stop",running:!1});await new Promise((e,t)=>{this.server.close(r=>{r?t(r):e()})}),this.server=void 0,this.events$.next({type:"stop",running:!0})}async restart(){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=Mt.createServer((t,r)=>{this.handleRequest(t,r,()=>this.defaultResponse(t,r))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort();let t={host:this.config.host,port:this.config.port,url:`http://${this.config.host}:${this.config.port}`};this.config.onStart?.(t),this.events$.next({...t,type:"start"}),e()})})}startHttpsServer(){return new Promise(e=>{let t={key:Tt(this.config.key??Se(this.framework.frameworkRoot,"..","certs","server.key")),cert:Tt(this.config.cert??Se(this.framework.frameworkRoot,"..","certs","server.crt"))};this.server=Lt.createServer(t,(r,n)=>{this.handleRequest(r,n,()=>this.defaultResponse(r,n))}),this.server.listen(this.config.port,this.config.host,()=>{this.setActualPort();let r={host:this.config.host,port:this.config.port,url:`https://${this.config.host}:${this.config.port}`};this.config.onStart?.(r),this.events$.next({...r,type:"start"}),e()})})}handleRequest(e,t,r){try{this.events$.next({type:"request",url:e.url??""}),this.config.onRequest?this.config.onRequest(e,t,r):r()}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 r=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",n=Se(this.rootDir,r);if(!n.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let o=await Ai(n);o.isDirectory()?await this.handleDirectory(n,r,t):o.isFile()&&await this.handleFile(n,t)}catch(o){this.events$.next({type:"error",error:o,url:e.url}),this.sendNotFound(t)}}async handleDirectory(e,t,r){let o=(await Pi(e)).map(l=>{let f=Se(t,l),p=Et(l).slice(1)||"folder";return p==="folder"?`
46
+ <a href="/${f}" class="folder-row">
27
47
  <div class="icon"><i class="fa-solid fa-folder"></i></div>
28
48
  <div class="meta"><div class="name">${l}</div><div class="sub">Folder</div></div>
29
49
  </a>
30
50
  `:`
31
- <a href="/${p}" class="file-row">
51
+ <a href="/${f}" class="file-row">
32
52
  <div class="icon"><i class="fa-solid fa-file-code"></i></div>
33
- <div class="meta"><div class="name">${l}</div><div class="sub">${f}</div></div>
53
+ <div class="meta"><div class="name">${l}</div><div class="sub">${p}</div></div>
34
54
  </a>
35
- `}).join("");n?n=`<div class="list">${n}</div>`:n='<div class="empty">No files or folders here.</div>';let s="/",a=t.split("/").map(l=>(s+=`${l}/`,`<li><a href="${s}">${l}</a></li>`)).join(""),c=Rt.replace("${ fileList }",n).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));i.writeHead(200,{"Content-Type":"text/html"}),i.end(c)}async handleFile(e,t){let i=Mt(e).slice(1)||"txt",o=this.getContentType(i),n=await ai(e);t.writeHead(200,{"Content-Type":o}),t.end(n)}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(I(),t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{matchesGlob as jt}from"path";import{stat as ci,watch as li}from"fs/promises";import{normalize as fi,join as pi}from"@remotex-labs/xmap";var he=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=li(this.framework.rootPath,{recursive:!0});for await(let{filename:o}of i){if(!o)continue;let n=fi(o);if(n.endsWith("~")||!this.include.some(a=>jt(n,a))||this.excludes.some(a=>jt(n,a)))continue;let s=pi(this.framework.rootPath,n);try{if(!(await ci(s)).isFile())continue}catch{}t.add(n),this.debounce(()=>this.handleChangedFiles(e,t))}}async handleChangedFiles(e,t){e?.([...t]),t.clear()}debounce(e,t=150){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}};import Ni from"typescript";import{build as Di}from"esbuild";import{writeFile as Yt,mkdir as ji,readFile as Li}from"fs/promises";import g from"typescript";import ui from"typescript";import{dirname as Lt,relative as di,toPosix as mi}from"@remotex-labs/xmap";var gi=/^#!.*(\r?\n)?/,hi=/export {};\n?/g,yi=/(?:\/\*\*[\s\S]*?\*\/\s*)+(\/\*\*[\s\S]*?\*\/)/g,vi=/^export\s+(?:default\s+)?/gm,xi=/(?<=[:;,{}\[\]()\w"'`])[ \t]*\/\*\*[^\r\n]*?\*\/[ \t]*$/gm;function bi(r){return r.charCodeAt(0)===35&&r.charCodeAt(1)===33?r.replace(gi,""):r}function Si(r){return r.includes("export {}")?r.replace(hi,""):r}function Ei(r){return r=r.replace(xi,""),r.replace(yi,"$1")}function Ht(r){return r.replace(vi,"")}function wi(r){return r.charCodeAt(0)===35||r.includes("export {}")||r.includes("/**")}function Te(r){return wi(r)&&(r=bi(r),r=Si(r),r=Ei(r)),r}function et(r,e){let{outDir:t,rootDir:i,declarationDir:o}=e,n=o||t||Lt(r),s=i||Lt(r),c=di(s,r).replace(/\.tsx?$/,".d.ts"),l=ui.sys.resolvePath(`${n}/${c}`);return mi(l)}var Vt,tt;Vt=[P({scope:"singleton"})];var Z=class{languageService;languageHostService;printer;nodesCache=new Map;filesCache=u(v);constructor(){this.printer=g.createPrinter({newLine:g.NewLineKind.LineFeed})}clear(){this.nodesCache.clear()}get(e){let t=this.filesCache.resolve(e);return this.nodesCache.get(t)}scan(e,t,i){let o=Object.assign(Object.create(Object.getPrototypeOf(this)),this,{languageService:t,languageHostService:i}),n=this.filesCache.getSnapshot(e.fileName).version.toString(),s=this.nodesCache.get(e.fileName);if(s?.version===n)return s;let a=this.initDeclaration(e.fileName,n),c=this.emitDeclaration.call(o,e);return a.content=this.stripImportsExports.call(o,c,a),this.nodesCache.set(e.fileName,a),a}initDeclaration(e,t){return{version:t,fileName:e,content:"",internalDeps:new Set,externalImports:{named:Object.create(null),default:Object.create(null),namespace:Object.create(null)},internalExports:{star:[],exports:[],namespace:Object.create(null)},externalExports:{star:[],exports:Object.create(null),namespace:Object.create(null)}}}resolveModule(e,t){if(!g.isStringLiteral(e))return null;let i=e.text,o=this.languageHostService.resolveModuleName(i,t).resolvedModule?.resolvedFileName;return!o||o.includes("node_modules")?{fileName:i,isExternal:!0}:{fileName:o,isExternal:!1}}addNamedElements(e,t){for(let i of t){let o=i.propertyName?`${i.propertyName.text} as ${i.name.text}`:i.name.text;e.push(o)}}hasExportModifier(e){return g.canHaveModifiers(e)?g.getModifiers(e)?.some(i=>i.kind===g.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 g.createSourceFile(e.fileName.replace(/\.tsx?$/,".d.ts"),i,g.ScriptTarget.Latest,!0)}stripImportsExports(e,t){let i=[],o=[];for(let c of e.statements){if(g.isImportDeclaration(c)){this.handleImport(c,t,i);continue}if(g.isExportDeclaration(c)){this.handleExport(c,t);continue}this.hasExportModifier(c)&&this.extractExportName(c,t),o.push(c)}let n=g.factory.createNodeArray(o),s=this.printer.printList(g.ListFormat.MultiLine,n,e),a=Ht(Te(s));for(let c of i)if(c.includes(" as ")){let[l,p]=c.split(" as ");a=a.replace(new RegExp(`\\b${p}\\b`,"g"),l)}else a=a.replace(new RegExp(`\\b${c}\\.`,"g"),"");return a}handleImport(e,t,i){let{importClause:o,moduleSpecifier:n}=e;if(!o||!n)return;let s=this.resolveModule(n,t.fileName);if(!s)return;let{fileName:a,isExternal:c}=s;if(!c){t.internalDeps.add(a);let{namedBindings:p}=o;if(!p)return;g.isNamespaceImport(p)?i.push(p.name.text):g.isNamedImports(p)&&this.addNamedElements(i,p.elements);return}if(!o){t.externalImports.namespace[a]="";return}o.name&&(t.externalImports.default[a]=o.name.text);let{namedBindings:l}=o;l&&(g.isNamespaceImport(l)?t.externalImports.namespace[l.name.text]=a:g.isNamedImports(l)&&this.addNamedElements(t.externalImports.named[a]??=[],l.elements))}handleExport(e,t){let{moduleSpecifier:i,exportClause:o}=e;if(!i)return;let n=this.resolveModule(i,t.fileName);if(!n)return;let{fileName:s,isExternal:a}=n;if(a||t.internalDeps.add(s),!o){a?t.externalExports.star.push(s):t.internalExports.star.push(s);return}if(g.isNamespaceExport(o)){a?t.externalExports.namespace[o.name.text]=s:t.internalExports.namespace[o.name.text]=s;return}g.isNamedExports(o)&&(a?this.addNamedElements(t.externalExports.exports[s]??=[],o.elements):this.addNamedElements(t.internalExports.exports,o.elements))}extractExportName(e,t){if(g.isVariableStatement(e)){for(let i of e.declarationList.declarations)g.isIdentifier(i.name)&&t.internalExports.exports.push(i.name.text);return}(g.isEnumDeclaration(e)||g.isClassDeclaration(e)||g.isFunctionDeclaration(e)||g.isInterfaceDeclaration(e)||g.isTypeAliasDeclaration(e))&&e.name&&g.isIdentifier(e.name)&&t.internalExports.exports.push(e.name.text)}};tt=F(null),Z=A(tt,0,"GraphModel",Vt,Z),k(tt,1,Z);import G from"typescript";import{matchesGlob as Mi}from"path";import{relative as Bi}from"@remotex-labs/xmap";import{mkdir as Ci,writeFile as Ii}from"fs/promises";import{join as Ti,dirname as Oi}from"@remotex-labs/xmap";var _t=`/**
36
- * This file was automatically generated by xBuild.
37
- * DO NOT EDIT MANUALLY.
38
- */
39
- `;var Oe=class{constructor(e,t){this.languageService=e;this.languageHostService=t}languageService;languageHostService;graphModel=u(Z);async emit(e,t){let i=this.languageService?.getProgram();if(!i)throw new Error("Language service program not available");let o=this.languageHostService.getCompilationSettings();t&&(o={...o,outDir:t}),await Promise.all(Object.entries(e).map(async([n,s])=>{let a=i.getSourceFile(s);if(!a)return;let c=Ti(o.outDir,`${n}.d.ts`);await this.bundleCollectDeclarations(a,i,c)}))}async bundleCollectDeclarations(e,t,i){let o=this.graphModel.scan(e,this.languageService,this.languageHostService),n=await this.getBundleContent(o,t);await Ci(Oi(i),{recursive:!0}),await Ii(i,n,"utf-8")}async getBundleContent(e,t){let i=new Set,o=new Set([e]),n=new Set([e]),s=[...e.internalDeps],a=new Set(e.internalExports.star),c="";for(;s.length>0;){let l=s.pop();if(i.has(l))continue;i.add(l);let p=t.getSourceFile(l);if(!p)continue;let f=this.graphModel.scan(p,this.languageService,this.languageHostService);if(n.add(f),a.has(l)){o.add(f);for(let d of f.internalExports.star)a.add(d)}for(let d of f.internalDeps)i.has(d)||s.push(d);c+=f.content}return c+=e.content,this.parseContent(c,n,o)}collectExternalImports(e){let t=new Map;for(let i of e){for(let[o,n]of Object.entries(i.externalImports.default)){t.has(o)||t.set(o,{named:new Set,namespace:new Map});let s=t.get(o);s.default||(s.default=n)}for(let[o,n]of Object.entries(i.externalImports.named)){t.has(o)||t.set(o,{named:new Set,namespace:new Map});for(let s of n)t.get(o).named.add(s)}for(let[o,n]of Object.entries(i.externalImports.namespace))t.has(n)||t.set(n,{named:new Set,namespace:new Map}),t.get(n).namespace.set(o,n)}return t}generateImportStatements(e){let t=[];for(let[i,{default:o,named:n,namespace:s}]of e){let a=[];if(o&&a.push(o),n.size>0&&a.push(`{ ${Array.from(n).sort().join(", ")} }`),s.size>0)for(let[c]of s)t.push(`import * as ${c} from '${i}';`);a.length>0&&t.push(`import ${a.join(", ")} from '${i}';`)}return t}collectNamespaceExports(e,t=new Set){if(t.has(e))return{exports:[],declarations:[]};t.add(e);let i=this.graphModel.get(e);if(!i)return{exports:[],declarations:[]};let o=[...i.internalExports.exports],n=[];for(let[s,a]of Object.entries(i.internalExports.namespace)){let c=this.collectNamespaceExports(a,t);c.exports.length>0&&(n.push(...c.declarations),n.push(`const ${s} = { ${c.exports.join(", ")} };`),o.push(s))}for(let s of i.externalExports.star){let a=this.collectNamespaceExports(s,t);o.push(...a.exports),n.push(...a.declarations)}return{exports:o,declarations:n}}collectBundleExports(e){let t=[],i=[],o=[];for(let n of e){t.push(...n.internalExports.exports);for(let[s,a]of Object.entries(n.internalExports.namespace)){let c=this.collectNamespaceExports(a);c.exports.length>0&&(i.push(...c.declarations),i.push(`const ${s} = { ${c.exports.join(", ")} };`),t.push(s))}for(let s of n.externalExports.star)i.push(`export * from '${s}';`);for(let[s,a]of Object.entries(n.externalExports.namespace))o.push(`export * as ${s} from '${a}';`);for(let[s,a]of Object.entries(n.externalExports.exports))o.push(`export { ${a.join(`,
40
- `)} } from '${s}';`)}return{exports:t,declarations:i,externalExports:o}}parseContent(e,t,i){let o=[_t],n=this.collectExternalImports(t),s=this.generateImportStatements(n);o.push(...s),s.length>0&&o.push("");let{exports:a,declarations:c,externalExports:l}=this.collectBundleExports(i);if(c.length>0&&(o.push(...c),o.push("")),o.push(e),a.length>0){let p=Array.from(new Set(a)).sort();o.push(`export {
41
- ${p.join(`,
42
- `)}
43
- };`)}return l.length>0&&o.push(...l),o.join(`
44
- `)}};import{dirname as Fi}from"@remotex-labs/xmap";import{mkdir as ki,writeFile as Ai}from"fs/promises";import{xterm as Pi}from"@remotex-labs/xansi/xterm.component";var Fe=class r{constructor(e,t){this.languageService=e;this.languageHostService=t}languageService;languageHostService;static emittedVersions=new Map;static clearCache(){this.emittedVersions.clear()}async emit(e){let t=this.languageService.getProgram();if(!t)throw new Error(`${Pi.deepOrange("[TS]")} Language service program is not available`);let i=this.languageHostService.getCompilationSettings();e&&(i={...i,outDir:e});let o=[],n=t.getSourceFiles();for(let s=0;s<n.length;s++){let a=n[s];this.shouldEmitFile(a,t,i)&&o.push(a)}o.length!==0&&await Promise.all(o.map(s=>this.emitSingleDeclaration(s,i)))}shouldEmitFile(e,t,i){if(e.isDeclarationFile||t.isSourceFileFromExternalLibrary(e))return!1;let o=et(e.fileName,i),n=r.emittedVersions.get(o),s=this.languageHostService.getScriptVersion(e.fileName);return!n||n!==s?(r.emittedVersions.set(o,s),!0):!1}async emitSingleDeclaration(e,t){let i=this.languageService.getEmitOutput(e.fileName,!0);if(i.emitSkipped)return;let o=i.outputFiles[0].text,n=et(e.fileName,t);o=Te(o),o=this.languageHostService.resolveAliases(o,e.fileName,".d.ts"),await ki(Fi(n),{recursive:!0}),await Ai(n,o,"utf8")}};import te from"typescript";import{relative as Ri,dirname as $i}from"@remotex-labs/xmap";var re=class r{constructor(e={}){this.compilerOptions=e;this.alias=r.generateAliasRegex(e),this.moduleResolutionCache=te.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}compilerOptions;static sys=te.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=te.createModuleResolutionCache(process.cwd(),t=>t,this.compilerOptions)}static reload(){let e=u(v);e.getTrackedFilePaths().map(t=>{e.touchFile(t)})}touchFile(e){return this.trackFiles.add(this.filesCache.resolve(e)),this.filesCache.touchFile(e)}touchFiles(e){for(let t of e)this.touchFile(t)}getCompilationSettings(){return this.compilerOptions}fileExists(e){return r.sys.fileExists(e)}readFile(e,t){return r.sys.readFile(e,t)}readDirectory(e,t,i,o,n){return r.sys.readDirectory(e,t,i,o,n)}getDirectories(e){return r.sys.getDirectories(e)}directoryExists(e){return r.sys.directoryExists(e)}getCurrentDirectory(){return r.sys.getCurrentDirectory()}getScriptFileNames(){return[...this.trackFiles]}getDefaultLibFileName(e){return te.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 te.resolveModuleName(e,t,this.compilerOptions,te.sys,this.moduleResolutionCache)}resolveModuleFileName(e,t){if(this.aliasCache.has(e))return this.aliasCache.get(e);let o=this.resolveModuleName(e,t).resolvedModule?.resolvedFileName;return this.aliasCache.set(e,o),o}resolveAliases(e,t,i=""){return this.alias?e.replace(this.alias,(o,n)=>{let s=this.resolveModuleFileName(n,t);if(!s)return o;let a=s.replace(/\.tsx?$/,i),c=Ri($i(t),a);return o.replace(n,c.startsWith(".")?c:"./"+c)}):e}static generateAliasRegex(e){let t=e.paths;if(!t||Object.keys(t).length<1)return;let i=Object.keys(t).map(o=>o.replace("/*","").replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`(?:^|\\s)(?:import|export)\\s+(?:type\\s+)?(?:[^'"]*from\\s+)?['"]((${i})[^'"]*)['"];?`,"gm")}};var Ut,rt;Ut=[P({providers:[{useValue:"tsconfig.json"}]})];var N=class N{constructor(e="tsconfig.json"){this.configPath=e;let{config:t,host:i,service:o}=this.acquireLanguageService();this.config=t,this.languageService=o,this.languageHostService=i,this.languageHostService.touchFiles(this.config.fileNames),this.emitterService=new Fe(o,i),this.bundlerService=new Oe(o,i)}configPath;config;languageService;languageHostService;static serviceCache=new Map;emitterService;bundlerService;check(e){let t=this.languageService.getProgram();if(!t)return[];let i=e&&e.length>0?e.map(o=>t.getSourceFile(o)):this.languageService.getProgram()?.getSourceFiles();return i?i.filter(o=>this.shouldCheckFile(o)).flatMap(o=>this.collectDiagnostics(o)):[]}touchFiles(e){for(let t of e)if(this.languageHostService.hasScriptSnapshot(t)&&this.languageHostService.touchFile(t),t.includes(this.configPath)){let i=N.serviceCache.get(this.configPath);i.config=this.parseConfig(),i.host.options=i.config.options}}async emitBundle(e,t){await this.bundlerService.emit(e,t)}async emit(e){await this.emitterService.emit(e)}dispose(e){let t=N.serviceCache.get(e);t&&(t.refCount--,N.cleanupUnusedServices())}static cleanupUnusedServices(){for(let[e,t]of this.serviceCache)t.refCount<1&&(t.service.dispose(),this.serviceCache.delete(e))}shouldCheckFile(e){if(!e||e.fileName.includes("node_modules"))return!1;if(this.config.raw?.exclude){for(let t of this.config.raw.exclude)if(Mi(Bi(this.config.options.rootDir,e.fileName),t))return!1}return!e.isDeclarationFile}collectDiagnostics(e){return[...this.languageService.getSemanticDiagnostics(e.fileName),...this.languageService.getSyntacticDiagnostics(e.fileName),...this.languageService.getSuggestionDiagnostics(e.fileName)].map(t=>this.formatDiagnostic(t))}acquireLanguageService(){let e=N.serviceCache.get(this.configPath);return e?(e.refCount++,e):this.createLanguageService()}createLanguageService(){let e=this.parseConfig(),t=new re(e.options),i=G.createLanguageService(t,G.createDocumentRegistry()),o={config:e,host:t,service:i,refCount:1};return N.serviceCache.set(this.configPath,o),o}parseConfig(){let e=G.getParsedCommandLineOfConfigFile(this.configPath,{sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0},{...G.sys,onUnRecoverableConfigFileDiagnostic:()=>{}});return e||(e={options:{strict:!0,target:G.ScriptTarget.ESNext,module:G.ModuleKind.NodeNext,sourceMap:!1,skipLibCheck:!0,stripInternal:!0,declarationMap:!1,emitDeclarationOnly:!0,moduleResolution:G.ModuleResolutionKind.NodeNext},errors:[],fileNames:[],projectReferences:void 0}),e.options={...e.options,rootDir:e.options?.rootDir??process.cwd()},e}formatDiagnostic(e){let t={message:G.flattenDiagnosticMessageText(e.messageText,`
45
- `),category:e.category};if(e.file&&e.start!==void 0){let{line:i,character:o}=e.file.getLineAndCharacterOfPosition(e.start);t.file=e.file.fileName,t.line=i+1,t.column=o+1,t.code=e.code}return t}};rt=F(null),N=A(rt,0,"TypescriptService",Ut,N),k(rt,1,N);var ie=N;import{cwd as ke}from"process";import{build as it}from"esbuild";var zt={write:!1,bundle:!0,minify:!0,outdir:`${ke()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Wt(r,e={}){try{return await it({absWorkingDir:ke(),...zt,...e,metafile:!0,entryPoints:r})}catch(t){if(V(t)){let i=new AggregateError([],"Failed to build entryPoints");throw de(t.errors,i.errors),i}throw t}}async function Gt(r,e,t={}){return await it({absWorkingDir:ke(),...zt,...t,stdin:{loader:"ts",contents:r,resolveDir:ke(),sourcefile:e},write:!1,metafile:!0,logLevel:"silent",sourcemap:"external"})}async function Kt(r,e={}){try{return await it({...e,outdir:"tmp",write:!1,bundle:!0,outfile:void 0,metafile:!0,packages:"external",logLevel:"silent",entryPoints:r})}catch(t){if(V(t)){let i=new AggregateError([],"Failed to analyze entryPoint");throw de(t.errors,i.errors),i}throw t}}import{relative as Hi,resolve as Vi,join as Xt,dirname as _i}from"@remotex-labs/xmap";function qt(r,e){if(Array.isArray(e)){let t={};return e.length>0&&typeof e[0]=="object"?e.forEach(i=>{t[i.out]=i.in}):typeof e[0]=="string"&&(t=we(r,e)),t}else{if(e&&typeof e=="object")return e;if(e===void 0)return}throw new S("Unsupported entry points format")}var Ae=class{constructor(e,t,i,o={}){this.name=e;this.lifecycle=t;this.buildConfig=i;this.argv=o;if(!this.buildConfig?.esbuild)throw new S(`Variant '${this.name}' not found configuration`);this.tsConfigPath=this.buildConfig.esbuild.tsconfig??"tsconfig.json",this.typescriptModule=new ie(this.tsConfigPath),this.buildConfig=this.initializeConfig(this.getConfig(this.buildConfig,this.configService.getValue().common)),this.lifecycle.onEnd(this.end.bind(this),`${this.name}-core`),this.lifecycle.onStart(this.start.bind(this),`${this.name}-core`),this.configUnsubscribe=this.configService.select(n=>({variantConfig:n.variants?.[this.name],commonConfig:n.common})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}name;lifecycle;buildConfig;argv;dependenciesFile;active=!0;tsConfigPath;typescriptModule;configUnsubscribe;configService=u(x);get typescript(){return this.typescriptModule}get config(){return this.buildConfig}get dependencies(){return this.dependenciesFile??{}}dispose(){this.configUnsubscribe(),this.typescriptModule.dispose(this.tsConfigPath)}touchFiles(e){this.typescriptModule.touchFiles(e)}async check(){return this.dependenciesFile||(this.dependenciesFile=await this.buildDependencyMap()),this.typescriptModule.check(Object.values(this.dependenciesFile))}async build(){if(!this.active)return;this.applyInjections();let e=Object.assign({},this.buildConfig.esbuild);if(this.dependenciesFile=await this.buildDependencyMap(),this.buildConfig.esbuild.bundle===!1&&Object.assign(e,{entryPoints:this.dependenciesFile}),this.config.define&&e.define)for(let[t,i]of Object.entries(this.config.define))typeof i=="function"&&(e.define[t]=JSON.stringify(i()));try{let t=await Di(e);return await this.packageTypeComponent(),t}catch(t){if(V(t)){if(t.errors.filter(o=>o.location).length>0)throw t;return{errors:t?.errors??[],warnings:t?.warnings??[]}}}}getConfig(e,t={}){return e?z({},t,e):null}async start(){let e={errors:[],warnings:[]};if(!this.buildConfig.types)return e;let t=this.typescriptModule.check(Object.values(this.dependenciesFile??{}));if(t.length===0)return e;if(typeof this.buildConfig.types=="object"&&!this.buildConfig.types.failOnError){let o=new M("Type checking failed",t);e.warnings?.push({detail:o,location:void 0})}else{let o=[],n=[],s=new M("Type checking failed",o),a=new M("Type checking failed",n);for(let c of t)(c.category===Ni.DiagnosticCategory.Error?o:n).push(c);o.length&&e.errors?.push({detail:s,location:void 0}),n.length&&e.warnings?.push({detail:a,location:void 0})}return e}async end(e){if(e.buildResult.errors?.length>0)return;let t={errors:[],warnings:[]};if(typeof e.buildResult.metafile?.outputs=="object"){let s=Object.keys(e.buildResult.metafile?.outputs);for(let a of s){if(!a.endsWith(".map"))continue;let c=_i(a),l=await Li(a,"utf8"),p=JSON.parse(l);p.sources=p.sources.map(f=>f.startsWith("http")?f:Xt(c,f)),await Yt(a,JSON.stringify(p),"utf8")}}if(!this.buildConfig.declaration)return;let i=this.buildConfig.declaration,o=typeof i=="object"?i.bundle!==!1:!0,n=typeof i=="object"?i.outDir:void 0;try{o?await this.typescriptModule.emitBundle(this.buildConfig.esbuild.entryPoints,n):await this.typescriptModule.emit(n)}catch(s){t.warnings?.push({detail:s,location:void 0})}return t}registerConfigHooks(e){if(!e)return;let{onStart:t,onResolve:i,onLoad:o,onEnd:n,onSuccess:s}=e;t&&this.lifecycle.onStart(t),i&&this.lifecycle.onResolve(i),o&&this.lifecycle.onLoad(o),n&&this.lifecycle.onEnd(n),s&&this.lifecycle.onSuccess(s)}async packageTypeComponent(){let e=this.buildConfig.esbuild.outdir??"dist",t=this.buildConfig.esbuild.format==="esm"?"module":"commonjs";await ji(e,{recursive:!0}),await Yt(Xt(e,"package.json"),`{"type": "${t}"}`)}initializeConfig(e){if(!e)throw new S(`Variant '${this.name}' not found configuration`);if(!e.esbuild.entryPoints&&!e.esbuild.stdin)throw new S("Entry points are required in esbuild configuration");let t=e.define,i=t?Object.fromEntries(Object.entries(t).flatMap(([o,n])=>typeof n=="function"?[]:[[o,JSON.stringify(n)]])):void 0;return this.registerConfigHooks(e.lifecycle),e.esbuild.entryPoints=qt(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 ie(this.tsConfigPath)))}stripExtension(e){let t=e.lastIndexOf(".");return t>0?e.substring(0,t):e}async buildDependencyMap(){let{esbuild:e}=this.buildConfig,t={...e,plugins:void 0},{metafile:i}=await Kt(e.entryPoints,t),o={};for(let n of Object.keys(i.inputs)){let s=Hi(this.typescriptModule.config.options.rootDir,Vi(n)),a=this.stripExtension(s);o[a]=n}return o}injectTextBlock(e){let t=this.buildConfig[e];if(!t)return;let i=this.buildConfig.esbuild;i[e]??={};for(let[o,n]of Object.entries(t))i[e][o]=typeof n=="function"?n(this.name,this.argv):n}applyInjections(){this.injectTextBlock("banner"),this.injectTextBlock("footer")}};import{readFile as Ui}from"fs/promises";import{resolve as zi}from"@remotex-labs/xmap";var Pe=class{constructor(e,t){this.variantName=e;this.argv=t}variantName;argv;filesModel=u(v);endHooks=new Map;loadHooks=new Map;startHooks=new Map;successHooks=new Map;resolveHooks=new Map;onStart(e,t=this.variantName){e&&this.startHooks.set(t,e)}onEnd(e,t=this.variantName){e&&this.endHooks.set(t,e)}onSuccess(e,t=this.variantName){e&&this.successHooks.set(t,e)}onResolve(e,t=this.variantName){e&&this.resolveHooks.set(t,e)}onLoad(e,t=this.variantName){e&&this.loadHooks.set(t,e)}clearAll(){this.endHooks.clear(),this.loadHooks.clear(),this.startHooks.clear(),this.successHooks.clear(),this.resolveHooks.clear()}create(){return{name:this.variantName,setup:e=>{let t={argv:this.argv,options:e.initialOptions,variantName:this.variantName,stage:{startTime:new Date}};e.initialOptions.metafile=!0,this.startHooks.size>0&&e.onStart(this.executeStartHooks.bind(this,t,e)),(this.endHooks.size>0||this.successHooks.size>0)&&e.onEnd(this.executeEndHooks.bind(this,t)),this.resolveHooks.size>0&&e.onResolve({filter:/.*/},this.executeResolveHooks.bind(this,t)),this.loadHooks.size>0&&e.onLoad({filter:/.*/},this.executeLoadHooks.bind(this,t))}}}pushError(e,t,i,o=this.variantName){e.push({id:t,detail:i,location:null,pluginName:o})}async executeStartHooks(e,t){e.stage.startTime=new Date;let i=[],o=[],n={build:t,...e};for(let[s,a]of this.startHooks.entries())try{let c=await a(n);c?.errors&&i.push(...c.errors),c?.warnings&&o.push(...c.warnings)}catch(c){this.pushError(i,"startHook",c,s)}return{errors:i,warnings:o}}async executeEndHooks(e,t){let{errors:i,warnings:o}=t,n=Date.now()-e.stage.startTime.getTime(),s={buildResult:t,duration:n,...e};for(let[a,c]of this.endHooks.entries())try{let l=await c(s);l?.errors&&i.push(...l.errors),l?.warnings&&o.push(...l.warnings)}catch(l){this.pushError(i,"endHook",l,a)}if(t.errors.length===0)for(let[a,c]of this.successHooks.entries())try{await c(s)}catch(l){this.pushError(i,"endHook",l,a)}}async executeResolveHooks(e,t){let i={errors:[]},o={args:t,...e};for(let[n,s]of this.resolveHooks.entries())try{let a=await s(o);if(!a)continue;i={...i,...a}}catch(a){this.pushError(i.errors,"endResolve",a,n)}return i}async executeLoadHooks(e,t){let i=[],o=[],n="default",s=zi(t.path),a=this.filesModel.getOrTouchFile(s),c;try{c=a?.contentSnapshot?a.contentSnapshot.text:await Ui(s,"utf8")}catch{return e.options.logOverride?.["lifecycle-file-ignored"]!=="silent"&&o.push({id:"",text:`${t.path} ignored`,pluginName:"lifecycle"}),{warnings:o,errors:i,loader:n}}for(let[l,p]of this.loadHooks.entries())try{let f=await p({contents:c,loader:n,args:t,...e});if(!f)continue;f.contents!==void 0&&(c=f.contents),f.loader&&(n=f.loader),f.errors&&i.push(...f.errors),f.warnings&&o.push(...f.warnings)}catch(f){this.pushError(i,"loadHook",f,l)}return{contents:c,loader:n,errors:i,warnings:o}}};import h from"typescript";import{createSourceFile as co}from"typescript";import{highlightCode as or}from"@remotex-labs/xmap/highlighter.component";import D from"typescript";var Wi="$$ifdef";function Gi(r,e,t,i=!1){let o=i?"export function ":"function ";return D.isArrowFunction(e)||D.isFunctionExpression(e)?Ki(r,e,t,o):`${i?"export const ":"const "}${r} = ${e.getText(t)};`}function Ki(r,e,t,i){let n=e.modifiers?.some(l=>l.kind===D.SyntaxKind.AsyncKeyword)??!1?"async ":"",s=e.parameters.map(l=>l.getText(t)).join(", "),a=e.type?`: ${e.type.getText(t)}`:"",c=qi(e,t);return`${n}${i}${r}(${s})${a} ${c}`}function qi(r,e){let t=r.body.getText(e);return D.isArrowFunction(r)&&!D.isBlock(r.body)?`{ return ${t}; }`:t}function Yi(r,e,t="",i="();"){return D.isArrowFunction(r)||D.isFunctionExpression(r)?`${r.modifiers?.some(s=>s.kind===D.SyntaxKind.AsyncKeyword)??!1?"async ":""}${t}(${r.getText(e)})${i}`:t?`${t}${r.getText(e)}`:`(() => { return ${r.getText(e)}; })${i}`}function Jt(r,e,t){let i=r in t&&!!t[r];return e===Wi===i}function Qt(r,e,t,i){let[o,n]=e.arguments;if(!D.isStringLiteral(o))return!1;let s=e.expression.text,a=o.text;if(!Jt(a,s,i.defines))return"undefined";let c=r.name.getText(i.sourceFile);return Gi(c,n,i.sourceFile,t)}function Re(r,e,t,i=!1,o){let[n,s]=r.arguments;if(!D.isStringLiteral(n))return!1;let a=n.text,c=r.expression.text;if(!Jt(a,c,e.defines))return"";let l="",p=t?.name.getText(e.sourceFile);return p&&(l=i?`export const ${p} = `:`const ${p} = `),Yi(s,e.sourceFile,l,o)}import B from"typescript";import{createRequire as Qi}from"module";var $e=class extends y{constructor(e,t=0){super(e.message,"InlineError"),this.errorMetadata=L(e,{lineOffset:t}),this.stack=H(this.errorMetadata,this.name,this.message)}};import{Script as Xi,createContext as Ji}from"vm";async function Zt(r,e={},t={}){let i=new Xi(r,t),o=Ji(e);return await i.runInContext(o,{breakOnSigint:!0,displayErrors:!1})}import{dirname as Zi,relative as eo}from"@remotex-labs/xmap";async function er(r,e,t){let[i,o]=(await Gt(r,e.sourceFile.fileName,{bundle:!0,format:"cjs",platform:"node",packages:"external"})).outputFiles;try{let n={exports:{}},s=Qi(e.sourceFile.fileName),a=to(e.sourceFile.fileName,n,s);a.context=e.context;let c=await Zt(o.text,a,{filename:e.sourceFile.fileName});return c===null?"undefined":typeof c=="number"||typeof c=="boolean"?String(c):JSON.stringify(c)}catch(n){ro(n,e,i.text,t)}return"undefined"}function to(r,e,t){return{...globalThis,Error,RegExp,process,Buffer,module:e,require:t,console,setTimeout,setInterval,clearTimeout,clearInterval,ReferenceError,__dirname:Zi(r),__filename:r}}function ro(r,e,t,i){(!r||typeof r!="object"||!("stack"in r))&&(r=new Error(String(r)));let o=i.getStart(e.sourceFile),{line:n}=e.sourceFile.getLineAndCharacterOfPosition(o);u(b).setSource(t,e.sourceFile.fileName);let s=new $e(r,n);e.errors.push({text:s.message,detail:s})}function io(r,e){let t=null,i=o=>{if(!t){if(B.isFunctionDeclaration(o)&&o.name?.text===r){t=o;return}B.isVariableStatement(o)&&(t=oo(o,r),t)||B.forEachChild(o,i)}};return i(e),t}function oo(r,e){for(let t of r.declarationList.declarations)if(B.isIdentifier(t.name)&&t.name.text===e&&t.initializer&&(B.isArrowFunction(t.initializer)||B.isFunctionExpression(t.initializer)))return t.initializer;return null}function tr(r){return`module.exports = (${r})();`}function no(r){return r&B.NodeFlags.Const?"const":r&B.NodeFlags.Let?"let":"var"}function rr(r,e){return r?B.isIdentifier(r)?so(r,e):B.isArrowFunction(r)||B.isFunctionExpression(r)?{node:r,data:tr(r.getText(e.sourceFile))}:{node:r,data:r.getText(e.sourceFile)}:null}function so(r,e){let t=io(r.text,e.sourceFile);return t?{node:t,data:tr(t.getText(e.sourceFile))}:(ao(r.text,e,r),{data:"",node:r})}function ao(r,e,t){let i=t.getStart(e.sourceFile),{line:o,character:n}=e.sourceFile.getLineAndCharacterOfPosition(i),s=eo(".",e.sourceFile.fileName);e.warnings.push({text:`Function $$inline(${r}); not found in ${s}`,location:{line:o+1,column:n,file:e.sourceFile.fileName,lineText:"asd"}})}async function ir(r,e,t,i,o){let n=t.arguments[0],s=rr(n,o);if(!s)return!1;let a=await er(s.data,o,s.node),c=no(e.declarationList.flags),l=i?"export ":"",p=r.name.getText(o.sourceFile);return`${l}${c} ${p} = ${a};`}async function ot(r,e){let t=r[0],i=rr(t,e);return i?er(i.data,e,i.node):!1}var K=["$$ifdef","$$ifndef","$$inline"];function nt(r,e){return K.some(t=>r.getText(e).includes(t))}function nr(r){return r===K[2]?1:2}async function lo(r,e,t){let i=!1;for(let o of r.declarationList.declarations){let n="",s,a=o.initializer;if(!a||(h.isCallExpression(a)&&h.isIdentifier(a.expression)?s=a:h.isCallExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)?(s=a.expression,n=`(${a.arguments.map(f=>f.getText(t.sourceFile)).join(", ")})`):h.isAsExpression(a)&&h.isCallExpression(a.expression)&&h.isIdentifier(a.expression.expression)&&(s=a.expression),!s))continue;let c=s.expression.text;if(!K.includes(c))continue;if(s.arguments.length!==nr(c)){let{line:p,character:f}=t.sourceFile.getLineAndCharacterOfPosition(s.getStart(t.sourceFile));throw new W({text:`Invalid macro call: ${c} with ${s.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:p+1,column:f}})}let l=r.modifiers?.some(p=>p.kind===h.SyntaxKind.ExportKeyword)??!1;c===K[2]?i=await ir(o,r,s,l,t):n?i=Re(s,t,o,l,n):i=Qt(o,s,l,t),i!==!1&&e.add({replacement:i,end:r.getEnd(),start:r.getStart(t.sourceFile)})}return i!==!1}async function fo(r,e,t){let i=r.expression;if(!i.expression||!h.isIdentifier(i.expression))return!1;let o=i.expression.text;if(!K.includes(o))return!1;if(i.arguments.length!==nr(o)){let{line:s,character:a}=t.sourceFile.getLineAndCharacterOfPosition(r.getStart(t.sourceFile));throw new W({text:`Invalid macro call: ${o} with ${i.arguments.length} arguments`,location:{file:t.sourceFile.fileName,line:s+1,column:a}})}let n=!1;return o==K[2]?(await ot(i.arguments,t),n="undefined"):n=Re(i,t),n!==!1&&e.add({replacement:n,end:i.getEnd(),start:i.getStart(t.sourceFile)}),n!==!1}async function po(r,e,t){if(!h.isCallExpression(r)||!nt(r,t.sourceFile))return!1;let i=r;if(!h.isIdentifier(i.expression))return!1;if(i.expression.text===K[2]){let s=await ot(i.arguments,t);return s===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:s}),!0)}let n=Re(i,t);return n===!1?!1:(e.add({start:r.getStart(t.sourceFile),end:r.getEnd(),replacement:n}),!0)}async function uo(r,e="unknow"){let t=r.stage.defineMetadata.disabledMacroNames,i=r.stage.defineMetadata.filesWithMacros.has(r.sourceFile.fileName);if(!i&&t.size===0)return r.contents;let o=[r.sourceFile],n=new Set;for(;o.length>0;){let c=o.pop(),l=c?.kind;if(!c||!l||i&&(l===h.SyntaxKind.VariableStatement&&await lo(c,n,r)||l===h.SyntaxKind.ExpressionStatement&&nt(c,r.sourceFile)&&await fo(c,n,r)||l===h.SyntaxKind.CallExpression&&nt(c,r.sourceFile)&&await po(c,n,r)))continue;if(t.size>0){if(l===h.SyntaxKind.CallExpression){let f=c;h.isIdentifier(f.expression)&&t.has(f.expression.text)&&n.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}else if(l===h.SyntaxKind.Identifier){let f=c;if(t.has(f.text)){let d=c.parent??c;if(d&&!h.isImportSpecifier(d)&&!h.isExportSpecifier(d)){let m=d?.getText(r.sourceFile);(!h.isCallExpression(d)||d.expression!==c)&&(!m||K.every($=>!m.includes($)))&&n.add({start:c.getStart(r.sourceFile),end:c.getEnd(),replacement:"undefined"})}}}}let p=c.getChildren(r.sourceFile);for(let f=p.length-1;f>=0;f--)o.push(p[f])}if(n.size===0)return r.contents;let s=Array.from(n);s.sort((c,l)=>l.start-c.start),r.stage.replacementInfo??={},r.stage.replacementInfo[e]??=[];let a=r.stage.replacementInfo[e];for(let{start:c,end:l,replacement:p}of s)a.push({source:or(r.contents.slice(c,l)),replacement:or(p)}),r.contents=r.contents.slice(0,c)+p+r.contents.slice(l);return r.contents}async function sr(r,e){let{args:t,loader:i,stage:o,contents:n,variantName:s,options:a,argv:c}=e;if(t.path.includes("node_modules")||n.length<1)return;let l=t.path.slice(t.path.lastIndexOf("."));if(![".js",".ts"].includes(l))return;let p=r.typescript.languageHostService.getCompilationSettings(),f=co(t.path,n.toString(),p.target??h.ScriptTarget.Latest,!0),d={stage:o,errors:[],contents:n.toString(),warnings:[],defines:r.config.define??{},sourceFile:f,context:{argv:c,options:a,variantName:s}},m=await uo(d,r.name);return r.config.esbuild.bundle||r.typescript.languageHostService.aliasRegex&&(m=r.typescript.languageHostService.resolveAliases(m,t.path,".js")),{loader:i,contents:m,warnings:d.warnings,errors:d.errors}}var ar="$$",cr=/(?:(?:export\s+)?(?:const|let|var)\s+([\w$]+)\s*=\s*)?\$\$(ifdef|ifndef|inline)\s*\(\s*(?:['"]([^'"]+)['"])?/g;function mo(r,e,t,i){let o=1;for(let s=0;s<i;s++)r[s]===`
46
- `&&o++;let n=r.lastIndexOf(`
47
- `,i-1)+1;return{file:t,line:o,column:r.indexOf(e,n)-n}}function go(r,e){let t=r.lastIndexOf(`
48
- `,e-1)+1;for(;t<e&&(r[t]===" "||r[t]===" ");)t++;if(t>=e)return!1;let i=r[t],o=r[t+1];return i==="/"&&(o==="/"||o==="*")||i==="*"}async function lr(r,e){let t={disabledMacroNames:new Set,filesWithMacros:new Set};e.stage.defineMetadata=t;let i=[],o=u(v),n=r.config.define??{},s=Object.values(r.dependencies??{});for(let a of s){let c=o.getOrTouchFile(a)?.contentSnapshot?.text;if(!c)continue;let l=o.resolve(a);cr.lastIndex=0;for(let p of c.matchAll(cr)){let f=p.index;if(go(c,f))continue;let[,d,m,$]=p;if(t.filesWithMacros.add(l),!d||(d.startsWith(ar)||i.push({text:`Macro function '${d}' not start with '${ar}' prefix to avoid conflicts`,location:mo(c,d,a,f)}),m==="inline"))continue;let _=!!n[$];m==="ifndef"===_&&t.disabledMacroNames.add(d)}}return{warnings:i}}var ye=class{constructor(e={}){this.argv=e;this.configuration.subscribe(this.parseVariants.bind(this))}argv;onEndCallback;onStartCallback;variants={};configuration=u(x);get config(){return this.configuration.getValue()}set onEnd(e){this.onEndCallback=e}set onStart(e){this.onStartCallback=e}reload({config:e,clearCache:t=!1}={}){t&&re.reload(),e&&this.configuration.reload(e),this.disposeVariants(this.compareKeys(this.config.variants,this.variants)),this.parseVariants()}touchFiles(e){for(let t of Object.values(this.variants))t.touchFiles(e)}setConfiguration(e){this.configuration.patch(e)}async typeChack(){let e={};for(let t of Object.values(this.variants))e[t.name]=await t.check();return e}async build(e){let t={cache:new Map,errors:[],results:{}};this.validateDependencies(e);let i=e??Object.keys(this.variants);if(await Promise.all(i.map(o=>this.buildVariant(o,t))),t.errors.length)throw new AggregateError(t.errors,"Build failed");return t.results}onEndTrigger(e){this.onEndCallback&&this.onEndCallback(e)}async onStartTrigger(e){try{let t=await lr(this.variants[e.variantName],e);return this.onStartCallback&&this.onStartCallback(e),t}catch(t){let i=[];if(t instanceof AggregateError){for(let o of t.errors)i.push({detail:o,text:o.message});return{errors:i}}throw t}}disposeVariants(e){if(e.length)for(let t of e)this.variants[t].dispose(),delete this.variants[t]}compareKeys(e,t){return[...Object.keys(t).filter(n=>!(n in e))]}parseVariants(){if(!this.config.variants)throw new S("Variants are not defined in the configuration");for(let e of Object.keys(this.config.variants)){if(this.variants[e])continue;let t=new Pe(e,this.argv);t.onEnd(this.onEndTrigger.bind(this),"build-service"),t.onStart(this.onStartTrigger.bind(this),"build-service"),this.variants[e]=new Ae(e,t,this.config.variants[e],this.argv),t.onLoad(sr.bind({},this.variants[e]),"build-service")}}getDependOn(e){let{dependOn:t}=this.config.variants?.[e]??{};return t?Array.isArray(t)?t:[t]:[]}validateDependencies(e){let t=new Set,i=new Set,o=(n,s)=>{if(i.has(n))throw new S(`Circular dependency detected: ${[...s,n].join(" \u2192 ")}`);if(!t.has(n)){i.add(n);for(let a of this.getDependOn(n))this.variants[a]&&o(a,[...s,n]);i.delete(n),t.add(n)}};for(let n of e??Object.keys(this.variants))o(n,[])}async executeBuild(e,t){let i=this.getDependOn(e).filter(n=>this.variants[n]);await Promise.all(i.map(n=>this.buildVariant(n,t)));let o=this.variants[e];if(o)try{let n=await o.build();n&&(t.results[e]=me(n))}catch(n){V(n)||n instanceof AggregateError?t.errors.push(...me({errors:n.errors}).errors):t.errors.push(n instanceof Error?n:new Error(String(n)))}}buildVariant(e,t){let i=t.cache.get(e);if(i)return i;let o=this.executeBuild(e,t);return t.cache.set(e,o),o}};function fr(r){u(x).reload(r)}function pr(r){u(x).patch(r)}import{platform as yo,exit as vo,stdin as Me,stdout as at}from"process";import{xterm as Be}from"@remotex-labs/xansi/xterm.component";var st={SIGINT:"",SIGQUIT:""},w={HELP:"h",QUIT:"q",CLEAR:"c",RELOAD:"r",VERBOSE:"v",SHOW_URL:"u",OPEN_BROWSER:"o"},ur={win32:"start",darwin:"open",linux:"xdg-open"};function xo(r=!1){let e=["\u{1F680} Shortcuts"],t=Be.dim(" press "),i=(o,n)=>{e.push(`${t}${Be.bold(o)}${Be.dim(n)}`)};return r&&(i(w.SHOW_URL," to show server url"),i(w.OPEN_BROWSER," to open in browser")),i(w.VERBOSE," to enable / disable verbose mode"),i(w.RELOAD," to reload"),i(w.CLEAR," to clear console"),i(w.QUIT,` to quit
49
- `),e.join(`
50
- `)}function ct(){let r=Math.max(0,at.rows-2);r>0&&console.log(`
51
- `.repeat(r)),lt.cursorTo(at,0,0),lt.clearScreenDown(at)}function bo(r){let e=ur[yo]??"xdg-open";ho(`${e} ${r}`)}function So(r,e,t,i,o){if(e?.name)switch((e.sequence===w.QUIT||r===st.SIGINT||r===st.SIGQUIT)&&(console.log(`
52
- \u{1F44B} Exiting...`),vo(0)),e.name){case w.CLEAR:ct();break;case w.VERBOSE:let n=u(x).getValue(s=>s.verbose);console.log(`\u{1F41E} Debug mode: ${n?"DISABLED":"ENABLED"}`),pr({verbose:!n});break;case w.RELOAD:ct(),t();break;case w.HELP:ct(),console.log(i);break;case w.SHOW_URL:o&&console.log(`${I()} ${Be.canaryYellow(o)}`);break;case w.OPEN_BROWSER:o&&bo(o);break}}function dr(r,e){if(!Me.isTTY)return;let t=xo(!!e);console.log(t),Me.setRawMode(!0),lt.emitKeypressEvents(Me),Me.on("keypress",(i,o)=>{So(i,o,r,t,e)})}import{existsSync as Eo}from"fs";import{runInThisContext as wo}from"vm";import{createRequire as Co}from"module";import{resolve as Io}from"@remotex-labs/xmap";var To={minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1};async function ft(r){if(!r||!Eo(r))return{};u(v).touchFile(r);let[e,t]=(await Wt([r],{...To,outdir:"tmp"})).outputFiles;u(b).setSource(e.text,r),globalThis.module={exports:{}},globalThis.require=Co(Io(r)),await wo(t.text,{filename:r});let i=module.exports.config??module.exports.default;return i||{}}import{relative as Oo}from"@remotex-labs/xmap";import{DiagnosticCategory as pt}from"typescript";var Ne=class r extends y{constructor(t,i){if(t instanceof y)return t;super(t.message,"VMRuntimeError");this.originalError=t;this.originalError instanceof AggregateError&&Array.isArray(this.originalError.errors)&&(this.errors=this.originalError.errors.map(o=>new r(o,i))),this.stack=this.originalError.stack,this.message=this.originalError.message,this.reformatStack(this.originalError,i)}originalError;errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(i=>`${i.formattedStack??i.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
53
- ${t}
54
- `}return this.formattedStack||this.stack}};import{xterm as dt}from"@remotex-labs/xansi/xterm.component";import{xterm as q}from"@remotex-labs/xansi/xterm.component";var mr=q.hex("#80a36b"),ve=q.hex("#dcdfe4"),oe=q.hex("#5798cd"),T=q.hex("#e5c07b"),Y=q.hex("#56b6c2"),R=q.hex("#e06c75"),ne=q.hex("#c678dd"),se=q.hex("#a5a7ab");var O=" ",ut=1024,gr=ut*1024,yr="\u2014",X="\u2192",J="\xD7",vr="\u2022";function ee(r,e=oe.dim(X)){return`${I()} ${e} ${oe(r)}`}function Fo(r){return r<ut?`${r} B`:r<gr?`${(r/ut).toFixed(2)} KB`:`${(r/gr).toFixed(2)} MB`}function xr(r){let e=r.file?Oo(process.cwd(),r.file):"(unknown)",t=T(String((r.line??0)+1)),i=T(String((r.column??0)+1));return`${Y(e)}:${t}:${i}`}function ko(r,e){if(!e.metadata?.formatCode)return;let t=e.metadata.formatCode.split(`
55
- `),i=e.metadata.stack.map(o=>o.format).join(`
56
- `);r.push("");for(let o of t)r.push(`${O}${o}`);r.push(""),r.push(`${O}Enhanced Stack Trace:`),r.push(` ${i}`)}function Ao(r){if(!r.metadata?.formatCode)return;let e=r.metadata.formatCode.split(`
57
- `).map(i=>`${O}${i}`).join(`
58
- `),t=r.metadata.stack.map(i=>i.format).join(`
59
- `);console.log(`
60
- ${e}
61
-
62
- ${O}Enhanced Stack Trace:
63
- ${t}`)}function Po(r,e,t){let i=xr(r),o=t(`TS${r.code}`),n=se(r.message);return`${O}${e} ${i} ${ve(X)} ${o} ${ve(yr)} ${n}`}function De(r,e,t=R){let i=xr(r),o=t(`TS${r.code}`),n=se(r.message);console.log(`${O}${e} ${i}`,ve(X),`${o} ${ve(yr)} ${n}`)}function Ro(r,e,t){let i=e.diagnostics.length;if(i===0)return r.push(`${O}${T(t)} ${T("TypesError")}: ${se(e.message||"Type checking warning")}`),1;r.push("");for(let o of e.diagnostics)r.push(Po(o,T(t),dt.deepOrange));return i}function $o(r,e,t,i){let o=`${i(e.name)}: ${e.message}`;r.push(`
64
- ${O}${i(t)} ${o}`),e instanceof y&&ko(r,e)}function Mo(r,e,t,i){return e instanceof M?Ro(r,e,t):($o(r,e,t,i),1)}function hr(r,e){if(r.length===0)return;e==="Errors"&&(process.exitCode=1);let t=e==="Errors",i=t?J:vr,o=t?R:T,n=0,s=[""];for(let a of r)n+=Mo(s,a,i,o);s[0]=`
65
- ${o(e)} (${n})`,console.log(s.join(`
66
- `))}function Bo(r){let e=Object.entries(r.outputs),t=e.length,i=[];i.push(`
67
- ${mr("Outputs")} (${t})`);for(let[o,n]of e){let s=T.dim(Fo(n.bytes));i.push(`${O}${oe(X)} ${Y(o)}: ${s}`)}i.push(""),console.log(i.join(`
68
- `))}function ae(r){if(r instanceof y){let e=`${R(r.name)}: ${r.message}`;console.log(`
69
- ${O}${R(J)} ${e}`),Ao(r)}else if(V(r))for(let e of r.errors)ae(e);else if(r instanceof M)for(let e of r.diagnostics)De(e,R(J));else r instanceof Error?ae(new Ne(r)):ae(new S(String(r)))}function No(r,e){let t=e.filter(c=>c.category>pt.Error),i=e.filter(c=>c.category===pt.Error),o=e.filter(c=>c.category===pt.Warning),n=i.length>0?T(r):ne(r),s=i.length>0?R(J):oe.dim(X),a=ee("completed",s);if(console.log(`${a} ${n}`),i.length>0){process.exitCode=1,console.log(`
70
- ${R("Errors")} (${i.length})`);for(let c of i)De(c,R(J))}if(o.length>0){console.log(`
71
- ${T("Warnings")} (${o.length})`);for(let c of o)De(c,T(vr))}if(t.length>0){console.log(`
72
- ${Y("Info")} (${t.length})`);for(let c of t)De(c,Y(X))}console.log("")}function br(r){for(let[e,t]of Object.entries(r))No(e,t)}function Sr({variantName:r}){console.log(`${ee("build")} ${ne(r)}`)}function Do(r,e){if(!u(x).getValue().verbose)return;let t=e?.replacementInfo?.[r];if(!t||!Array.isArray(t)||t.length===0)return;let i=O+Y(X),o=[ee(`macro ${T("replacement")}`)];for(let{source:n,replacement:s}of t){let a=dt.dim("// "+n).replaceAll(`
73
- `,`
74
- ${O}`);if(s&&s!=="undefined"){let c=s.replaceAll(`
75
- `,`
76
- ${O}`);o.push(`
77
- ${i} ${c} ${a}`)}else o.push(`
78
- ${i} ${a}`)}console.log(o.join(`
79
- `))}function Er({variantName:r,duration:e,buildResult:t,stage:i}){let{errors:o,warnings:n,metafile:s}=me(t),a=!!s,c=a?ne(r):T(r),l=a?oe.dim(X):R(J),p=ee("completed",l);console.log(`${p} ${c} ${dt.dim(`in ${e} ms`)}`),hr(o,"Errors"),hr(n,"Warnings"),(o.length||n.length)&&console.log(""),Do(r,i),a?Bo(s):console.log("")}var Vo=["!node_modules/**","!dist/**","!bundle/**","!**/*.d.ts"],_o=["dist","dist/**",".git/**",".idea/**","node_modules/**"];function Uo(r,e){if(!e.entryPoints)return;let t=[...e.entryPoints,...Vo];e.outdir&&t.push(`!${e.outdir}/**`,`!${e.outdir}`),r.common?.esbuild?.outdir&&t.push(`!${r.common.esbuild.outdir}/**`,`!${r.common.esbuild.outdir}`),r.variants={argv:{esbuild:{entryPoints:we(Lo(),t)}}}}function zo(r,e){e.verbose!==void 0&&(r.verbose=e.verbose);let t=Object.values(r.variants??{});for(let i of t)e.types!==void 0&&(i.types=e.types),e.outdir!==void 0&&(i.esbuild.outdir=e.outdir),e.bundle!==void 0&&(i.esbuild.minify=e.bundle),e.minify!==void 0&&(i.esbuild.minify=e.minify),e.tsconfig!==void 0&&(i.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(i.esbuild.platform=e.platform),e.declaration!==void 0&&(i.declaration=e.declaration),e.failOnError!==void 0&&(i.types={failOnError:e.failOnError})}function Wo(r){let e=[..._o];r.common?.esbuild?.outdir&&e.push(r.common.esbuild.outdir,`${r.common.esbuild.outdir}/**`);let t=Object.values(r.variants??{});for(let i of t)i.esbuild.outdir&&e.push(i.esbuild.outdir,`${i.esbuild.outdir}/**`);return e}async function Go(r,e){if(!((e.serve??!1)!==!1||r.serve?.start))return;let i,o=r.serve?.dir||e.serve||"dist",n={...r.serve,onStart({host:a,port:c,url:l}){i=l,console.log(`${ee("serve")} ${ne(o)} ${Y(l)}
80
- `),r.serve?.onStart?.({host:a,port:c,url:l})}};return await new ge(n,o).start(),i}async function je(r,e){try{let t=Ho(process.cwd(),"dist");if(jo(t,{recursive:!0,force:!0}),e.typeCheck){let i=await r.typeChack();br(i)}else{let i=await r.build(e.build);Object.entries(i).forEach(([o,n])=>{let s=n.errors.filter(c=>c?.id==="endHook");if(!s.length)return;let a=ee("onEnd-hook",R(J));console.log(a,o),s.forEach(c=>ae(c)),console.log("")})}}catch(t){ae(t),process.exitCode=1}}async function Ko(r,e,t,i){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let n=Wo(e),s=new he(n);dr(async()=>{r.reload({clearCache:!0}),await je(r,t)},i),await je(r,t),await s.start(async a=>{if(r.touchFiles(a),a.includes(t.config)){let c=await ft(t.config);r.reload({config:c})}console.log(`
81
- ${I()} ${se("Rebuilding")}: files (${a.length})
82
- `),await je(r,t)})}async function qo(){console.log($t());let r=u(Q),e=r.parseConfigFile(process.argv);globalThis.$argv=e;let t=await ft(e.config),i=r.enhancedParse(process.argv,t.userArgv),o=r.parseUserArgv(process.argv,t.userArgv);Uo(t,i),zo(t,i),fr(t);let n=new ye(o);n.onEnd=Er,n.onStart=Sr;let s=await Go(t,i);await Ko(n,t,i,s),await je(n,i)}qo();
55
+ `}).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=$t.replace("${ fileList }",o).replace("${ paths }",'<li><a href="/">root</a></li>'+a).replace("${ up }","/"+t.split("/").slice(0,-1).join("/"));r.writeHead(200,{"Content-Type":"text/html"}),r.end(c)}async handleFile(e,t){let r=Et(e).slice(1)||"txt",n=this.getContentType(r),o=await Oi(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){this.events$.next({type:"error",error:t}),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{inject as Zi}from"@remotex-labs/xinject";var j=class extends F{constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{Subject as en}from"@remotex-labs/xobservable";import{parseSync as Zt}from"oxc-parser";import{relative as Xi}from"@remotex-labs/xmap";import{inject as Qe}from"@remotex-labs/xinject";function ji(i,e,t){if(e===void 0)return t;if(Object.hasOwn(i,e))return i[e];for(let r in i)try{if(new RegExp(`^(?:${r})$`).test(e))return i[r]}catch{if(e===r)return i[r]}return t}function We(i,e,t,r){let n=ji(e,t.id,r);n!=="silent"&&i[n].push(t)}function Rt(i,e,t,r,n){for(let o of t)n&&(o.pluginName=n),We(i,e,o,r)}import{parseSync as Bi}from"oxc-parser";import{inject as Fi}from"@remotex-labs/xinject";var _="$$",Ie="$$if",x=(r=>(r.ifdef=`${_}ifdef`,r.ifndef=`${_}ifndef`,r.inline=`${_}inline`,r))(x||{}),Dt=new Set(["false","null","undefined"]),Pt=new Set(["id","label","local","params","exported","imported"]);function ke(i,e){let t=i[e];return t!==void 0&&!Dt.has(t.trim())}function At(i,e,t,r){let{call:n,suffix:o}=t,s=n.arguments[1],a=i.slice(s.start,s.end);if(s.type!=="ArrowFunctionExpression"&&s.type!=="FunctionExpression")return`${r}const ${e} = ${a}${o};`;if(o)return`${r}const ${e} = (${a})${o};`;let{body:c}=s,l=s.params.map(S=>i.slice(S.start,S.end)).join(", "),f=s.returnType?i.slice(s.returnType.start,s.returnType.end):"",p=`${r}${s.async?"async ":""}function ${e}(${l})${f}`;return c?c.type==="BlockStatement"?`${p} ${i.slice(c.start,c.end)}`:`${p} { return ${i.slice(c.start,c.end)}; }`:`${p} {}`}function Ot(i,e,t){let{call:r,suffix:n}=e,o=r.arguments[1],s=i.slice(o.start,o.end),a=t?";":"";if(o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return`${s}${n}${a}`;if(n||!t)return`(${s})${n||"()"}${a}`;let{body:c}=o;return c?c.type!=="BlockStatement"?`${i.slice(c.start,c.end)};`:i.slice(c.start+1,c.end-1).trim():""}function jt(i,e){let t=new Set,r=Fi(h);for(let n of i){let o=r.touch(n).snapshot?.text;if(!o?.includes(Ie))continue;let{program:s}=Bi(n,o,{sourceType:"module"});for(let a of s.body)if(a.type==="ExportNamedDeclaration"&&a.declaration?.type==="VariableDeclaration")for(let c of a.declaration.declarations){let l=c.init;if(l?.type!=="CallExpression"||l.callee.type!=="Identifier")continue;let f=l.callee.name;if(f!==x.ifdef&&f!==x.ifndef)continue;let p=l.arguments[0];p?.type!=="Literal"||typeof p.value!="string"||c.id.type==="Identifier"&&f===x.ifdef!==ke(e,p.value)&&t.add(c.id.name)}}return t}import{visitorKeys as zi}from"oxc-parser";import{createRequire as Ui}from"module";import{inject as Wi}from"@remotex-labs/xinject";import{Script as Ni,createContext as Vi}from"vm";async function Ce(i,e={},t={},r=!1){let n={},o=Object.getOwnPropertyDescriptors(globalThis);delete o.globalThis,r&&delete o.console,Object.defineProperties(n,o),Object.assign(n,e);let s=Vi(n);return await new Ni(i,t).runInContext(s,{breakOnSigint:!0,displayErrors:!1})}import{cwd as Bt}from"process";import{build as ze}from"esbuild";import{dirname as Hi,basename as _i}from"@remotex-labs/xmap";var qe={write:!1,bundle:!0,minify:!0,outdir:"dist",format:"cjs",target:"esnext",logLimit:0,logLevel:"silent",platform:"browser",sourcemap:"external"};async function Ft(i={}){return await ze({absWorkingDir:Bt(),...qe,...i,metafile:!0})}async function $e(i,e,t={}){return await ze({absWorkingDir:Bt(),...qe,...t,stdin:{loader:"ts",contents:i,resolveDir:Hi(e),sourcefile:_i(e)},write:!1,metafile:!0,sourcemap:"external"})}async function Ke(i={}){return await ze({...i,write:!1,bundle:!0,outdir:"tmp",outfile:void 0,metafile:!0,packages:"external",logLevel:"silent"})}function qi(i){return i==null?"undefined":typeof i=="function"?i.toString():typeof i=="number"||typeof i=="boolean"?String(i):ye(i)??"undefined"}async function Nt(i,e){let t=i.target+".inline",r=i.code.slice(e.arguments[0].start,e.arguments[0].end),[n,o]=(await $e(`module.exports = (${r})();`,t,{format:"cjs",platform:"node",packages:"external"})).outputFiles,s={exports:void 0};Wi(u).addSourceMap(t,n.text,!0);let a=await Ce(o.text,{module:s,require:Ui(i.target)},{filename:t});return qi(a??s.exports)}function Vt(i){return typeof i=="object"&&i!==null&&typeof i.type=="string"}function Ee(i,e,t=null,r=""){if(e(i,t,r))return;let n=zi[i.type];for(let o of n??[]){let s=i[o];if(Array.isArray(s))for(let a of s)Vt(a)&&Ee(a,e,i,o);else Vt(s)&&Ee(s,e,i,o)}}function qt(i,e,t,r){let{code:n}=i,o=1,s=0;for(let a=n.indexOf(`
56
+ `);a!==-1&&a<e;a=n.indexOf(`
57
+ `,a+1))o++,s=a+1;r.location={file:i.target,line:o,column:e-s},We(i.logs,i.overrides,r,t)}function E(i,e,t){return i.edits.push({start:e.start,end:e.end,text:t}),!0}function zt(i,e,t,r){let n={start:e.start,end:e.end,text:""};return i.edits.push(n),i.pending.push(Nt(i,t).then(o=>{n.text=r(o)},o=>{n.text=r("undefined"),qt(i,t.start,"error",{detail:o,id:"macro-inline",text:`${x.inline} failed: ${o?.message??String(o)}`})})),!0}function Ht(i){if(i.type!=="CallExpression"||i.callee.type!=="Identifier")return!1;let{name:e}=i.callee;if(e===x.inline)return i.arguments.length===1;if(e!==x.ifdef&&e!==x.ifndef||i.arguments.length!==2)return!1;let t=i.arguments[0];return t.type==="Literal"&&typeof t.value=="string"}function Ge(i,e){let t=e.arguments[0],r=t.type==="Literal"?String(t.value):"";return e.callee.name===x.ifdef===ke(i.defines,r)}function _t(i,e){return e.type==="CallExpression"&&e.callee.type==="Identifier"&&i.dropped.has(e.callee.name)}function Te(i,e){if(e){if(Ht(e))return{call:e,suffix:""};if(e.type==="TSAsExpression")return Te(i,e.expression);if(!(e.type!=="CallExpression"||!Ht(e.callee)))return{call:e.callee,suffix:i.code.slice(e.callee.end,e.end)}}}function Kt(i,e){let t=e.type==="ExportNamedDeclaration"?e.declaration:e;if(t?.type!=="VariableDeclaration"||t.declarations.length!==1)return;let{id:r,init:n}=t.declarations[0];if(r.type!=="Identifier")return;let o=Te(i,n);return o&&[r,o]}function Ki(i,e){let t=[],r=[],n=!1;for(let s of e.specifiers){let a=i.code.slice(s.start,s.end);s.type!=="ImportSpecifier"?r.push(a):i.dropped.has(s.local.name)?n=!0:t.push(a)}if(!n)return!1;let o=i.code.slice(e.source.start,e.source.end);return t.length>0&&r.push(`{ ${t.join(", ")} }`),r.length<1?E(i,e,`import ${o};`):E(i,e,`import ${r.join(", ")} from ${o};`)}function Gi(i,e){let{specifiers:t}=e,r=t.filter(({local:n})=>!i.dropped.has(n.type==="Literal"?n.value:n.name));return r.length===t.length?!1:r.length<1?E(i,e,""):E(i,e,`export { ${r.map(n=>i.code.slice(n.start,n.end)).join(", ")} };`)}function Ut(i,e){let t=Kt(i,e);if(!t)return!1;let[r,n]=t,{call:o,suffix:s}=n,a=e.type==="ExportNamedDeclaration"?"export ":"";return r.name.startsWith("$$")||qt(i,r.start,"warning",{id:"macro-prefix",text:`Macro '${r.name}' does not start with the '${"$$"}' prefix to avoid conflicts`}),o.callee.name===x.inline?zt(i,e,o,c=>`${a}const ${r.name} = ${c}${s};`):E(i,e,Ge(i,o)?At(i.code,r.name,n,a):"")}function Wt(i,e,t,r){let{call:n,suffix:o}=t;return n.callee.name===x.inline?zt(i,e,n,s=>r?"":`${s}${o}`):Ge(i,n)?E(i,e,Ot(i.code,t,r)):E(i,e,r?"":"undefined")}function Yi(i,e,t,r){switch(e.type){case"Identifier":return!i.dropped.has(e.name)||!t?!1:!(r==="key"||r==="property"?!("computed"in t)||!t.computed:Pt.has(r))&&E(i,e,"undefined");case"ImportDeclaration":return Ki(i,e);case"ExportNamedDeclaration":return Ut(i,e)?!0:e.source||e.specifiers.length<1?!1:Gi(i,e);case"VariableDeclaration":return Ut(i,e);case"ExpressionStatement":{if(_t(i,e.expression))return E(i,e,"");let n=Te(i,e.expression);return n!==void 0&&Wt(i,e,n,!0)}case"CallExpression":case"TSAsExpression":{if(_t(i,e))return E(i,e,"undefined");let n=Te(i,e);return n!==void 0&&Wt(i,e,n,!1)}}return!1}async function Gt(i,e,t,r){if(t.length<1||e.includes("node_modules"))return t;let{dropped:n}=r.stage;if(n.size<1&&!t.includes("$$"))return t;let o={target:e,dropped:n,code:t,logs:r.logs,edits:[],pending:[],defines:r.options.define??{},overrides:r.overrides};return t.includes(Ie)&&Ee(i.program,s=>{let a=Kt(o,s);if(!a)return!1;let[c,{call:l}]=a;return l.callee.name!==x.inline&&!Ge(o,l)&&n.add(c.name),!1}),Ee(i.program,Yi.bind(null,o)),o.pending.length>0&&await Promise.all(o.pending),K(t,o.edits)}import{cwd as Ye}from"process";import{relative as Ji}from"@remotex-labs/xmap";function Yt(i,e=Ye()){if(i===void 0)return;if(!Array.isArray(i)){if(typeof i!="object"||i===null)throw new Error("Unsupported entry points format");return i}let t={};if(i.length<1)return t;if(typeof i[0]=="object"){for(let o of i)t[o.out]=o.in;return t}let r=Ji(Ye(),u.resolve(e)),n=r&&r!=="."?`${r}/`:"";for(let o of It(Ye(),i)){let s=n&&o.startsWith(n)?o.slice(n.length):o,a=s.lastIndexOf(".");t[a>s.lastIndexOf("/")+1?s.slice(0,a):s]=o}return t}var Jt=["banner","footer","define"],Qt=["warning","error","info"];import{parseErrorStack as Qi}from"@remotex-labs/xmap/parser.component";function Xt(i){if(i===null||typeof i!="object")return!1;let e=i.errors;if(!Array.isArray(e)||e.length===0)return!1;let t=e[0];return t!==null&&typeof t=="object"&&"detail"in t}function Je(i,e="",t=""){let r={detail:i,id:e,pluginName:t},n=Qi(i),o=n.stack[0];return r.text=n.message,o?.fileName&&o.line&&o.column&&(r.location={line:o.line,file:o.fileName,column:o.column,namespace:"file"}),r}var U=class i{constructor(e,t,r={}){this.name=e;this.events$=t;this.argv=r;i.instances.set(e,this),this.configUnsubscribe=Qe($).select(n=>({common:n.common,variant:n.variants?.[this.name]})).subscribe(this.handleConfigChange.bind(this),n=>{throw n})}name;events$;argv;static filesModel=Qe(h);static instances=new Map;configUnsubscribe;hooks=[];isDisposed=!1;typescriptModule;buildConfig;static has(e){return i.instances.has(e)}static get(){return i.instances.values()}async check(){let{metafile:e}=await Ke({...this.buildConfig.esbuild,plugins:void 0}),t={info:[],verbose:[],error:[],warning:[]};return this.diagnostics(this.typescriptModule.check(new Set(Object.keys(e.inputs))),t),t}async build(){if(this.isDisposed)throw new j(`Variant ${this.name} is disposed`);let e={info:[],verbose:[],error:[],warning:[]},t=await Ft({...this.buildConfig.esbuild,plugins:[this.lifecycle(e)],logLimit:0,logLevel:"silent"}).catch(()=>({}));return this.toResult(t,e)}dispose(){this.isDisposed=!0,this.configUnsubscribe?.(),this.typescriptModule?.dispose?.(),i.instances.delete(this.name)}[Symbol.dispose](){this.dispose()}collect(e,t,r,n){t?.length&&Rt(e,this.buildConfig.logOverride,t,r,n)}fail(e,t,r=this.name){e.error.push(Je(t instanceof Error?t:new Error(String(t)),"",r))}toResult(e,t){return Object.assign(e,{info:t.info,errors:t.error,verbose:t.verbose,warnings:t.warning})}async dispatch(e,t,r=()=>!1){for(let n of this.hooks)try{let o=await t(n);if(!o)continue;if(this.collect(e,o.errors,"error",n.name),this.collect(e,o.warnings,"warning",n.name),r(o))return o}catch(o){this.fail(e,o,n.name)}}async declarations(e){let{declaration:t}=this.buildConfig,r=e.options.entryPoints,n=(typeof t=="object"?t.outDir:void 0)??e.options.outdir;e.options.bundle?await this.typescriptModule.emitBundle(r,n):await this.typescriptModule.emit(r,n)}handleConfigChange({common:e,variant:t}){if(!t)return this.dispose();let r=this.typescriptModule,n=C({},e??{},t);this.typescriptModule=Qe(y,n.esbuild.tsconfig),n.esbuild.entryPoints=Yt(n.esbuild.entryPoints),n.logOverride??={},r?.dispose(),this.buildConfig=n,this.hooks=[...n.plugins??[],{name:this.name,...n.lifecycle}]}injectTextBlock(e,t){let r=this.buildConfig[t];if(!r)return;let n=e[t]??={};for(let[o,s]of Object.entries(r)){let a=typeof s=="function"?s(this.name,this.argv):s;a!=null&&(n[o]=ye(a))}}diagnostics(e,t,r=!0){for(let{category:n,code:o,message:s,file:a,line:c,column:l}of e){let f={text:s};o!==void 0&&(f.id=`TS${o}`),a&&(f.location={file:a,line:c,column:l});let p=Qt[n]??"verbose";f.detail={code:o,category:n,message:s},this.collect(t,[f],p==="error"&&!r?"warning":p,"typescript")}}async start(e,t){let{logs:r}=e;if(await this.dispatch(r,n=>n.onStart?.({context:e,esbuild:t})),this.buildConfig.types&&r.error.length<1){let n=this.buildConfig.types,o=typeof n=="object"?n.failOnError:!0;this.diagnostics(this.typescriptModule.check(e.stage.reachableFiles),e.logs,o)}return{errors:r.error}}async resolve(e,t){return await this.dispatch(e.logs,n=>n.onResolve?.({context:e,args:t}),()=>!0)??{errors:e.logs.error}}async load(e,t){let r=i.filesModel.resolve(t.path),n="default",o=i.filesModel.touch(r).snapshot?.text??"";try{let a=Zt(r,o,{sourceType:"module"});if(o=await Gt(a,r,o,e),!e.options.bundle){let c=Zt(r,o,{sourceType:"module"});o=St(c,r,o,this.typescriptModule)}}catch(a){this.fail(e.logs,a)}let s={};return await this.dispatch(e.logs,a=>a.onLoad?.({context:e,contents:o,loader:n,args:t}),a=>(s={...s,...a},n=a.loader??n,a.contents!==void 0&&(o=typeof a.contents=="string"?a.contents:Buffer.from(a.contents).toString()),!1)),{...s,contents:o,loader:n,errors:[],warnings:[]}}async end(e,t){this.collect(e.logs,t.errors.filter(n=>!n.pluginName),"error"),this.collect(e.logs,t.warnings.filter(n=>!n.pluginName),"warning");let r={context:e,duration:Date.now()-e.stage.startTime.getTime(),buildResult:this.toResult(t,e.logs)};if(e.logs.error.length<1)try{this.buildConfig.declaration&&await this.declarations(e)}catch(n){Je(n,"",this.name)}await this.dispatch(e.logs,async n=>{r.buildResult.errors.length<1&&await n.onSuccess?.(r),await n.onEnd?.(r)}),this.events$.next({...r,type:"end"})}async setup(e,t){let r=t.initialOptions;try{for(let o of Jt)this.injectTextBlock(r,o);let n=await this.buildDependencyMap();e.stage.reachableFiles=new Set(Object.values(n)),r.bundle||(r.entryPoints=n),e.stage.dropped=jt(e.stage.reachableFiles,r.define??{})}catch(n){Xt(n)&&n.errors?e.logs.error.push(...n.errors):this.fail(e.logs,n,"")}await this.dispatch(e.logs,n=>n.onSetup?.(e))}async buildDependencyMap(){let e=this.typescriptModule.config.options.rootDir,{metafile:t}=await Ke({...this.buildConfig.esbuild,plugins:void 0});return Object.fromEntries(Object.keys(t.inputs).map(r=>{let n=Xi(e,i.filesModel.resolve(r)),o=n.lastIndexOf(".");return[o>0?n.slice(0,o):n,r]}))}lifecycle(e){return{name:this.name,setup:async t=>{let r={logs:e,argv:this.argv,options:t.initialOptions,overrides:this.buildConfig.logOverride,variantName:this.name,stage:{startTime:new Date,dropped:new Set,reachableFiles:new Set}};t.onEnd(this.end.bind(this,r)),t.onStart(this.start.bind(this,r,t.esbuild)),t.onLoad({filter:/.*/},this.load.bind(this,r)),t.onResolve({filter:/.*/},this.resolve.bind(this,r)),await this.setup(r,t),this.events$.next({context:r,esbuild:t.esbuild,type:"start"})}}}};var Me=class{constructor(e,t={}){this.argv=t;this.config$.patch(e),this.config$.subscribe(this.parseVariants.bind(this))}argv;events$=new en;config$=Zi($);get pipe(){return this.events$.pipe.bind(this.events$)}get subscribe(){return this.events$.subscribe.bind(this.events$)}set configuration(e){this.config$.reload(e)}async build(e){let t=new Map(Array.from(U.get(),a=>[a.name,a])),r=new Map,n=Promise.withResolvers(),o=(a,c=[])=>{if(c.includes(a))throw new j(`Circular dependency detected: ${[...c,a].join(" \u2192 ")}`);if(!t.has(a))throw new j(`Variant "${c.at(-1)}" depends on "${a}", which is not a variant`);if(!r.has(a)){let l=this.getDependOn(a);r.set(a,Promise.all([n.promise,...l.map(f=>o(f,[...c,a]))]).then(([,...f])=>{let p=l.filter((S,d)=>Object.keys(f[d]?.metafile?.outputs??{}).length<1);return p.length?this.skipped(a,p):t.get(a).build()}))}return r.get(a)},s=Array.from(e?.filter(a=>t.has(a))??t.keys(),a=>o(a));return n.resolve(),Promise.all(s)}async typeChack(e){let t={};for(let r of U.get())(!e||e.includes(r.name))&&(t[r.name]=await r.check());return t}async reload(){y.reload()}parseVariants(e){if(!e)throw new j("Variants are not defined in the configuration");for(let t of Object.keys(e.variants??[]))U.has(t)||new U(t,this.events$,this.argv)}skipped(e,t){let r=t.map(c=>`"${c}"`).join(", "),n=[{id:"dependency-failed",text:`Variant "${e}" was not built, because ${r} failed`,notes:[],detail:void 0,location:null,pluginName:e}],o=this.config$.getValue().variants?.[e],s={info:[],verbose:[],error:n,warning:[]},a={info:s.info,verbose:s.verbose,errors:s.error,warnings:s.warning};return this.events$.next({type:"end",duration:0,context:{argv:this.argv,logs:s,options:o?.esbuild??{},overrides:o?.logOverride??{},variantName:e,stage:{startTime:new Date,dropped:new Set,reachableFiles:new Set}},buildResult:a}),a}getDependOn(e){return[this.config$.getValue().variants?.[e]?.dependOn??[]].flat()}};import{Injectable as tn}from"@remotex-labs/xinject";import{Subject as rn}from"@remotex-labs/xobservable";import{resolve as nn,join as er,relative as on}from"@remotex-labs/xmap";import{watch as sn,realpathSync as an,readdirSync as cn,lstatSync as ln,statSync as fn}from"fs";var J=class extends rn{constructor(t,r){super();this.options=r;this.base=nn(t),this.matcher=se(this.options?.filter??[],{dot:this.options?.dot??!1})}options;base;matcher;watchers=new Map;pending=new Map;subscriptions=0;timer;subscribe(t,r,n){let o=super.subscribe(t,r,n);return++this.subscriptions===1&&this.start(),this.toUnsubscribe(()=>{o(),--this.subscriptions===0&&this.stop()})}get debounce(){return this.options?.debounce??150}start(){this.watch(this.base,this.ignored.bind(this),this.options?.recursive),this.options?.followSymlinks&&this.watchSymlinks(this.base)}stop(){this.timer&&clearTimeout(this.timer);for(let t of this.watchers.values())t.close();this.timer=void 0,this.pending.clear(),this.watchers.clear()}flush(){if(this.timer=void 0,this.pending.size===0)return;let t=Object.fromEntries(this.pending);this.pending.clear();try{this.next(t)}catch{}}watcherClose(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t))}watcherEvent(t,r){let n=on(this.base,r),o=ln(r,{throwIfNoEntry:!1}),s=o?.isSymbolicLink()?fn(r,{throwIfNoEntry:!1}):o;if(o?.isSymbolicLink()){if(!s)return;t==="rename"&&this.watcherClose(r),s.isFile()&&this.matcher(r)?this.watch(r):s.isDirectory()&&this.options?.recursive&&this.watch(r,this.ignored.bind(this),!0)}if(!this.matcher(n))return;this.timer?this.timer.refresh():this.timer=setTimeout(this.flush.bind(this),this.debounce);let a;s?a=s.birthtimeMs===s.mtimeMs?0:1:(this.watcherClose(r),a=2),this.pending.set(n,{type:a,stats:s})}watch(t,r,n=!1){if(this.watchers.has(t)||this.ignored(t))return;let o=sn(an(t),{recursive:n,ignore:r},(s,a)=>{if(!a)return;let c=t.includes(a)?t:er(t,a);this.watcherEvent(s,c)});o.on("error",s=>{this.watcherClose(t),this.error(s)}),this.watchers.set(t,o)}ignored(t){return!!(!t||t.endsWith("~")||!this.options?.dot&&t&&t.split(/[/\\]/).some(r=>r.startsWith(".")))}watchSymlinks(t){let r=[t];for(;r.length;){let n=r.pop(),o;try{o=cn(n,{withFileTypes:!0})}catch{continue}for(let s of o){let a=er(s.parentPath??n,s.name);this.ignored(a)||(s.isSymbolicLink()?this.watch(a,this.ignored.bind(this),this.options?.recursive):this.options?.recursive&&s.isDirectory()&&r.push(a))}}}};J=b([tn({scope:"singleton"})],J);import{resolve as pn}from"path";import un from"node:process";import{createRequire as dn}from"module";import{dirname as mn}from"@remotex-labs/xmap";import{inject as Xe}from"@remotex-labs/xinject";async function tr(i,e,t={},r=!1){let n={exports:{config:{},default:{}}};return await Ce(i,{require:dn(pn(e)),module:n,$argv:t},{filename:e},r),n.exports.config??n.exports.default??{}}async function Ze(i,e={}){let r=Xe(h).touch(i).snapshot?.text;if(!r)return{};let[n,o]=(await $e(r,i,{minify:!1,format:"cjs",outdir:mn(i),platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,minifyWhitespace:!0,minifyIdentifiers:!1})).outputFiles,s=Xe(O);Xe(u).addSourceMap(i,n.text,!0);let a=await tr(o.text,i,{},!0),c=s.enhancedParse(un.argv,a.userArgv??{});Object.assign(e,c);let l=await tr(o.text,i,c);return C({},{watch:{filter:["**/*.{js,ts,json}","!**/*.d.ts"],recursive:!0}},l)}function hn(i,e){e.entryPoints&&(i.variants={argv:{esbuild:{entryPoints:e.entryPoints}}})}function ir(i,e){let t=i.common?.esbuild?.outdir??"dist",r=Object.values(i.variants??{});t&&i.watch?.filter?.push(`!${t}/**`);for(let n of r)e.types!==void 0&&(n.types=e.types),e.outdir!==void 0&&(n.esbuild.outdir=e.outdir),e.bundle!==void 0&&(n.esbuild.minify=e.bundle),e.minify!==void 0&&(n.esbuild.minify=e.minify),e.tsconfig!==void 0&&(n.esbuild.tsconfig=e.tsconfig),e.platform!==void 0&&(n.esbuild.platform=e.platform),e.declaration!==void 0&&(n.declaration=e.declaration),e.failOnError!==void 0&&(n.types={failOnError:e.failOnError}),n.esbuild.outdir&&n.esbuild.outdir!==t&&i.watch?.filter?.push(`!${n.esbuild.outdir}/**`)}async function rr(i,e){e.clean&&gn("dist",{recursive:!0,force:!0}),await i.build(e.build)}async function yn(i,e,t){if(!((e.serve??!1)!==!1||i.serve?.start))return;let n=i.serve?.dir||e.serve||"dist",o=new we({...i.serve},n);o.subscribe(t.serverEvent.bind(t)),await o.start()}async function vn(i,e,t,r){if(!(t.watch||t.serve!==void 0||e.serve?.start))return;let o=et(h),s=o.touch(t.config).version;new J(process.cwd(),e.watch).subscribe(async c=>{if(o.refreshAll(),s!==o.touch(t.config).version){s=o.touch(t.config).version;let f=await Ze(t.config);ir(f,t),i.configuration=f}let l=Object.keys(c).length;await r.rebuild(`${l} ${l===1?"file":"files"} changed`)}),await ht(r)}async function bn(){console.log(st());let e=et(O).parseConfigFile(process.argv),t={},r=await Ze(e.config,t);hn(r,t),ir(r,t);let n=new Me(r,t),o=et(Y,rr.bind({},n,t));n.subscribe(o.buildEvent.bind(o)),t.typeCheck&&o.diagnostics(await n.typeChack(t.build)),await yn(r,t,o),await vn(n,r,t,o),await rr(n,t)}await bn();export{ir as applyCommandLineOverrides,hn as configureEntryPoints,yn as startServer,vn as startWatchMode};
83
58
  //# sourceMappingURL=bash.js.map