jitar 0.10.3 → 0.10.5

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/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import e from"node:path";import t,{promises as r}from"node:fs";import{fileURLToPath as s}from"node:url";import{glob as n}from"glob";import a from"mime-types";import i from"dotenv";import{B as o,N as c,F as u,a as l,A as h,O as d,b as m,P as p,T as g,U as f,S as w,V as y,c as v,R as b,d as S,e as M}from"./Response-DEjrdAZ9.js";import x from"crypto";import E from"express";class A extends Error{constructor(e){super(`Missing argument '${e}'`)}}class P{#e;#t;constructor(e){this.#e=e[2],this.#t=this.#r(e)}getCommand(){return this.#e}containsKey(e){return this.#t.has(e)}getRequiredArgument(e){const t=this.#t.get(e);if(void 0===t)throw new A(e);return t}getOptionalArgument(e,t){return this.#t.get(e)??t}#r(e){const t=e.slice(3),r=new Map;return t.forEach(e=>{const[t,s]=e.split("=");r.set(t.trim(),s?.trim())}),r}}class I{name="help";description="Shows all available commands (this message).";options=[{key:"[command]",required:!1,description:"The command name to show more details for"}];#s;constructor(e){this.#s=e}async execute(e){for(const t of this.#s.values())if(e.containsKey(t.name))return this.#n(t);this.#a()}#a(){console.log("\njitar <command>\n"),console.log("Available commands:");const e=[...this.#s.values()],t=e.map(e=>e.name),r=this.#i(t);for(const t of e){const e=t.name.padEnd(r," "),s=t.description;console.log(` ${e} ${s}`)}console.log("\nFor the options per command, use:"),console.log(" jitar help [command]\n")}#n(e){console.log(`\n${e.description}\n`);const t=e.options;if(0===t.length)return void console.log("No options available.\n");console.log("Options:");const r=t.map(e=>e.key),s=this.#i(r);for(const e of t){const t=e.key.padEnd(s," "),r=e.description,n=e.defaultValue?`default: ${e.defaultValue}`:"no default value",a=e.required?"required":`optional - ${n}`;console.log(` ${t} ${r} (${a})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class O{name="about";description="Shows information about Jitar.";options=[];async execute(e){console.log("\nJitar is a JavaScript Distributed Runtime created and maintained by Masking Technology.\n\nMore information can be found at:\n- https://jitar.dev\n- https://masking.tech\n")}}class R{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.3")}}class k extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class T extends Error{constructor(e){super(`Unknown template: ${e}`)}}const N=/^[a-zA-Z.\-_]+$/,C={_gitignore:".gitignore"};class ${#o;#c;constructor(e="./"){this.#o=this.#u(),this.#c=this.#l(e)}async init(e,t){this.#h(e,"project"),this.#h(t,"template");if(!1===await this.#d(t))throw new T(t);await this.#m(e,t),this.#p(e)}#u(){const t=e.dirname(s(import.meta.url));return e.join(t,"templates")}#l(t){return e.resolve(t)}#h(e,t){if(!1===N.test(e))throw new k(e,t)}async#d(t){try{const s=e.join(this.#o,t);return(await r.stat(s)).isDirectory()}catch{return!1}}#m(t,s){const n=e.join(this.#o,s),a=e.join(this.#c,t);return r.cp(n,a,{recursive:!0,force:!0})}async#p(t){const s=e.join(this.#c,t),n=Object.entries(C),a=[];for(const[t,i]of n){const n=e.join(s,t),o=e.join(s,i);a.push(r.rename(n,o))}await Promise.all(a)}}class F{name="init";description="Initializes a new Jitar project from a template.";options=[{key:"--name",required:!0,description:"Project name used for creating the project folder"},{key:"--template",required:!0,description:"Template to use [react, vue, backend]"},{key:"--location",required:!1,description:"The root location of the project",defaultValue:"./"}];async execute(e){const t=e.getRequiredArgument("--name"),r=e.getRequiredArgument("--template"),s=e.getOptionalArgument("--location",void 0);this.#g(t,r),await this.#f(t,r,s),this.#w(t)}#g(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#f(e,t,r){return new $(r).init(e,t)}#w(e){console.log(`SUCCESS! Run the following commands to continue:\ncd ${e}\nnpm install\nnpm run build\nnpm run standalone`)}}const L=0,z=1,j=2,H=3,D=4;class q{#y;#v;constructor(e=z,t=console){this.#y=e,this.#v=t}debug(...e){if(this.#y>L)return;const t=this.#b("DEBUG",e);this.#v.debug(t)}info(...e){if(this.#y>z)return;const t=this.#b("INFO",e);this.#v.info(t)}warn(...e){if(this.#y>j)return;const t=this.#b("WARN",e);this.#v.warn(t)}error(...e){if(this.#y>H)return;const t=this.#b("ERROR",e);this.#v.error(t)}fatal(...e){const t=this.#b("FATAL",e);this.#v.error(t)}#b(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#S(e)).join(" ")}`}#S(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#M(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#x(t)}${r}`}#M(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#S(e,t)).join(",\n")}\n${this.#x(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#x(e){return" ".repeat(e)}}class V extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class B{parse(e){switch(e.toUpperCase()){case"DEBUG":return L;case"INFO":return z;case"WARN":return j;case"ERROR":return H;case"FATAL":return D;default:throw new V(e)}}}const W="**/*.js",K="**/*.json",G="**/*.json";class U extends Error{#E;constructor(e){super(`Invalid location: ${e}`),this.#E=e}get location(){return this.#E}}class _ extends Error{#A;constructor(e){super(`The file '${e}' could not be found`),this.#A=e}get filename(){return this.#A}}class J{#E;#P;#I;constructor(e,t,r){this.#E=e,this.#P=t,this.#I=r}get location(){return this.#E}get type(){return this.#P}get content(){return this.#I}get size(){return this.#I.length}}class Y{#E;#O;#R;constructor(e,t){const r=t.resolve(e);this.#E=t.normalize(e),this.#O=t.normalize(r),this.#R=t}getAbsoluteLocation(e){const t=this.#R.isAbsolute(e)?e:this.#R.join(this.#E,e),r=this.#R.resolve(t),s=this.#R.normalize(r);return this.#k(s,e),s}getRelativeLocation(e){const t=this.#R.relative(this.#E,e);return this.#R.normalize(t)}normalizeLocation(e){return this.#R.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#R.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#R.exists(t))throw new _(e);return this.#R.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#R.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#R.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),r=await this.getType(t),s=await this.getContent(t);return new J(e,r,s)}async write(e,t){const r=this.getAbsoluteLocation(e);return this.#R.write(r,t)}async copy(e,t){const r=this.getAbsoluteLocation(e),s=this.getAbsoluteLocation(t);return this.#R.copy(r,s)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#R.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),r=this.#R.normalize(e);return(await this.#R.filter(t,r)).map(e=>this.#R.normalize(e))}#k(e,t){if(!1===e.startsWith(this.#O))throw new U(t)}}class X{copy(e,t){return r.cp(e,t,{recursive:!0,force:!0})}delete(e){return r.rm(e,{recursive:!0,force:!0})}async exists(e){try{return await r.stat(e),!0}catch{return!1}}isAbsolute(t){return e.isAbsolute(t)}isDirectory(e){try{return t.statSync(e).isDirectory()}catch{return!1}}filter(e,t){return n(`${e}/${t}`)}join(...t){return e.join(...t)}read(e){return r.readFile(e)}resolve(t){return e.resolve(t)}relative(t,r){return e.relative(t,r)}normalize(t){return t.replaceAll(e.win32.sep,e.posix.sep)}async mimeType(e){const t=a.lookup(e);if(!1!==t)return t}async write(s,n){const a=e.dirname(s);return t.mkdirSync(a,{recursive:!0}),r.writeFile(s,n)}}class Q extends Y{constructor(e){super(e,new X)}}let Z=class extends Error{#T;#N;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#T=e,this.#N=t}get url(){return this.#T}get reason(){return this.#N}};class ee{#C;constructor(e){this.#C=e}async import(e){const t=this.#C.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new Z(t,r)}}}class te{#$;constructor(e){this.#$=e}locate(e){return`file://${e.startsWith("/")?this.#$.getAbsoluteLocation(`.${e}`):this.#$.getAbsoluteLocation(e)}`}}class re extends ee{constructor(e){super(new te(e))}}class se{#$;#F;constructor(e,t){this.#$=e,this.#F=t}async filter(...e){return(await Promise.all(e.map(e=>this.#$.filter(e)))).flat().map(e=>this.#$.getRelativeLocation(e))}exists(e){return this.#$.exists(e)}read(e){return this.#$.read(e)}import(e){return this.#F.import(e)}}class ne extends se{constructor(e){const t=new Q(e);super(t,new re(t))}}let ae=class{#L;#z;#j;constructor(e,t,r){this.#L=e,this.#z=t,this.#j=r}get resources(){return this.#z}get repository(){return this.#L}get segmentation(){return this.#j}};class ie{#z;constructor(e){this.#z=e}isResourceModule(e){return this.#z.includes(e)}}const oe="private",ce="0.0.0",ue="index.js",le=".json",he="default",de=/import\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,me=/export\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,pe="*";let ge=class{#H=0;next(){return"$"+ ++this.#H}};const fe="js",we=/\.js$/,ye=[".","/","http:","https:"];class ve{translatePath(e){const t=e.split("/"),r=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":r.pop();continue}r.push(e)}return r.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const r=e.split("/"),s=t.split("/");for(;r[0]===s[0];)r.shift(),s.shift();const n=s.map(()=>"..").join("/");return`${s.length>0?n:"."}/${r.join("/")}`}makePathAbsolute(e,t){const r=""!==t?`${t}/${e}`:e;return this.translatePath(r)}extractPath(e){return e.split("/").slice(0,-1).join("/")}stripPath(e){return e.substring(1,e.length-1)}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${fe}`)?e:`${e}.${fe}`}addSubExtension(e,t){return e.replace(we,`.${t}.${fe}`)}isApplicationModule(e){return ye.some(t=>e.startsWith(t))}}let be=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class Se{#D;#q;#V=new ve;constructor(e,t){this.#D=e,this.#q=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#B(e)));return new ie(t.flat())}async#B(e){try{const t=await this.#D.getContent(e);return JSON.parse(t.toString()).map(e=>this.#W(e))}catch(t){const r=t instanceof Error?t.message:String(t);throw new be(e,r)}}#W(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${ue}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}}let Me=class{#A;#K;#G;constructor(e,t,r){this.#K=t,this.#A=e,this.#G=r}get filename(){return this.#A}get code(){return this.#K}get model(){return this.#G}};class xe{#U;constructor(e){this.#U=e}get modules(){return this.#U}get(e){return this.#U.find(t=>t.filename===e)}}class Ee{#_;#J;constructor(e,t){this.#_=e,this.#J=t}get name(){return this.#_}get as(){return this.#J}toString(){return`${this.#_} as ${this.#J}`}}class Ae{#Y;constructor(e){this.#Y=e}get definition(){return this.#Y}toString(){return this.#Y}}class Pe extends Ae{}class Ie{#_;#X;#Q;constructor(e,t=!1,r=!1){this.#_=e,this.#X=t,this.#Q=r}get name(){return this.#_}get isStatic(){return this.#X}get isPrivate(){return this.#Q}get isPublic(){return!1===this.#Q}}class Oe extends Ie{#Z;#ee;constructor(e,t,r){super(e),this.#Z=t,this.#ee=r}get parentName(){return this.#Z}get scope(){return this.#ee}get members(){return this.#ee.members}get declarations(){return this.#ee.declarations}get functions(){return this.#ee.functions}get getters(){return this.#ee.getters}get setters(){return this.#ee.setters}get generators(){return this.#ee.generators}get readable(){const e=new Map;return this.getters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get writable(){const e=new Map;return this.setters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get callable(){return this.functions.filter(e=>e.isPublic)}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGetter(e){return this.#ee.getGetter(e)}getSetter(e){return this.#ee.getSetter(e)}getGenerator(e){return this.#ee.getGenerator(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGetter(e){return this.#ee.hasGetter(e)}hasSetter(e){return this.#ee.hasSetter(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}canRead(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasGetter(e)}canWrite(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasSetter(e)}canCall(e){const t=this.getFunction(e);return t?.isPublic??!1}toString(){const e=void 0!==this.#Z?` extends ${this.#Z}`:"";return`class ${this.name}${e} { ${this.#ee.toString()} }`}}class Re extends Ie{#te;#re;constructor(e,t,r=!1,s=!1){super(e.toString(),r,s),this.#te=e,this.#re=t}get identifier(){return this.#te}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class ke{#se;constructor(e){this.#se=e}get members(){return this.#se}toString(){return this.#se.map(e=>e.toString()).join(" , ")}}class Te extends ke{toString(){return`[ ${super.toString()} ]`}}class Ne extends ke{toString(){return`{ ${super.toString()} }`}}class Ce extends Ie{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){const e=this.#ne?` from '${this.#ne}'`:"";return`export { ${this.#se.join(", ")} }${e}`}}class $e extends Ae{}class Fe{#_;#re;constructor(e,t){this.#_=e,this.#re=t}get name(){return this.#_}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class Le extends Ie{#ae;#ie;#oe;constructor(e,t,r,s=!1,n=!1,a=!1){super(e,s,a),this.#ae=t,this.#ie=r,this.#oe=n}get parameters(){return this.#ae}get body(){return this.#ie}get isAsync(){return this.#oe}toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}(${e.join(", ")}) { ${this.body} }`}}class ze extends Le{toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}*(${e.join(", ")}) { ${this.body} }`}}class je extends Le{toString(){return`get ${super.toString()}`}}class He extends Ie{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){return`import { ${this.#se.map(e=>e.toString()).join(", ")} } from '${this.#ne}';`}}class De{#ee;constructor(e){this.#ee=e}get scope(){return this.#ee}get members(){return this.#ee.members}get exportedMembers(){return this.#ce(this.#ee.members)}get imports(){return this.#ee.imports}get exports(){return this.#ee.exports}get declarations(){return this.#ee.declarations}get exportedDeclarations(){return this.#ce(this.#ee.declarations)}get functions(){return this.#ee.functions}get exportedFunctions(){return this.#ce(this.#ee.functions)}get generators(){return this.#ee.generators}get exportedGenerators(){return this.#ce(this.#ee.generators)}get classes(){return this.#ee.classes}get exportedClasses(){return this.#ce(this.#ee.classes)}get exported(){const e=new Map;for(const t of this.exports)for(const r of t.members){const t=this.getMember(r.name);void 0!==t&&e.set(r.as,t)}return e}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGenerator(e){return this.#ee.getGenerator(e)}getClass(e){return this.#ee.getClass(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}hasClass(e){return this.#ee.hasClass(e)}getImport(e){return this.imports.find(t=>t.hasMember(e))}getImported(e){for(const t of this.imports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}isExported(e){for(const t of this.exports)for(const r of t.members)if(r.name===e.name)return!0;return!1}getExport(e){return this.exports.find(t=>t.hasMember(e))}getExported(e){for(const t of this.exports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}#ce(e){return e.filter(e=>this.isExported(e))}}class qe extends Ae{}class Ve extends Le{toString(){return`set ${super.toString()}`}}const Be=He.name,We=Ce.name,Ke=Re.name,Ge=Le.name,Ue=je.name,_e=Ve.name,Je=ze.name,Ye=Oe.name;class Xe{#se;constructor(e){this.#se=e}get members(){return this.#se}get imports(){return this.#se.filter(e=>e.constructor.name===Be)}get exports(){return this.#se.filter(e=>e.constructor.name===We)}get declarations(){return this.#se.filter(e=>e.constructor.name===Ke)}get functions(){return this.#se.filter(e=>e.constructor.name===Ge)}get getters(){return this.#se.filter(e=>e.constructor.name===Ue)}get setters(){return this.#se.filter(e=>e.constructor.name===_e)}get generators(){return this.#se.filter(e=>e.constructor.name===Je)}get classes(){return this.#se.filter(e=>e.constructor.name===Ye)}getMember(e){return this.#se.find(t=>t.name===e)}getDeclaration(e){return this.declarations.find(t=>t.name===e)}getFunction(e){return this.functions.find(t=>t.name===e)}getGetter(e){return this.getters.find(t=>t.name===e)}getSetter(e){return this.setters.find(t=>t.name===e)}getGenerator(e){return this.generators.find(t=>t.name===e)}getClass(e){return this.classes.find(t=>t.name===e)}hasMember(e){return void 0!==this.getMember(e)}hasDeclaration(e){return void 0!==this.getDeclaration(e)}hasFunction(e){return void 0!==this.getFunction(e)}hasGetter(e){return void 0!==this.getGetter(e)}hasSetter(e){return void 0!==this.getSetter(e)}hasGenerator(e){return void 0!==this.getGenerator(e)}hasClass(e){return void 0!==this.getClass(e)}toString(){return this.#se.map(e=>e.toString()).join("\n")}}const Qe={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},Ze=Object.values(Qe);const et=".",tt="(",rt=")",st="[",nt="]",at="{",it="}",ot={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},ct=Object.values(ot);function ut(e){return ct.includes(e)}const lt={UNDEFINED:void 0,NULL:null,STRING:""},ht=Object.values(lt);function dt(e){return ht.includes(e)}const mt={OPEN:tt,CLOSE:rt};function pt(e){return e===mt.OPEN||e===mt.CLOSE}const gt={EXPORT:"export",DEFAULT:"default",CLASS:"class",FUNCTION:"function",CONST:"const",LET:"let",VAR:"var",AS:"as",FROM:"from",IMPORT:"import",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",ASYNC:"async",RETURN:"return"},ft=Object.values(gt);function wt(e){return ft.includes(e)}function yt(e){return e===gt.AS||e===gt.ASYNC||e===gt.FROM||e===gt.GET||e===gt.SET}const vt={OPEN:st,CLOSE:nt};function bt(e){return e===vt.OPEN||e===vt.CLOSE}const St=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function Mt(e){return St.includes(e)}const xt={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_DIVIDE:"/=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_MODULO:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",ASSIGN_XOR:"^=",BITWISE_AND:"&",BITWISE_OR:"|",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",MODULO:"%",MULTIPLY:"*",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",XOR:"^"},Et=Object.values(xt);function At(e){return Et.includes(e)}const Pt={OPEN:at,CLOSE:it};function It(e){return e===Pt.OPEN||e===Pt.CLOSE}const Ot={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},Rt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},kt=Object.values(Rt);function Tt(e){return kt.includes(e)}class Nt{#ue;#le;constructor(e){this.#ue=e,this.#le=0}get items(){return this.#ue}get position(){return this.#le}get size(){return this.#ue.length}get eol(){return this.#le>=this.#ue.length}get current(){return this.#ue[this.#le]}get next(){return this.#ue[this.#le+1]}get previous(){return this.#ue[this.#le-1]}notAtEnd(){return!1===this.eol}get(e){return this.#ue[e]}step(e=1){return this.#le+=e,this.current}stepBack(e=1){return this.#le-=e,this.current}hasNext(){return this.#le+1<this.#ue.length}}class Ct extends Nt{constructor(e){super(e.split(""))}}class $t{#P;#re;#he;#de;constructor(e,t,r,s){this.#P=e,this.#re=t,this.#he=r,this.#de=s}get type(){return this.#P}get value(){return this.#re}get start(){return this.#he}get end(){return this.#de}isType(e){return this.#P===e}hasValue(e){return this.#re===e}toString(){return`${this.#re}`}}class Ft extends Nt{}class Lt{tokenize(e){const t=new Ct(e),r=[];let s;for(;t.notAtEnd();){const e=this.#me(t,s);if(void 0===e)break;e.isType(Ot.WHITESPACE)||e.isType(Ot.COMMENT)?t.step():(r.push(e),this.#pe(e)&&(s=e),t.step())}return new Ft(r)}#pe(e){return!1===[Ot.WHITESPACE,Ot.COMMENT].includes(e.type)}#me(e,t){const r=e.current,s=e.position;if(Tt(r)){const t=e.position;return new $t(Ot.WHITESPACE,r,s,t)}if(function(e){return Ze.includes(e)}(r+e.next)){const t=this.#ge(e),r=e.position;return new $t(Ot.COMMENT,t,s,r)}if(this.#fe(r,t)){const t=this.#we(e),r=e.position;return new $t(Ot.REGEX,t,s,r)}if(Mt(r)){const t=this.#ye(e),r=e.position;return new $t(Ot.LITERAL,t,s,r)}if(At(r)){const t=this.#ve(e),r=e.position;return new $t(Ot.OPERATOR,t,s,r)}if(ut(r)){const t=e.position;return new $t(Ot.DIVIDER,r,s,t)}if(pt(r)){const t=e.position;return new $t(Ot.GROUP,r,s,t)}if(It(r)){const t=e.position;return new $t(Ot.SCOPE,r,s,t)}if(bt(r)){const t=e.position;return new $t(Ot.LIST,r,s,t)}if(dt(r))return;const n=this.#be(e),a=wt(n)?Ot.KEYWORD:Ot.IDENTIFIER,i=e.position;return new $t(a,n,s,i)}#ge(e){const t=e.current+e.next===Qe.MULTI_START,r=t?Qe.MULTI_END:Rt.NEWLINE;let s=t?Qe.MULTI_START:Qe.SINGLE;for(e.step(2);e.notAtEnd();){const n=e.current;if((t?n+e.next:n)===r){e.step(r.length-1);break}s+=n,e.step()}return t?s+Qe.MULTI_END:s.trim()}#fe(e,t){return e===xt.DIVIDE&&(void 0===t||([Ot.OPERATOR,Ot.DIVIDER,Ot.KEYWORD].includes(t.type)||[mt.OPEN,vt.OPEN].includes(t.value)))}#Se(e){return Tt(e)||e==et||!1===this.#Me(e)}#we(e){let t=e.current,r=!1;for(e.step();e.notAtEnd();){const s=e.current,n=e.previous;if(s===xt.DIVIDE&&"\\"!==n)r=!0;else if(!0===r&&this.#Se(s)){e.stepBack();break}t+=s,e.step()}return t}#ye(e){const t=e.current;let r=t,s=!1;for(e.step();e.notAtEnd();){const n=e.current;if(!1===s){if(n===t){r+=n;break}"\\"===n&&(s=!0)}else s=!1;r+=n,e.step()}return r}#Me(e){return!1===(dt(e)||Tt(e)||At(e)||Mt(e)||ut(e)||pt(e)||It(e)||bt(e))}#be(e){let t="";for(;e.notAtEnd();){const r=e.current;if(!1===this.#Me(r)){e.stepBack();break}t+=r,e.step()}return t}#ve(e){let t=e.current;for(e.step();e.notAtEnd();){const r=e.current;if(!1===At(r)||!1===At(t+r)){e.stepBack();break}t+=r,e.step()}return t}}class zt extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class jt extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Ht extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class Dt extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class qt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const Vt="default",Bt=" ";class Wt{#xe;constructor(e=new Lt){this.#xe=e}parse(e){const t=this.#xe.tokenize(e),r=this.#Ee(t);return new De(r)}parseFirst(e){const t=this.#xe.tokenize(e);return this.#Ae(t)}parseValue(e){const t=this.parseFirst(e);if(t instanceof Ae==!1)throw new Dt("a value definition");return t}parseImport(e){const t=this.parseFirst(e);if(t instanceof He==!1)throw new Dt("an import definition");return t}parseExport(e){const t=this.parseFirst(e);if(t instanceof Ce==!1)throw new Dt("an export definition");return t}parseDeclaration(e){const t=this.parseFirst(e);if(t instanceof Re==!1)throw new Dt("a declaration definition");return t}parseFunction(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof Le==!1)throw new Dt("a function definition");return r}parseClass(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof Oe==!1)throw new Dt("a class definition");return r}#Ee(e){const t=[];for(;e.notAtEnd();){const r=this.#Ae(e);r instanceof Ie&&t.push(r)}return new Xe(t)}#Ae(e,t=!1){const r=e.current;if(r.isType(Ot.LITERAL))return this.#Ie(e);if(r.isType(Ot.IDENTIFIER)){const r=e.next;return r?.hasValue(xt.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.isType(Ot.KEYWORD)){if(yt(r.value)){const t=e.next,s=void 0!==t&&(t.hasValue(gt.FUNCTION)||t.hasValue(mt.OPEN));if(r.hasValue(gt.ASYNC)&&s)return e.step(),this.#Ae(e,!0);if(void 0===t||this.#Re(t))return this.#Ie(e)}return r.hasValue(gt.RETURN)?this.#Ie(e):this.#Pe(e,t)}if(r.isType(Ot.REGEX))return this.#Ie(e);if(r.hasValue(mt.OPEN)){const r=this.#ke(e,mt.OPEN,mt.CLOSE);return r?.hasValue(xt.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.hasValue(Pt.OPEN))return this.#Te(e);if(r.hasValue(vt.OPEN))return this.#Ne(e);if(r.hasValue(xt.NOT)||r.hasValue(xt.SUBTRACT))return this.#Ie(e);if(!ut(r.value))throw new qt(r.value,r.start);e.step()}#Pe(e,t=!1){const r=e.current;switch(e.step(),r.value){case gt.IMPORT:return this.#Ce(e);case gt.EXPORT:return this.#$e(e);case gt.CLASS:return this.#Fe(e);case gt.FUNCTION:return this.#Le(e,t);case gt.VAR:case gt.LET:case gt.CONST:return this.#ze(e,!1,!0);case gt.ASYNC:return this.#Pe(e,!0);default:throw new Ht(r.value,r.start)}}#Ce(e){const t=[];let r=e.current;if(r.isType(Ot.LITERAL))return new He(t,r.value);if(r.hasValue(mt.OPEN)){r=e.step();const s=r.value;return e.step(2),new He(t,s)}if(!1===r.hasValue(Pt.OPEN)){const s=r.hasValue(xt.MULTIPLY)?xt.MULTIPLY:Vt;let n=r.value;r=e.step(),r.hasValue(gt.AS)&&(r=e.step(),n=r.value,r=e.step()),t.push(new Ee(s,n))}if(r.hasValue(ot.SEPARATOR)&&(r=e.step()),r.hasValue(Pt.OPEN)){const s=this.#je(e);t.push(...s),r=e.current}if(!1===r.hasValue(gt.FROM))throw new zt(gt.FROM,r.start);r=e.step();const s=r.value;return e.step(),new He(t,s)}#$e(e){switch(e.current.value){case gt.DEFAULT:return e.step(),this.#He(e,!0);case Pt.OPEN:return this.#De(e);default:return this.#He(e,!1)}}#He(e,t){let r=e.current,s=0;var n;r.hasValue(gt.ASYNC)&&(r=e.step(),s++),((n=r.value)===gt.CLASS||n===gt.FUNCTION||n===gt.CONST||n===gt.LET||n===gt.VAR)&&(r=e.step(),s++);const a=this.#Me(r)?r.value:"",i=t?Vt:a;let o;r=e.step(),r?.hasValue(gt.FROM)&&(r=e.step(),o=r.value),s>0&&(s++,e.stepBack(s));const c=new Ee(a,i);return new Ce([c],o)}#De(e){const t=this.#je(e);let r,s=e.current;return s?.hasValue(gt.FROM)&&(s=e.step(),r=s.value),e.step(),new Ce(t,r)}#je(e){const t=[];let r=e.step();for(;e.notAtEnd();){if(r.hasValue(Pt.CLOSE)){e.step();break}if(r.hasValue(ot.SEPARATOR)){r=e.step();continue}const s=this.#qe(e);t.push(s),r=e.step()}return t}#qe(e){let t=e.current;const r=t.value;let s=r;return e.next.hasValue(gt.AS)&&(t=e.step(2),s=t.value),new Ee(r,s)}#ze(e,t,r=!1){let s,n,a=e.current,i=!1;return a.hasValue(vt.OPEN)?(s=this.#Ve(e),a=e.current):a.hasValue(Pt.OPEN)?(s=this.#Be(e),a=e.current):(i=a.value.startsWith("#"),s=i?a.value.substring(1):a.value,a=e.step()),a.hasValue(xt.ASSIGN)&&(e.step(),n=this.#Ae(e,!1),a=e.current),void 0!==a&&(a.hasValue(ot.TERMINATOR)?e.step():!0===r&&a.hasValue(ot.SEPARATOR)&&(e.step(),this.#ze(e,t,!0))),n instanceof ze?new ze(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof Le?new Le(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof Oe?new Oe(s.toString(),n.parentName,n.scope):new Re(s,n,t,i)}#Le(e,t,r=!1,s=!1,n=!1){let a=e.current,i="",o=!1,c=!1;a.hasValue(xt.MULTIPLY)&&(o=!0,a=e.step()),this.#Me(a)&&(c=a.value.startsWith("#"),i=c?a.value.substring(1):a.value,a=e.step());const u=this.#We(e,mt.CLOSE);if(a=e.current,!1===a.hasValue(Pt.OPEN))throw new jt(Pt.OPEN,a.start);const l=this.#Ke(e,Pt.OPEN,Pt.CLOSE);return o?new ze(i,u,l,r,t,c):s?new je(i,u,l,r,t,c):n?new Ve(i,u,l,r,t,c):new Le(i,u,l,r,t,c)}#Oe(e,t){let r,s=e.current;if(s.hasValue(mt.OPEN)?(r=this.#We(e,mt.CLOSE),s=e.current):(r=[new Fe(s.value,void 0)],s=e.step()),!1===s.hasValue(xt.ARROW))throw new jt(xt.ARROW,s.start);s=e.step();const n=s.hasValue(Pt.OPEN)?this.#Ke(e,Pt.OPEN,Pt.CLOSE):this.#Ie(e).definition;return new Le("",r,n,!1,t,!1)}#We(e,t){const r=[];for(e.step();e.notAtEnd();){const s=e.current;if(s.hasValue(t)){e.step();break}if(s.hasValue(ot.SEPARATOR)){e.step();continue}let n;n=s.hasValue(Pt.OPEN)?this.#Be(e):s.hasValue(vt.OPEN)?this.#Ve(e):this.#Ge(e),r.push(n)}return r}#Fe(e){let t,r=e.current,s="";if(this.#Me(r)&&(s=r.value,r=e.step()),r.hasValue(gt.EXTENDS)&&(r=e.step(),t=r.value,r=e.step()),!1===r.hasValue(Pt.OPEN))throw new jt(Pt.OPEN,r.start);const n=this.#Ue(e);return new Oe(s,t,n)}#Ue(e){let t=e.step();const r=[];for(;e.notAtEnd();){if(t.hasValue(Pt.CLOSE)){e.step();break}const s=this.#_e(e);r.push(s),t=e.current}return new Xe(r)}#_e(e){let t=e.current,r=!1,s=!1,n=!1,a=!1;for(;e.notAtEnd();){if(t.hasValue(gt.STATIC))s=!0;else if(t.hasValue(gt.ASYNC))r=!0;else if(t.hasValue(gt.GET))n=!0;else{if(!t.hasValue(gt.SET)){if(t.hasValue(xt.MULTIPLY))return this.#Le(e,r,s,!1,!1);break}a=!0}t=e.step()}return e.next.hasValue(mt.OPEN)?this.#Le(e,r,s,n,a):this.#ze(e,s)}#Ne(e){const t=this.#Ke(e,vt.OPEN,vt.CLOSE);return new Pe(t)}#Ve(e){const t=this.#We(e,vt.CLOSE);return new Te(t)}#Te(e){const t=this.#Ke(e,Pt.OPEN,Pt.CLOSE);return new qe(t)}#Be(e){const t=this.#We(e,Pt.CLOSE);return new Ne(t)}#Ge(e){let t=e.current;const r=t.value;let s;return t=e.step(),t.hasValue(xt.ASSIGN)&&(e.step(),s=this.#Ae(e,!1)),new Fe(r,s)}#Ie(e){let t=e.current,r="";for(;e.notAtEnd();){if(t.hasValue(vt.OPEN)){r+=this.#Ke(e,vt.OPEN,vt.CLOSE)+Bt,t=e.current}else if(t.hasValue(mt.OPEN)){r+=this.#Ke(e,mt.OPEN,mt.CLOSE)+Bt,t=e.current}else if(t.hasValue(Pt.OPEN)){r+=this.#Ke(e,Pt.OPEN,Pt.CLOSE)+Bt,t=e.current}else r+=t.toString()+Bt,t=e.step();if(void 0===t||this.#Re(t))break}return new $e(r.trim())}#Ke(e,t,r){let s=e.step(),n=t+Bt;for(;e.notAtEnd();)if(s.hasValue(t))n+=this.#Ke(e,t,r)+Bt,s=e.current;else{if(s.hasValue(r))return e.step(),n+=r,n;n+=s.toString()+Bt,s=e.step()}return n}#ke(e,t,r){const s=e.position;this.#Ke(e,t,r);const n=e.current,a=e.position;return e.stepBack(a-s),n}#Re(e){return[ot.TERMINATOR,ot.SEPARATOR].includes(e.value)||[vt.CLOSE,mt.CLOSE,Pt.CLOSE].includes(e.value)||wt(e.value)}#Me(e){return e.isType(Ot.IDENTIFIER)||e.isType(Ot.KEYWORD)&&yt(e.value)}}class Kt{merge(e,t){const r=this.#Je(e.declarations,t.declarations),s=this.#Ye(e.functions,t.functions),n=this.#Ye(e.getters,t.getters),a=this.#Ye(e.setters,t.setters),i=[...r.values(),...s.values(),...n.values(),...a.values()];return new Oe(e.name,t.name,new Xe(i))}#Je(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}#Ye(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}}class Gt{#Xe=new Wt;#Qe=new Kt;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,n]of r){if("function"!=typeof n.toString)continue;const r=n.toString();if(r.startsWith("class"))s.push(this.fromClass(n,t));else if(r.startsWith("function"))s.push(this.fromFunction(n));else{const t=new $e(r);s.push(new Re(e,t))}}return new De(new Xe(s))}fromClass(e,t=!1){const r=this.isClass(e)?this.#Ze(e):this.#et(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const n=this.fromClass(s,!0);return this.#Qe.merge(r,n)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#Xe.parseFunction(t)}createInstance(e,t=[]){return new e(...t)}getClass(e){return e.constructor}getParentClass(e){return Object.getPrototypeOf(e)}isClassObject(e){return this.isClass(e.constructor)}isFunctionObject(e){return this.isFunction(e.constructor)}isClass(e){return e.toString().startsWith("class")}isFunction(e){return e.toString().startsWith("function")||e.toString().startsWith("async function")}#Ze(e){const t=e.toString();return this.#Xe.parseClass(t)}#et(e){const t=this.createInstance(e),r=this.#tt(e,t),s=new Xe(r);return new Oe(e.name,void 0,s)}#tt(e,t){return[...this.#rt(t),...this.#st(e)]}#rt(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],n=void 0!==t?new Ae(String(t)):void 0,a=new Re(e,n);s.push(a)}return s}#st(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],n=s.value;if(n instanceof Function==!1)continue;const a=this.fromFunction(n);void 0!==s.get?r.push(new je(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):void 0!==s.set?r.push(new Ve(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):r.push(a)}return r}}let Ut=class extends Error{constructor(e,t){super(`Failed to load module file '${e}' because of: ${t}`)}},_t=class{#q;#Xe=new Wt;#V=new ve;constructor(e){this.#q=e}rewrite(e,t){const r=this.#nt(e,t);return this.#at(e,r)}#nt(e,t){return t.replaceAll(de,t=>this.#it(e,t))}#at(e,t){return t.replaceAll(me,t=>this.#ot(e,t))}#it(e,t){const r=this.#Xe.parseImport(t),s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ot(e,t){const r=this.#Xe.parseExport(t);if(void 0===r.from)return t;const s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ct(e,t){const r=this.#V.extractPath(e),s=this.#V.makePathAbsolute(t,r);return this.#q.isDirectory(s)?`${t}/${ue}`:this.#V.assureExtension(t)}},Jt=class{#q;#Xe;#ut;constructor(e,t=new Wt){this.#q=e,this.#Xe=t,this.#ut=new _t(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new xe(t)}async read(e){const t=this.#q.getRelativeLocation(e),r=await this.#lt(e),s=this.#ut.rewrite(t,r),n=this.#Xe.parse(s);return new Me(t,s,n)}async#lt(e){try{return(await this.#q.getContent(e)).toString()}catch(t){const r=t instanceof Error?t.message:String(t);throw new Ut(e,r)}}};class Yt{#_;#U=new Map;#ht=new Map;#dt=new Map;constructor(e){this.#_=e}get name(){return this.#_}get modules(){return[...this.#U.values()]}get classes(){return[...this.#ht.values()]}get procedures(){return[...this.#dt.values()]}hasModule(e){return this.#U.has(e)}getModule(e){return this.#U.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#U.set(e.filename,e)}hasProcedure(e){return this.#dt.has(e)}getProcedure(e){return this.#dt.get(e)}setProcedure(e){this.#dt.set(e.fqn,e)}setClass(e){this.#ht.set(e.fqn,e)}}class Xt{#H;#mt;#pt;constructor(e,t,r){this.#H=e,this.#mt=t,this.#pt=r}get id(){return this.#H}get importKey(){return this.#mt}get fqn(){return this.#pt}}class Qt extends Xt{#G;constructor(e,t,r,s){super(e,t,r),this.#G=s}get model(){return this.#G}}class Zt extends Xt{#gt;#ft;#G;constructor(e,t,r,s,n,a){super(e,t,r),this.#gt=s,this.#ft=n,this.#G=a}get access(){return this.#gt}get version(){return this.#ft}get model(){return this.#G}}class er{#A;#E;#wt;#se=[];#yt;constructor(e,t,r,s){this.#A=e,this.#E=t,this.#wt=r,this.#yt=s}get filename(){return this.#A}get location(){return this.#E}get imports(){return this.#wt}get members(){return this.#se}get segmented(){return this.#yt}hasClasses(){return this.#se.some(e=>e instanceof Qt)}getClasses(){return this.#se.filter(e=>e instanceof Qt)}hasImplementations(){return this.#se.some(e=>e instanceof Zt)}getImplementations(){return this.#se.filter(e=>e instanceof Zt)}addMember(e){this.#se.push(e)}addImports(e){const t=Object.keys(e);for(const r of t)this.#wt[r]=e[r]}}class tr{#pt;#vt=[];constructor(e,t=[]){this.#pt=e,this.#vt=t}get fqn(){return this.#pt}get implementations(){return this.#vt}addImplementation(e){this.#vt.push(e)}}class rr{#bt;constructor(e){this.#bt=e}get segments(){return this.#bt}getSegment(e){return this.#bt.find(t=>t.name===e)}isSegmentedModule(e){return this.#bt.some(t=>t.hasModule(e))}getSegments(e){return this.#bt.filter(t=>t.hasModule(e))}}class sr extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class nr extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class ar extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class ir extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class or extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class cr extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class ur{#L;#V=new ve;constructor(e){this.#L=e}locate(e,t){const r=[];return{trace:r,model:this.#St(e,t,r)}}#St(e,t,r){r.push({filename:e,importKey:t});const s=this.#Mt(e);return this.#xt(s,t)?this.#Et(s,t,r):this.#At(s,t)}#Mt(e){const t=this.#L.get(e);if(void 0===t)throw new cr(e);return t}#xt(e,t){const r=e.model.getImport(t),s=e.model.getExport(t);return void 0!==r||void 0!==s?.from}#Et(e,t,r){const s=this.#Pt(e,t)??this.#It(e,t),n=s?.from,a=s?.name,i=this.#V.extractPath(e.filename),o=this.#V.stripPath(n),c=this.#V.makePathAbsolute(o,i);return this.#St(c,a,r)}#At(e,t){const r=this.#It(e,t);if(void 0===r)throw new or(e.filename,t);const s=e.model.getMember(r.name);if(void 0===s)throw new or(e.filename,r.name);return s}#It(e,t){const r=e.model.getExport(t),s=r?.getMember(t);if(void 0!==s)return{from:r?.from,name:s.name}}#Pt(e,t){const r=e.model.getImport(t),s=r?.getMember(t);if(void 0!==r&&void 0!==s)return{from:r.from,name:s.name}}}class lr{#Ot;#q;#Rt;#V=new ve;constructor(e,t,r){this.#Ot=e,this.#q=t,this.#Rt=new ur(r)}async readAll(e){const t=await Promise.all(e.map(e=>this.#kt(e)));return new rr(t)}async#kt(e){const t=await this.#Tt(e),r=this.#Nt(e),s=new Yt(r);return this.#Ct(s,t),this.#$t(s),s}#Nt(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new nr(e);return t.replace(le,"")}async#Tt(e){try{const t=await this.#Ot.getContent(e);return JSON.parse(t.toString())}catch(t){const r=t instanceof Error?t.message:String(t);throw new ar(e,r)}}#Ct(e,t){for(const[r,s]of Object.entries(t))this.#Ft(e,r,s,!0)}#Ft(e,t,r,s){const n=this.#Lt(t),a=this.#V.extractPath(n),i=e.hasModule(n)?e.getModule(n):new er(n,a,{},s);i.addImports(r),e.setModule(i)}#Lt(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${ue}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#$t(e){const t=new ge;for(const r of e.modules)for(const s in r.imports)this.#zt(e,r,s,t)}#zt(e,t,r,s){const{model:n,trace:a}=this.#Rt.locate(t.filename,r),i=this.#jt(t,n,r,s);this.#Ht(e,t,n,i),a.shift();for(const t of a){const r={[t.importKey]:{access:i.access}};this.#Ft(e,t.filename,r,!1)}}#jt(e,t,r,s){const n=e.imports[r],a=s.next(),i=n.as??t.name;return{id:a,importKey:r,name:i,access:n.access??oe,version:n.version??ce,fqn:this.#Dt(e,i,r)}}#Dt(e,t,r){return this.#qt(e)?t:this.#Vt(e)&&this.#Bt(r)?e.location:`${e.location}/${t}`}#qt(e){return""===e.location}#Vt(e){return e.filename.endsWith(ue)}#Bt(e){return e===he}#Ht(e,t,r,s){if(r instanceof Oe)return this.#Wt(e,t,r,s);if(r instanceof Le)return this.#Kt(e,t,r,s);throw new ir(t.filename,s.importKey)}#Wt(e,t,r,s){const n=new Qt(s.id,s.importKey,s.fqn,r);t.addMember(n),e.setClass(n)}#Kt(e,t,r,s){if(!1===r.isAsync)throw new sr(t.filename,s.name);const n=new Zt(s.id,s.importKey,s.fqn,s.access,s.version,r);this.#Gt(e,t,n)}#Gt(e,t,r){const s=e.hasProcedure(r.fqn)?e.getProcedure(r.fqn):new tr(r.fqn);s.addImplementation(r),t.addMember(r),e.setProcedure(s)}}class hr{#Ut;constructor(e){this.#Ut=e}async read(e,t,r){const s=this.#Ut.source,n=this.#Ut.resource,a=this.#Ut.segment,i=new Jt(s),o=await i.readAll(e),c=new Se(n,s),u=await c.readAll(t),l=new lr(a,s,o),h=await l.readAll(r);return new ae(o,u,h)}}class dr{#_t;#z;#j;#Jt;#Xe=new Wt;#V=new ve;constructor(e,t,r,s){this.#_t=e,this.#z=t,this.#j=r,this.#Jt=s}get parser(){return this.#Xe}rewrite(e){return e.replaceAll(this.replacementPattern,e=>this.replaceStatement(e))}replaceStatement(e){const t=this.parseStatement(e);return void 0===t.from?e:this.#Yt(t)?this.#Xt(t):this.#Qt(t)}#Xt(e){const t=this.#Zt(e);return this.#z.isResourceModule(t)?this.#er(t,e):this.#tr(t,e)}#Qt(e){const t=this.#rr(e),r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#tr(e,t){if(0===t.members.length)return this.#sr(e,t,[]);const{segmentKeys:r,remoteKeys:s,commonKeys:n}=this.#nr(e,t),a=[];return r.length>0&&a.push(this.#ar(e,t,r)),s.length>0&&a.push(this.#ir(e,t,s)),n.length>0&&a.push(this.#sr(e,t,n)),a.filter(e=>e.length>0).join("\n")}#er(e,t){const r=this.#or(e);return this.excludeFromBundle(t,r)}#ar(e,t,r){const s=this.#or(e,this.#Jt.name);return this.includeInBundle(t,s,r)}#ir(e,t,r){const s=this.#or(e,"remote");return this.includeInBundle(t,s,r)}#sr(e,t,r){const s=this.#or(e);return this.includeInBundle(t,s,r)}#Yt(e){const t=this.#V.stripPath(e.from);return this.#V.isApplicationModule(t)}#Zt(e){const t=this.#V.stripPath(e.from),r=this.#V.extractPath(this.#_t.filename);return this.#V.makePathAbsolute(t,r)}#nr(e,t){const r=this.#cr(e,this.#Jt),s=this.#ur(e,r),n=this.#lr(t,r),a=this.#lr(t,s);return{segmentKeys:n,remoteKeys:a,commonKeys:this.#hr(t,[...n,...a])}}#cr(e,t){if(void 0===t)return[];const r=t.getModule(e);return void 0!==r?Object.keys(r.imports):[]}#ur(e,t){const r=this.#j.getSegments(e).filter(e=>e!==this.#Jt).map(t=>this.#cr(e,t)).flat();return[...new Set(r)].filter(e=>!1===t.includes(e))}#lr(e,t){return e.members.filter(e=>t.includes(e.name)).map(e=>e.name)}#hr(e,t){return e.members.filter(e=>!1===t.includes(e.name)).map(e=>e.name)}#or(e,t){const r=this.#V.extractPath(this.#_t.filename),s=this.#V.makePathRelative(e,r);return void 0!==t?this.#V.addSubExtension(s,t):s}#rr(e){return this.#V.stripPath(e.from)}}class mr extends dr{get replacementPattern(){return de}parseStatement(e){return this.parser.parseImport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`import "${t}";`;return`import ${this.#dr(e,r)} from "${t}";`}excludeFromBundle(e,t){if(0===e.members.length)return`await import("${t}");`;return`const ${this.#mr(e)} = await import("${t}");`}#dr(e,t){const r=e.members.filter(e=>t.includes(e.name)),s=r.find(e=>e.name===he),n=void 0!==s,a=n?s.as:"",i=r.filter(e=>e.name!==he).map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name),o=i.length>0;return`${a}${n&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#mr(e){if(this.#pr(e))return e.members[0].as;return`{ ${e.members.map(e=>e.name!==e.as?`${e.name} : ${e.as}`:e.name).join(", ")} }`}#pr(e){return 1===e.members.length&&e.members[0].name===pe}}class pr extends dr{get replacementPattern(){return me}parseStatement(e){return this.parser.parseExport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`export "${t}";`;return`export ${this.#gr(e,r)} from "${t}";`}excludeFromBundle(e,t){const r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#gr(e,t){const r=e.members.filter(e=>t.includes(e.name));if(1===r.length&&""===r[0].name){const e=r[0];return e.name!==e.as?`${pe} as ${e.as}`:pe}return`{ ${r.map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name).join(", ")} }`}}class gr{build(e,t,r,s){const n=new mr(e,t,r,s),a=new pr(e,t,r,s),i=n.rewrite(e.code);return a.rewrite(i)}}const fr="normal",wr="dry",yr=200,vr=400,br=401,Sr=402,Mr=403,xr=404,Er=418,Ar=500,Pr=501;class Ir extends o{#fr;constructor(e){super(`Invalid version number '${e}'`),this.#fr=e}get number(){return this.#fr}}class Or extends c{#pt;constructor(e){super(`Procedure '${e}' not found`),this.#pt=e}get fqn(){return this.#pt}}class Rr extends u{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class kr extends o{#wr;constructor(e){super(`Unknown parameter ${e}`),this.#wr=e}get parameterName(){return this.#wr}}class Tr extends o{#wr;constructor(e){super(`Missing value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class Nr extends o{#wr;constructor(e){super(`Invalid value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class Cr{extract(e,t){const r=this.#yr(e,t),s=[];for(const t of e){const e=this.#vr(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new kr(e)}return s}#yr(e,t){const r=new Map;for(const[s,n]of t){if(this.#br(s)){const t=this.#Sr(s);!0===this.#Mr(e,t)&&r.set(t,n);continue}r.set(s,n)}return r}#br(e){return e.startsWith("*")}#Sr(e){return e.substring(1)}#Mr(e,t){return void 0!==e.find(e=>e.name===t)}#vr(e,t,r){return e instanceof l?this.#xr(e,t,r):this.#Er(e,t)}#xr(e,t,r){const s=t.get(e.name);if(this.#Ar(e,s,r))throw new Tr(e.name);if(this.#Pr(e,s,r))throw new Nr(e.name);return t.delete(e.name),s}#Er(e,t){return e instanceof h?this.#Ir(e,t):this.#Or(e,t)}#Ir(e,t){const r=this.#Rr(e,t);return void 0!==r?Object.values(r):void 0}#Or(e,t){return this.#Rr(e,t)}#Rr(e,t){const r=e instanceof h,s={},n=[];let a=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#vr(o,t,e);void 0!==u?a=!0:!1===o.isOptional&&n.push(o.name),s[c]=u}if(!0===a&&n.length>0)throw new Tr(n[0]);return a?s:void 0}#Ar(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#Pr(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof h&&t instanceof Array==!1||r instanceof d&&t instanceof Object==!1)}}class $r{toStatus(e){return e instanceof o?vr:e instanceof u?Mr:e instanceof c?xr:e instanceof m?Pr:e instanceof p?Sr:e instanceof g?Er:e instanceof f?br:Ar}fromStatus(e,t){switch(e){case vr:return new o(t);case Mr:return new u(t);case xr:return new c(t);case Pr:return new m(t);case Sr:return new p(t);case Er:return new g(t);case br:return new f(t);default:return new w(t)}}}const Fr=/^\d+(?:\.\d+){0,2}$/;class Lr{parse(e){if(0===e.trim().length)return y.DEFAULT;if(!1===Fr.test(e))throw new Ir(e);const t=e.split(".");switch(t.length){case 1:return new y(Number.parseInt(t[0]));case 2:return new y(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new y(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class zr extends c{#pt;#ft;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#pt=e,this.#ft=t}get fqn(){return this.#pt}get version(){return this.#ft}}class jr extends w{constructor(){super("Invalid segment")}}class Hr{#bt=new Map;addSegment(e){this.#bt.set(e.id,e)}clearSegments(){this.#bt.clear()}getClassNames(){const e=new Set;for(const t of this.#bt.values()){t.getClasses().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasClass(e){return this.getClassNames().includes(e)}getClass(e){for(const t of this.#bt.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#bt.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#bt.values()){t.getExposedProcedures().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}getProcedure(e){for(const t of this.#bt.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Dr{#kr;#Tr;#Nr=new Cr;#Cr=new $r;#$r=new Hr;constructor(e,t=[]){this.#kr=e,this.#Tr=t}async start(){return this.#Fr()}async stop(){return this.#Lr()}async loadSegment(e){const t=await this.#kr.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof v==!1)throw new jr;this.#$r.addSegment(e)}getClassNames(){return this.#$r.getClassNames()}hasClass(e){return this.#$r.hasClass(e)}getClass(e){return this.#$r.getClass(e)}getClassByImplementation(e){return this.#$r.getClassByImplementation(e)}getProcedureNames(){return this.#$r.getProcedureNames()}hasProcedure(e){return this.#$r.hasProcedure(e)}getProcedure(e){return this.#$r.getProcedure(e)}async run(e){const t=this.#zr(e.fqn,e.version),r=this.#Nr.extract(t.parameters,e.args);return e.mode===wr?new b(yr,void 0):this.#jr(e,t,r)}async#Fr(){await Promise.all(this.#Tr.map(e=>this.loadSegment(e)))}#Lr(){this.#$r.clearSegments()}#zr(e,t){const r=this.#$r.getProcedure(e);if(void 0===r)throw new Or(e);const s=r.getImplementation(t);if(void 0===s)throw new zr(r.fqn,t.toString());return s}async#jr(e,t,r){try{const s=await t.executable.call(e,...r);return new b(yr,s)}catch(e){const t=this.#Cr.toStatus(e);return new b(t,e)}}}class qr{build(e){let t="";for(const r of e)t+=r.access===S.PRIVATE?this.#Hr(r):this.#Dr(r);return t.trim()}#Hr(e){const t=e.fqn,r=e.version,s=this.#qr(e),n=`throw new ProcedureNotAccessible('${t}', '${r}');`;return this.#Vr(s,n)}#Dr(e){const t=e.fqn,r=e.version,s=this.#Br(e.model.parameters),n=this.#qr(e),a=`return __run('${t}', '${r}', { ${s} }, this);`;return this.#Vr(n,a)}#Wr(e){const t=[];for(const r of e)r instanceof Fe?t.push(r.name):(r instanceof Te||r instanceof Ne)&&t.push(r.toString());return t.join(", ")}#Br(e){return this.#Kr(e).join(", ")}#Kr(e){const t=[];for(const r of e)if(r instanceof ke){const e=this.#Kr(r.members);t.push(...e)}else if(r instanceof Fe){const e=this.#Gr(r);t.push(e)}return t}#Gr(e){const t=e.name,r=t.startsWith("...")?t.substring(3):t;return`'${t}': ${r}`}#qr(e){const t=e.model.name,r=this.#Wr(e.model.parameters);return`\nexport ${e.importKey===he?`${he} `:""}async function ${t}(${r})`}#Vr(e,t){return`${e} {\n\t${t}\n}\n`}}let Vr=class{#Ur;#_r=new gr;#Jr=new qr;#V=new ve;constructor(e){this.#Ur=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,n=t.modules.map(e=>this.#Yr(e,s,r));await Promise.all(n)}async#Yr(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#Xr(e,t,r);const n=s.map(s=>this.#Qr(e,t,s,r)),a=s[0].getModule(e.filename).hasImplementations()?this.#Zr(e,s):Promise.resolve();await Promise.all([...n,a]),this.#Ur.delete(e.filename)}async#Xr(e,t,r){const s=e.filename,n=this.#_r.build(e,t,r);return this.#Ur.write(s,n)}async#Qr(e,t,r,s){const n=this.#V.addSubExtension(e.filename,r.name),a=this.#_r.build(e,t,s,r);return this.#Ur.write(n,a)}async#Zr(e,t){const r=this.#es(e,t),s=this.#V.addSubExtension(e.filename,"remote"),n=this.#Jr.build(r);return this.#Ur.write(s,n)}#es(e,t){const r=t.map(t=>t.getModule(e.filename)).flatMap(e=>e.getImplementations()),s=new Map;for(const e of r){const t=`${e.fqn}:${e.version.toString()}`;s.set(t,e)}return[...s.values()]}};let Br=class{#Ur;#ts;#V=new ve;#rs=new Lr;constructor(e,t){this.#Ur=e,this.#ts=t}async build(e){const t=e.segmentation.segments.map(e=>this.#ss(e));await Promise.all(t)}async#ss(e){const t=`${e.name}.segment.js`,r=this.#ns(e);await this.#Ur.write(t,r),this.#ts.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}#ns(e){return`${this.#as(e)}\n${this.#is(e)}`}#as(e){return`import { Segment, Class, Procedure, Implementation, Version, NamedParameter, ArrayParameter, ObjectParameter } from "jitar";\n${this.#os(e)}`}#os(e){const t=[];for(const r of e.getSegmentedModules()){if(0===r.members.length)continue;const s=this.#V.addSubExtension(r.filename,e.name),n=`import ${this.#cs(r)} from "./${s}";`;t.push(n)}return t.join("\n")}#cs(e){const t=e.members,r=t.find(e=>e.importKey===he),s=void 0!==r,n=s?r.id:"",a=t.filter(e=>e.importKey!==he),i=a.map(e=>`${e.importKey} as ${e.id}`),o=a.length>0;return`${n}${s&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#is(e){const t=[];t.push(`export default new Segment("${e.name}")`);for(const r of e.classes)t.push(`\t.addClass(new Class("${r.fqn}", ${r.id}))`);for(const r of e.procedures){t.push(`\t.addProcedure(new Procedure("${r.fqn}")`);for(const e of r.implementations){const r=this.#us(e.version),s=this.#ls(e.model);t.push(`\t\t.addImplementation(new Implementation(${r}, "${e.access}", ${s}, ${e.id}))`)}t.push("\t)")}return t.join("\n")}#us(e){const t=this.#rs.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#ls(e){return`[${this.#hs(e.parameters).join(", ")}]`}#hs(e){const t=[];for(const r of e)t.push(this.#ds(r));return t}#ds(e){return e instanceof Te?this.#ms(e):e instanceof Ne?this.#ps(e):this.#gs(e)}#gs(e){return`new NamedParameter("${e.name}", ${void 0!==e.value})`}#ms(e){return`new ArrayParameter([${this.#hs(e.members).join(", ")}])`}#ps(e){return`new ObjectParameter([${this.#hs(e.members).join(", ")}])`}};class Wr{#fs;#ws;constructor(e,t){const r=e.target;this.#fs=new Vr(r),this.#ws=new Br(r,t)}async build(e){await Promise.all([this.#fs.build(e),this.#ws.build(e)])}}class Kr{#ys;#vs;#bs;#Jt;constructor(e,t,r,s){this.#ys=e,this.#vs=t,this.#bs=r,this.#Jt=s}get source(){return this.#ys}get target(){return this.#vs}get resource(){return this.#bs}get segment(){return this.#Jt}}class Gr{#ts;#$;#Ss;#Ms;constructor(e,t){this.#ts=new q(t);const r=new Q(e.source),s=new Q(e.target),n=new Q(e.resources),a=new Q(e.segments);this.#$=new Kr(r,s,n,a),this.#Ss=new hr(this.#$),this.#Ms=new Wr(this.#$,this.#ts)}async build(){const e=this.#$.source,t=this.#$.resource,r=this.#$.segment,s=await e.filter(W),n=await t.filter(K),a=await r.filter(G),i=await this.#Ss.read(s,n,a);return this.#Ms.build(i)}}class Ur{#xs;constructor(e=!0){this.#xs=e}validate(e,t){const r=[];this.#Es("",e,t,r);return{valid:0===r.length,errors:r}}#Es(e,t,r,s){this.#xs&&this.#As(e,t,r,s),this.#Ps(e,t,r,s)}#As(e,t,r,s){const n=Object.keys(t),a=Object.keys(r);for(const t of n)if(!1===a.includes(t)){const r=this.#Is(e,t);s.push(`Unknown field '${r}'`)}}#Ps(e,t,r,s){const n=Object.keys(r);for(const a of n){const n=this.#Is(e,a),i=r[a],o=t[a];this.#Os(n,o,i,s)}}#Os(e,t,r,s){if(void 0!==t)switch(r.type){case"string":return this.#Rs(e,t,r,s);case"integer":return this.#ks(e,t,r,s);case"real":return this.#Ts(e,t,r,s);case"boolean":return this.#Ns(e,t,r,s);case"url":return this.#Cs(e,t,r,s);case"group":return this.#$s(e,t,r,s);case"list":return this.#Fs(e,t,r,s)}else!0===r.required&&s.push(`Field '${e}' is required`)}#Rs(e,t,r,s){"string"!=typeof t&&s.push(`Field '${e}' is not a string`)}#ks(e,t,r,s){"number"==typeof t&&!1!==Number.isInteger(t)||s.push(`Field '${e}' is not an integer`)}#Ts(e,t,r,s){"number"!=typeof t&&s.push(`Field '${e}' is not a real number`)}#Ns(e,t,r,s){"boolean"!=typeof t&&s.push(`Field '${e}' is not a boolean`)}#Cs(e,t,r,s){"string"==typeof t&&!1!==t.startsWith("http")||s.push(`Field '${e}' is not a valid URL`)}#$s(e,t,r,s){"object"==typeof t?this.#Es(e,t,r.fields,s):s.push(`Field '${e}' is not an object`)}#Fs(e,t,r,s){if(!Array.isArray(t))return void s.push(`Field '${e}' is not a list`);const n=t;for(const t in n){const a=this.#Is(e,t),i=n[t];this.#Os(a,i,r.items,s)}}#Is(e,t){return""===e?t:`${e}.${t}`}}class _r{async configure(e){i.config({path:e})}}class Jr extends Error{constructor(e){super(`Runtime configuration is invalid:\n${e.errors.join("\n")}`)}}const Yr="./jitar.json",Xr="./src",Qr="./dist",Zr="./segments",es="./resources",ts={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1}};let rs=class{#Ls;#zs;constructor(e,t){this.#Ls=e,this.#zs=t}async build(e=Yr){const t=await this.#Ls.read(e),r=this.#zs.validate(t,ts);if(!1===r.valid)throw new Jr(r);return t.source??=Xr,t.target??=Qr,t.segments??=Zr,t.resources??=es,t}};const ss="\n => ";class ns extends Error{constructor(e){const t=e.errors.join(ss);super(`Invalid server configuration:${ss}${t}`)}}const as={url:{type:"url",required:!0},setUp:{type:"list",required:!1,items:{type:"string"}},tearDown:{type:"list",required:!1,items:{type:"string"}},middleware:{type:"list",required:!1,items:{type:"string"}},healthChecks:{type:"list",required:!1,items:{type:"string"}},gateway:{type:"group",required:!1,fields:{monitorInterval:{type:"integer",required:!1},trustKey:{type:"string",required:!1}}},proxy:{type:"group",required:!1,fields:{gateway:{type:"url",required:!0},repository:{type:"url",required:!0}}},repository:{type:"group",required:!1,fields:{indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},standalone:{type:"group",required:!1,fields:{segments:{type:"list",required:!0,items:{type:"string"}},indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},worker:{type:"group",required:!1,fields:{gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}}},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class is{#Ls;#zs;constructor(e,t){this.#Ls=e,this.#zs=t}async build(e){const t=await this.#Ls.read(e),r=this.#zs.validate(t,as);if(!1===r.valid)throw new ns(r);return t}}class os extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const cs=/\${([^}]*)}/g;class us{#$;constructor(e){this.#$=e}async read(e){if(!1===await this.#$.exists(e))return{};const t=await this.#$.read(e);if(!1===t.type.includes("json"))throw new os(e);const r=t.content.toString(),s=this.#js(r);return this.#Hs(s)}#js(e){return e.replace(cs,(e,t)=>process.env[t]??"null")}#Hs(e){return JSON.parse(e)}}class ls{#Ds;#qs;#Vs;constructor(e="./"){const t=new Q(e),r=new us(t),s=new Ur;this.#Ds=new _r,this.#qs=new rs(r,s),this.#Vs=new is(r,s)}configureEnvironment(e=".env"){return this.#Ds.configure(e)}getRuntimeConfiguration(e){return this.#qs.build(e)}getServerConfiguration(e){return this.#Vs.build(e)}}class hs{name="build";description="Builds the application (creates segment bundles).";options=[{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getOptionalArgument("--log-level",void 0),n=this.#Bs(s),a=new ls;await a.configureEnvironment(t);const i=await a.getRuntimeConfiguration(r);return new Gr(i,n).build()}#Bs(e){if(void 0===e)return;return(new B).parse(e)}}const ds="content-type",ms="x-content-type-options",ps="x-jitar-content-type",gs="x-jitar-procedure-version",fs="x-powered-by",ws="nosniff",ys="application/json",vs="application/octet-stream";class bs extends Error{constructor(){super("Invalid worker id")}}class Ss{#T;#Ws;#Cr=new $r;#zs=new Ur;constructor(e,t){this.#T=e,this.#Ws=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#T}/${e}`,r=await this.#Ks(t,{method:"GET"}),s=r.headers.get(ds)??vs,n=await r.arrayBuffer(),a=Buffer.from(n);return new J(e,s,a)}async isHealthy(){const e=`${this.#T}/health/status`,t=await this.#Ks(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#T}/health`,t=await this.#Ks(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#T}/workers`,n={url:e,procedureNames:t,trustKey:r},a={method:"POST",headers:{"Content-Type":ys},body:JSON.stringify(n)},i=await this.#Ks(s,a),o=i.headers.get(ds);if(null===o||!1===o.includes(ys))throw new bs;const c=await i.json();if(!1===this.#zs.validate(c,{id:{type:"string",required:!0}}).valid)throw new bs;return c.id}async reportWorker(e,t){const r=`${this.#T}/workers/${e}/report`,s={state:t},n={method:"POST",headers:{"Content-Type":ys},body:JSON.stringify(s)};await this.#Ks(r,n)}async removeWorker(e){const t=`${this.#T}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":ys}};await this.#Ks(t,r)}async run(e){e.setHeader(ds,ys);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[gs]=s;const n=`${this.#T}/rpc/${e.fqn}`,a={method:"POST",redirect:"manual",headers:r,body:await this.#Gs(t)},i=await this.#Ks(n,a,!1),o=i.status,c=await this.#Us(i),u=this.#_s(i);return new b(o,c,u)}async#Ks(e,t,r=!0){const s=await this.#Ws.execute(e,t);if(r&&this.#Js(s)){const e=await this.#Us(s);throw this.#Cr.fromStatus(s.status,String(e))}return s}#Js(e){return e.status<200||e.status>399}async#Gs(e){return JSON.stringify(e)}async#Us(e){const t=e.headers.get(ps)??e.headers.get(ds);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const r=await e.text();return t?.includes("boolean")?"true"===r:t?.includes("number")?Number(r):r}#_s(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class Ms{async execute(e,t){return fetch(e,t)}}class xs{#Ws;constructor(e=new Ms){this.#Ws=e}build(e){return new Ss(e,this.#Ws)}}const Es={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class As{get url(){throw new m}get state(){return Es.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return Es.AVAILABLE}provide(e){throw new m}}class Ps{get url(){throw new m}get state(){return Es.AVAILABLE}get trustKey(){throw new m}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return Es.AVAILABLE}getProcedureNames(){throw new m}hasProcedure(e){throw new m}run(e){throw new m}}class Is{#Ys=Es.STOPPED;get state(){return this.#Ys}set state(e){this.#Ys=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#Xs(Es.STOPPED)}isStopped(){return this.#Qs(Es.STOPPED)}isAvailable(){return this.#Qs(Es.AVAILABLE)}setStarting(){this.#Ys=Es.STARTING}setAvailable(){this.#Ys=Es.AVAILABLE}setUnavailable(){this.#Ys=Es.UNAVAILABLE}setAvailability(e){return this.#Ys=e?Es.AVAILABLE:Es.UNAVAILABLE,this.#Ys}setStopping(){this.#Ys=Es.STOPPING}setStopped(){this.#Ys=Es.STOPPED}#Qs(...e){return e.includes(this.#Ys)}#Xs(...e){return!1===this.#Qs(...e)}}class Os extends f{constructor(){super("Invalid trust key")}}class Rs{#T;#Zs;#en;#tn;#rn=new Is;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#en=e.healthManager,this.#tn=e.workerManager}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await Promise.all([this.#en.start(),this.#tn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.all([this.#tn.stop(),this.#en.stop()])})}async isHealthy(){return this.#en.isHealthy()}async getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async addWorker(e){if(this.#sn(e.trustKey))throw new Os;return await e.start(),this.#tn.addWorker(e)}getWorker(e){return this.#tn.getWorker(e)}async reportWorker(e,t){return this.#tn.reportWorker(e,t)}async removeWorker(e){return this.#tn.removeWorker(e).stop()}getProcedureNames(){return this.#tn.getProcedureNames()}hasProcedure(e){return this.#tn.hasProcedure(e)}async run(e){return this.#tn.run(e)}#sn(e){return void 0!==this.#Zs&&e!==this.#Zs}}class ks{#T;#nn;#rn=new Is;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}getProcedureNames(){throw new m}hasProcedure(e){throw new m}addWorker(e){return this.#nn.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#nn.reportWorker(e,t)}removeWorker(e){return this.#nn.removeWorker(e)}run(e){return this.#nn.run(e)}}class Ts extends w{#_;constructor(e){super(`No worker available for procedure '${e}'`),this.#_=e}get name(){return this.#_}}class Ns{#an=[];#in=0;get workers(){return this.#an}addWorker(e){this.#an.includes(e)||this.#an.push(e)}removeWorker(e){const t=this.#an.indexOf(e);-1!==t&&this.#an.splice(t,1)}getNextWorker(){const e=this.#an.filter(e=>e.isAvailable());if(0!==e.length)return this.#in>=e.length&&(this.#in=0),e[this.#in++];this.#in=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new Ts(e.fqn);return t.run(e)}}class Cs{generate(){return x.randomUUID()}}class $s extends w{#H;constructor(e){super(`Unknown worker id '${e}'`),this.#H=e}get id(){return this.#H}}class Fs{#an=new Map;#on=new Map;#cn=new Cs;#un;constructor(e,t){this.#un=e.create(()=>this.#ln(),t)}get workers(){return[...this.#an.values()]}get balancers(){return this.#on}start(){this.#un.start()}stop(){this.#un.stop()}getProcedureNames(){const e=this.workers.map(e=>e.getProcedureNames());return[...new Set(e.flat()).values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}addWorker(e){e.id=this.#cn.generate(),this.#an.set(e.id,e);for(const t of e.getProcedureNames()){this.#hn(t).addWorker(e)}return e.id}getWorker(e){const t=this.#an.get(e);if(void 0===t)throw new $s(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#an.delete(e);for(const e of t.getProcedureNames()){const r=this.#dn(e);void 0!==r&&r.removeWorker(t)}return t}#dn(e){return this.#on.get(e)}#hn(e){let t=this.#dn(e);return void 0===t&&(t=new Ns,this.#on.set(e,t)),t}async run(e){const t=this.#dn(e.fqn);if(void 0===t)throw new Or(e.fqn);return t.run(e)}async#ln(){const e=this.workers.map(e=>this.#mn(e));await Promise.allSettled(e)}async#mn(e){await e.updateState()===Es.STOPPED&&this.removeWorker(e.id)}}class Ls{#T;#pn;#gn;#rn=new Is;constructor(e){this.#T=e.url,this.#pn=e.provider,this.#gn=e.runner}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#gn.trustKey}get provider(){return this.#pn}get runner(){return this.#gn}async start(){return this.#rn.start(async()=>{await Promise.all([this.#pn.start(),this.#gn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.allSettled([this.#gn.stop(),this.#pn.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#pn.isHealthy(),this.#gn.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#pn.getHealth(),this.#gn.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#pn.provide(e)}getProcedureNames(){return this.#gn.getProcedureNames()}hasProcedure(e){return this.#gn.hasProcedure(e)}run(e){return this.#gn.run(e)}}class zs{#T;#en;#fn;#wn;#yn;#vn;#rn=new Is;constructor(e){this.#T=e.url,this.#en=e.healthManager,this.#fn=e.sourcingManager,this.#wn=e.assets,this.#yn=e.indexFilename??"index.html",this.#vn=e.serveIndexOnNotFound??false}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#en.start(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#en.stop()})}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async provide(e){if(this.#bn(e))return this.provide(this.#yn);if(!1===this.#wn.has(e))throw new _(e);return this.#fn.read(e)}#bn(e){return""===e||e!==this.#yn&&(this.#vn&&!1===this.#wn.has(e))}}class js{#T;#nn;#rn=new Is;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#nn.provide(e)}}class Hs extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class Ds extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class qs extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Vs extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Bs{#Sn=[];addSerializer(e){e.parent=this,this.#Sn.unshift(e)}async serialize(e){const t=this.#Sn.find(t=>t.canSerialize(e));if(void 0===t)throw new Vs(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Sn.find(t=>t.canDeserialize(e));if(void 0===t)throw new qs(typeof e);return t.deserialize(e)}}class Ws extends Error{constructor(){super("Parent serializer not set")}}class Ks{#Mn;set parent(e){this.#Mn=e}serializeOther(e){if(void 0===this.#Mn)throw new Ws;return this.#Mn.serialize(e)}deserializeOther(e){if(void 0===this.#Mn)throw new Ws;return this.#Mn.deserialize(e)}}class Gs extends Ks{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const r of e)t.push(await this.serializeOther(r));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Us extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class _s extends Ks{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new Us(e.value)}}}class Js extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ys extends Ks{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Js(e.base64)}}}const Xs=new Gt;class Qs extends Ks{#xn;constructor(e){super(),this.#xn=e}canSerialize(e){return e instanceof Object&&Xs.isClassObject(e)}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"class"===t.name&&"string"==typeof t.key&&t.args instanceof Object&&t.args.constructor===Object&&t.fields instanceof Object&&t.fields.constructor===Object}async serialize(e){const t=Xs.getClass(e),r=Xs.fromClass(t,!0),s=this.#En(r),n=this.#xn.resolveKey(t);if(void 0===n)throw new Hs(t.name);return{serialized:!0,key:n,name:"class",args:await this.#An(r,s,e),fields:await this.#Pn(r,s,e)}}#En(e){const t=e.getFunction("constructor");return(t?.parameters??[]).map(e=>e.name)}async#An(e,t,r){const s={};for(const[n,a]of t.entries()){const t=e.canRead(a)?await this.serializeOther(r[a]):void 0;s[n.toString()]=t}return s}async#Pn(e,t,r){const s={};for(const n of e.writable){const a=n.name;t.includes(a)||!1===e.canRead(a)||(s[a]=await this.serializeOther(r[a]))}return s}async deserialize(e){const t=await this.#In(e);if(void 0===t)throw new Hs(e.key);if(t instanceof Function==!1)throw new Ds(e.key);const r=await this.#On(t,e.args),s=Xs.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#On(e,t){const r=Xs.fromClass(e,!0).getFunction("constructor"),s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),n=t[s];return this.deserializeOther(n)});return Promise.all(s)}async#In(e){return globalThis[e.key]??this.#xn.resolveClass(e.key)}}class Zs extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class en extends Ks{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new Zs(e.value);return t}}class tn extends Ks{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class rn extends Ks{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],r=[];for(const[s,n]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(n));return{serialized:!0,name:"Map",entries:{keys:t,values:r}}}async deserialize(e){const t=e.entries.keys,r=e.entries.values,s=new Map;for(let e=0;e<t.length;e++){const n=await this.deserializeOther(t[e]),a=await this.deserializeOther(r[e]);s.set(n,a)}return s}}class sn extends Ks{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.serializeOther(s)}return t}async deserialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.deserializeOther(s)}return t}}class nn extends Ks{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class an extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class on extends Ks{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new an(e.source,e.flags)}}}class cn extends Ks{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const r of e.values())t.push(await this.serializeOther(r));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const un=new Gt;class ln extends Ks{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,r=new DataView(e.buffer),s=[];for(let e=0;e<r.byteLength;e++)s.push(r.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:s}}async deserialize(e){const t=e.type,r=e.bytes,s=new ArrayBuffer(r.length),n=new DataView(s);for(let e=0;e<r.length;e++)n.setUint8(e,r[e]);const a=globalThis[t];return un.createInstance(a,[s])}}class hn extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class dn extends Ks{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new hn(e.value)}}}class mn{static build(e){const t=new Bs;return t.addSerializer(new nn),t.addSerializer(new sn),void 0!==e&&t.addSerializer(new Qs(e)),t.addSerializer(new tn),t.addSerializer(new on),t.addSerializer(new _s),t.addSerializer(new dn),t.addSerializer(new en),t.addSerializer(new cn),t.addSerializer(new rn),t.addSerializer(new Gs),t.addSerializer(new ln),"undefined"!=typeof Buffer&&t.addSerializer(new Ys),t}}class pn{#Rn;constructor(e){this.#Rn=e}resolveKey(e){const t=this.#Rn.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Rn.getClass(e);return t?.implementation}}class gn extends f{constructor(){super("Request not trusted")}}const fn="X-Jitar-Trust-Key",wn="X-Jitar-Data-Encoding",yn="serialized";class vn{#H;#T;#Zs;#kn;#Tn;#Rn;#en;#Nn;#Cn;#rn=new Is;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#kn=e.gateway,this.#Tn=!0===e.registerAtGateway,this.#Rn=e.executionManager,this.#en=e.healthManager;const t=e.scheduleManager;this.#Nn=t.create(()=>this.#$n(),e.reportInterval);const r=new pn(this.#Rn);this.#Cn=mn.build(r)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await Promise.all([this.#Rn.start(),this.#en.start()]),void 0!==this.#kn&&(await this.#kn.start(),this.#Tn&&(this.#H=await this.#kn.addWorker(this),this.#Nn.start())),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{void 0!==this.#kn&&(void 0!==this.#H&&(this.#Nn.stop(),await this.#kn.removeWorker(this.#H)),await this.#kn.stop()),await Promise.all([this.#en.stop(),this.#Rn.stop()])})}getProcedureNames(){return this.#Rn.getProcedureNames()}hasProcedure(e){return this.#Rn.hasProcedure(e)}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async reportState(e){if(void 0!==this.#kn&&void 0!==this.#H)return this.#kn.reportWorker(this.#H,e)}async run(e){return this.#Fn(e)?this.#Ln(e):this.#zn(e)}#Fn(e){return void 0===this.#kn||this.#Rn.hasProcedure(e.fqn)}async#Ln(e){const t=this.#Rn.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#jn(r))throw new Or(e.fqn);if(this.#Hn(e,r))throw new gn;const s=e.getHeader(wn);s===yn&&(e=await this.#Dn(e)),e.removeHeader(wn);const n=await this.#Rn.run(e);return s===yn?this.#qn(n):n}#jn(e){return void 0===e||e.private}#Hn(e,t){if(t.public)return!1;const r=e.getHeader(fn);return this.#Zs!==r}async#zn(e){(e=await this.#Vn(e)).setHeader(wn,yn),void 0!==this.#Zs&&e.setHeader(fn,this.#Zs);const t=await this.#kn.run(e);return this.#Bn(t)}async#Vn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.serialize(s);t.set(r,e)}return new M(e.fqn,e.version,t,e.headers,e.mode)}async#Dn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.deserialize(s);t.set(r,e)}return new M(e.fqn,e.version,t,e.headers,e.mode)}async#qn(e){const t=await this.#Cn.serialize(e.result);return new b(e.status,t,e.headers)}async#Bn(e){const t=await this.#Cn.deserialize(e.result);return new b(e.status,t,e.headers)}async#$n(){const e=await this.updateState();return this.reportState(e)}}class bn extends Is{#Wn;#Kn;#Gn=Date.now();#Un=Date.now();constructor(e=6e3,t=18e3){super(),this.#Wn=e,this.#Kn=t}report(e){this.#Gn=Date.now(),this.state=e}update(){this.#Un=Date.now();const e=this.#Un-this.#Gn;return e>=this.#Wn&&(this.state=e>=this.#Kn?Es.STOPPED:Es.UNAVAILABLE),this.state}}class Sn{#H;#T;#Zs;#_n;#nn;#rn;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#_n=e.procedureNames,this.#nn=e.remote,this.#rn=new bn(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}getProcedureNames(){return[...this.#_n.values()]}hasProcedure(e){return this.#_n.has(e)}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){return this.#rn.update()}async reportState(e){this.#rn.report(e)}run(e){return this.#nn.run(e)}}class Mn{#Jr;#Wn;#Kn;constructor(e,t,r){this.#Jr=e,this.#Wn=t,this.#Kn=r}build(e,t,r){const s=this.#Jr.build(e),n=new Set(t),a=this.#Wn,i=this.#Kn;return new Sn({url:e,trustKey:r,remote:s,procedureNames:n,unavailableThreshold:a,stoppedThreshold:i})}}class xn{#gn;constructor(e){this.#gn=e}async handle(e,t){return this.#gn.run(e)}}class En{#rs=new Lr;constructor(){this.#Jn()}#Jn(){const e=globalThis;e.__run=this.#Yn.bind(this),e.ProcedureNotAccessible=Rr}async#Yn(e,t,r,s){const n=this.#rs.parse(t),a=new Map(Object.entries(r)),i=s instanceof M?s.headers:new Map,o=new M(e,n,a,i,fr),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==yr)throw u.result;return u.result}}const An="starting",Pn="started",In="stopping",On="stopped";class Rn extends w{constructor(){super("Invalid health check")}}class kn{#Ys=On;#Xn=new Map;#kr;#Qn;constructor(e,t=[]){this.#kr=e,this.#Qn=t}get state(){return this.#Ys}async start(){if(this.#Ys===On)try{this.#Ys=An,await this.#Zn(),this.#Ys=Pn}catch(e){throw this.#Ys=On,e}}async stop(){if(this.#Ys===Pn)try{this.#Ys=In,this.clearHealthChecks(),this.#Ys=On}catch(e){throw this.#Ys=Pn,e}}async loadHealthCheck(e){const t=await this.#ea(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new Rn;this.#Xn.set(e.name,e)}clearHealthChecks(){this.#Xn.clear()}async isHealthy(){const e=[];for(const t of this.#Xn.values()){const r=this.#ta(t);e.push(r)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,r]of this.#Xn){const s=this.#ta(r).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(s)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#ra(e,t))).then(()=>t)}async#Zn(){(await Promise.all(this.#Qn.map(e=>this.#ea(e)))).forEach(e=>this.addHealthCheck(e))}async#ea(e){return(await this.#kr.import(e)).default}#ra(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#ta(e){const t=e.isHealthy(),r=e.timeout;if(void 0===r)return t;const s=new Promise(e=>{setTimeout(e,r)}).then(()=>!1);return Promise.race([s,t])}}const Tn="starting",Nn="started",Cn="stopping",$n="stopped";class Fn extends w{constructor(){super("Invalid middleware")}}class Ln{#Ys=$n;#sa=[];#kr;#na;constructor(e,t=[]){this.#kr=e,this.#na=t}get state(){return this.#Ys}async start(){if(this.#Ys===$n)try{this.#Ys=Tn,await this.#aa(),this.#Ys=Nn}catch(e){throw this.#Ys=$n,e}}async stop(){if(this.#Ys===Nn)try{this.#Ys=Cn,this.clearMiddlewares(),this.#Ys=$n}catch(e){throw this.#Ys=Nn,e}}async loadMiddleware(e){const t=await this.#ia(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Fn;this.#sa.push(e)}getMiddleware(e){return this.#sa.find(t=>t instanceof e)}clearMiddlewares(){this.#sa=[]}handle(e){return this.#oa(e,0)()}async#aa(){(await Promise.all(this.#na.map(e=>this.#ia(e)))).forEach(e=>this.addMiddleware(e))}async#ia(e){return(await this.#kr.import(e)).default}#oa(e,t){const r=this.#sa[t];if(void 0===r)return async()=>new b(yr);const s=this.#oa(e,t+1);return async()=>await r.handle(e,s)}}class zn{#ts;#ca;#ua;#la=null;constructor(e,t,r=5e3){this.#ts=e,this.#ca=t,this.#ua=r}start(){this.#ha()}stop(){null!==this.#la&&(clearTimeout(this.#la),this.#la=null)}#ha(){this.#la=setTimeout(async()=>{null!==this.#la&&(await this.#da(),this.#ha())},this.#ua)}async#da(){try{await this.#ca()}catch(e){this.#ts.warn("Scheduled task failed",e)}}}class jn{#ma=[];#ts;constructor(e){this.#ts=e}create(e,t){const r=new zn(this.#ts,e,t);return this.#ma.push(r),r}remove(e){const t=this.#ma.indexOf(e);t<0||this.#ma.splice(t,1)}startAll(){this.#ma.forEach(e=>e.start())}stopAll(){this.#ma.forEach(e=>e.stop())}}const Hn="application/null",Dn="application/undefined",qn="application/boolean",Vn="application/number",Bn="application/json",Wn="text/plain",Kn=200,Gn=400,Un=401,_n=402,Jn=403,Yn=404,Xn=418,Qn=500,Zn=501;class ea extends En{#pa;#ga;#fa;#wa;#ts;#rs=new Lr;constructor(e){super(),this.#pa=e.proxy,this.#ga=e.remoteWorkerBuilder,this.#fa=e.resourceManager,this.#wa=e.middlewareManager,this.#ts=e.logger}get proxy(){return this.#pa}getTrustKey(){return this.#pa.trustKey}async start(){await this.#ya(),this.#ts.info(`Server started at ${this.#pa.url}`),this.#pa.runner instanceof vn&&this.#ts.info("RPC procedures:",this.#pa.runner.getProcedureNames())}async stop(){await this.#va(),this.#ts.info("Server stopped")}async getHealth(){try{const e=await this.#pa.getHealth();return this.#ts.debug("Got health"),this.#ba(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health:",t),this.#Sa(e)}}async isHealthy(){try{const e=await this.#pa.isHealthy();return this.#ts.debug("Got health status"),this.#Ma(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health status:",t),this.#Sa(e)}}async provide(e){try{const t=await this.#pa.provide(e.filename);return this.#ts.info("Provided file:",e.filename),this.#xa(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.warn("Failed to provide file:",t),this.#Sa(e)}}async run(e){try{const t=this.#Ea(e),r=await this.#wa.handle(t);return this.#ts.info("Ran request:",t.fqn),this.#Aa(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed run request:",t),this.#Sa(e)}}async runInternal(e){return this.#pa.run(e)}async addWorker(e){try{const t=this.#Pa(),r=this.#ga.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#ts.info("Added worker:",r.url),this.#Ia({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to add worker:",t),this.#Sa(e)}}async reportWorker(e){try{const t=this.#Oa(e.state),r=this.#Pa();return await r.reportWorker(e.id,t),this.#ts.debug("Reported worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to report worker:",t),this.#Sa(e)}}async removeWorker(e){try{const t=this.#Pa();return await t.removeWorker(e.id),this.#ts.info("Removed worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to remove worker:",t),this.#Sa(e)}}async#ya(){await this.#fa.start(),await Promise.all([this.#pa.start(),this.#wa.start()]);const e=new xn(this.#pa);this.#wa.addMiddleware(e)}async#va(){await Promise.all([this.#wa.stop(),this.#pa.stop()]),await this.#fa.stop()}#Ea(e){const t=this.#Ra(e.fqn),r=this.#ka(e.version),s=this.#Ta(e.args),n=this.#Na(e.headers);return new M(t,r,s,n,e.mode)}#Ra(e){if(0===e.length)throw new o("Missing procedure name");if(e.includes(".."))throw new o("Invalid procedure name");return e}#ka(e){return"string"!=typeof e?y.DEFAULT:this.#rs.parse(e)}#Ta(e){return new Map(Object.entries(e))}#Na(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();t.set(e,n)}return t}#Oa(e){if(!1===Object.values(Es).includes(e))throw new o("Invalid state value");return e}#ba(e){return{result:Object.fromEntries(e),contentType:Bn,headers:{},status:Kn}}#Ma(e){return{result:e,contentType:qn,headers:{},status:Kn}}#xa(e){return{result:e.content,contentType:e.type,headers:{},status:Kn}}#Aa(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Ca(t),headers:this.#$a(e.headers),status:e.status}}#Sa(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Ca(t),headers:{},status:this.#Fa(e)}}#Ia(e){return{result:e,contentType:this.#Ca(e),headers:{},status:Kn}}#Ca(e){if(void 0===e)return Dn;if(null===e)return Hn;switch(typeof e){case"boolean":return qn;case"number":return Vn;case"object":return Bn;default:return Wn}}#$a(e){return Object.fromEntries(e)}#Fa(e){return e instanceof o?Gn:e instanceof u?Jn:e instanceof c?Yn:e instanceof m?Zn:e instanceof p?_n:e instanceof g?Xn:e instanceof f?Un:Qn}#Pa(){const e=this.#pa.runner;if(e instanceof Rs==!1)throw new o("Cannot remove worker from remote gateway");return e}}class ta extends Error{constructor(){super("Unknown service configured")}}class ra{#fn;#La;#za;constructor(e,t=[],r=[]){this.#fn=e,this.#La=t,this.#za=r}async start(){return this.#ja()}async stop(){return this.#Ha()}#ja(){return this.#Da(this.#La)}#Ha(){return this.#Da(this.#za)}async#Da(e){await Promise.all(e.map(e=>this.#fn.import(e)))}}class sa{#fn;#Jr;constructor(e,t){this.#fn=e,this.#Jr=t}async build(e,t){const r=e.setUp,s=e.tearDown,n=e.middleware,a=e.healthChecks,i=new q(t),o=this.#qa(a),c=this.#Va(i),u=await this.#Ba(e,o,c),l=this.#fn,h=this.#Wa(r,s),d=this.#Ka(n),m=this.#Ga(e);return new ea({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:m,logger:i})}#Ba(e,t,r){if(void 0!==e.gateway)return this.#Ua(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#_a(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Ja(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Ya(e.url,e.proxy);if(void 0!==e.standalone)return this.#Xa(e.url,e.standalone,t,r);throw new ta}async#Ua(e,t,r,s){const n=new As,a=this.#Qa(e,t,r,s);return new Ls({url:e,provider:n,runner:a})}async#_a(e,t,r,s){const n=new As,a=this.#Za(e,t,r,s);return new Ls({url:e,provider:n,runner:a})}async#Ja(e,t,r){const s=await this.#ei(e,t,r),n=new Ps;return new Ls({url:e,provider:s,runner:n})}#Qa(e,t,r,s){const n=t.trustKey,a=t.monitorInterval,i=new Fs(s,a);return new Rs({url:e,trustKey:n,healthManager:r,workerManager:i})}#ti(e){const t=this.#Jr.build(e);return new ks({url:e,remote:t})}#Za(e,t,r,s){const n=t.trustKey,a=t.gateway?this.#ti(t.gateway):void 0,i=t.reportInterval,o=void 0!==a,c=this.#ri(t.segments);return new vn({url:e,trustKey:n,reportInterval:i,gateway:a,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#ei(e,t,r){const s=this.#fn,n=await this.#si(t.assets),a=t.indexFilename,i=t.serveIndexOnNotFound;return new zs({url:e,sourcingManager:s,assets:n,indexFilename:a,serveIndexOnNotFound:i,healthManager:r})}#ni(e){const t=this.#Jr.build(e);return new js({url:e,remote:t})}async#Ya(e,t){const r=this.#ni(t.repository),s=this.#ti(t.gateway);return new Ls({url:e,provider:r,runner:s})}async#Xa(e,t,r,s){const n=await this.#ei(e,t,r),a=this.#Za(e,t,r,s);return new Ls({url:e,provider:n,runner:a})}#Wa(e=[],t=[]){const r=e.map(e=>this.#ai(e)),s=t.map(e=>this.#ai(e));return new ra(this.#fn,r,s)}#qa(e=[]){const t=e.map(e=>this.#ai(e));return new kn(this.#fn,t)}#Ka(e=[]){const t=e.map(e=>this.#ai(e));return new Ln(this.#fn,t)}#ri(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new Dr(this.#fn,t)}#Va(e){return new jn(e)}#Ga(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new Mn(this.#Jr,t,r)}async#si(e){if(void 0===e)return new Set;const t=await this.#fn.filter(...e);return new Set(t)}#ai(e){return e.endsWith(".js")?e:e+".js"}}const na="3000",aa=204800,ia=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class oa{#ii;#oi;#ci;#ui;#zs=new Ur;constructor(e,t=na,r=aa){this.#ii=e,this.#oi=t,this.#ci=E(),this.#li(r),this.#hi()}async start(){return await this.#ii.start(),this.#di()}async stop(){return await this.#mi(),this.#ii.stop()}#li(e){this.#ci.use(E.json({limit:e})),this.#ci.use(E.urlencoded({extended:!0})),this.#ci.use(this.#pi.bind(this)),this.#ci.disable(fs)}#hi(){this.#ci.get("/health",(e,t)=>{this.#gi(e,t)}),this.#ci.get("/health/status",(e,t)=>{this.#fi(e,t)}),this.#ci.get("/rpc/*procedure",(e,t)=>{this.#wi(e,t)}),this.#ci.post("/rpc/*procedure",(e,t)=>{this.#yi(e,t)}),this.#ci.options("/rpc/*procedure",(e,t)=>{this.#vi(e,t)}),this.#ci.post("/workers",(e,t)=>{this.#bi(e,t)}),this.#ci.post("/workers/:id/report",(e,t)=>{this.#Si(e,t)}),this.#ci.delete("/workers/:id",(e,t)=>{this.#Mi(e,t)}),this.#ci.use((e,t)=>{this.#xi(e,t)})}#di(){return void 0!==this.#ui?Promise.resolve():new Promise((e,t)=>{this.#ui=this.#ci.listen(this.#oi,t),e()})}#mi(){return void 0===this.#ui?Promise.resolve():new Promise(e=>{this.#ui.close(()=>e())})}#pi(e,t,r){t.setHeader(ms,ws),r()}async#gi(e,t){const r=await this.#ii.getHealth();return this.#Ei(t,r)}async#fi(e,t){const r=await this.#ii.isHealthy();return this.#Ei(t,r)}async#wi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ii(e),a=this.#Oi(e),i=fr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#yi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=fr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#vi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=wr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#bi(e,t){const r=this.#Ri(e),s=this.#zs.validate(r,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.url,a=r.procedureNames,i=r.trustKey;try{const e=await this.#ii.addWorker({url:n,procedureNames:a,trustKey:i});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Si(e,t){const r={id:e.params.id,state:e.body.state},s=this.#zs.validate(r,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.id,a=r.state;try{const e=await this.#ii.reportWorker({id:n,state:a});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Mi(e,t){const r={id:e.params.id},s=this.#zs.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.id;try{const e=await this.#ii.removeWorker({id:n});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#xi(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),n=await this.#ii.provide({filename:s});return this.#Ei(t,n)}#Ai(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#Pi(e){const t=e.headers[gs];return Array.isArray(t)?t[0]:t}#Ii(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#Ri(e){return e.body}#Oi(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();ia.includes(e)||(t[e]=n)}return t}#Ei(e,t){const r=this.#ki(t),s=this.#Ti(t);e.status(r),e.setHeader(ds,s),e.setHeader(ps,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const n=this.#Ni(t);return e.send(n)}#ki(e){return void 0!==e.headers.location?302:e.status}#Ti(e){const t=e.contentType.toLowerCase();switch(t){case qn:case Vn:case Dn:case Hn:return Wn}return t}#Ni(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class ca{name="start";description="Starts a server with the configured service.";options=[{key:"--service",required:!0,description:"Path to the service configuration file"},{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"},{key:"--http-body-limit",required:!1,description:"Maximum HTTP body size in bytes",defaultValue:204800}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getRequiredArgument("--service"),n=e.getOptionalArgument("--log-level",void 0),a=this.#Bs(n),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Ci(i),c=new ls;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#$i(u,l,o,a);return this.#Fi(h)}async#$i(e,t,r,s){const[,,n]=t.url.split(":"),a=new ne(e.target),i=new xs,o=new sa(a,i),c=await o.build(t,s);return new oa(c,n,r)}#Fi(e){let t=!1;return process.on("SIGINT",async()=>{t||(t=!0,e.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),e.start()}#Bs(e){if(void 0===e)return;return(new B).parse(e)}#Ci(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class ua extends Error{constructor(e){super(`Command ${e} not found`)}}class la{#s=new Set;constructor(){this.#s.add(new I(this.#s)),this.#s.add(new O),this.#s.add(new R),this.#s.add(new F),this.#s.add(new hs),this.#s.add(new ca)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new ua(e)}}class ha{#Li;#zi;constructor(){this.#Li=new P(process.argv),this.#zi=new la}start(){const e=this.#Li.getCommand()??"help";return this.#zi.run(e,this.#Li)}}try{const e=new ha;await e.start()}catch(e){const t=new q,r=e instanceof Error?e.message:String(e);t.fatal(r)}
2
+ import e,{promises as t,existsSync as r}from"node:fs";import s from"node:path";import{fileURLToPath as n}from"node:url";import{glob as a}from"glob";import i from"mime-types";import o from"dotenv";import{B as c,N as u,F as l,a as h,A as d,O as m,b as p,P as g,T as f,U as w,S as y,V as v,c as b,R as S,d as M,e as x}from"./Response-DEjrdAZ9.js";import E from"crypto";import A from"express";class P extends Error{constructor(e){super(`Missing argument '${e}'`)}}class I{#e;#t;constructor(e){this.#e=e[2],this.#t=this.#r(e)}getCommand(){return this.#e}containsKey(e){return this.#t.has(e)}getRequiredArgument(e){const t=this.#t.get(e);if(void 0===t)throw new P(e);return t}getOptionalArgument(e,t){return this.#t.get(e)??t}#r(e){const t=e.slice(3),r=new Map;return t.forEach(e=>{const[t,s]=e.split("=");r.set(t.trim(),s?.trim())}),r}}class O{name="help";description="Shows all available commands (this message).";options=[{key:"[command]",required:!1,description:"The command name to show more details for"}];#s;constructor(e){this.#s=e}async execute(e){for(const t of this.#s.values())if(e.containsKey(t.name))return this.#n(t);this.#a()}#a(){console.log("\njitar <command>\n"),console.log("Available commands:");const e=[...this.#s.values()],t=e.map(e=>e.name),r=this.#i(t);for(const t of e){const e=t.name.padEnd(r," "),s=t.description;console.log(` ${e} ${s}`)}console.log("\nFor the options per command, use:"),console.log(" jitar help [command]\n")}#n(e){console.log(`\n${e.description}\n`);const t=e.options;if(0===t.length)return void console.log("No options available.\n");console.log("Options:");const r=t.map(e=>e.key),s=this.#i(r);for(const e of t){const t=e.key.padEnd(s," "),r=e.description,n=e.defaultValue?`default: ${e.defaultValue}`:"no default value",a=e.required?"required":`optional - ${n}`;console.log(` ${t} ${r} (${a})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class R{name="about";description="Shows information about Jitar.";options=[];async execute(e){console.log("\nJitar is a JavaScript Distributed Runtime created and maintained by Masking Technology.\n\nMore information can be found at:\n- https://jitar.dev\n- https://masking.tech\n")}}class k{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class T extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class N extends Error{constructor(e){super(`Unknown template: ${e}`)}}const C=/^[a-zA-Z.\-_]+$/,$={_gitignore:".gitignore","_package.json":"package.json","_tsconfig.json":"tsconfig.json","_vite.config.ts":"vite.config.ts"};class F{#o;#c;constructor(e="./"){this.#o=this.#u(),this.#c=this.#l(e)}async init(e,t){this.#h(e,"project"),this.#h(t,"template");if(!1===await this.#d(t))throw new N(t);await this.#m(e,t),this.#p(e)}#u(){const e=s.dirname(n(import.meta.url));return s.join(e,"templates")}#l(e){return s.resolve(e)}#h(e,t){if(!1===C.test(e))throw new T(e,t)}async#d(e){try{const r=s.join(this.#o,e);return(await t.stat(r)).isDirectory()}catch{return!1}}#m(e,r){const n=s.join(this.#o,r),a=s.join(this.#c,e);return t.cp(n,a,{recursive:!0,force:!0})}async#p(e){const n=s.join(this.#c,e),a=Object.entries($),i=[];for(const[e,o]of a){const a=s.join(n,e),c=s.join(n,o);r(a)&&i.push(t.rename(a,c))}await Promise.all(i)}}class L{name="init";description="Initializes a new Jitar project from a template.";options=[{key:"--name",required:!0,description:"Project name used for creating the project folder"},{key:"--template",required:!0,description:"Template to use [react, vue, backend]"},{key:"--location",required:!1,description:"The root location of the project",defaultValue:"./"}];async execute(e){const t=e.getRequiredArgument("--name"),r=e.getRequiredArgument("--template"),s=e.getOptionalArgument("--location",void 0);this.#g(t,r),await this.#f(t,r,s),this.#w(t)}#g(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#f(e,t,r){return new F(r).init(e,t)}#w(e){console.log(`SUCCESS! Run the following commands to continue:\ncd ${e}\nnpm install\nnpm run build\nnpm run standalone`)}}const j=0,z=1,H=2,D=3,q=4;class V{#y;#v;constructor(e=z,t=console){this.#y=e,this.#v=t}debug(...e){if(this.#y>j)return;const t=this.#b("DEBUG",e);this.#v.debug(t)}info(...e){if(this.#y>z)return;const t=this.#b("INFO",e);this.#v.info(t)}warn(...e){if(this.#y>H)return;const t=this.#b("WARN",e);this.#v.warn(t)}error(...e){if(this.#y>D)return;const t=this.#b("ERROR",e);this.#v.error(t)}fatal(...e){const t=this.#b("FATAL",e);this.#v.error(t)}#b(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#S(e)).join(" ")}`}#S(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#M(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#x(t)}${r}`}#M(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#S(e,t)).join(",\n")}\n${this.#x(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#x(e){return" ".repeat(e)}}class B extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class W{parse(e){switch(e.toUpperCase()){case"DEBUG":return j;case"INFO":return z;case"WARN":return H;case"ERROR":return D;case"FATAL":return q;default:throw new B(e)}}}const K="**/*.js",G="**/*.json",U="**/*.json";class _ extends Error{#E;constructor(e){super(`Invalid location: ${e}`),this.#E=e}get location(){return this.#E}}class J extends Error{#A;constructor(e){super(`The file '${e}' could not be found`),this.#A=e}get filename(){return this.#A}}class Y{#E;#P;#I;constructor(e,t,r){this.#E=e,this.#P=t,this.#I=r}get location(){return this.#E}get type(){return this.#P}get content(){return this.#I}get size(){return this.#I.length}}class X{#E;#O;#R;constructor(e,t){const r=t.resolve(e);this.#E=t.normalize(e),this.#O=t.normalize(r),this.#R=t}getAbsoluteLocation(e){const t=this.#R.isAbsolute(e)?e:this.#R.join(this.#E,e),r=this.#R.resolve(t),s=this.#R.normalize(r);return this.#k(s,e),s}getRelativeLocation(e){const t=this.#R.relative(this.#E,e);return this.#R.normalize(t)}normalizeLocation(e){return this.#R.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#R.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#R.exists(t))throw new J(e);return this.#R.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#R.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#R.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),r=await this.getType(t),s=await this.getContent(t);return new Y(e,r,s)}async write(e,t){const r=this.getAbsoluteLocation(e);return this.#R.write(r,t)}async copy(e,t){const r=this.getAbsoluteLocation(e),s=this.getAbsoluteLocation(t);return this.#R.copy(r,s)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#R.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),r=this.#R.normalize(e);return(await this.#R.filter(t,r)).map(e=>this.#R.normalize(e))}#k(e,t){if(!1===e.startsWith(this.#O))throw new _(t)}}class Q{copy(e,r){return t.cp(e,r,{recursive:!0,force:!0})}delete(e){return t.rm(e,{recursive:!0,force:!0})}async exists(e){try{return await t.stat(e),!0}catch{return!1}}isAbsolute(e){return s.isAbsolute(e)}isDirectory(t){try{return e.statSync(t).isDirectory()}catch{return!1}}filter(e,t){return a(`${e}/${t}`)}join(...e){return s.join(...e)}read(e){return t.readFile(e)}resolve(e){return s.resolve(e)}relative(e,t){return s.relative(e,t)}normalize(e){return e.replaceAll(s.win32.sep,s.posix.sep)}async mimeType(e){const t=i.lookup(e);if(!1!==t)return t}async write(r,n){const a=s.dirname(r);return e.mkdirSync(a,{recursive:!0}),t.writeFile(r,n)}}class Z extends X{constructor(e){super(e,new Q)}}let ee=class extends Error{#T;#N;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#T=e,this.#N=t}get url(){return this.#T}get reason(){return this.#N}};class te{#C;constructor(e){this.#C=e}async import(e){const t=this.#C.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new ee(t,r)}}}class re{#$;constructor(e){this.#$=e}locate(e){return`file://${e.startsWith("/")?this.#$.getAbsoluteLocation(`.${e}`):this.#$.getAbsoluteLocation(e)}`}}class se extends te{constructor(e){super(new re(e))}}class ne{#$;#F;constructor(e,t){this.#$=e,this.#F=t}async filter(...e){return(await Promise.all(e.map(e=>this.#$.filter(e)))).flat().map(e=>this.#$.getRelativeLocation(e))}exists(e){return this.#$.exists(e)}read(e){return this.#$.read(e)}import(e){return this.#F.import(e)}}class ae extends ne{constructor(e){const t=new Z(e);super(t,new se(t))}}let ie=class{#L;#j;#z;constructor(e,t,r){this.#L=e,this.#j=t,this.#z=r}get resources(){return this.#j}get repository(){return this.#L}get segmentation(){return this.#z}};class oe{#j;constructor(e){this.#j=e}isResourceModule(e){return this.#j.includes(e)}}const ce="private",ue="0.0.0",le="index.js",he=".json",de="default",me=/import\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,pe=/export\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,ge="*";let fe=class{#H=0;next(){return"$"+ ++this.#H}};const we="js",ye=/\.js$/,ve=[".","/","http:","https:"];class be{translatePath(e){const t=e.split("/"),r=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":r.pop();continue}r.push(e)}return r.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const r=e.split("/"),s=t.split("/");for(;r[0]===s[0];)r.shift(),s.shift();const n=s.map(()=>"..").join("/");return`${s.length>0?n:"."}/${r.join("/")}`}makePathAbsolute(e,t){const r=""!==t?`${t}/${e}`:e;return this.translatePath(r)}extractPath(e){return e.split("/").slice(0,-1).join("/")}stripPath(e){return e.substring(1,e.length-1)}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${we}`)?e:`${e}.${we}`}addSubExtension(e,t){return e.replace(ye,`.${t}.${we}`)}isApplicationModule(e){return ve.some(t=>e.startsWith(t))}}let Se=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class Me{#D;#q;#V=new be;constructor(e,t){this.#D=e,this.#q=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#B(e)));return new oe(t.flat())}async#B(e){try{const t=await this.#D.getContent(e);return JSON.parse(t.toString()).map(e=>this.#W(e))}catch(t){const r=t instanceof Error?t.message:String(t);throw new Se(e,r)}}#W(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${le}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}}let xe=class{#A;#K;#G;constructor(e,t,r){this.#K=t,this.#A=e,this.#G=r}get filename(){return this.#A}get code(){return this.#K}get model(){return this.#G}};class Ee{#U;constructor(e){this.#U=e}get modules(){return this.#U}get(e){return this.#U.find(t=>t.filename===e)}}class Ae{#_;#J;constructor(e,t){this.#_=e,this.#J=t}get name(){return this.#_}get as(){return this.#J}toString(){return`${this.#_} as ${this.#J}`}}class Pe{#Y;constructor(e){this.#Y=e}get definition(){return this.#Y}toString(){return this.#Y}}class Ie extends Pe{}class Oe{#_;#X;#Q;constructor(e,t=!1,r=!1){this.#_=e,this.#X=t,this.#Q=r}get name(){return this.#_}get isStatic(){return this.#X}get isPrivate(){return this.#Q}get isPublic(){return!1===this.#Q}}class Re extends Oe{#Z;#ee;constructor(e,t,r){super(e),this.#Z=t,this.#ee=r}get parentName(){return this.#Z}get scope(){return this.#ee}get members(){return this.#ee.members}get declarations(){return this.#ee.declarations}get functions(){return this.#ee.functions}get getters(){return this.#ee.getters}get setters(){return this.#ee.setters}get generators(){return this.#ee.generators}get readable(){const e=new Map;return this.getters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get writable(){const e=new Map;return this.setters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get callable(){return this.functions.filter(e=>e.isPublic)}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGetter(e){return this.#ee.getGetter(e)}getSetter(e){return this.#ee.getSetter(e)}getGenerator(e){return this.#ee.getGenerator(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGetter(e){return this.#ee.hasGetter(e)}hasSetter(e){return this.#ee.hasSetter(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}canRead(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasGetter(e)}canWrite(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasSetter(e)}canCall(e){const t=this.getFunction(e);return t?.isPublic??!1}toString(){const e=void 0!==this.#Z?` extends ${this.#Z}`:"";return`class ${this.name}${e} { ${this.#ee.toString()} }`}}class ke extends Oe{#te;#re;constructor(e,t,r=!1,s=!1){super(e.toString(),r,s),this.#te=e,this.#re=t}get identifier(){return this.#te}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class Te{#se;constructor(e){this.#se=e}get members(){return this.#se}toString(){return this.#se.map(e=>e.toString()).join(" , ")}}class Ne extends Te{toString(){return`[ ${super.toString()} ]`}}class Ce extends Te{toString(){return`{ ${super.toString()} }`}}class $e extends Oe{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){const e=this.#ne?` from '${this.#ne}'`:"";return`export { ${this.#se.join(", ")} }${e}`}}class Fe extends Pe{}class Le{#_;#re;constructor(e,t){this.#_=e,this.#re=t}get name(){return this.#_}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class je extends Oe{#ae;#ie;#oe;constructor(e,t,r,s=!1,n=!1,a=!1){super(e,s,a),this.#ae=t,this.#ie=r,this.#oe=n}get parameters(){return this.#ae}get body(){return this.#ie}get isAsync(){return this.#oe}toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}(${e.join(", ")}) { ${this.body} }`}}class ze extends je{toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}*(${e.join(", ")}) { ${this.body} }`}}class He extends je{toString(){return`get ${super.toString()}`}}class De extends Oe{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){return`import { ${this.#se.map(e=>e.toString()).join(", ")} } from '${this.#ne}';`}}class qe{#ee;constructor(e){this.#ee=e}get scope(){return this.#ee}get members(){return this.#ee.members}get exportedMembers(){return this.#ce(this.#ee.members)}get imports(){return this.#ee.imports}get exports(){return this.#ee.exports}get declarations(){return this.#ee.declarations}get exportedDeclarations(){return this.#ce(this.#ee.declarations)}get functions(){return this.#ee.functions}get exportedFunctions(){return this.#ce(this.#ee.functions)}get generators(){return this.#ee.generators}get exportedGenerators(){return this.#ce(this.#ee.generators)}get classes(){return this.#ee.classes}get exportedClasses(){return this.#ce(this.#ee.classes)}get exported(){const e=new Map;for(const t of this.exports)for(const r of t.members){const t=this.getMember(r.name);void 0!==t&&e.set(r.as,t)}return e}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGenerator(e){return this.#ee.getGenerator(e)}getClass(e){return this.#ee.getClass(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}hasClass(e){return this.#ee.hasClass(e)}getImport(e){return this.imports.find(t=>t.hasMember(e))}getImported(e){for(const t of this.imports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}isExported(e){for(const t of this.exports)for(const r of t.members)if(r.name===e.name)return!0;return!1}getExport(e){return this.exports.find(t=>t.hasMember(e))}getExported(e){for(const t of this.exports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}#ce(e){return e.filter(e=>this.isExported(e))}}class Ve extends Pe{}class Be extends je{toString(){return`set ${super.toString()}`}}const We=De.name,Ke=$e.name,Ge=ke.name,Ue=je.name,_e=He.name,Je=Be.name,Ye=ze.name,Xe=Re.name;class Qe{#se;constructor(e){this.#se=e}get members(){return this.#se}get imports(){return this.#se.filter(e=>e.constructor.name===We)}get exports(){return this.#se.filter(e=>e.constructor.name===Ke)}get declarations(){return this.#se.filter(e=>e.constructor.name===Ge)}get functions(){return this.#se.filter(e=>e.constructor.name===Ue)}get getters(){return this.#se.filter(e=>e.constructor.name===_e)}get setters(){return this.#se.filter(e=>e.constructor.name===Je)}get generators(){return this.#se.filter(e=>e.constructor.name===Ye)}get classes(){return this.#se.filter(e=>e.constructor.name===Xe)}getMember(e){return this.#se.find(t=>t.name===e)}getDeclaration(e){return this.declarations.find(t=>t.name===e)}getFunction(e){return this.functions.find(t=>t.name===e)}getGetter(e){return this.getters.find(t=>t.name===e)}getSetter(e){return this.setters.find(t=>t.name===e)}getGenerator(e){return this.generators.find(t=>t.name===e)}getClass(e){return this.classes.find(t=>t.name===e)}hasMember(e){return void 0!==this.getMember(e)}hasDeclaration(e){return void 0!==this.getDeclaration(e)}hasFunction(e){return void 0!==this.getFunction(e)}hasGetter(e){return void 0!==this.getGetter(e)}hasSetter(e){return void 0!==this.getSetter(e)}hasGenerator(e){return void 0!==this.getGenerator(e)}hasClass(e){return void 0!==this.getClass(e)}toString(){return this.#se.map(e=>e.toString()).join("\n")}}const Ze={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},et=Object.values(Ze);const tt=".",rt="(",st=")",nt="[",at="]",it="{",ot="}",ct={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},ut=Object.values(ct);function lt(e){return ut.includes(e)}const ht={UNDEFINED:void 0,NULL:null,STRING:""},dt=Object.values(ht);function mt(e){return dt.includes(e)}const pt={OPEN:rt,CLOSE:st};function gt(e){return e===pt.OPEN||e===pt.CLOSE}const ft={EXPORT:"export",DEFAULT:"default",CLASS:"class",FUNCTION:"function",CONST:"const",LET:"let",VAR:"var",AS:"as",FROM:"from",IMPORT:"import",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",ASYNC:"async",RETURN:"return"},wt=Object.values(ft);function yt(e){return wt.includes(e)}function vt(e){return e===ft.AS||e===ft.ASYNC||e===ft.FROM||e===ft.GET||e===ft.SET}const bt={OPEN:nt,CLOSE:at};function St(e){return e===bt.OPEN||e===bt.CLOSE}const Mt=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xt(e){return Mt.includes(e)}const Et={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_DIVIDE:"/=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_MODULO:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",ASSIGN_XOR:"^=",BITWISE_AND:"&",BITWISE_OR:"|",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",MODULO:"%",MULTIPLY:"*",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",XOR:"^"},At=Object.values(Et);function Pt(e){return At.includes(e)}const It={OPEN:it,CLOSE:ot};function Ot(e){return e===It.OPEN||e===It.CLOSE}const Rt={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},kt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Tt=Object.values(kt);function Nt(e){return Tt.includes(e)}class Ct{#ue;#le;constructor(e){this.#ue=e,this.#le=0}get items(){return this.#ue}get position(){return this.#le}get size(){return this.#ue.length}get eol(){return this.#le>=this.#ue.length}get current(){return this.#ue[this.#le]}get next(){return this.#ue[this.#le+1]}get previous(){return this.#ue[this.#le-1]}notAtEnd(){return!1===this.eol}get(e){return this.#ue[e]}step(e=1){return this.#le+=e,this.current}stepBack(e=1){return this.#le-=e,this.current}hasNext(){return this.#le+1<this.#ue.length}}class $t extends Ct{constructor(e){super(e.split(""))}}class Ft{#P;#re;#he;#de;constructor(e,t,r,s){this.#P=e,this.#re=t,this.#he=r,this.#de=s}get type(){return this.#P}get value(){return this.#re}get start(){return this.#he}get end(){return this.#de}isType(e){return this.#P===e}hasValue(e){return this.#re===e}toString(){return`${this.#re}`}}class Lt extends Ct{}class jt{tokenize(e){const t=new $t(e),r=[];let s;for(;t.notAtEnd();){const e=this.#me(t,s);if(void 0===e)break;e.isType(Rt.WHITESPACE)||e.isType(Rt.COMMENT)?t.step():(r.push(e),this.#pe(e)&&(s=e),t.step())}return new Lt(r)}#pe(e){return!1===[Rt.WHITESPACE,Rt.COMMENT].includes(e.type)}#me(e,t){const r=e.current,s=e.position;if(Nt(r)){const t=e.position;return new Ft(Rt.WHITESPACE,r,s,t)}if(function(e){return et.includes(e)}(r+e.next)){const t=this.#ge(e),r=e.position;return new Ft(Rt.COMMENT,t,s,r)}if(this.#fe(r,t)){const t=this.#we(e),r=e.position;return new Ft(Rt.REGEX,t,s,r)}if(xt(r)){const t=this.#ye(e),r=e.position;return new Ft(Rt.LITERAL,t,s,r)}if(Pt(r)){const t=this.#ve(e),r=e.position;return new Ft(Rt.OPERATOR,t,s,r)}if(lt(r)){const t=e.position;return new Ft(Rt.DIVIDER,r,s,t)}if(gt(r)){const t=e.position;return new Ft(Rt.GROUP,r,s,t)}if(Ot(r)){const t=e.position;return new Ft(Rt.SCOPE,r,s,t)}if(St(r)){const t=e.position;return new Ft(Rt.LIST,r,s,t)}if(mt(r))return;const n=this.#be(e),a=yt(n)?Rt.KEYWORD:Rt.IDENTIFIER,i=e.position;return new Ft(a,n,s,i)}#ge(e){const t=e.current+e.next===Ze.MULTI_START,r=t?Ze.MULTI_END:kt.NEWLINE;let s=t?Ze.MULTI_START:Ze.SINGLE;for(e.step(2);e.notAtEnd();){const n=e.current;if((t?n+e.next:n)===r){e.step(r.length-1);break}s+=n,e.step()}return t?s+Ze.MULTI_END:s.trim()}#fe(e,t){return e===Et.DIVIDE&&(void 0===t||([Rt.OPERATOR,Rt.DIVIDER,Rt.KEYWORD].includes(t.type)||[pt.OPEN,bt.OPEN].includes(t.value)))}#Se(e){return Nt(e)||e==tt||!1===this.#Me(e)}#we(e){let t=e.current,r=!1;for(e.step();e.notAtEnd();){const s=e.current,n=e.previous;if(s===Et.DIVIDE&&"\\"!==n)r=!0;else if(!0===r&&this.#Se(s)){e.stepBack();break}t+=s,e.step()}return t}#ye(e){const t=e.current;let r=t,s=!1;for(e.step();e.notAtEnd();){const n=e.current;if(!1===s){if(n===t){r+=n;break}"\\"===n&&(s=!0)}else s=!1;r+=n,e.step()}return r}#Me(e){return!1===(mt(e)||Nt(e)||Pt(e)||xt(e)||lt(e)||gt(e)||Ot(e)||St(e))}#be(e){let t="";for(;e.notAtEnd();){const r=e.current;if(!1===this.#Me(r)){e.stepBack();break}t+=r,e.step()}return t}#ve(e){let t=e.current;for(e.step();e.notAtEnd();){const r=e.current;if(!1===Pt(r)||!1===Pt(t+r)){e.stepBack();break}t+=r,e.step()}return t}}class zt extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Ht extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Dt extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class qt extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class Vt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const Bt="default",Wt=" ";class Kt{#xe;constructor(e=new jt){this.#xe=e}parse(e){const t=this.#xe.tokenize(e),r=this.#Ee(t);return new qe(r)}parseFirst(e){const t=this.#xe.tokenize(e);return this.#Ae(t)}parseValue(e){const t=this.parseFirst(e);if(t instanceof Pe==!1)throw new qt("a value definition");return t}parseImport(e){const t=this.parseFirst(e);if(t instanceof De==!1)throw new qt("an import definition");return t}parseExport(e){const t=this.parseFirst(e);if(t instanceof $e==!1)throw new qt("an export definition");return t}parseDeclaration(e){const t=this.parseFirst(e);if(t instanceof ke==!1)throw new qt("a declaration definition");return t}parseFunction(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof je==!1)throw new qt("a function definition");return r}parseClass(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof Re==!1)throw new qt("a class definition");return r}#Ee(e){const t=[];for(;e.notAtEnd();){const r=this.#Ae(e);r instanceof Oe&&t.push(r)}return new Qe(t)}#Ae(e,t=!1){const r=e.current;if(r.isType(Rt.LITERAL))return this.#Ie(e);if(r.isType(Rt.IDENTIFIER)){const r=e.next;return r?.hasValue(Et.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.isType(Rt.KEYWORD)){if(vt(r.value)){const t=e.next,s=void 0!==t&&(t.hasValue(ft.FUNCTION)||t.hasValue(pt.OPEN));if(r.hasValue(ft.ASYNC)&&s)return e.step(),this.#Ae(e,!0);if(void 0===t||this.#Re(t))return this.#Ie(e)}return r.hasValue(ft.RETURN)?this.#Ie(e):this.#Pe(e,t)}if(r.isType(Rt.REGEX))return this.#Ie(e);if(r.hasValue(pt.OPEN)){const r=this.#ke(e,pt.OPEN,pt.CLOSE);return r?.hasValue(Et.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.hasValue(It.OPEN))return this.#Te(e);if(r.hasValue(bt.OPEN))return this.#Ne(e);if(r.hasValue(Et.NOT)||r.hasValue(Et.SUBTRACT))return this.#Ie(e);if(!lt(r.value))throw new Vt(r.value,r.start);e.step()}#Pe(e,t=!1){const r=e.current;switch(e.step(),r.value){case ft.IMPORT:return this.#Ce(e);case ft.EXPORT:return this.#$e(e);case ft.CLASS:return this.#Fe(e);case ft.FUNCTION:return this.#Le(e,t);case ft.VAR:case ft.LET:case ft.CONST:return this.#je(e,!1,!0);case ft.ASYNC:return this.#Pe(e,!0);default:throw new Dt(r.value,r.start)}}#Ce(e){const t=[];let r=e.current;if(r.isType(Rt.LITERAL))return new De(t,r.value);if(r.hasValue(pt.OPEN)){r=e.step();const s=r.value;return e.step(2),new De(t,s)}if(!1===r.hasValue(It.OPEN)){const s=r.hasValue(Et.MULTIPLY)?Et.MULTIPLY:Bt;let n=r.value;r=e.step(),r.hasValue(ft.AS)&&(r=e.step(),n=r.value,r=e.step()),t.push(new Ae(s,n))}if(r.hasValue(ct.SEPARATOR)&&(r=e.step()),r.hasValue(It.OPEN)){const s=this.#ze(e);t.push(...s),r=e.current}if(!1===r.hasValue(ft.FROM))throw new zt(ft.FROM,r.start);r=e.step();const s=r.value;return e.step(),new De(t,s)}#$e(e){switch(e.current.value){case ft.DEFAULT:return e.step(),this.#He(e,!0);case It.OPEN:return this.#De(e);default:return this.#He(e,!1)}}#He(e,t){let r=e.current,s=0;var n;r.hasValue(ft.ASYNC)&&(r=e.step(),s++),((n=r.value)===ft.CLASS||n===ft.FUNCTION||n===ft.CONST||n===ft.LET||n===ft.VAR)&&(r=e.step(),s++);const a=this.#Me(r)?r.value:"",i=t?Bt:a;let o;r=e.step(),r?.hasValue(ft.FROM)&&(r=e.step(),o=r.value),s>0&&(s++,e.stepBack(s));const c=new Ae(a,i);return new $e([c],o)}#De(e){const t=this.#ze(e);let r,s=e.current;return s?.hasValue(ft.FROM)&&(s=e.step(),r=s.value),e.step(),new $e(t,r)}#ze(e){const t=[];let r=e.step();for(;e.notAtEnd();){if(r.hasValue(It.CLOSE)){e.step();break}if(r.hasValue(ct.SEPARATOR)){r=e.step();continue}const s=this.#qe(e);t.push(s),r=e.step()}return t}#qe(e){let t=e.current;const r=t.value;let s=r;return e.next.hasValue(ft.AS)&&(t=e.step(2),s=t.value),new Ae(r,s)}#je(e,t,r=!1){let s,n,a=e.current,i=!1;return a.hasValue(bt.OPEN)?(s=this.#Ve(e),a=e.current):a.hasValue(It.OPEN)?(s=this.#Be(e),a=e.current):(i=a.value.startsWith("#"),s=i?a.value.substring(1):a.value,a=e.step()),a.hasValue(Et.ASSIGN)&&(e.step(),n=this.#Ae(e,!1),a=e.current),void 0!==a&&(a.hasValue(ct.TERMINATOR)?e.step():!0===r&&a.hasValue(ct.SEPARATOR)&&(e.step(),this.#je(e,t,!0))),n instanceof ze?new ze(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof je?new je(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof Re?new Re(s.toString(),n.parentName,n.scope):new ke(s,n,t,i)}#Le(e,t,r=!1,s=!1,n=!1){let a=e.current,i="",o=!1,c=!1;a.hasValue(Et.MULTIPLY)&&(o=!0,a=e.step()),this.#Me(a)&&(c=a.value.startsWith("#"),i=c?a.value.substring(1):a.value,a=e.step());const u=this.#We(e,pt.CLOSE);if(a=e.current,!1===a.hasValue(It.OPEN))throw new Ht(It.OPEN,a.start);const l=this.#Ke(e,It.OPEN,It.CLOSE);return o?new ze(i,u,l,r,t,c):s?new He(i,u,l,r,t,c):n?new Be(i,u,l,r,t,c):new je(i,u,l,r,t,c)}#Oe(e,t){let r,s=e.current;if(s.hasValue(pt.OPEN)?(r=this.#We(e,pt.CLOSE),s=e.current):(r=[new Le(s.value,void 0)],s=e.step()),!1===s.hasValue(Et.ARROW))throw new Ht(Et.ARROW,s.start);s=e.step();const n=s.hasValue(It.OPEN)?this.#Ke(e,It.OPEN,It.CLOSE):this.#Ie(e).definition;return new je("",r,n,!1,t,!1)}#We(e,t){const r=[];for(e.step();e.notAtEnd();){const s=e.current;if(s.hasValue(t)){e.step();break}if(s.hasValue(ct.SEPARATOR)){e.step();continue}let n;n=s.hasValue(It.OPEN)?this.#Be(e):s.hasValue(bt.OPEN)?this.#Ve(e):this.#Ge(e),r.push(n)}return r}#Fe(e){let t,r=e.current,s="";if(this.#Me(r)&&(s=r.value,r=e.step()),r.hasValue(ft.EXTENDS)&&(r=e.step(),t=r.value,r=e.step()),!1===r.hasValue(It.OPEN))throw new Ht(It.OPEN,r.start);const n=this.#Ue(e);return new Re(s,t,n)}#Ue(e){let t=e.step();const r=[];for(;e.notAtEnd();){if(t.hasValue(It.CLOSE)){e.step();break}const s=this.#_e(e);r.push(s),t=e.current}return new Qe(r)}#_e(e){let t=e.current,r=!1,s=!1,n=!1,a=!1;for(;e.notAtEnd();){if(t.hasValue(ft.STATIC))s=!0;else if(t.hasValue(ft.ASYNC))r=!0;else if(t.hasValue(ft.GET))n=!0;else{if(!t.hasValue(ft.SET)){if(t.hasValue(Et.MULTIPLY))return this.#Le(e,r,s,!1,!1);break}a=!0}t=e.step()}return e.next.hasValue(pt.OPEN)?this.#Le(e,r,s,n,a):this.#je(e,s)}#Ne(e){const t=this.#Ke(e,bt.OPEN,bt.CLOSE);return new Ie(t)}#Ve(e){const t=this.#We(e,bt.CLOSE);return new Ne(t)}#Te(e){const t=this.#Ke(e,It.OPEN,It.CLOSE);return new Ve(t)}#Be(e){const t=this.#We(e,It.CLOSE);return new Ce(t)}#Ge(e){let t=e.current;const r=t.value;let s;return t=e.step(),t.hasValue(Et.ASSIGN)&&(e.step(),s=this.#Ae(e,!1)),new Le(r,s)}#Ie(e){let t=e.current,r="";for(;e.notAtEnd();){if(t.hasValue(bt.OPEN)){r+=this.#Ke(e,bt.OPEN,bt.CLOSE)+Wt,t=e.current}else if(t.hasValue(pt.OPEN)){r+=this.#Ke(e,pt.OPEN,pt.CLOSE)+Wt,t=e.current}else if(t.hasValue(It.OPEN)){r+=this.#Ke(e,It.OPEN,It.CLOSE)+Wt,t=e.current}else r+=t.toString()+Wt,t=e.step();if(void 0===t||this.#Re(t))break}return new Fe(r.trim())}#Ke(e,t,r){let s=e.step(),n=t+Wt;for(;e.notAtEnd();)if(s.hasValue(t))n+=this.#Ke(e,t,r)+Wt,s=e.current;else{if(s.hasValue(r))return e.step(),n+=r,n;n+=s.toString()+Wt,s=e.step()}return n}#ke(e,t,r){const s=e.position;this.#Ke(e,t,r);const n=e.current,a=e.position;return e.stepBack(a-s),n}#Re(e){return[ct.TERMINATOR,ct.SEPARATOR].includes(e.value)||[bt.CLOSE,pt.CLOSE,It.CLOSE].includes(e.value)||yt(e.value)}#Me(e){return e.isType(Rt.IDENTIFIER)||e.isType(Rt.KEYWORD)&&vt(e.value)}}class Gt{merge(e,t){const r=this.#Je(e.declarations,t.declarations),s=this.#Ye(e.functions,t.functions),n=this.#Ye(e.getters,t.getters),a=this.#Ye(e.setters,t.setters),i=[...r.values(),...s.values(),...n.values(),...a.values()];return new Re(e.name,t.name,new Qe(i))}#Je(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}#Ye(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}}class Ut{#Xe=new Kt;#Qe=new Gt;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,n]of r){if("function"!=typeof n.toString)continue;const r=n.toString();if(r.startsWith("class"))s.push(this.fromClass(n,t));else if(r.startsWith("function"))s.push(this.fromFunction(n));else{const t=new Fe(r);s.push(new ke(e,t))}}return new qe(new Qe(s))}fromClass(e,t=!1){const r=this.isClass(e)?this.#Ze(e):this.#et(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const n=this.fromClass(s,!0);return this.#Qe.merge(r,n)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#Xe.parseFunction(t)}createInstance(e,t=[]){return new e(...t)}getClass(e){return e.constructor}getParentClass(e){return Object.getPrototypeOf(e)}isClassObject(e){return this.isClass(e.constructor)}isFunctionObject(e){return this.isFunction(e.constructor)}isClass(e){return e.toString().startsWith("class")}isFunction(e){return e.toString().startsWith("function")||e.toString().startsWith("async function")}#Ze(e){const t=e.toString();return this.#Xe.parseClass(t)}#et(e){const t=this.createInstance(e),r=this.#tt(e,t),s=new Qe(r);return new Re(e.name,void 0,s)}#tt(e,t){return[...this.#rt(t),...this.#st(e)]}#rt(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],n=void 0!==t?new Pe(String(t)):void 0,a=new ke(e,n);s.push(a)}return s}#st(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],n=s.value;if(n instanceof Function==!1)continue;const a=this.fromFunction(n);void 0!==s.get?r.push(new He(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):void 0!==s.set?r.push(new Be(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):r.push(a)}return r}}let _t=class extends Error{constructor(e,t){super(`Failed to load module file '${e}' because of: ${t}`)}},Jt=class{#q;#Xe=new Kt;#V=new be;constructor(e){this.#q=e}rewrite(e,t){const r=this.#nt(e,t);return this.#at(e,r)}#nt(e,t){return t.replaceAll(me,t=>this.#it(e,t))}#at(e,t){return t.replaceAll(pe,t=>this.#ot(e,t))}#it(e,t){const r=this.#Xe.parseImport(t),s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ot(e,t){const r=this.#Xe.parseExport(t);if(void 0===r.from)return t;const s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ct(e,t){const r=this.#V.extractPath(e),s=this.#V.makePathAbsolute(t,r);return this.#q.isDirectory(s)?`${t}/${le}`:this.#V.assureExtension(t)}},Yt=class{#q;#Xe;#ut;constructor(e,t=new Kt){this.#q=e,this.#Xe=t,this.#ut=new Jt(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new Ee(t)}async read(e){const t=this.#q.getRelativeLocation(e),r=await this.#lt(e),s=this.#ut.rewrite(t,r),n=this.#Xe.parse(s);return new xe(t,s,n)}async#lt(e){try{return(await this.#q.getContent(e)).toString()}catch(t){const r=t instanceof Error?t.message:String(t);throw new _t(e,r)}}};class Xt{#_;#U=new Map;#ht=new Map;#dt=new Map;constructor(e){this.#_=e}get name(){return this.#_}get modules(){return[...this.#U.values()]}get classes(){return[...this.#ht.values()]}get procedures(){return[...this.#dt.values()]}hasModule(e){return this.#U.has(e)}getModule(e){return this.#U.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#U.set(e.filename,e)}hasProcedure(e){return this.#dt.has(e)}getProcedure(e){return this.#dt.get(e)}setProcedure(e){this.#dt.set(e.fqn,e)}setClass(e){this.#ht.set(e.fqn,e)}}class Qt{#H;#mt;#pt;constructor(e,t,r){this.#H=e,this.#mt=t,this.#pt=r}get id(){return this.#H}get importKey(){return this.#mt}get fqn(){return this.#pt}}class Zt extends Qt{#G;constructor(e,t,r,s){super(e,t,r),this.#G=s}get model(){return this.#G}}class er extends Qt{#gt;#ft;#G;constructor(e,t,r,s,n,a){super(e,t,r),this.#gt=s,this.#ft=n,this.#G=a}get access(){return this.#gt}get version(){return this.#ft}get model(){return this.#G}}class tr{#A;#E;#wt;#se=[];#yt;constructor(e,t,r,s){this.#A=e,this.#E=t,this.#wt=r,this.#yt=s}get filename(){return this.#A}get location(){return this.#E}get imports(){return this.#wt}get members(){return this.#se}get segmented(){return this.#yt}hasClasses(){return this.#se.some(e=>e instanceof Zt)}getClasses(){return this.#se.filter(e=>e instanceof Zt)}hasImplementations(){return this.#se.some(e=>e instanceof er)}getImplementations(){return this.#se.filter(e=>e instanceof er)}addMember(e){this.#se.push(e)}addImports(e){const t=Object.keys(e);for(const r of t)this.#wt[r]=e[r]}}class rr{#pt;#vt=[];constructor(e,t=[]){this.#pt=e,this.#vt=t}get fqn(){return this.#pt}get implementations(){return this.#vt}addImplementation(e){this.#vt.push(e)}}class sr{#bt;constructor(e){this.#bt=e}get segments(){return this.#bt}getSegment(e){return this.#bt.find(t=>t.name===e)}isSegmentedModule(e){return this.#bt.some(t=>t.hasModule(e))}getSegments(e){return this.#bt.filter(t=>t.hasModule(e))}}class nr extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class ar extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class ir extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class or extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class cr extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class ur extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class lr{#L;#V=new be;constructor(e){this.#L=e}locate(e,t){const r=[];return{trace:r,model:this.#St(e,t,r)}}#St(e,t,r){r.push({filename:e,importKey:t});const s=this.#Mt(e);return this.#xt(s,t)?this.#Et(s,t,r):this.#At(s,t)}#Mt(e){const t=this.#L.get(e);if(void 0===t)throw new ur(e);return t}#xt(e,t){const r=e.model.getImport(t),s=e.model.getExport(t);return void 0!==r||void 0!==s?.from}#Et(e,t,r){const s=this.#Pt(e,t)??this.#It(e,t),n=s?.from,a=s?.name,i=this.#V.extractPath(e.filename),o=this.#V.stripPath(n),c=this.#V.makePathAbsolute(o,i);return this.#St(c,a,r)}#At(e,t){const r=this.#It(e,t);if(void 0===r)throw new cr(e.filename,t);const s=e.model.getMember(r.name);if(void 0===s)throw new cr(e.filename,r.name);return s}#It(e,t){const r=e.model.getExport(t),s=r?.getMember(t);if(void 0!==s)return{from:r?.from,name:s.name}}#Pt(e,t){const r=e.model.getImport(t),s=r?.getMember(t);if(void 0!==r&&void 0!==s)return{from:r.from,name:s.name}}}class hr{#Ot;#q;#Rt;#V=new be;constructor(e,t,r){this.#Ot=e,this.#q=t,this.#Rt=new lr(r)}async readAll(e){const t=await Promise.all(e.map(e=>this.#kt(e)));return new sr(t)}async#kt(e){const t=await this.#Tt(e),r=this.#Nt(e),s=new Xt(r);return this.#Ct(s,t),this.#$t(s),s}#Nt(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new ar(e);return t.replace(he,"")}async#Tt(e){try{const t=await this.#Ot.getContent(e);return JSON.parse(t.toString())}catch(t){const r=t instanceof Error?t.message:String(t);throw new ir(e,r)}}#Ct(e,t){for(const[r,s]of Object.entries(t))this.#Ft(e,r,s,!0)}#Ft(e,t,r,s){const n=this.#Lt(t),a=this.#V.extractPath(n),i=e.hasModule(n)?e.getModule(n):new tr(n,a,{},s);i.addImports(r),e.setModule(i)}#Lt(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${le}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#$t(e){const t=new fe;for(const r of e.modules)for(const s in r.imports)this.#jt(e,r,s,t)}#jt(e,t,r,s){const{model:n,trace:a}=this.#Rt.locate(t.filename,r),i=this.#zt(t,n,r,s);this.#Ht(e,t,n,i),a.shift();for(const t of a){const r={[t.importKey]:{access:i.access}};this.#Ft(e,t.filename,r,!1)}}#zt(e,t,r,s){const n=e.imports[r],a=s.next(),i=n.as??t.name;return{id:a,importKey:r,name:i,access:n.access??ce,version:n.version??ue,fqn:this.#Dt(e,i,r)}}#Dt(e,t,r){return this.#qt(e)?t:this.#Vt(e)&&this.#Bt(r)?e.location:`${e.location}/${t}`}#qt(e){return""===e.location}#Vt(e){return e.filename.endsWith(le)}#Bt(e){return e===de}#Ht(e,t,r,s){if(r instanceof Re)return this.#Wt(e,t,r,s);if(r instanceof je)return this.#Kt(e,t,r,s);throw new or(t.filename,s.importKey)}#Wt(e,t,r,s){const n=new Zt(s.id,s.importKey,s.fqn,r);t.addMember(n),e.setClass(n)}#Kt(e,t,r,s){if(!1===r.isAsync)throw new nr(t.filename,s.name);const n=new er(s.id,s.importKey,s.fqn,s.access,s.version,r);this.#Gt(e,t,n)}#Gt(e,t,r){const s=e.hasProcedure(r.fqn)?e.getProcedure(r.fqn):new rr(r.fqn);s.addImplementation(r),t.addMember(r),e.setProcedure(s)}}class dr{#Ut;constructor(e){this.#Ut=e}async read(e,t,r){const s=this.#Ut.source,n=this.#Ut.resource,a=this.#Ut.segment,i=new Yt(s),o=await i.readAll(e),c=new Me(n,s),u=await c.readAll(t),l=new hr(a,s,o),h=await l.readAll(r);return new ie(o,u,h)}}class mr{#_t;#j;#z;#Jt;#Xe=new Kt;#V=new be;constructor(e,t,r,s){this.#_t=e,this.#j=t,this.#z=r,this.#Jt=s}get parser(){return this.#Xe}rewrite(e){return e.replaceAll(this.replacementPattern,e=>this.replaceStatement(e))}replaceStatement(e){const t=this.parseStatement(e);return void 0===t.from?e:this.#Yt(t)?this.#Xt(t):this.#Qt(t)}#Xt(e){const t=this.#Zt(e);return this.#j.isResourceModule(t)?this.#er(t,e):this.#tr(t,e)}#Qt(e){const t=this.#rr(e),r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#tr(e,t){if(0===t.members.length)return this.#sr(e,t,[]);const{segmentKeys:r,remoteKeys:s,commonKeys:n}=this.#nr(e,t),a=[];return r.length>0&&a.push(this.#ar(e,t,r)),s.length>0&&a.push(this.#ir(e,t,s)),n.length>0&&a.push(this.#sr(e,t,n)),a.filter(e=>e.length>0).join("\n")}#er(e,t){const r=this.#or(e);return this.excludeFromBundle(t,r)}#ar(e,t,r){const s=this.#or(e,this.#Jt?.name);return this.includeInBundle(t,s,r)}#ir(e,t,r){const s=this.#or(e,"remote");return this.includeInBundle(t,s,r)}#sr(e,t,r){const s=this.#or(e);return this.includeInBundle(t,s,r)}#Yt(e){const t=this.#V.stripPath(e.from);return this.#V.isApplicationModule(t)}#Zt(e){const t=this.#V.stripPath(e.from),r=this.#V.extractPath(this.#_t.filename);return this.#V.makePathAbsolute(t,r)}#nr(e,t){const r=this.#cr(e,this.#Jt),s=this.#ur(e,r),n=this.#lr(t,r),a=this.#lr(t,s);return{segmentKeys:n,remoteKeys:a,commonKeys:this.#hr(t,[...n,...a])}}#cr(e,t){if(void 0===t)return[];const r=t.getModule(e);return void 0!==r?Object.keys(r.imports):[]}#ur(e,t){const r=this.#z.getSegments(e).filter(e=>e!==this.#Jt).map(t=>this.#cr(e,t)).flat();return[...new Set(r)].filter(e=>!1===t.includes(e))}#lr(e,t){return e.members.filter(e=>t.includes(e.name)).map(e=>e.name)}#hr(e,t){return e.members.filter(e=>!1===t.includes(e.name)).map(e=>e.name)}#or(e,t){const r=this.#V.extractPath(this.#_t.filename),s=this.#V.makePathRelative(e,r);return void 0!==t?this.#V.addSubExtension(s,t):s}#rr(e){return this.#V.stripPath(e.from)}}class pr extends mr{get replacementPattern(){return me}parseStatement(e){return this.parser.parseImport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`import "${t}";`;return`import ${this.#dr(e,r)} from "${t}";`}excludeFromBundle(e,t){if(0===e.members.length)return`await import("${t}");`;return`const ${this.#mr(e)} = await import("${t}");`}#dr(e,t){const r=e.members.filter(e=>t.includes(e.name)),s=r.find(e=>e.name===de),n=void 0!==s,a=n?s.as:"",i=r.filter(e=>e.name!==de).map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name),o=i.length>0;return`${a}${n&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#mr(e){if(this.#pr(e))return e.members[0].as;return`{ ${e.members.map(e=>e.name!==e.as?`${e.name} : ${e.as}`:e.name).join(", ")} }`}#pr(e){return 1===e.members.length&&e.members[0].name===ge}}class gr extends mr{get replacementPattern(){return pe}parseStatement(e){return this.parser.parseExport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`export "${t}";`;return`export ${this.#gr(e,r)} from "${t}";`}excludeFromBundle(e,t){const r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#gr(e,t){const r=e.members.filter(e=>t.includes(e.name));if(1===r.length&&""===r[0].name){const e=r[0];return e.name!==e.as?`${ge} as ${e.as}`:ge}return`{ ${r.map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name).join(", ")} }`}}class fr{build(e,t,r,s){const n=new pr(e,t,r,s),a=new gr(e,t,r,s),i=n.rewrite(e.code);return a.rewrite(i)}}const wr="normal",yr="dry",vr=200,br=400,Sr=401,Mr=402,xr=403,Er=404,Ar=418,Pr=500,Ir=501;class Or extends c{#fr;constructor(e){super(`Invalid version number '${e}'`),this.#fr=e}get number(){return this.#fr}}class Rr extends u{#pt;constructor(e){super(`Procedure '${e}' not found`),this.#pt=e}get fqn(){return this.#pt}}class kr extends l{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class Tr extends c{#wr;constructor(e){super(`Unknown parameter ${e}`),this.#wr=e}get parameterName(){return this.#wr}}class Nr extends c{#wr;constructor(e){super(`Missing value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class Cr extends c{#wr;constructor(e){super(`Invalid value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class $r{extract(e,t){const r=this.#yr(e,t),s=[];for(const t of e){const e=this.#vr(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new Tr(e)}return s}#yr(e,t){const r=new Map;for(const[s,n]of t){if(this.#br(s)){const t=this.#Sr(s);!0===this.#Mr(e,t)&&r.set(t,n);continue}r.set(s,n)}return r}#br(e){return e.startsWith("*")}#Sr(e){return e.substring(1)}#Mr(e,t){return void 0!==e.find(e=>e.name===t)}#vr(e,t,r){return e instanceof h?this.#xr(e,t,r):this.#Er(e,t)}#xr(e,t,r){const s=t.get(e.name);if(this.#Ar(e,s,r))throw new Nr(e.name);if(this.#Pr(e,s,r))throw new Cr(e.name);return t.delete(e.name),s}#Er(e,t){return e instanceof d?this.#Ir(e,t):this.#Or(e,t)}#Ir(e,t){const r=this.#Rr(e,t);return void 0!==r?Object.values(r):void 0}#Or(e,t){return this.#Rr(e,t)}#Rr(e,t){const r=e instanceof d,s={},n=[];let a=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#vr(o,t,e);void 0!==u?a=!0:!1===o.isOptional&&n.push(o.name),s[c]=u}if(!0===a&&n.length>0)throw new Nr(n[0]);return a?s:void 0}#Ar(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#Pr(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof d&&t instanceof Array==!1||r instanceof m&&t instanceof Object==!1)}}class Fr{toStatus(e){return e instanceof c?br:e instanceof l?xr:e instanceof u?Er:e instanceof p?Ir:e instanceof g?Mr:e instanceof f?Ar:e instanceof w?Sr:Pr}fromStatus(e,t){switch(e){case br:return new c(t);case xr:return new l(t);case Er:return new u(t);case Ir:return new p(t);case Mr:return new g(t);case Ar:return new f(t);case Sr:return new w(t);default:return new y(t)}}}const Lr=/^\d+(?:\.\d+){0,2}$/;class jr{parse(e){if(0===e.trim().length)return v.DEFAULT;if(!1===Lr.test(e))throw new Or(e);const t=e.split(".");switch(t.length){case 1:return new v(Number.parseInt(t[0]));case 2:return new v(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new v(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class zr extends u{#pt;#ft;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#pt=e,this.#ft=t}get fqn(){return this.#pt}get version(){return this.#ft}}class Hr extends y{constructor(){super("Invalid segment")}}class Dr{#bt=new Map;addSegment(e){this.#bt.set(e.id,e)}clearSegments(){this.#bt.clear()}getClassNames(){const e=new Set;for(const t of this.#bt.values()){t.getClasses().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasClass(e){return this.getClassNames().includes(e)}getClass(e){for(const t of this.#bt.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#bt.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#bt.values()){t.getExposedProcedures().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}getProcedure(e){for(const t of this.#bt.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class qr{#kr;#Tr;#Nr=new $r;#Cr=new Fr;#$r=new Dr;constructor(e,t=[]){this.#kr=e,this.#Tr=t}async start(){return this.#Fr()}async stop(){return this.#Lr()}async loadSegment(e){const t=await this.#kr.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof b==!1)throw new Hr;this.#$r.addSegment(e)}getClassNames(){return this.#$r.getClassNames()}hasClass(e){return this.#$r.hasClass(e)}getClass(e){return this.#$r.getClass(e)}getClassByImplementation(e){return this.#$r.getClassByImplementation(e)}getProcedureNames(){return this.#$r.getProcedureNames()}hasProcedure(e){return this.#$r.hasProcedure(e)}getProcedure(e){return this.#$r.getProcedure(e)}async run(e){const t=this.#jr(e.fqn,e.version),r=this.#Nr.extract(t.parameters,e.args);return e.mode===yr?new S(vr,void 0):this.#zr(e,t,r)}async#Fr(){await Promise.all(this.#Tr.map(e=>this.loadSegment(e)))}#Lr(){this.#$r.clearSegments()}#jr(e,t){const r=this.#$r.getProcedure(e);if(void 0===r)throw new Rr(e);const s=r.getImplementation(t);if(void 0===s)throw new zr(r.fqn,t.toString());return s}async#zr(e,t,r){try{const s=await t.executable.call(e,...r);return new S(vr,s)}catch(e){const t=this.#Cr.toStatus(e);return new S(t,e)}}}class Vr{build(e){let t="";for(const r of e)t+=r.access===M.PRIVATE?this.#Hr(r):this.#Dr(r);return t.trim()}#Hr(e){const t=e.fqn,r=e.version,s=this.#qr(e),n=`throw new ProcedureNotAccessible('${t}', '${r}');`;return this.#Vr(s,n)}#Dr(e){const t=e.fqn,r=e.version,s=this.#Br(e.model.parameters),n=this.#qr(e),a=`return __run('${t}', '${r}', { ${s} }, this);`;return this.#Vr(n,a)}#Wr(e){const t=[];for(const r of e)r instanceof Le?t.push(r.name):(r instanceof Ne||r instanceof Ce)&&t.push(r.toString());return t.join(", ")}#Br(e){return this.#Kr(e).join(", ")}#Kr(e){const t=[];for(const r of e)if(r instanceof Te){const e=this.#Kr(r.members);t.push(...e)}else if(r instanceof Le){const e=this.#Gr(r);t.push(e)}return t}#Gr(e){const t=e.name,r=t.startsWith("...")?t.substring(3):t;return`'${t}': ${r}`}#qr(e){const t=e.model.name,r=this.#Wr(e.model.parameters);return`\nexport ${e.importKey===de?`${de} `:""}async function ${t}(${r})`}#Vr(e,t){return`${e} {\n\t${t}\n}\n`}}let Br=class{#Ur;#_r=new fr;#Jr=new Vr;#V=new be;constructor(e){this.#Ur=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,n=t.modules.map(e=>this.#Yr(e,s,r));await Promise.all(n)}async#Yr(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#Xr(e,t,r);const n=s.map(s=>this.#Qr(e,t,s,r)),a=s[0].getModule(e.filename),i=a?.hasImplementations()?this.#Zr(e,s):Promise.resolve();await Promise.all([...n,i]),this.#Ur.delete(e.filename)}async#Xr(e,t,r){const s=e.filename,n=this.#_r.build(e,t,r);return this.#Ur.write(s,n)}async#Qr(e,t,r,s){const n=this.#V.addSubExtension(e.filename,r.name),a=this.#_r.build(e,t,s,r);return this.#Ur.write(n,a)}async#Zr(e,t){const r=this.#es(e,t),s=this.#V.addSubExtension(e.filename,"remote"),n=this.#Jr.build(r);return this.#Ur.write(s,n)}#es(e,t){const r=t.map(t=>t.getModule(e.filename)).flatMap(e=>e.getImplementations()),s=new Map;for(const e of r){const t=`${e.fqn}:${e.version.toString()}`;s.set(t,e)}return[...s.values()]}};let Wr=class{#Ur;#ts;#V=new be;#rs=new jr;constructor(e,t){this.#Ur=e,this.#ts=t}async build(e){const t=e.segmentation.segments.map(e=>this.#ss(e));await Promise.all(t)}async#ss(e){const t=`${e.name}.segment.js`,r=this.#ns(e);await this.#Ur.write(t,r),this.#ts.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}#ns(e){return`${this.#as(e)}\n${this.#is(e)}`}#as(e){return`import { Segment, Class, Procedure, Implementation, Version, NamedParameter, ArrayParameter, ObjectParameter } from "jitar";\n${this.#os(e)}`}#os(e){const t=[];for(const r of e.getSegmentedModules()){if(0===r.members.length)continue;const s=this.#V.addSubExtension(r.filename,e.name),n=`import ${this.#cs(r)} from "./${s}";`;t.push(n)}return t.join("\n")}#cs(e){const t=e.members,r=t.find(e=>e.importKey===de),s=void 0!==r,n=s?r.id:"",a=t.filter(e=>e.importKey!==de),i=a.map(e=>`${e.importKey} as ${e.id}`),o=a.length>0;return`${n}${s&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#is(e){const t=[];t.push(`export default new Segment("${e.name}")`);for(const r of e.classes)t.push(`\t.addClass(new Class("${r.fqn}", ${r.id}))`);for(const r of e.procedures){t.push(`\t.addProcedure(new Procedure("${r.fqn}")`);for(const e of r.implementations){const r=this.#us(e.version),s=this.#ls(e.model);t.push(`\t\t.addImplementation(new Implementation(${r}, "${e.access}", ${s}, ${e.id}))`)}t.push("\t)")}return t.join("\n")}#us(e){const t=this.#rs.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#ls(e){return`[${this.#hs(e.parameters).join(", ")}]`}#hs(e){const t=[];for(const r of e)t.push(this.#ds(r));return t}#ds(e){return e instanceof Ne?this.#ms(e):e instanceof Ce?this.#ps(e):this.#gs(e)}#gs(e){return`new NamedParameter("${e.name}", ${void 0!==e.value})`}#ms(e){return`new ArrayParameter([${this.#hs(e.members).join(", ")}])`}#ps(e){return`new ObjectParameter([${this.#hs(e.members).join(", ")}])`}};class Kr{#fs;#ws;constructor(e,t){const r=e.target;this.#fs=new Br(r),this.#ws=new Wr(r,t)}async build(e){await Promise.all([this.#fs.build(e),this.#ws.build(e)])}}class Gr{#ys;#vs;#bs;#Jt;constructor(e,t,r,s){this.#ys=e,this.#vs=t,this.#bs=r,this.#Jt=s}get source(){return this.#ys}get target(){return this.#vs}get resource(){return this.#bs}get segment(){return this.#Jt}}class Ur{#ts;#$;#Ss;#Ms;constructor(e,t){this.#ts=new V(t);const r=new Z(e.source),s=new Z(e.target),n=new Z(e.resources),a=new Z(e.segments);this.#$=new Gr(r,s,n,a),this.#Ss=new dr(this.#$),this.#Ms=new Kr(this.#$,this.#ts)}async build(){const e=this.#$.source,t=this.#$.resource,r=this.#$.segment,s=await e.filter(K),n=await t.filter(G),a=await r.filter(U),i=await this.#Ss.read(s,n,a);return this.#Ms.build(i)}}class _r{#xs;constructor(e=!0){this.#xs=e}validate(e,t){const r=[];this.#Es("",e,t,r);return{valid:0===r.length,errors:r}}#Es(e,t,r,s){this.#xs&&this.#As(e,t,r,s),this.#Ps(e,t,r,s)}#As(e,t,r,s){const n=Object.keys(t),a=Object.keys(r);for(const t of n)if(!1===a.includes(t)){const r=this.#Is(e,t);s.push(`Unknown field '${r}'`)}}#Ps(e,t,r,s){const n=Object.keys(r);for(const a of n){const n=this.#Is(e,a),i=r[a],o=t[a];this.#Os(n,o,i,s)}}#Os(e,t,r,s){if(void 0!==t)switch(r.type){case"string":return this.#Rs(e,t,r,s);case"integer":return this.#ks(e,t,r,s);case"real":return this.#Ts(e,t,r,s);case"boolean":return this.#Ns(e,t,r,s);case"url":return this.#Cs(e,t,r,s);case"group":return this.#$s(e,t,r,s);case"list":return this.#Fs(e,t,r,s)}else!0===r.required&&s.push(`Field '${e}' is required`)}#Rs(e,t,r,s){"string"!=typeof t&&s.push(`Field '${e}' is not a string`)}#ks(e,t,r,s){"number"==typeof t&&!1!==Number.isInteger(t)||s.push(`Field '${e}' is not an integer`)}#Ts(e,t,r,s){"number"!=typeof t&&s.push(`Field '${e}' is not a real number`)}#Ns(e,t,r,s){"boolean"!=typeof t&&s.push(`Field '${e}' is not a boolean`)}#Cs(e,t,r,s){"string"==typeof t&&!1!==t.startsWith("http")||s.push(`Field '${e}' is not a valid URL`)}#$s(e,t,r,s){"object"==typeof t?this.#Es(e,t,r.fields,s):s.push(`Field '${e}' is not an object`)}#Fs(e,t,r,s){if(!Array.isArray(t))return void s.push(`Field '${e}' is not a list`);const n=t;for(const t in n){const a=this.#Is(e,t),i=n[t];this.#Os(a,i,r.items,s)}}#Is(e,t){return""===e?t:`${e}.${t}`}}class Jr{async configure(e){o.config({path:e})}}class Yr extends Error{constructor(e){super(`Runtime configuration is invalid:\n${e.errors.join("\n")}`)}}const Xr="./jitar.json",Qr="./src",Zr="./dist",es="./segments",ts="./resources",rs={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1}};let ss=class{#Ls;#js;constructor(e,t){this.#Ls=e,this.#js=t}async build(e=Xr){const t=await this.#Ls.read(e),r=this.#js.validate(t,rs);if(!1===r.valid)throw new Yr(r);return t.source??=Qr,t.target??=Zr,t.segments??=es,t.resources??=ts,t}};const ns="\n => ";class as extends Error{constructor(e){const t=e.errors.join(ns);super(`Invalid server configuration:${ns}${t}`)}}const is={url:{type:"url",required:!0},setUp:{type:"list",required:!1,items:{type:"string"}},tearDown:{type:"list",required:!1,items:{type:"string"}},middleware:{type:"list",required:!1,items:{type:"string"}},healthChecks:{type:"list",required:!1,items:{type:"string"}},gateway:{type:"group",required:!1,fields:{monitorInterval:{type:"integer",required:!1},trustKey:{type:"string",required:!1}}},proxy:{type:"group",required:!1,fields:{gateway:{type:"url",required:!0},repository:{type:"url",required:!0}}},repository:{type:"group",required:!1,fields:{indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},standalone:{type:"group",required:!1,fields:{segments:{type:"list",required:!0,items:{type:"string"}},indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},worker:{type:"group",required:!1,fields:{gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}}},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class os{#Ls;#js;constructor(e,t){this.#Ls=e,this.#js=t}async build(e){const t=await this.#Ls.read(e),r=this.#js.validate(t,is);if(!1===r.valid)throw new as(r);return t}}class cs extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const us=/\${([^}]*)}/g;class ls{#$;constructor(e){this.#$=e}async read(e){if(!1===await this.#$.exists(e))return{};const t=await this.#$.read(e);if(!1===t.type.includes("json"))throw new cs(e);const r=t.content.toString(),s=this.#zs(r);return this.#Hs(s)}#zs(e){return e.replace(us,(e,t)=>process.env[t]??"null")}#Hs(e){return JSON.parse(e)}}class hs{#Ds;#qs;#Vs;constructor(e="./"){const t=new Z(e),r=new ls(t),s=new _r;this.#Ds=new Jr,this.#qs=new ss(r,s),this.#Vs=new os(r,s)}configureEnvironment(e=".env"){return this.#Ds.configure(e)}getRuntimeConfiguration(e){return this.#qs.build(e)}getServerConfiguration(e){return this.#Vs.build(e)}}class ds{name="build";description="Builds the application (creates segment bundles).";options=[{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getOptionalArgument("--log-level",void 0),n=this.#Bs(s),a=new hs;await a.configureEnvironment(t);const i=await a.getRuntimeConfiguration(r);return new Ur(i,n).build()}#Bs(e){if(void 0===e)return;return(new W).parse(e)}}const ms="content-type",ps="x-content-type-options",gs="x-jitar-content-type",fs="x-jitar-procedure-version",ws="x-powered-by",ys="nosniff",vs="application/json",bs="application/octet-stream";class Ss extends Error{constructor(){super("Invalid worker id")}}class Ms{#T;#Ws;#Cr=new Fr;#js=new _r;constructor(e,t){this.#T=e,this.#Ws=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#T}/${e}`,r=await this.#Ks(t,{method:"GET"}),s=r.headers.get(ms)??bs,n=await r.arrayBuffer(),a=Buffer.from(n);return new Y(e,s,a)}async isHealthy(){const e=`${this.#T}/health/status`,t=await this.#Ks(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#T}/health`,t=await this.#Ks(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#T}/workers`,n={url:e,procedureNames:t,trustKey:r},a={method:"POST",headers:{"Content-Type":vs},body:JSON.stringify(n)},i=await this.#Ks(s,a),o=i.headers.get(ms);if(null===o||!1===o.includes(vs))throw new Ss;const c=await i.json();if(!1===this.#js.validate(c,{id:{type:"string",required:!0}}).valid)throw new Ss;return c.id}async reportWorker(e,t){const r=`${this.#T}/workers/${e}/report`,s={state:t},n={method:"POST",headers:{"Content-Type":vs},body:JSON.stringify(s)};await this.#Ks(r,n)}async removeWorker(e){const t=`${this.#T}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":vs}};await this.#Ks(t,r)}async run(e){e.setHeader(ms,vs);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[fs]=s;const n=`${this.#T}/rpc/${e.fqn}`,a={method:"POST",redirect:"manual",headers:r,body:await this.#Gs(t)},i=await this.#Ks(n,a,!1),o=i.status,c=await this.#Us(i),u=this.#_s(i);return new S(o,c,u)}async#Ks(e,t,r=!0){const s=await this.#Ws.execute(e,t);if(r&&this.#Js(s)){const e=await this.#Us(s);throw this.#Cr.fromStatus(s.status,String(e))}return s}#Js(e){return e.status<200||e.status>399}async#Gs(e){return JSON.stringify(e)}async#Us(e){const t=e.headers.get(gs)??e.headers.get(ms);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const r=await e.text();return t?.includes("boolean")?"true"===r:t?.includes("number")?Number(r):r}#_s(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class xs{async execute(e,t){return fetch(e,t)}}class Es{#Ws;constructor(e=new xs){this.#Ws=e}build(e){return new Ms(e,this.#Ws)}}const As={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class Ps{get url(){throw new p}get state(){return As.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return As.AVAILABLE}provide(e){throw new p}}class Is{get url(){throw new p}get state(){return As.AVAILABLE}get trustKey(){throw new p}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return As.AVAILABLE}getProcedureNames(){throw new p}hasProcedure(e){throw new p}run(e){throw new p}}class Os{#Ys=As.STOPPED;get state(){return this.#Ys}set state(e){this.#Ys=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#Xs(As.STOPPED)}isStopped(){return this.#Qs(As.STOPPED)}isAvailable(){return this.#Qs(As.AVAILABLE)}setStarting(){this.#Ys=As.STARTING}setAvailable(){this.#Ys=As.AVAILABLE}setUnavailable(){this.#Ys=As.UNAVAILABLE}setAvailability(e){return this.#Ys=e?As.AVAILABLE:As.UNAVAILABLE,this.#Ys}setStopping(){this.#Ys=As.STOPPING}setStopped(){this.#Ys=As.STOPPED}#Qs(...e){return e.includes(this.#Ys)}#Xs(...e){return!1===this.#Qs(...e)}}class Rs extends w{constructor(){super("Invalid trust key")}}class ks{#T;#Zs;#en;#tn;#rn=new Os;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#en=e.healthManager,this.#tn=e.workerManager}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await Promise.all([this.#en.start(),this.#tn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.all([this.#tn.stop(),this.#en.stop()])})}async isHealthy(){return this.#en.isHealthy()}async getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async addWorker(e){if(this.#sn(e.trustKey))throw new Rs;return await e.start(),this.#tn.addWorker(e)}getWorker(e){return this.#tn.getWorker(e)}async reportWorker(e,t){return this.#tn.reportWorker(e,t)}async removeWorker(e){return this.#tn.removeWorker(e).stop()}getProcedureNames(){return this.#tn.getProcedureNames()}hasProcedure(e){return this.#tn.hasProcedure(e)}async run(e){return this.#tn.run(e)}#sn(e){return void 0!==this.#Zs&&e!==this.#Zs}}class Ts{#T;#nn;#rn=new Os;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}getProcedureNames(){throw new p}hasProcedure(e){throw new p}addWorker(e){return this.#nn.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#nn.reportWorker(e,t)}removeWorker(e){return this.#nn.removeWorker(e)}run(e){return this.#nn.run(e)}}class Ns extends y{#_;constructor(e){super(`No worker available for procedure '${e}'`),this.#_=e}get name(){return this.#_}}class Cs{#an=[];#in=0;get workers(){return this.#an}addWorker(e){this.#an.includes(e)||this.#an.push(e)}removeWorker(e){const t=this.#an.indexOf(e);-1!==t&&this.#an.splice(t,1)}getNextWorker(){const e=this.#an.filter(e=>e.isAvailable());if(0!==e.length)return this.#in>=e.length&&(this.#in=0),e[this.#in++];this.#in=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new Ns(e.fqn);return t.run(e)}}class $s{generate(){return E.randomUUID()}}class Fs extends y{#H;constructor(e){super(`Unknown worker id '${e}'`),this.#H=e}get id(){return this.#H}}class Ls{#an=new Map;#on=new Map;#cn=new $s;#un;constructor(e,t){this.#un=e.create(()=>this.#ln(),t)}get workers(){return[...this.#an.values()]}get balancers(){return this.#on}start(){this.#un.start()}stop(){this.#un.stop()}getProcedureNames(){const e=this.workers.map(e=>e.getProcedureNames());return[...new Set(e.flat()).values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}addWorker(e){e.id=this.#cn.generate(),this.#an.set(e.id,e);for(const t of e.getProcedureNames()){this.#hn(t).addWorker(e)}return e.id}getWorker(e){const t=this.#an.get(e);if(void 0===t)throw new Fs(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#an.delete(e);for(const e of t.getProcedureNames()){const r=this.#dn(e);void 0!==r&&r.removeWorker(t)}return t}#dn(e){return this.#on.get(e)}#hn(e){let t=this.#dn(e);return void 0===t&&(t=new Cs,this.#on.set(e,t)),t}async run(e){const t=this.#dn(e.fqn);if(void 0===t)throw new Rr(e.fqn);return t.run(e)}async#ln(){const e=this.workers.map(e=>this.#mn(e));await Promise.allSettled(e)}async#mn(e){await e.updateState()===As.STOPPED&&this.removeWorker(e.id)}}class js{#T;#pn;#gn;#rn=new Os;constructor(e){this.#T=e.url,this.#pn=e.provider,this.#gn=e.runner}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#gn.trustKey}get provider(){return this.#pn}get runner(){return this.#gn}async start(){return this.#rn.start(async()=>{await Promise.all([this.#pn.start(),this.#gn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.allSettled([this.#gn.stop(),this.#pn.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#pn.isHealthy(),this.#gn.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#pn.getHealth(),this.#gn.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#pn.provide(e)}getProcedureNames(){return this.#gn.getProcedureNames()}hasProcedure(e){return this.#gn.hasProcedure(e)}run(e){return this.#gn.run(e)}}class zs{#T;#en;#fn;#wn;#yn;#vn;#rn=new Os;constructor(e){this.#T=e.url,this.#en=e.healthManager,this.#fn=e.sourcingManager,this.#wn=e.assets,this.#yn=e.indexFilename??"index.html",this.#vn=e.serveIndexOnNotFound??false}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#en.start(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#en.stop()})}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async provide(e){if(this.#bn(e))return this.provide(this.#yn);if(!1===this.#wn.has(e))throw new J(e);return this.#fn.read(e)}#bn(e){return""===e||e!==this.#yn&&(this.#vn&&!1===this.#wn.has(e))}}class Hs{#T;#nn;#rn=new Os;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#nn.provide(e)}}class Ds extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class qs extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class Vs extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Bs extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Ws{#Sn=[];addSerializer(e){e.parent=this,this.#Sn.unshift(e)}async serialize(e){const t=this.#Sn.find(t=>t.canSerialize(e));if(void 0===t)throw new Bs(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Sn.find(t=>t.canDeserialize(e));if(void 0===t)throw new Vs(typeof e);return t.deserialize(e)}}class Ks extends Error{constructor(){super("Parent serializer not set")}}class Gs{#Mn;set parent(e){this.#Mn=e}serializeOther(e){if(void 0===this.#Mn)throw new Ks;return this.#Mn.serialize(e)}deserializeOther(e){if(void 0===this.#Mn)throw new Ks;return this.#Mn.deserialize(e)}}class Us extends Gs{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const r of e)t.push(await this.serializeOther(r));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class _s extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Js extends Gs{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new _s(e.value)}}}class Ys extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Xs extends Gs{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Ys(e.base64)}}}const Qs=new Ut;class Zs extends Gs{#xn;constructor(e){super(),this.#xn=e}canSerialize(e){return e instanceof Object&&Qs.isClassObject(e)}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"class"===t.name&&"string"==typeof t.key&&t.args instanceof Object&&t.args.constructor===Object&&t.fields instanceof Object&&t.fields.constructor===Object}async serialize(e){const t=Qs.getClass(e),r=Qs.fromClass(t,!0),s=this.#En(r),n=this.#xn.resolveKey(t);if(void 0===n)throw new Ds(t.name);return{serialized:!0,key:n,name:"class",args:await this.#An(r,s,e),fields:await this.#Pn(r,s,e)}}#En(e){const t=e.getFunction("constructor");return(t?.parameters??[]).map(e=>e.name)}async#An(e,t,r){const s={};for(const[n,a]of t.entries()){const t=e.canRead(a)?await this.serializeOther(r[a]):void 0;s[n.toString()]=t}return s}async#Pn(e,t,r){const s={};for(const n of e.writable){const a=n.name;t.includes(a)||!1===e.canRead(a)||(s[a]=await this.serializeOther(r[a]))}return s}async deserialize(e){const t=await this.#In(e);if(void 0===t)throw new Ds(e.key);if(t instanceof Function==!1)throw new qs(e.key);const r=await this.#On(t,e.args),s=Qs.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#On(e,t){const r=Qs.fromClass(e,!0).getFunction("constructor"),s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),n=t[s];return this.deserializeOther(n)});return Promise.all(s)}async#In(e){return globalThis[e.key]??this.#xn.resolveClass(e.key)}}class en extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class tn extends Gs{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new en(e.value);return t}}class rn extends Gs{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class sn extends Gs{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],r=[];for(const[s,n]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(n));return{serialized:!0,name:"Map",entries:{keys:t,values:r}}}async deserialize(e){const t=e.entries.keys,r=e.entries.values,s=new Map;for(let e=0;e<t.length;e++){const n=await this.deserializeOther(t[e]),a=await this.deserializeOther(r[e]);s.set(n,a)}return s}}class nn extends Gs{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.serializeOther(s)}return t}async deserialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.deserializeOther(s)}return t}}class an extends Gs{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class on extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class cn extends Gs{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new on(e.source,e.flags)}}}class un extends Gs{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const r of e.values())t.push(await this.serializeOther(r));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const ln=new Ut;class hn extends Gs{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,r=new DataView(e.buffer),s=[];for(let e=0;e<r.byteLength;e++)s.push(r.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:s}}async deserialize(e){const t=e.type,r=e.bytes,s=new ArrayBuffer(r.length),n=new DataView(s);for(let e=0;e<r.length;e++)n.setUint8(e,r[e]);const a=globalThis[t];return ln.createInstance(a,[s])}}class dn extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class mn extends Gs{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new dn(e.value)}}}class pn{static build(e){const t=new Ws;return t.addSerializer(new an),t.addSerializer(new nn),void 0!==e&&t.addSerializer(new Zs(e)),t.addSerializer(new rn),t.addSerializer(new cn),t.addSerializer(new Js),t.addSerializer(new mn),t.addSerializer(new tn),t.addSerializer(new un),t.addSerializer(new sn),t.addSerializer(new Us),t.addSerializer(new hn),"undefined"!=typeof Buffer&&t.addSerializer(new Xs),t}}class gn{#Rn;constructor(e){this.#Rn=e}resolveKey(e){const t=this.#Rn.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Rn.getClass(e);return t?.implementation}}class fn extends w{constructor(){super("Request not trusted")}}const wn="X-Jitar-Trust-Key",yn="X-Jitar-Data-Encoding",vn="serialized";class bn{#H;#T;#Zs;#kn;#Tn;#Rn;#en;#Nn;#Cn;#rn=new Os;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#kn=e.gateway,this.#Tn=!0===e.registerAtGateway,this.#Rn=e.executionManager,this.#en=e.healthManager;const t=e.scheduleManager;this.#Nn=t.create(()=>this.#$n(),e.reportInterval);const r=new gn(this.#Rn);this.#Cn=pn.build(r)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await Promise.all([this.#Rn.start(),this.#en.start()]),void 0!==this.#kn&&(await this.#kn.start(),this.#Tn&&(this.#H=await this.#kn.addWorker(this),this.#Nn.start())),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{void 0!==this.#kn&&(void 0!==this.#H&&(this.#Nn.stop(),await this.#kn.removeWorker(this.#H)),await this.#kn.stop()),await Promise.all([this.#en.stop(),this.#Rn.stop()])})}getProcedureNames(){return this.#Rn.getProcedureNames()}hasProcedure(e){return this.#Rn.hasProcedure(e)}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async reportState(e){if(void 0!==this.#kn&&void 0!==this.#H)return this.#kn.reportWorker(this.#H,e)}async run(e){return this.#Fn(e)?this.#Ln(e):this.#jn(e)}#Fn(e){return void 0===this.#kn||this.#Rn.hasProcedure(e.fqn)}async#Ln(e){const t=this.#Rn.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#zn(r))throw new Rr(e.fqn);if(this.#Hn(e,r))throw new fn;const s=e.getHeader(yn);s===vn&&(e=await this.#Dn(e)),e.removeHeader(yn);const n=await this.#Rn.run(e);return s===vn?this.#qn(n):n}#zn(e){return void 0===e||e.private}#Hn(e,t){if(t.public)return!1;const r=e.getHeader(wn);return this.#Zs!==r}async#jn(e){(e=await this.#Vn(e)).setHeader(yn,vn),void 0!==this.#Zs&&e.setHeader(wn,this.#Zs);const t=await this.#kn.run(e);return this.#Bn(t)}async#Vn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.serialize(s);t.set(r,e)}return new x(e.fqn,e.version,t,e.headers,e.mode)}async#Dn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.deserialize(s);t.set(r,e)}return new x(e.fqn,e.version,t,e.headers,e.mode)}async#qn(e){const t=await this.#Cn.serialize(e.result);return new S(e.status,t,e.headers)}async#Bn(e){const t=await this.#Cn.deserialize(e.result);return new S(e.status,t,e.headers)}async#$n(){const e=await this.updateState();return this.reportState(e)}}class Sn extends Os{#Wn;#Kn;#Gn=Date.now();#Un=Date.now();constructor(e=6e3,t=18e3){super(),this.#Wn=e,this.#Kn=t}report(e){this.#Gn=Date.now(),this.state=e}update(){this.#Un=Date.now();const e=this.#Un-this.#Gn;return e>=this.#Wn&&(this.state=e>=this.#Kn?As.STOPPED:As.UNAVAILABLE),this.state}}class Mn{#H;#T;#Zs;#_n;#nn;#rn;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#_n=e.procedureNames,this.#nn=e.remote,this.#rn=new Sn(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}getProcedureNames(){return[...this.#_n.values()]}hasProcedure(e){return this.#_n.has(e)}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){return this.#rn.update()}async reportState(e){this.#rn.report(e)}run(e){return this.#nn.run(e)}}class xn{#Jr;#Wn;#Kn;constructor(e,t,r){this.#Jr=e,this.#Wn=t,this.#Kn=r}build(e,t,r){const s=this.#Jr.build(e),n=new Set(t),a=this.#Wn,i=this.#Kn;return new Mn({url:e,trustKey:r,remote:s,procedureNames:n,unavailableThreshold:a,stoppedThreshold:i})}}class En{#gn;constructor(e){this.#gn=e}async handle(e,t){return this.#gn.run(e)}}class An{#rs=new jr;constructor(){this.#Jn()}#Jn(){const e=globalThis;e.__run=this.#Yn.bind(this),e.ProcedureNotAccessible=kr}async#Yn(e,t,r,s){const n=this.#rs.parse(t),a=new Map(Object.entries(r)),i=s instanceof x?s.headers:new Map,o=new x(e,n,a,i,wr),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==vr)throw u.result;return u.result}}const Pn="starting",In="started",On="stopping",Rn="stopped";class kn extends y{constructor(){super("Invalid health check")}}class Tn{#Ys=Rn;#Xn=new Map;#kr;#Qn;constructor(e,t=[]){this.#kr=e,this.#Qn=t}get state(){return this.#Ys}async start(){if(this.#Ys===Rn)try{this.#Ys=Pn,await this.#Zn(),this.#Ys=In}catch(e){throw this.#Ys=Rn,e}}async stop(){if(this.#Ys===In)try{this.#Ys=On,this.clearHealthChecks(),this.#Ys=Rn}catch(e){throw this.#Ys=In,e}}async loadHealthCheck(e){const t=await this.#ea(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new kn;this.#Xn.set(e.name,e)}clearHealthChecks(){this.#Xn.clear()}async isHealthy(){const e=[];for(const t of this.#Xn.values()){const r=this.#ta(t);e.push(r)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,r]of this.#Xn){const s=this.#ta(r).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(s)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#ra(e,t))).then(()=>t)}async#Zn(){(await Promise.all(this.#Qn.map(e=>this.#ea(e)))).forEach(e=>this.addHealthCheck(e))}async#ea(e){return(await this.#kr.import(e)).default}#ra(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#ta(e){const t=e.isHealthy(),r=e.timeout;if(void 0===r)return t;const s=new Promise(e=>{setTimeout(e,r)}).then(()=>!1);return Promise.race([s,t])}}const Nn="starting",Cn="started",$n="stopping",Fn="stopped";class Ln extends y{constructor(){super("Invalid middleware")}}class jn{#Ys=Fn;#sa=[];#kr;#na;constructor(e,t=[]){this.#kr=e,this.#na=t}get state(){return this.#Ys}async start(){if(this.#Ys===Fn)try{this.#Ys=Nn,await this.#aa(),this.#Ys=Cn}catch(e){throw this.#Ys=Fn,e}}async stop(){if(this.#Ys===Cn)try{this.#Ys=$n,this.clearMiddlewares(),this.#Ys=Fn}catch(e){throw this.#Ys=Cn,e}}async loadMiddleware(e){const t=await this.#ia(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Ln;this.#sa.push(e)}getMiddleware(e){return this.#sa.find(t=>t instanceof e)}clearMiddlewares(){this.#sa=[]}handle(e){return this.#oa(e,0)()}async#aa(){(await Promise.all(this.#na.map(e=>this.#ia(e)))).forEach(e=>this.addMiddleware(e))}async#ia(e){return(await this.#kr.import(e)).default}#oa(e,t){const r=this.#sa[t];if(void 0===r)return async()=>new S(vr);const s=this.#oa(e,t+1);return async()=>await r.handle(e,s)}}class zn{#ts;#ca;#ua;#la=null;constructor(e,t,r=5e3){this.#ts=e,this.#ca=t,this.#ua=r}start(){this.#ha()}stop(){null!==this.#la&&(clearTimeout(this.#la),this.#la=null)}#ha(){this.#la=setTimeout(async()=>{null!==this.#la&&(await this.#da(),this.#ha())},this.#ua)}async#da(){try{await this.#ca()}catch(e){this.#ts.warn("Scheduled task failed",e)}}}class Hn{#ma=[];#ts;constructor(e){this.#ts=e}create(e,t){const r=new zn(this.#ts,e,t);return this.#ma.push(r),r}remove(e){const t=this.#ma.indexOf(e);t<0||this.#ma.splice(t,1)}startAll(){this.#ma.forEach(e=>e.start())}stopAll(){this.#ma.forEach(e=>e.stop())}}const Dn="application/null",qn="application/undefined",Vn="application/boolean",Bn="application/number",Wn="application/json",Kn="text/plain",Gn=200,Un=400,_n=401,Jn=402,Yn=403,Xn=404,Qn=418,Zn=500,ea=501;class ta extends An{#pa;#ga;#fa;#wa;#ts;#rs=new jr;constructor(e){super(),this.#pa=e.proxy,this.#ga=e.remoteWorkerBuilder,this.#fa=e.resourceManager,this.#wa=e.middlewareManager,this.#ts=e.logger}get proxy(){return this.#pa}getTrustKey(){return this.#pa.trustKey}async start(){await this.#ya(),this.#ts.info(`Server started at ${this.#pa.url}`),this.#pa.runner instanceof bn&&this.#ts.info("RPC procedures:",this.#pa.runner.getProcedureNames())}async stop(){await this.#va(),this.#ts.info("Server stopped")}async getHealth(){try{const e=await this.#pa.getHealth();return this.#ts.debug("Got health"),this.#ba(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health:",t),this.#Sa(e)}}async isHealthy(){try{const e=await this.#pa.isHealthy();return this.#ts.debug("Got health status"),this.#Ma(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health status:",t),this.#Sa(e)}}async provide(e){try{const t=await this.#pa.provide(e.filename);return this.#ts.info("Provided file:",e.filename),this.#xa(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.warn("Failed to provide file:",t),this.#Sa(e)}}async run(e){try{const t=this.#Ea(e),r=await this.#wa.handle(t);return this.#ts.info("Ran request:",t.fqn),this.#Aa(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed run request:",t),this.#Sa(e)}}async runInternal(e){return this.#pa.run(e)}async addWorker(e){try{const t=this.#Pa(),r=this.#ga.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#ts.info("Added worker:",r.url),this.#Ia({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to add worker:",t),this.#Sa(e)}}async reportWorker(e){try{const t=this.#Oa(e.state),r=this.#Pa();return await r.reportWorker(e.id,t),this.#ts.debug("Reported worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to report worker:",t),this.#Sa(e)}}async removeWorker(e){try{const t=this.#Pa();return await t.removeWorker(e.id),this.#ts.info("Removed worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to remove worker:",t),this.#Sa(e)}}async#ya(){await this.#fa.start(),await Promise.all([this.#pa.start(),this.#wa.start()]);const e=new En(this.#pa);this.#wa.addMiddleware(e)}async#va(){await Promise.all([this.#wa.stop(),this.#pa.stop()]),await this.#fa.stop()}#Ea(e){const t=this.#Ra(e.fqn),r=this.#ka(e.version),s=this.#Ta(e.args),n=this.#Na(e.headers);return new x(t,r,s,n,e.mode)}#Ra(e){if(0===e.length)throw new c("Missing procedure name");if(e.includes(".."))throw new c("Invalid procedure name");return e}#ka(e){return"string"!=typeof e?v.DEFAULT:this.#rs.parse(e)}#Ta(e){return new Map(Object.entries(e))}#Na(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();t.set(e,n)}return t}#Oa(e){if(!1===Object.values(As).includes(e))throw new c("Invalid state value");return e}#ba(e){return{result:Object.fromEntries(e),contentType:Wn,headers:{},status:Gn}}#Ma(e){return{result:e,contentType:Vn,headers:{},status:Gn}}#xa(e){return{result:e.content,contentType:e.type,headers:{},status:Gn}}#Aa(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Ca(t),headers:this.#$a(e.headers),status:e.status}}#Sa(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Ca(t),headers:{},status:this.#Fa(e)}}#Ia(e){return{result:e,contentType:this.#Ca(e),headers:{},status:Gn}}#Ca(e){if(void 0===e)return qn;if(null===e)return Dn;switch(typeof e){case"boolean":return Vn;case"number":return Bn;case"object":return Wn;default:return Kn}}#$a(e){return Object.fromEntries(e)}#Fa(e){return e instanceof c?Un:e instanceof l?Yn:e instanceof u?Xn:e instanceof p?ea:e instanceof g?Jn:e instanceof f?Qn:e instanceof w?_n:Zn}#Pa(){const e=this.#pa.runner;if(e instanceof ks==!1)throw new c("Cannot remove worker from remote gateway");return e}}class ra extends Error{constructor(){super("Unknown service configured")}}class sa{#fn;#La;#ja;constructor(e,t=[],r=[]){this.#fn=e,this.#La=t,this.#ja=r}async start(){return this.#za()}async stop(){return this.#Ha()}#za(){return this.#Da(this.#La)}#Ha(){return this.#Da(this.#ja)}async#Da(e){await Promise.all(e.map(e=>this.#fn.import(e)))}}class na{#fn;#Jr;constructor(e,t){this.#fn=e,this.#Jr=t}async build(e,t){const r=e.setUp,s=e.tearDown,n=e.middleware,a=e.healthChecks,i=new V(t),o=this.#qa(a),c=this.#Va(i),u=await this.#Ba(e,o,c),l=this.#fn,h=this.#Wa(r,s),d=this.#Ka(n),m=this.#Ga(e);return new ta({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:m,logger:i})}#Ba(e,t,r){if(void 0!==e.gateway)return this.#Ua(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#_a(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Ja(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Ya(e.url,e.proxy);if(void 0!==e.standalone)return this.#Xa(e.url,e.standalone,t,r);throw new ra}async#Ua(e,t,r,s){const n=new Ps,a=this.#Qa(e,t,r,s);return new js({url:e,provider:n,runner:a})}async#_a(e,t,r,s){const n=new Ps,a=this.#Za(e,t,r,s);return new js({url:e,provider:n,runner:a})}async#Ja(e,t,r){const s=await this.#ei(e,t,r),n=new Is;return new js({url:e,provider:s,runner:n})}#Qa(e,t,r,s){const n=t.trustKey,a=t.monitorInterval,i=new Ls(s,a);return new ks({url:e,trustKey:n,healthManager:r,workerManager:i})}#ti(e){const t=this.#Jr.build(e);return new Ts({url:e,remote:t})}#Za(e,t,r,s){const n=t.trustKey,a=t.gateway?this.#ti(t.gateway):void 0,i=t.reportInterval,o=void 0!==a,c=this.#ri(t.segments);return new bn({url:e,trustKey:n,reportInterval:i,gateway:a,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#ei(e,t,r){const s=this.#fn,n=await this.#si(t.assets),a=t.indexFilename,i=t.serveIndexOnNotFound;return new zs({url:e,sourcingManager:s,assets:n,indexFilename:a,serveIndexOnNotFound:i,healthManager:r})}#ni(e){const t=this.#Jr.build(e);return new Hs({url:e,remote:t})}async#Ya(e,t){const r=this.#ni(t.repository),s=this.#ti(t.gateway);return new js({url:e,provider:r,runner:s})}async#Xa(e,t,r,s){const n=await this.#ei(e,t,r),a=this.#Za(e,t,r,s);return new js({url:e,provider:n,runner:a})}#Wa(e=[],t=[]){const r=e.map(e=>this.#ai(e)),s=t.map(e=>this.#ai(e));return new sa(this.#fn,r,s)}#qa(e=[]){const t=e.map(e=>this.#ai(e));return new Tn(this.#fn,t)}#Ka(e=[]){const t=e.map(e=>this.#ai(e));return new jn(this.#fn,t)}#ri(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new qr(this.#fn,t)}#Va(e){return new Hn(e)}#Ga(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new xn(this.#Jr,t,r)}async#si(e){if(void 0===e)return new Set;const t=await this.#fn.filter(...e);return new Set(t)}#ai(e){return e.endsWith(".js")?e:e+".js"}}const aa="3000",ia=204800,oa=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class ca{#ii;#oi;#ci;#ui;#js=new _r;constructor(e,t=aa,r=ia){this.#ii=e,this.#oi=t,this.#ci=A(),this.#li(r),this.#hi()}async start(){return await this.#ii.start(),this.#di()}async stop(){return await this.#mi(),this.#ii.stop()}#li(e){this.#ci.use(A.json({limit:e})),this.#ci.use(A.urlencoded({extended:!0})),this.#ci.use(this.#pi.bind(this)),this.#ci.disable(ws)}#hi(){this.#ci.get("/health",(e,t)=>{this.#gi(e,t)}),this.#ci.get("/health/status",(e,t)=>{this.#fi(e,t)}),this.#ci.get("/rpc/*procedure",(e,t)=>{this.#wi(e,t)}),this.#ci.post("/rpc/*procedure",(e,t)=>{this.#yi(e,t)}),this.#ci.options("/rpc/*procedure",(e,t)=>{this.#vi(e,t)}),this.#ci.post("/workers",(e,t)=>{this.#bi(e,t)}),this.#ci.post("/workers/:id/report",(e,t)=>{this.#Si(e,t)}),this.#ci.delete("/workers/:id",(e,t)=>{this.#Mi(e,t)}),this.#ci.use((e,t)=>{this.#xi(e,t)})}#di(){return void 0!==this.#ui?Promise.resolve():new Promise((e,t)=>{this.#ui=this.#ci.listen(this.#oi,t),e()})}#mi(){return void 0===this.#ui?Promise.resolve():new Promise(e=>{this.#ui.close(()=>e())})}#pi(e,t,r){t.setHeader(ps,ys),r()}async#gi(e,t){const r=await this.#ii.getHealth();return this.#Ei(t,r)}async#fi(e,t){const r=await this.#ii.isHealthy();return this.#Ei(t,r)}async#wi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ii(e),a=this.#Oi(e),i=wr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#yi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=wr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#vi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=yr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#bi(e,t){const r=this.#Ri(e),s=this.#js.validate(r,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.url,a=r.procedureNames,i=r.trustKey;try{const e=await this.#ii.addWorker({url:n,procedureNames:a,trustKey:i});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Si(e,t){const r={id:e.params.id,state:e.body.state},s=this.#js.validate(r,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.id,a=r.state;try{const e=await this.#ii.reportWorker({id:n,state:a});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Mi(e,t){const r={id:e.params.id},s=this.#js.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.id;try{const e=await this.#ii.removeWorker({id:n});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#xi(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),n=await this.#ii.provide({filename:s});return this.#Ei(t,n)}#Ai(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#Pi(e){const t=e.headers[fs];return Array.isArray(t)?t[0]:t}#Ii(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#Ri(e){return e.body}#Oi(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();oa.includes(e)||(t[e]=n)}return t}#Ei(e,t){const r=this.#ki(t),s=this.#Ti(t);e.status(r),e.setHeader(ms,s),e.setHeader(gs,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const n=this.#Ni(t);return e.send(n)}#ki(e){return void 0!==e.headers.location?302:e.status}#Ti(e){const t=e.contentType.toLowerCase();switch(t){case Vn:case Bn:case qn:case Dn:return Kn}return t}#Ni(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class ua{name="start";description="Starts a server with the configured service.";options=[{key:"--service",required:!0,description:"Path to the service configuration file"},{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"},{key:"--http-body-limit",required:!1,description:"Maximum HTTP body size in bytes",defaultValue:204800}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getRequiredArgument("--service"),n=e.getOptionalArgument("--log-level",void 0),a=this.#Bs(n),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Ci(i),c=new hs;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#$i(u,l,o,a);return this.#Fi(h)}async#$i(e,t,r,s){const[,,n]=t.url.split(":"),a=new ae(e.target),i=new Es,o=new na(a,i),c=await o.build(t,s);return new ca(c,n,r)}#Fi(e){let t=!1;return process.on("SIGINT",async()=>{t||(t=!0,e.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),e.start()}#Bs(e){if(void 0===e)return;return(new W).parse(e)}#Ci(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class la extends Error{constructor(e){super(`Command ${e} not found`)}}class ha{#s=new Set;constructor(){this.#s.add(new O(this.#s)),this.#s.add(new R),this.#s.add(new k),this.#s.add(new L),this.#s.add(new ds),this.#s.add(new ua)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new la(e)}}class da{#Li;#ji;constructor(){this.#Li=new I(process.argv),this.#ji=new ha}start(){const e=this.#Li.getCommand()??"help";return this.#ji.run(e,this.#Li)}}try{const e=new da;await e.start()}catch(e){const t=new V,r=e instanceof Error?e.message:String(e);t.fatal(r)}
package/dist/lib.d.ts CHANGED
@@ -168,14 +168,5 @@ interface HealthCheck {
168
168
  isHealthy(): Promise<boolean>;
169
169
  }
170
170
 
171
- declare class CorsMiddleware implements Middleware {
172
- #private;
173
- constructor(origin?: string, headers?: string);
174
- get allowOrigin(): string;
175
- get allowMethods(): string;
176
- get allowHeaders(): string;
177
- handle(request: Request, next: NextHandler): Promise<Response>;
178
- }
179
-
180
- export { ArrayParameter, BadRequest, Class, CorsMiddleware, Forbidden, Implementation, NamedParameter, NotFound, NotImplemented, ObjectParameter, PaymentRequired, Procedure, Request, Response, Segment, ServerError, Teapot, Unauthorized, Version };
171
+ export { ArrayParameter, BadRequest, Class, Forbidden, Implementation, NamedParameter, NotFound, NotImplemented, ObjectParameter, PaymentRequired, Procedure, Request, Response, Segment, ServerError, Teapot, Unauthorized, Version };
181
172
  export type { HealthCheck, Middleware, NextHandler };
package/dist/lib.js CHANGED
@@ -1 +1 @@
1
- import{V as t,d as s}from"./Response-DEjrdAZ9.js";export{A as ArrayParameter,B as BadRequest,F as Forbidden,a as NamedParameter,N as NotFound,b as NotImplemented,O as ObjectParameter,P as PaymentRequired,e as Request,R as Response,c as Segment,S as ServerError,T as Teapot,U as Unauthorized}from"./Response-DEjrdAZ9.js";class r{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get fqn(){return this.#e}get implementation(){return this.#t}}class n{#e;#s=new Map;#a;constructor(e){this.#e=e}get fqn(){return this.#e}get public(){return[...this.#s.values()].some(e=>e.public)}get protected(){return[...this.#s.values()].some(e=>e.protected)}addImplementation(e){return this.#s.set(e.version,e),this.#r(e)&&(this.#a=e),this}#r(e){return void 0===this.#a||e.version.greater(this.#a.version)}getImplementation(e){const t=this.#n(e);return this.#s.get(t)}#n(e){let s=t.DEFAULT;for(const t of this.#s.keys()){if(t.equals(e))return t;t.greater(e)||s.less(t)&&(s=t)}return s}}class i{#i;#o;#l;#m;constructor(e,t,s,a){this.#i=e,this.#o=t,this.#l=s,this.#m=a}get version(){return this.#i}get public(){return this.#o===s.PUBLIC}get protected(){return this.#o===s.PROTECTED}get private(){return this.#o===s.PRIVATE}get parameters(){return this.#l}get executable(){return this.#m}}class o{#c;#h="GET, POST";#u;constructor(e="*",t="*"){this.#c=e,this.#u=t}get allowOrigin(){return this.#c}get allowMethods(){return this.#h}get allowHeaders(){return this.#u}async handle(e,t){const s=await t();return this.#p(s),s}#p(e){e.setHeader("Access-Control-Allow-Origin",this.#c),e.setHeader("Access-Control-Allow-Methods",this.#h),e.setHeader("Access-Control-Allow-Headers",this.#u)}}export{r as Class,o as CorsMiddleware,i as Implementation,n as Procedure,t as Version};
1
+ import{V as t,d as s}from"./Response-DEjrdAZ9.js";export{A as ArrayParameter,B as BadRequest,F as Forbidden,a as NamedParameter,N as NotFound,b as NotImplemented,O as ObjectParameter,P as PaymentRequired,e as Request,R as Response,c as Segment,S as ServerError,T as Teapot,U as Unauthorized}from"./Response-DEjrdAZ9.js";class r{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get fqn(){return this.#e}get implementation(){return this.#t}}class n{#e;#s=new Map;#a;constructor(e){this.#e=e}get fqn(){return this.#e}get public(){return[...this.#s.values()].some(e=>e.public)}get protected(){return[...this.#s.values()].some(e=>e.protected)}addImplementation(e){return this.#s.set(e.version,e),this.#r(e)&&(this.#a=e),this}#r(e){return void 0===this.#a||e.version.greater(this.#a.version)}getImplementation(e){const t=this.#n(e);return this.#s.get(t)}#n(e){let s=t.DEFAULT;for(const t of this.#s.keys()){if(t.equals(e))return t;t.greater(e)||s.less(t)&&(s=t)}return s}}class i{#i;#o;#m;#l;constructor(e,t,s,a){this.#i=e,this.#o=t,this.#m=s,this.#l=a}get version(){return this.#i}get public(){return this.#o===s.PUBLIC}get protected(){return this.#o===s.PROTECTED}get private(){return this.#o===s.PRIVATE}get parameters(){return this.#m}get executable(){return this.#l}}export{r as Class,i as Implementation,n as Procedure,t as Version};
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "jitar",
3
- "version": "0.10.3",
3
+ "version": "0.10.5",
4
4
  "description": "Distributed runtime for JavaScript and TypeScript to chop monolithic applications into micros.",
5
5
  "author": "Masking Technology <info@masking.tech> (https://jitar.dev)",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
8
  "types": "./dist/lib.d.ts",
9
9
  "sideEffects": true,
10
+ "private": false,
10
11
  "exports": {
11
12
  ".": "./dist/lib.js",
12
13
  "./client": "./dist/client.js"
@@ -30,9 +31,9 @@
30
31
  },
31
32
  "dependencies": {
32
33
  "dotenv": "17.2.3",
33
- "express": "5.1.0",
34
- "glob": "12.0.0",
35
- "mime-types": "3.0.1"
34
+ "express": "5.2.1",
35
+ "glob": "13.0.0",
36
+ "mime-types": "3.0.2"
36
37
  },
37
38
  "devDependencies": {
38
39
  "@jitar/cli": "*",
@@ -43,12 +44,12 @@
43
44
  "@jitar/logging": "*",
44
45
  "@jitar/middleware": "*",
45
46
  "@jitar/runtime": "*",
46
- "@rollup/plugin-node-resolve": "16.0.1",
47
- "@rollup/plugin-replace": "6.0.2",
47
+ "@rollup/plugin-node-resolve": "16.0.3",
48
+ "@rollup/plugin-replace": "6.0.3",
48
49
  "@rollup/plugin-terser": "0.4.4",
49
- "@rollup/plugin-typescript": "12.1.4",
50
- "rollup": "4.52.3",
51
- "rollup-plugin-dts": "6.2.3"
50
+ "@rollup/plugin-typescript": "12.3.0",
51
+ "rollup": "4.54.0",
52
+ "rollup-plugin-dts": "6.3.0"
52
53
  },
53
54
  "engines": {
54
55
  "node": ">=20.0"