jitar 0.11.0 → 0.11.2
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/ConfigurationManager-B7adTVpS.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/client.js +1 -1
- package/dist/lib.d.ts +3 -0
- package/dist/lib.js +1 -1
- package/dist/templates/backend/jitar.json +1 -1
- package/dist/templates/backend/{_package.json → package.json} +4 -3
- package/dist/templates/backend/src/tsconfig.json +8 -0
- package/dist/templates/{react/tsconfig.base.json → backend/tsconfig.json} +4 -11
- package/dist/templates/react/jitar.json +1 -1
- package/dist/templates/react/package.json +28 -0
- package/dist/templates/react/services/standalone.json +1 -0
- package/dist/templates/react/src/{webui → app/components}/App.tsx +3 -3
- package/dist/templates/react/{index.html → src/app/index.html} +1 -1
- package/dist/templates/react/src/app/public/vite.svg +1 -0
- package/dist/templates/react/src/app/tsconfig.json +9 -0
- package/dist/templates/react/src/app/vite.config.ts +25 -0
- package/dist/templates/react/src/tsconfig.json +8 -0
- package/dist/templates/react/tsconfig.json +15 -0
- package/dist/templates/vue/jitar.json +1 -1
- package/dist/templates/vue/package.json +27 -0
- package/dist/templates/vue/services/standalone.json +1 -0
- package/dist/templates/vue/src/{webui → app/components}/App.vue +3 -3
- package/dist/templates/vue/{index.html → src/app/index.html} +1 -1
- package/dist/templates/vue/src/app/public/vite.svg +1 -0
- package/dist/templates/vue/src/app/tsconfig.json +7 -0
- package/dist/templates/vue/src/app/vite.config.ts +25 -0
- package/dist/templates/vue/src/domain/sayHello.js +3 -0
- package/dist/templates/vue/src/tsconfig.json +8 -0
- package/dist/templates/vue/tsconfig.json +15 -0
- package/package.json +1 -1
- package/dist/ConfigurationManager-CYD-3rnJ.js +0 -1
- package/dist/templates/backend/_gitignore +0 -25
- package/dist/templates/backend/_tsconfig.json +0 -20
- package/dist/templates/react/_gitignore +0 -25
- package/dist/templates/react/_package.json +0 -28
- package/dist/templates/react/_tsconfig.json +0 -6
- package/dist/templates/react/_vite.config.ts +0 -14
- package/dist/templates/react/public/vite.svg +0 -1
- package/dist/templates/react/src/vite-env.d.ts +0 -1
- package/dist/templates/react/tsconfig.build.json +0 -11
- package/dist/templates/vue/_gitignore +0 -25
- package/dist/templates/vue/_package.json +0 -26
- package/dist/templates/vue/_tsconfig.json +0 -19
- package/dist/templates/vue/_vite.config.ts +0 -14
- package/dist/templates/vue/public/vite.svg +0 -1
- package/dist/templates/vue/src/vite-env.d.ts +0 -1
- package/dist/templates/vue/tsconfig.build.json +0 -10
- /package/dist/templates/react/src/{webui → app}/assets/jitar.svg +0 -0
- /package/dist/templates/react/src/{webui → app}/assets/react.svg +0 -0
- /package/dist/templates/react/src/{webui → app/components}/App.css +0 -0
- /package/dist/templates/react/src/{webui → app/components}/index.css +0 -0
- /package/dist/templates/react/src/{webui → app/components}/main.tsx +0 -0
- /package/dist/templates/vue/src/{webui → app}/assets/jitar.svg +0 -0
- /package/dist/templates/vue/src/{webui → app}/assets/vue.svg +0 -0
- /package/dist/templates/vue/src/{webui → app/components}/main.ts +0 -0
- /package/dist/templates/vue/src/{webui → app/components}/style.css +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e,{promises as t}from"node:fs";import s from"node:path";import{glob as r}from"glob";import i from"mime-types";import n from"dotenv";const o={MODULE_PATTERN:"**/*.js",RESOURCE_PATTERN:"**/*.json",SEGMENT_PATTERN:"**/*.json"};class a extends Error{#e;constructor(e){super(`Invalid location: ${e}`),this.#e=e}get location(){return this.#e}}class c extends Error{#t;constructor(e){super(`The file '${e}' could not be found`),this.#t=e}get filename(){return this.#t}}class u{#e;#s;#r;constructor(e,t,s){this.#e=e,this.#s=t,this.#r=s}get location(){return this.#e}get type(){return this.#s}get content(){return this.#r}get size(){return this.#r.length}}class l{#e;#i;#n;constructor(e,t){const s=t.resolve(e);this.#e=t.normalize(e),this.#i=t.normalize(s),this.#n=t}getAbsoluteLocation(e){const t=this.#n.isAbsolute(e)?e:this.#n.join(this.#e,e),s=this.#n.resolve(t),r=this.#n.normalize(s);return this.#o(r,e),r}getRelativeLocation(e){const t=this.#n.relative(this.#e,e);return this.#n.normalize(t)}normalizeLocation(e){return this.#n.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#n.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#n.exists(t))throw new c(e);return this.#n.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#n.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#n.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new u(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#n.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#n.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#n.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#n.normalize(e);return(await this.#n.filter(t,s)).map(e=>this.#n.normalize(e))}async filterWithIgnores(e,t){const s=await this.filter(e),r=t.map(e=>this.filter(e)),i=await Promise.all(r),n=new Set(i.flat());return s.filter(e=>!1===n.has(e))}#o(e,t){if(!1===e.startsWith(this.#i))throw new a(t)}}class h{copy(e,s){return t.cp(e,s,{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 r(`${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,i){const n=s.dirname(r);return e.mkdirSync(n,{recursive:!0}),t.writeFile(r,i)}}class p extends l{constructor(e){super(e,new h)}}class d{#a;#c;#u;constructor(e,t,s){this.#a=e,this.#c=t,this.#u=s}get resources(){return this.#c}get repository(){return this.#a}get segmentation(){return this.#u}}class m{#c;constructor(e){this.#c=e}isResourceModule(e){return this.#c.includes(e)}}const f="private",g="0.0.0",E="index.js",y=".json",w="default";class S{#l=0;next(){return"$"+ ++this.#l}}const b="js",A=/\.js$/,T=[".","/","http:","https:"];class I{translatePath(e){const t=e.split("/"),s=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":s.pop();continue}s.push(e)}return s.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const s=e.split("/"),r=t.split("/");for(;s[0]===r[0];)s.shift(),r.shift();const i=r.map(()=>"..").join("/");return`${r.length>0?i:"."}/${s.join("/")}`}makePathAbsolute(e,t,s="/"){const r=""!==t?`${t}/${e}`:e;return`${s}${this.translatePath(r)}`}extractPath(e){return e.split("/").slice(0,-1).join("/")}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${b}`)?e:`${e}.${b}`}addSubExtension(e,t){return e.replace(A,`.${t}.${b}`)}isApplicationModule(e){return T.some(t=>e.startsWith(t))}}let v=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class O{#h;#p;#d=new I;constructor(e,t){this.#h=e,this.#p=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#m(e)));return new m(t.flat())}async#m(e){try{const t=await this.#h.getContent(e);return JSON.parse(t.toString()).map(e=>this.#f(e))}catch(t){const s=t instanceof Error?t.message:String(t);throw new v(e,s)}}#f(e){const t=this.#p.normalizeLocation(e),s=this.#p.isDirectory(t)?`${t}/${E}`:this.#d.assureExtension(t);return s.startsWith("./")?s.substring(2):s.startsWith("/")?s.substring(1):s}}let N=class{#t;#g;constructor(e,t){this.#t=e,this.#g=t}get filename(){return this.#t}get model(){return this.#g}};class R{#E;constructor(e){this.#E=e}get modules(){return this.#E}get(e){return this.#E.find(t=>t.filename===e)}}class x{}class M extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new M(e)}toString(){return`[${this.elements.map(e=>e.toString()).join(",")}]`}}class C{}class $ extends C{identifier;constructor(e){super(),this.identifier=e}is(e){return this.identifier===e}}class L extends ${parameters;body;isAsync;constructor(e,t,s,r=!1){super(e),this.parameters=t,this.body=s,this.isAsync=r}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new L(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier?` ${this.identifier}`:"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function${t}(${s.join(",")})${r}`}}class P extends L{constructor(e,t,s=!1){super(void 0,e,t,s)}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new P(e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.parameters.map(e=>e.toString()),s=this.body.toString();return`${e}(${t.join(", ")})=>${s}`}}class F{binding;initializer;constructor(e,t){this.binding=e,this.initializer=t}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new F(e,t)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class V extends C{code;constructor(e){super(),this.code=e}clone(){return new V(this.code)}toString(){return this.code}}class D{identifier;visibility;location;constructor(e,t,s){this.identifier=e,this.visibility=t,this.location=s}is(e){return this.identifier===e}}class k extends D{parameters;body;constructor(e,t){super("constructor","public","instance"),this.parameters=e,this.body=t}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new k(e,t)}toString(){const e=this.parameters.map(e=>e.toString()),t=this.body.toString();return`${this.identifier}(${e.join(",")}) ${t}`}}class B extends D{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new B(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.body.toString();return`${e}get ${t}${this.identifier}()${s}`}}class j extends D{parameter;body;constructor(e,t,s,r,i){super(e,t,s),this.parameter=r,this.body=i}clone(){const e=this.parameter.clone(),t=this.body.clone();return new j(this.identifier,this.visibility,this.location,e,t)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.parameter.toString(),r=this.body.toString();return`${e}set ${t}${this.identifier}(${s})${r}`}}class q extends D{parameters;body;isAsync;constructor(e,t,s,r,i,n=!1){super(e,t,s),this.parameters=r,this.body=i,this.isAsync=n}clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new q(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=this.isAsync?"async ":"",r=this.parameters.map(e=>e.toString()),i=this.body.toString();return`${e}${s}${t}${this.identifier}(${r.join(",")})${i}`}}class U extends D{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new U(this.identifier,this.visibility,this.location,e)}toString(){const e="static"===this.location?"static ":"",t="private"===this.visibility?"#":"",s=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:";";return`${e}${t}${this.identifier}${s}`}}class G extends ${parent;members;constructor(e,t,s){super(e),this.parent=t,this.members=s}get construct(){return this.members.find(e=>e instanceof k)}get fields(){return this.members.filter(e=>e instanceof U)}get getters(){return this.members.filter(e=>e instanceof B)}get setters(){return this.members.filter(e=>e instanceof j)}get methods(){return this.members.filter(e=>e instanceof q)}get publicFields(){return this.fields.filter(e=>"public"===e.visibility)}get publicGetters(){return this.getters.filter(e=>"public"===e.visibility)}get publicSetters(){return this.setters.filter(e=>"public"===e.visibility)}get publicMethods(){return this.methods.filter(e=>"public"===e.visibility)}get readable(){return[...this.publicFields,...this.publicGetters]}get writable(){return[...this.publicFields,...this.publicSetters]}getMember(e){return this.members.find(t=>t.is(e))}hasMember(e){return this.members.some(t=>t.is(e))}getField(e){return this.fields.find(t=>t.is(e))}hasField(e){return this.fields.some(t=>t.is(e))}getGetter(e){return this.getters.find(t=>t.is(e))}hasGetter(e){return this.getters.some(t=>t.is(e))}getSetter(e){return this.setters.find(t=>t.is(e))}hasSetter(e){return this.setters.some(t=>t.is(e))}getMethod(e){return this.methods.find(t=>t.is(e))}hasMethod(e){return this.methods.some(t=>t.is(e))}canRead(e){return this.readable.some(t=>t.is(e))}canWrite(e){return this.writable.some(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new G(this.identifier,this.parent,e)}toString(){return`class ${this.identifier??""}${void 0!==this.parent?` extends ${this.parent}`:""}{${this.members.map(e=>e.toString()).join("")}}`}}class H extends C{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new H(e,this.from)}toString(){const e=this.members.map(e=>e.toString()),t=this.from?` from '${this.from}'`:"";return`export {${e.join(",")}}${t};`}}class K extends C{code;constructor(e){super(),this.code=e}clone(){return new K(this.code)}toString(e=!0){const t=!1===e||this.code.endsWith("}")?"":";";return`${this.code}${t}`}}class _ extends L{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new _(this.identifier,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier??"",s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}function* ${t}(${s.join(",")})${r}`}}class W extends q{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new W(this.identifier,this.visibility,this.location,e,t,this.isAsync)}toString(){const e=this.isAsync?"async ":"",t=this.identifier,s=this.parameters.map(e=>e.toString()),r=this.body.toString();return`${e}*${t}(${s.join(",")})${r}`}}class z extends x{identifier;isRest;constructor(e,t=!1){super(),this.identifier=e,this.isRest=t}clone(){return new z(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class Y extends C{members;from;constructor(e,t){super(),this.members=e,this.from=t}hasMember(e){return this.members.some(t=>t.is(e))}getMember(e){return this.members.find(t=>t.is(e))}clone(){const e=this.members.map(e=>e.clone());return new Y(e,this.from)}toString(){if(0===this.members.length)return`import '${this.from}';`;return`import {${this.members.map(e=>e.toString()).join(",")}} from '${this.from}';`}}class X extends ${type;binding;initializer;constructor(e,t,s){super(t.toString()),this.type=e,this.binding=t,this.initializer=s}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new X(this.type,e,t)}toString(){const e=void 0!==this.initializer?`=${this.initializer.toString(!0)}`:"",t=e.endsWith(";")?"":";";return`${this.type} ${this.identifier}${e}${t}`}}class Q{statements;constructor(e){this.statements=e}get exports(){return this.statements.filter(e=>e instanceof H)}get imports(){return this.statements.filter(e=>e instanceof Y)}get expressions(){return this.statements.filter(e=>e instanceof K)}get declarations(){return this.statements.filter(e=>e instanceof $)}get variables(){return this.statements.filter(e=>e instanceof X)}get functions(){return this.statements.filter(e=>e instanceof L)}get classes(){return this.statements.filter(e=>e instanceof G)}get exported(){const e=[];for(const t of this.exports)for(const s of t.members){const t=this.getDeclaration(s.identifier);void 0!==t&&e.push(t)}return e}get exportedVariables(){return this.exported.filter(e=>e instanceof X)}get exportedFunctions(){return this.exported.filter(e=>e instanceof L)}get exportedClasses(){return this.exported.filter(e=>e instanceof G)}getExport(e){return this.exports.find(t=>t.hasMember(e))}getImport(e){return this.imports.find(t=>t.hasMember(e))}hasDeclaration(e){return this.declarations.some(t=>t.is(e))}getDeclaration(e){return this.declarations.find(t=>t.is(e))}hasVariable(e){return this.variables.some(t=>t.is(e))}getVariable(e){return this.variables.find(t=>t.is(e))}hasFunction(e){return this.functions.some(t=>t.is(e))}getFunction(e){return this.functions.find(t=>t.is(e))}hasClass(e){return this.classes.some(t=>t.is(e))}getClass(e){return this.classes.find(t=>t.is(e))}clone(){const e=this.statements.map(e=>e.clone());return new Q(e)}toString(){return this.statements.map(e=>e.toString(!0)).join("\n")}}class J{identifier;alias;constructor(e,t){this.identifier=e,this.alias=t}is(e){return this.alias===e||void 0===this.alias&&this.identifier===e}clone(){return new J(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class Z extends x{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Z(e)}toString(){return`{${this.elements.map(e=>e.toString()).join(",")}}`}}const ee={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},te=Object.values(ee);const se=".",re="(",ie=")",ne="[",oe="]",ae="{",ce="}",ue="_",le={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},he=Object.values(le);function pe(e){return he.includes(e)}const de={UNDEFINED:void 0,NULL:null,STRING:""},me=["null","undefined"],fe=Object.values(de);function ge(e){return fe.includes(e)}const Ee={OPEN:re,CLOSE:ie};function ye(e){return e===Ee.OPEN||e===Ee.CLOSE}const we={IMPORT:"import",EXPORT:"export",AS:"as",FROM:"from",DEFAULT:"default",ASYNC:"async",AWAIT:"await",USING:"using",CONST:"const",LET:"let",VAR:"var",FUNCTION:"function",RETURN:"return",YIELD:"yield",CLASS:"class",CONSTRUCTOR:"constructor",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",NEW:"new",THIS:"this",DO:"do",WHILE:"while",FOR:"for",OF:"of",IN:"in",BREAK:"break",CONTINUE:"continue",IF:"if",ELSE:"else",SWITCH:"switch",CASE:"case",THROW:"throw",TRY:"try",CATCH:"catch",FINALLY:"finally"},Se=Object.values(we),be=[we.IMPORT,we.EXPORT,we.VAR,we.LET,we.CONST,we.FUNCTION,we.CLASS,we.ASYNC],Ae=[we.VAR,we.LET,we.CONST,we.FUNCTION,we.CLASS,we.USING],Te=[we.AS,we.ASYNC,we.GET,we.SET,we.OF,we.YIELD,we.FROM,we.STATIC];function Ie(e){return be.includes(e)}function ve(e){return Te.includes(e)}const Oe={OPEN:ne,CLOSE:oe};function Ne(e){return e===Oe.OPEN||e===Oe.CLOSE}const Re=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xe(e){return Re.includes(e)}const Me={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_BITWISE_XOR:"^=",ASSIGN_DIVIDE:"/=",ASSIGN_EXPONENTIAL:"**=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_REMAINDER:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_NULLISH:"??=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",BITWISE_AND:"&",BITWISE_OR:"|",BITWISE_NOT:"~",BITWISE_XOR:"^",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",EXPONENTIAL:"**",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",REMAINDER:"%",MULTIPLY:"*",NULLISH:"??",CHAINING:".",OPTIONAL_CHAINING:"?.",SPREAD:"...",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",$BRIDGE_CHAINING_SPREAD:".."},Ce=Object.values(Me);function $e(e){return Ce.includes(e)}const Le={OPEN:ae,CLOSE:ce};function Pe(e){return e===Le.OPEN||e===Le.CLOSE}const Fe={BOOLEAN:"boolean",COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",NOTHING:"nothing",NUMBER:"number",OPERATOR:"operator",INDICATOR:"indicator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace",NONE:"none"},Ve={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},De=Object.values(Ve);function ke(e){return De.includes(e)}class Be{#y;#w;constructor(e){this.#y=e,this.#w=0}get items(){return this.#y}get position(){return this.#w}get size(){return this.#y.length}get eol(){return this.#w>=this.#y.length}get current(){return this.#y[this.#w]}get next(){return this.#y[this.#w+1]}get previous(){return this.#y[this.#w-1]}notAtEnd(){return!1===this.eol}get(e){return this.#y[e]}step(e=1){return this.#w+=e,this.current}stepBack(e=1){return this.#w-=e,this.current}hasNext(){return this.#w+1<this.#y.length}insert(...e){this.#y.splice(this.#w,0,...e)}}class je extends Be{constructor(e){super(e.split(""))}}class qe{#s;#S;#b;#A;constructor(e,t,s,r){this.#s=e,this.#S=t,this.#b=s,this.#A=r}get type(){return this.#s}get value(){return this.#S}get start(){return this.#b}get end(){return this.#A}isType(e){return this.#s===e}hasValue(e){return this.#S===e}toString(){return`${this.#S}`}}class Ue extends Be{}const Ge=["true","false"];const He=["0","1","2","3","4","5","6","7","8","9"],Ke=[...He,"a","b","c","d","e","f","A","B","C","D","E","F"],_e=["0","1"];function We(e){return He.includes(e)}const ze={GENERATOR:"*",PRIVATE:"#"},Ye=Object.values(ze);class Xe{tokenize(e){const t=new je(e),s=[];let r;for(;t.notAtEnd();){const e=this.#T(t,r);if(void 0===e)break;e.isType(Fe.WHITESPACE)||e.isType(Fe.COMMENT)?t.step():(s.push(e),this.#I(e)&&(r=e),t.step())}return new Ue(s)}#I(e){return!1===[Fe.WHITESPACE,Fe.COMMENT].includes(e.type)}#T(e,t){const s=e.current,r=e.position;if(ke(s)){const t=e.position;return new qe(Fe.WHITESPACE,s,r,t)}if(function(e){return te.includes(e)}(s+e.next)){const t=this.#v(e),s=e.position;return new qe(Fe.COMMENT,t,r,s)}if(this.#O(s,t)){const t=this.#N(e),s=e.position;return new qe(Fe.REGEX,t,r,s)}if(this.#R(e,t)){const t=this.#x(e),s=e.position;return new qe(Fe.NUMBER,t,r,s)}if(xe(s)){const t=this.#M(e),s=e.position;return new qe(Fe.LITERAL,t,r,s)}if($e(s)){const t=this.#C(e),s=e.position;return new qe(Fe.OPERATOR,t,r,s)}if(function(e){return Ye.includes(e)}(s)){const t=this.#C(e),s=e.position;return new qe(Fe.INDICATOR,t,r,s)}if(pe(s)){const t=e.position;return new qe(Fe.DIVIDER,s,r,t)}if(ye(s)){const t=e.position;return new qe(Fe.GROUP,s,r,t)}if(Pe(s)){const t=e.position;return new qe(Fe.SCOPE,s,r,t)}if(Ne(s)){const t=e.position;return new qe(Fe.LIST,s,r,t)}if(ge(s))return;const i=this.#$(e),n=e.position;return function(e){return Se.includes(e)}(i)?new qe(Fe.KEYWORD,i,r,n):function(e){return Ge.includes(e)}(i)?new qe(Fe.BOOLEAN,i,r,n):function(e){return me.includes(e)}(i)?new qe(Fe.NOTHING,i,r,n):new qe(Fe.IDENTIFIER,i,r,n)}#v(e){const t=e.current+e.next===ee.MULTI_START,s=t?ee.MULTI_END:Ve.NEWLINE;let r=t?ee.MULTI_START:ee.SINGLE;for(e.step(2);e.notAtEnd();){const i=e.current;if((t?i+e.next:i)===s){e.step(s.length-1);break}r+=i,e.step()}return t?r+ee.MULTI_END:r.trim()}#O(e,t){return e===Me.DIVIDE&&(void 0===t||([Fe.OPERATOR,Fe.DIVIDER,Fe.KEYWORD].includes(t.type)||[Ee.OPEN,Oe.OPEN].includes(t.value)))}#L(e){return ke(e)||e==se||!1===this.#P(e)}#N(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Me.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#L(r)){e.stepBack();break}t+=r,e.step()}return t}#R(e,t){const s=e.current,r=e.next;return!!We(s)||s===Me.SUBTRACT&&(!t?.isType(Fe.NUMBER)&&We(r))}#F(e,t,s){return t?!1===(r=e,Ke.includes(r))&&e!==ue:s?!1===function(e){return _e.includes(e)}(e)&&e!==ue:!1===We(e)&&e!==se&&e!==ue&&"e"!==e;var r}#x(e){let t=e.current;t===Me.SUBTRACT&&(t+=e.step()),e.step();const s="x"===e.current,r="b"===e.current;for((s||r)&&(t+=e.current,e.step());e.notAtEnd();){const i=e.current;if(this.#F(i,s,r)){e.stepBack();break}t+=i,e.step()}return t}#M(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const i=e.current;if(!1===r){if(i===t){s+=i;break}"\\"===i&&(r=!0)}else r=!1;s+=i,e.step()}return s}#P(e){return!1===(ge(e)||ke(e)||$e(e)||xe(e)||pe(e)||ye(e)||Pe(e)||Ne(e))}#$(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#P(s)){e.stepBack();break}t+=s,e.step()}return t}#C(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===$e(s)||!1===$e(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Qe extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Je extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Ze extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class et extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class tt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const st=new qe(Fe.NONE,"",-1,0);class rt{#V;constructor(e=[]){this.#V=e}get tokens(){return this.#V}append(...e){this.#V.push(...e)}merge(e){this.append(...e.tokens)}generate(){let e="";for(let t=0;t<this.#V.length;t++){const s=this.#V[t-1]??st,r=this.#V[t],i=this.#V[t+1]??st,n=this.#D(s,r)?" ":"",o=this.#k(r,i)?" ":"";e+=`${n}${r.value}${o}`}return e}#D(e,t){return!(!t.isType(Fe.KEYWORD)||!this.#B(e))||!(!t.isType(Fe.OPERATOR)||!e.isType(Fe.OPERATOR))}#k(e,t){return e.isType(Fe.KEYWORD)&&(t.isType(Fe.KEYWORD)||this.#B(t))}#B(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.isType(Fe.NUMBER)}}const it="default";class nt{#j;constructor(e=new Xe){this.#j=e}parse(e){const t=this.#j.tokenize(e),s=this.#q(t);return new Q(s)}parseStatement(e){const t=this.#j.tokenize(e),s=this.#U(t);if(void 0===s)throw new et("a statement");return s}parseImport(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof Y==!1)throw new et("an import definition");return s}parseExport(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof H==!1)throw new et("an export definition");return s}parseVariable(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof X==!1)throw new et("a variable definition");return s}parseFunction(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof L==!1)throw new et("a function definition");return s}parseClass(e){const t=this.#j.tokenize(e),s=this.#G(t);if(s instanceof G==!1)throw new et("a class definition");return s}#q(e){const t=[];for(;e.notAtEnd();){const s=this.#U(e);void 0!==s&&t.push(s)}return t}#U(e,t=!1){const s=e.current;if(this.#H(s))return this.#K(e);if(s.isType(Fe.IDENTIFIER)){const s=e.next;return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#K(e)}if(s.isType(Fe.KEYWORD)){if(ve(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(we.FUNCTION)||t.hasValue(Ee.OPEN));if(s.hasValue(we.ASYNC)&&r)return e.step(),this.#U(e,!0);if(void 0===t||this.#W(t))return this.#K(e)}return s.hasValue(we.RETURN)?this.#K(e):!1===Ie(s.value)?this.#K(e):this.#G(e,t)}if(s.isType(Fe.REGEX))return this.#K(e);if(s.hasValue(Ee.OPEN)){const s=this.#z(e,Ee.OPEN,Ee.CLOSE);return s?.hasValue(Me.ARROW)?this.#_(e,t):this.#K(e)}if(s.hasValue(Le.OPEN))return this.#K(e);if(s.hasValue(Oe.OPEN))return this.#K(e);if(s.hasValue(Me.NOT)||s.hasValue(Me.SUBTRACT))return this.#K(e);if(!pe(s.value))throw new tt(s.value,s.start);e.step()}#H(e){return e.isType(Fe.LITERAL)||e.isType(Fe.NUMBER)||e.isType(Fe.BOOLEAN)||e.isType(Fe.NOTHING)||e.hasValue(we.NEW)}#G(e,t=!1){const s=e.current;switch(e.step(),s.value){case we.IMPORT:return this.#Y(e);case we.EXPORT:return this.#X(e);case we.CLASS:return this.#Q(e);case we.FUNCTION:return this.#J(e,t);case we.VAR:return this.#Z(e,"var");case we.LET:return this.#Z(e,"let");case we.CONST:return this.#Z(e,"const");case we.ASYNC:return this.#U(e,!0);default:throw new Ze(s.value,s.start)}}#Y(e){const t=[];let s=e.current;if(s.isType(Fe.LITERAL)){const e=this.#ee(s.value);return new Y(t,e)}if(s.hasValue(Ee.OPEN)){s=e.step();const r=this.#ee(s.value);return e.step(2),new Y(t,r)}if(!1===s.hasValue(Le.OPEN)){const r=s.hasValue(Me.MULTIPLY)?Me.MULTIPLY:it;let i=s.value;s=e.step(),s.hasValue(we.AS)&&(s=e.step(),i=s.value,s=e.step()),t.push(new J(r,i))}if(s.hasValue(le.SEPARATOR)&&(s=e.step()),s.hasValue(Le.OPEN)){const r=this.#te(e);t.push(...r),s=e.current}if(!1===s.hasValue(we.FROM))throw new Qe(we.FROM,s.start);s=e.step();const r=this.#ee(s.value);return e.step(),new Y(t,r)}#X(e){switch(e.current.value){case we.DEFAULT:return e.step(),this.#se(e,!0);case Le.OPEN:return this.#re(e);default:return this.#se(e,!1)}}#se(e,t){let s=e.current,r=0;if(t&&this.#ie(e)){const t=`$_EXPORT_${s.start}_${s.end}`;e.insert(new qe(Fe.KEYWORD,we.CONST,0,0),new qe(Fe.IDENTIFIER,t,0,0),new qe(Fe.OPERATOR,Me.ASSIGN,0,0)),s=e.current}var i;s.hasValue(we.ASYNC)&&(s=e.step(),r++),i=s.value,Ae.includes(i)&&(s=e.step(),r++);const n=this.#P(s)?s.value:"",o=t?it:void 0;let a;s=e.step(),s?.hasValue(we.FROM)&&(s=e.step(),a=this.#ee(s.value)),r>0&&(r++,e.stepBack(r));const c=new J(n,o);return new H([c],a)}#ie(e){const t=e.current;if(this.#H(t))return!0;const s=e.next;return this.#P(t)&&s?.hasValue(Ee.OPEN)}#re(e){const t=this.#te(e);let s,r=e.current;return r?.hasValue(we.FROM)&&(r=e.step(),s=this.#ee(r.value)),e.step(),new H(t,s)}#ee(e){return e.slice(1,-1)}#te(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Le.CLOSE)){e.step();break}if(s.hasValue(le.SEPARATOR)){s=e.step();continue}const r=this.#ne(e);t.push(r),s=e.step()}return t}#ne(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(we.AS)&&(t=e.step(2),r=t.value),new J(s,r)}#Z(e,t){const s=this.#oe(e),r=this.#ae(e);return new X(t,s,r)}#oe(e){const t=e.current;return t.hasValue(Oe.OPEN)?this.#ce(e):t.hasValue(Le.OPEN)?this.#ue(e):this.#le(e)}#ce(e){const t=this.#he(e,Oe.CLOSE);return new M(t)}#ue(e){const t=this.#he(e,Le.CLOSE);return new Z(t)}#he(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(le.SEPARATOR)){e.step();continue}const i=this.#oe(e),n=this.#ae(e),o=new F(i,n);s.push(o)}return s}#le(e){let t=e.current,s=!1;t.hasValue(Me.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new z(r,s)}#ae(e){const t=e.current;if(!1!==t.hasValue(Me.ASSIGN))return e.step(),this.#U(e,!1);t.hasValue(le.TERMINATOR)&&e.step()}#J(e,t){let s,r=e.current,i=!1;r.hasValue(ze.GENERATOR)&&(i=!0,r=e.step()),this.#P(r)&&(s=r.value,e.step());const n=this.#he(e,Ee.CLOSE);if(r=e.current,!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const o=this.#pe(e);return i?new _(s,n,o,t):new L(s,n,o,t)}#_(e,t){let s,r,i=e.current;if(i.hasValue(Ee.OPEN))s=this.#he(e,Ee.CLOSE);else{const t=this.#le(e);s=[new F(t,void 0)]}if(i=e.current,!1===i.hasValue(Me.ARROW))throw new Je(Me.ARROW,i.start);if(i=e.step(),i.hasValue(Le.OPEN))r=this.#pe(e);else{const t=this.#K(e);r=new V(t.code)}return new P(s,r,t)}#Q(e){let t,s,r=e.current;if(this.#P(r)&&(t=r.value,r=e.step()),r.hasValue(we.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const i=this.#de(e);return new G(t,s,i)}#de(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Le.CLOSE)){e.step();break}const r=this.#me(e);s.push(r),t=e.current}return s}#me(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(ze.PRIVATE))s="private";else if(t.hasValue(we.STATIC))r="static";else{if(!t.hasValue(we.ASYNC)){if(t.hasValue(we.CONSTRUCTOR))return this.#fe(e);if(t.hasValue(we.GET))return this.#ge(e,r);if(t.hasValue(we.SET))return this.#Ee(e,r);if(t.hasValue(ze.GENERATOR))return e.step(),this.#ye(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(Ee.OPEN)?this.#ye(e,s,r,i,!1):this.#we(e,s,r)}#fe(e){e.step();const t=this.#he(e,Ee.CLOSE),s=e.current;if(!1===s.hasValue(Le.OPEN))throw new Je(Le.OPEN,s.start);const r=this.#pe(e);return new k(t,r)}#ge(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#he(e,Ee.CLOSE).length)throw new et("an empty parameter list");if(r=e.current,!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const n=this.#pe(e);return new B(i,s,t,n)}#Ee(e,t){let s="public",r=e.step();r.hasValue(ze.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#he(e,Ee.CLOSE);if(r=e.current,1!==n.length)throw new et("exactly one setter parameter");if(!1===r.hasValue(Le.OPEN))throw new Je(Le.OPEN,r.start);const o=this.#pe(e);return new j(i,s,t,n[0],o)}#ye(e,t,s,r,i){let n=e.current;const o=n.value;e.step();const a=this.#he(e,Ee.CLOSE);if(n=e.current,!1===n.hasValue(Le.OPEN))throw new Je(Le.OPEN,n.start);const c=this.#pe(e);return i?new W(o,t,s,a,c,r):new q(o,t,s,a,c,r)}#we(e,t,s){const r=e.current.value;e.step();const i=this.#ae(e);return new U(r,t,s,i)}#pe(e){const t=this.#Se(e,Le.OPEN,Le.CLOSE).generate();return new V(t)}#K(e){const t=new rt;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(Oe.OPEN)){const r=this.#Se(e,Oe.OPEN,Oe.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Ee.OPEN)){const r=this.#Se(e,Ee.OPEN,Ee.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Le.OPEN)){const r=this.#Se(e,Le.OPEN,Le.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#W(s)){s.hasValue(le.TERMINATOR)&&e.step();break}}const r=t.generate();return new K(r)}#Se(e,t,s){let r=e.current;const i=new rt([r]);for(r=e.step();e.notAtEnd();){if(r.hasValue(t)){const n=this.#Se(e,t,s);i.merge(n),r=e.current;continue}if(r.hasValue(s))return e.step(),i.append(r),i;i.append(r),r=e.step()}return i}#z(e,t,s){const r=e.position;this.#Se(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#W(e){return[le.TERMINATOR,le.SEPARATOR].includes(e.value)||[Oe.CLOSE,Ee.CLOSE,Le.CLOSE].includes(e.value)||Ie(e.value)}#P(e){return e.isType(Fe.IDENTIFIER)||e.isType(Fe.KEYWORD)&&ve(e.value)}}let ot=class extends Error{constructor(e,t){super(`Failed to load module file '${e}' because of: ${t}`)}};class at{#p;#d=new I;constructor(e){this.#p=e}rewrite(e,t){e.imports.forEach(e=>this.#be(e,t)),e.exports.forEach(e=>this.#Ae(e,t))}#be(e,t){const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Te(t,s))}#Ae(e,t){if(void 0===e.from)return;const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Te(t,s))}#Te(e,t){const s=this.#d.extractPath(e),r=this.#d.makePathAbsolute(t,s,"");return this.#p.isDirectory(r)?`${t}/${E}`:this.#d.assureExtension(t)}}let ct=class{#p;#Ie;#ve;constructor(e,t=new nt){this.#p=e,this.#Ie=t,this.#ve=new at(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new R(t)}async read(e){try{const t=this.#p.getRelativeLocation(e),s=await this.#Oe(e),r=this.#Ie.parse(s);return this.#ve.rewrite(r,t),new N(t,r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new ot(e,s)}}async#Oe(e){return(await this.#p.getContent(e)).toString()}},ut=class{#Ne;#E=new Map;#Re=new Map;#xe=new Map;constructor(e){this.#Ne=e}get name(){return this.#Ne}get modules(){return[...this.#E.values()]}get classes(){return[...this.#Re.values()]}get procedures(){return[...this.#xe.values()]}hasModule(e){return this.#E.has(e)}getModule(e){return this.#E.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#E.set(e.filename,e)}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}setProcedure(e){this.#xe.set(e.fqn,e)}setClass(e){this.#Re.set(e.fqn,e)}};class lt{#l;#Me;#Ce;constructor(e,t,s){this.#l=e,this.#Me=t,this.#Ce=s}get id(){return this.#l}get importKey(){return this.#Me}get fqn(){return this.#Ce}}class ht extends lt{#g;constructor(e,t,s,r){super(e,t,s),this.#g=r}get model(){return this.#g}}class pt extends lt{#$e;#Le;#g;constructor(e,t,s,r,i,n){super(e,t,s),this.#$e=r,this.#Le=i,this.#g=n}get access(){return this.#$e}get version(){return this.#Le}get model(){return this.#g}}class dt{#t;#e;#Pe;#Fe=[];#Ve;constructor(e,t,s,r){this.#t=e,this.#e=t,this.#Pe=s,this.#Ve=r}get filename(){return this.#t}get location(){return this.#e}get imports(){return this.#Pe}get members(){return this.#Fe}get segmented(){return this.#Ve}hasClasses(){return this.#Fe.some(e=>e instanceof ht)}getClasses(){return this.#Fe.filter(e=>e instanceof ht)}hasImplementations(){return this.#Fe.some(e=>e instanceof pt)}getImplementations(){return this.#Fe.filter(e=>e instanceof pt)}addMember(e){this.#Fe.push(e)}addImports(e){const t=Object.keys(e);for(const s of t){const t=s.trim();this.#Pe[t]=e[s]}}}class mt{#Ce;#De=[];constructor(e,t=[]){this.#Ce=e,this.#De=t}get fqn(){return this.#Ce}get implementations(){return this.#De}addImplementation(e){this.#De.push(e)}}class ft{#ke;constructor(e){this.#ke=e}get segments(){return this.#ke}getSegment(e){return this.#ke.find(t=>t.name===e)}isSegmentedModule(e){return this.#ke.some(t=>t.hasModule(e))}getSegments(e){return this.#ke.filter(t=>t.hasModule(e))}}class gt extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class Et extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class yt extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class wt extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class St extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class bt extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class At{#a;#d=new I;constructor(e){this.#a=e}locate(e,t){const s=[];return{trace:s,model:this.#Be(e,t,s)}}#Be(e,t,s){s.push({filename:e,importKey:t});const r=this.#je(e);return this.#qe(r,t)?this.#Ue(r,t,s):this.#Ge(r,t)}#je(e){const t=this.#a.get(e);if(void 0===t)throw new bt(e);return t}#qe(e,t){const s=e.model.getImport(t),r=e.model.getExport(t);return void 0!==s||void 0!==r?.from}#Ue(e,t,s){const r=this.#He(e,t)??this.#Ke(e,t),i=r?.from,n=r?.name,o=this.#d.extractPath(e.filename),a=i,c=this.#d.makePathAbsolute(a,o,"");return this.#Be(c,n,s)}#Ge(e,t){const s=this.#Ke(e,t);if(void 0===s)throw new St(e.filename,t);const r=e.model.getDeclaration(s.name);if(void 0===r)throw new St(e.filename,s.name);return r}#Ke(e,t){const s=e.model.getExport(t),r=s?.getMember(t);if(void 0!==r)return{from:s?.from,name:r.identifier}}#He(e,t){const s=e.model.getImport(t),r=s?.getMember(t);if(void 0!==s&&void 0!==r)return{from:s.from,name:r.identifier}}}class Tt{#_e;#p;#We;#d=new I;constructor(e,t,s){this.#_e=e,this.#p=t,this.#We=new At(s)}async readAll(e){const t=await Promise.all(e.map(e=>this.#ze(e)));return new ft(t)}async#ze(e){const t=await this.#Ye(e),s=this.#Xe(e),r=new ut(s);return this.#Qe(r,t),this.#Je(r),r}#Xe(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new Et(e);return t.replace(y,"")}async#Ye(e){try{const t=await this.#_e.getContent(e);return JSON.parse(t.toString())}catch(t){const s=t instanceof Error?t.message:String(t);throw new yt(e,s)}}#Qe(e,t){for(const[s,r]of Object.entries(t))this.#Ze(e,s,r,!0)}#Ze(e,t,s,r){const i=this.#et(t),n=this.#d.extractPath(i),o=e.hasModule(i)?e.getModule(i):new dt(i,n,{},r);o.addImports(s),e.setModule(o)}#et(e){const t=e.trim(),s=this.#p.normalizeLocation(t),r=this.#p.isDirectory(s)?`${s}/${E}`:this.#d.assureExtension(s);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#Je(e){const t=new S;for(const s of e.modules)for(const r in s.imports)this.#tt(e,s,r,t)}#tt(e,t,s,r){const{model:i,trace:n}=this.#We.locate(t.filename,s),o=this.#st(t,i,s,r);this.#rt(e,t,i,o),n.shift();for(const t of n){const s={[t.importKey]:{access:o.access}};this.#Ze(e,t.filename,s,!1)}}#st(e,t,s,r){const i=e.imports[s],n=r.next(),o=i.as??t.identifier;return{id:n,importKey:s,name:o,access:i.access??f,version:i.version??g,fqn:this.#it(e,o,s)}}#it(e,t,s){return this.#nt(e)?t:this.#ot(e)&&this.#at(s)?e.location:`${e.location}/${t}`}#nt(e){return""===e.location}#ot(e){return e.filename.endsWith(E)}#at(e){return e===w}#rt(e,t,s,r){if(s instanceof G)return this.#ct(e,t,s,r);if(s instanceof L)return this.#ut(e,t,s,r);throw new wt(t.filename,r.importKey)}#ct(e,t,s,r){const i=new ht(r.id,r.importKey,r.fqn,s);t.addMember(i),e.setClass(i)}#ut(e,t,s,r){if(!1===s.isAsync)throw new gt(t.filename,r.name);const i=new pt(r.id,r.importKey,r.fqn,r.access,r.version,s);this.#lt(e,t,i)}#lt(e,t,s){const r=e.hasProcedure(s.fqn)?e.getProcedure(s.fqn):new mt(s.fqn);r.addImplementation(s),t.addMember(s),e.setProcedure(r)}}class It{#ht;constructor(e){this.#ht=e}async read(e,t,s){const r=this.#ht.source,i=this.#ht.resource,n=this.#ht.segment,o=new ct(r),a=await o.readAll(e),c=new O(i,r),u=await c.readAll(t),l=new Tt(n,r,a),h=await l.readAll(s);return new d(a,u,h)}}class vt extends Error{constructor(e){super(`Could not find the rewrite item: ${e}`)}}class Ot{#pt;#c;#u;#dt;#d=new I;constructor(e,t,s,r){this.#pt=e,this.#c=t,this.#u=s,this.#dt=r}generate(){const e=this.#pt.model.clone();return this.#mt(e,e.imports),this.#mt(e,e.exports),e.toString()}#mt(e,t){for(const s of t){const t=this.#ft(s);if(0===t.length)continue;const r=e.statements.indexOf(s);if(-1===r)throw new vt(s.toString());e.statements.splice(r,1,...t)}}#ft(e){if(this.#gt(e))return[];const t=this.#Et(e);return this.#c.isResourceModule(t)?this.#yt(e,t):this.#wt(e,t)}#gt(e){return void 0===e.from||this.#St(e)}#St(e){return!1===this.#d.isApplicationModule(e.from)}#Et(e){const t=e.from,s=this.#d.extractPath(this.#pt.filename);return this.#d.makePathAbsolute(t,s,"")}#yt(e,t){const s=e.clone();return s.from=this.#bt(t),[s]}#wt(e,t){if(0===e.members.length)return[this.#At(t,e,[])];const{segmentKeys:s,remoteKeys:r,commonKeys:i}=this.#Tt(t,e),n=[];return s.length>0&&n.push(this.#It(t,e,s)),r.length>0&&n.push(this.#vt(t,e,r)),i.length>0&&n.push(this.#At(t,e,i)),n}#Tt(e,t){const s=this.#Ot(e,this.#dt),r=this.#Nt(e,s),i=this.#Rt(t,s),n=this.#Rt(t,r);return{segmentKeys:i,remoteKeys:n,commonKeys:this.#xt(t,[...i,...n])}}#Ot(e,t){if(void 0===t)return[];const s=t.getModule(e);return void 0===s?[]:Object.keys(s.imports)}#Nt(e,t){const s=this.#u.getSegments(e).filter(e=>e!==this.#dt).flatMap(t=>this.#Ot(e,t));return[...new Set(s)].filter(e=>!1===t.includes(e))}#Rt(e,t){return e.members.filter(e=>t.includes(e.identifier)).map(e=>e.identifier)}#xt(e,t){return e.members.filter(e=>!1===t.includes(e.identifier)).map(e=>e.identifier)}#It(e,t,s){const r=t.clone();return r.from=this.#bt(e,this.#dt?.name),r.members=this.#Mt(t.members,s),r}#vt(e,t,s){const r=t.clone();return r.from=this.#bt(e,"remote"),r.members=this.#Mt(t.members,s),r}#At(e,t,s){const r=t.clone();return r.from=this.#bt(e),r.members=this.#Mt(t.members,s),r}#Mt(e,t){const s=[];for(const r of t){const t=e.find(e=>e.identifier===r);void 0!==t&&s.push(t)}return s}#bt(e,t){const s=this.#d.extractPath(this.#pt.filename),r=this.#d.makePathRelative(e,s);return void 0!==t?this.#d.addSubExtension(r,t):r}}const Nt={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};class Rt extends Error{constructor(e="Invalid request"){super(e)}}class xt extends Error{constructor(e="Forbidden"){super(e)}}class Mt extends Error{constructor(e="Not found"){super(e)}}class Ct extends Error{constructor(e="Not implemented"){super(e)}}class $t extends Error{constructor(e="Payment required"){super(e)}}class Lt extends Error{constructor(e="Server error"){super(e)}}class Pt extends Error{constructor(e="I'm a teapot"){super(e)}}class Ft extends Error{constructor(e="Unauthorized"){super(e)}}class Vt{#l;#Re=new Map;#xe=new Map;constructor(e){this.#l=e}get id(){return this.#l}addClass(e){return this.#Re.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#Re.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#Re.values()]}addProcedure(e){return this.#xe.set(e.fqn,e),this}hasProcedure(e){return this.#xe.has(e)}getProcedure(e){return this.#xe.get(e)}getExposedProcedures(){return[...this.#xe.values()].filter(e=>e.public||e.protected)}}class Dt{static get DEFAULT(){return new Dt(0,0,0)}#Ct;#$t;#Lt;constructor(e=0,t=0,s=0){this.#Ct=e,this.#$t=t,this.#Lt=s}get major(){return this.#Ct}get minor(){return this.#$t}get patch(){return this.#Lt}equals(e){return this.#Ct===e.major&&this.#$t===e.minor&&this.#Lt===e.patch}greater(e){return this.#Ct!==e.major?this.#Ct>e.major:this.#$t!==e.minor?this.#$t>e.minor:this.#Lt!==e.patch&&this.#Lt>e.patch}less(e){return this.#Ct!==e.major?this.#Ct<e.major:this.#$t!==e.minor?this.#$t<e.minor:this.#Lt!==e.patch&&this.#Lt<e.patch}toString(){return`${this.#Ct}.${this.#$t}.${this.#Lt}`}}class kt{#Ne;#Pt;constructor(e,t=!1){this.#Ne=e,this.#Pt=t}get name(){return this.#Ne}get isOptional(){return this.#Pt}}class Bt extends kt{}class jt extends kt{#Ft;constructor(e,t,s){super(t??"(anonymous)",s),this.#Ft=e}get variables(){return this.#Ft}}class qt extends jt{}class Ut extends jt{}class Gt{#Ce;#Le;#Vt;#Dt=new Map;#kt;constructor(e,t,s,r,i){this.#Ce=e,this.#Le=t,this.#Vt=s,this.#Dt=r,this.#kt=i}get fqn(){return this.#Ce}get version(){return this.#Le}get args(){return this.#Vt}get headers(){return this.#Dt}get mode(){return this.#kt}clearArguments(){this.#Vt.clear()}setArgument(e,t){this.#Vt.set(e,t)}getArgument(e){return this.#Vt.get(e)}hasArgument(e){return this.#Vt.has(e)}removeArgument(e){this.#Vt.delete(e)}clearHeaders(){this.#Dt.clear()}setHeader(e,t){this.#Dt.set(e.toLowerCase(),t)}getHeader(e){return this.#Dt.get(e.toLowerCase())}hasHeader(e){return this.#Dt.has(e.toLowerCase())}removeHeader(e){this.#Dt.delete(e.toLowerCase())}}class Ht{#Bt;#jt;#Dt;constructor(e,t=void 0,s=new Map){this.#Bt=e,this.#jt=t,this.#Dt=s}get status(){return this.#Bt}get result(){return this.#jt}set result(e){this.#jt=e}get headers(){return this.#Dt}clearHeaders(){this.#Dt.clear()}setHeader(e,t){this.#Dt.set(e.toLowerCase(),t)}getHeader(e){return this.#Dt.get(e.toLowerCase())}hasHeader(e){return this.#Dt.has(e.toLowerCase())}removeHeader(e){this.#Dt.delete(e.toLowerCase())}}class Kt{#pt;#ke;constructor(e,t){this.#pt=e,this.#ke=t}generate(){const e=[],t=this.#qt();for(const s of t){const t=s.access===Nt.PRIVATE?this.#Ut(s):this.#Gt(s);e.push(...t)}return new Q(e).toString()}#qt(){const e=this.#ke.map(e=>e.getModule(this.#pt.filename)).flatMap(e=>e.getImplementations()),t=new Map;for(const s of e){const e=`${s.fqn}:${s.version.toString()}`;t.set(e,s)}return[...t.values()]}#Ut(e){const t=`throw new ProcedureNotAccessible('${e.fqn}','${e.version}');`;return[this.#Ht(e),this.#Kt(e,t)]}#Gt(e){const t=`return __run('${e.fqn}','${e.version}',{${this.#_t(e.model.parameters)}},this);`;return[this.#Ht(e),this.#Kt(e,t)]}#Ht(e){const t=e.model.identifier,s=e.importKey===w?w:void 0,r=new J(t,s);return new H([r],void 0)}#Kt(e,t){const s=e.model.identifier,r=e.model.parameters,i=new V(`{${t}}`),n=e.model.isAsync;return new L(s,r,i,n)}#_t(e){return this.#Wt(e).join(",")}#Wt(e){const t=[];for(const s of e)if(s.binding instanceof z){const e=this.#zt(s.binding);t.push(e)}else if(s.binding instanceof M){const e=this.#Wt(s.binding.elements);t.push(...e)}else if(s.binding instanceof Z){const e=this.#Wt(s.binding.elements);t.push(...e)}return t}#zt(e){return`'${e.identifier}':${e.toString()}`}}class _t{#Yt;#Xt;#Qt;#dt;#Jt;constructor(e,t,s,r,i){this.#Yt=e,this.#Xt=t,this.#Qt=s,this.#dt=r,this.#Jt=i}get source(){return this.#Yt}get target(){return this.#Xt}get resource(){return this.#Qt}get segment(){return this.#dt}get sourceIgnores(){return this.#Jt}}class Wt{#Zt;constructor(e=!0){this.#Zt=e}validate(e,t){const s=[];this.#es("",e,t,s);return{valid:0===s.length,errors:s}}#es(e,t,s,r){this.#Zt&&this.#ts(e,t,s,r),this.#ss(e,t,s,r)}#ts(e,t,s,r){const i=Object.keys(t),n=Object.keys(s);for(const t of i)if(!1===n.includes(t)){const s=this.#rs(e,t);r.push(`Unknown field '${s}'`)}}#ss(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#rs(e,n),o=s[n],a=t[n];this.#is(i,a,o,r)}}#is(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#ns(e,t,s,r);case"integer":return this.#os(e,t,s,r);case"real":return this.#as(e,t,s,r);case"boolean":return this.#cs(e,t,s,r);case"url":return this.#us(e,t,s,r);case"group":return this.#ls(e,t,s,r);case"list":return this.#hs(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#ns(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#os(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#as(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#cs(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#us(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#ls(e,t,s,r){"object"==typeof t?this.#es(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#hs(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const i=t;for(const t in i){const n=this.#rs(e,t),o=i[t];this.#is(n,o,s.items,r)}}#rs(e,t){return""===e?t:`${e}.${t}`}}class zt{#ps;constructor(e){this.#ps=e}async configure(e){const t=this.#ps.getAbsoluteLocation(e);n.config({path:t})}}class Yt extends Error{constructor(e){super(`Runtime configuration is invalid:\n${e.errors.join("\n")}`)}}const Xt="./jitar.json",Qt="./src",Jt="./dist",Zt="./segments",es="./resources",ts={ignore:[]},ss=[],rs={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1},build:{type:"group",fields:{ignore:{type:"list",items:{type:"string"},required:!1}},required:!1}};let is=class{#ds;#ms;constructor(e,t){this.#ds=e,this.#ms=t}async build(e=Xt){const t=await this.#ds.read(e),s=this.#ms.validate(t,rs);if(!1===s.valid)throw new Yt(s);return t.source??=Qt,t.target??=Jt,t.segments??=Zt,t.resources??=es,t.build??=ts,t.build.ignore??=ss,t.meta={root:this.#ds.getRootLocation(),configFile:e},t}};const ns="\n => ";class os extends Error{constructor(e){const t=e.errors.join(ns);super(`Invalid server configuration:${ns}${t}`)}}const as={indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assetRoot:{type:"string",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}},cs={gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}},us={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:as},standalone:{type:"group",required:!1,fields:{...as,segments:cs.segments}},worker:{type:"group",required:!1,fields:cs},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class ls{#ds;#ms;constructor(e,t){this.#ds=e,this.#ms=t}async build(e){const t=await this.#ds.read(e),s=this.#ms.validate(t,us);if(!1===s.valid)throw new os(s);return t.meta={root:this.#ds.getRootLocation(),configFile:e},t}}class hs extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const ps=/\${([^}]*)}/g;class ds{#ps;constructor(e){this.#ps=e}getRootLocation(){return this.#ps.getAbsoluteLocation(".")}async read(e){if(!1===await this.#ps.exists(e))return{};const t=await this.#ps.read(e);if(!1===t.type.includes("json"))throw new hs(e);const s=t.content.toString(),r=this.#fs(s);return this.#gs(r)}#fs(e){return e.replace(ps,(e,t)=>process.env[t]??"null")}#gs(e){return JSON.parse(e)}}class ms{#Es;#ys;#ws;constructor(e="./"){const t=new p(e),s=new ds(t),r=new Wt;this.#Es=new zt(t),this.#ys=new is(s,r),this.#ws=new ls(s,r)}configureEnvironment(e=".env"){return this.#Es.configure(e)}getRuntimeConfiguration(e){return this.#ys.build(e)}getServerConfiguration(e){return this.#ws.build(e)}}export{qt as A,Rt as B,ms as C,c as D,G as E,xt as F,Gt as G,Nt as H,p as L,Mt as N,Ut as O,nt as P,Ht as R,Lt as S,Pt as T,Ft as U,Dt as V,z as a,K as b,X as c,Q as d,U as e,k as f,B as g,j as h,q as i,Bt as j,Ct as k,$t as l,Vt as m,I as n,Ot as o,Kt as p,Y as q,J as r,H as s,M as t,Z as u,_t as v,It as w,o as x,Wt as y,u as z};
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{promises as e,existsSync as t}from"node:fs";import r from"node:path";import{fileURLToPath as s}from"node:url";import{L as a,E as n,P as i,a as o,b as c,c as u,d as l,e as h,f as d,g as p,h as m,i as g,B as w,N as f,F as y,j as v,A as b,O as M,k as x,l as S,T as k,U as P,S as A,V as z,m as R,R as C,n as E,o as H,p as O,q as N,r as T,s as I,t as j,u as $,v as L,w as F,x as q,C as B,y as W,z as D,D as V,G as K}from"./ConfigurationManager-CYD-3rnJ.js";import _ from"node:crypto";import U from"express";import"glob";import"mime-types";import"dotenv";class G extends Error{constructor(e){super(`Missing argument '${e}'`)}}class J{#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 G(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 X{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.#a(t);this.#n()}#n(){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")}#a(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,a=e.defaultValue?`default: ${e.defaultValue}`:"no default value",n=e.required?"required":`optional - ${a}`;console.log(` ${t} ${r} (${n})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class Q{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 Z{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class Y extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class ee extends Error{constructor(e){super(`Unknown template: ${e}`)}}const te=/^[a-zA-Z.\-_]+$/,re={_gitignore:".gitignore","_package.json":"package.json","_tsconfig.json":"tsconfig.json","_vite.config.ts":"vite.config.ts"};class se{#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 ee(t);await this.#p(e,t),this.#m(e)}#u(){const e=r.dirname(s(import.meta.url));return r.join(e,"templates")}#l(e){return r.resolve(e)}#h(e,t){if(!1===te.test(e))throw new Y(e,t)}async#d(t){try{const s=r.join(this.#o,t);return(await e.stat(s)).isDirectory()}catch{return!1}}#p(t,s){const a=r.join(this.#o,s),n=r.join(this.#c,t);return e.cp(a,n,{recursive:!0,force:!0})}async#m(s){const a=r.join(this.#c,s),n=Object.entries(re),i=[];for(const[s,o]of n){const n=r.join(a,s),c=r.join(a,o);t(n)&&i.push(e.rename(n,c))}await Promise.all(i)}}class ae{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.#w(t,r,s),this.#f(t)}#g(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#w(e,t,r){return new se(r).init(e,t)}#f(e){console.log(`SUCCESS! Run the following commands to continue:\ncd ${e}\nnpm install\nnpm run build\nnpm run standalone`)}}class ne extends Error{#y;#v;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#y=e,this.#v=t}get url(){return this.#y}get reason(){return this.#v}}class ie{#b;constructor(e){this.#b=e}async import(e){const t=this.#b.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new ne(t,r)}}}class oe{#M;constructor(e){this.#M=e}locate(e){return`file://${e.startsWith("/")?this.#M.getAbsoluteLocation(`.${e}`):this.#M.getAbsoluteLocation(e)}`}}class ce extends ie{constructor(e){super(new oe(e))}}class ue{#M;#x;constructor(e,t){this.#M=e,this.#x=t}get fileManager(){return this.#M}get importManager(){return this.#x}async filter(...e){return(await Promise.all(e.map(e=>this.#M.filter(e)))).flat().map(e=>this.#M.getRelativeLocation(e))}exists(e){return this.#M.exists(e)}read(e){return this.#M.read(e)}import(e){return this.#x.import(e)}}class le extends ue{constructor(e){const t=new a(e);super(t,new ce(t))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new le(t)}}class he{merge(e,t){const r=void 0!==e.construct?[e.construct]:[],s=[...this.#S(e.fields,t.fields),...r,...this.#S(e.methods,t.methods),...this.#S(e.getters,t.getters),...this.#S(e.setters,t.setters)];return new n(e.identifier,t.identifier,s)}#S(e,t){const r=new Map;return t.forEach(e=>r.set(e.identifier,e)),e.forEach(e=>r.set(e.identifier,e)),[...r.values()]}}class de{#k=new i;#P=new he;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,a]of r){if("function"!=typeof a.toString)continue;const r=a.toString();if(r.startsWith("class"))s.push(this.fromClass(a,t));else if(r.startsWith("function"))s.push(this.fromFunction(a));else{const t=new o(e,!1),a=new c(r);s.push(new u("var",t,a))}}return new l(s)}fromClass(e,t=!1){const r=this.isClass(e)?this.#A(e):this.#z(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const a=this.fromClass(s,!0);return this.#P.merge(r,a)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#k.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")}#A(e){const t=e.toString();return this.#k.parseClass(t)}#z(e){const t=this.createInstance(e),r=this.#R(e,t);return new n(e.name,void 0,r)}#R(e,t){return[...this.#C(t),...this.#E(e)]}#C(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],a=void 0!==t?new c(String(t)):void 0,n=new h(e,"public","instance",a);s.push(n)}return s}#E(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],a=s.value;if(a instanceof Function==!1)continue;const n=this.fromFunction(a);"constructor"===n.identifier?r.push(new d(n.parameters,n.body)):void 0!==s.get?r.push(new p(n.identifier,"public","instance",n.body)):void 0!==s.set?r.push(new m(n.identifier,"public","instance",n.parameters[0],n.body)):r.push(new g(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return r}}const pe="normal",me="dry",ge=200,we=400,fe=401,ye=402,ve=403,be=404,Me=418,xe=500,Se=501;class ke extends w{#H;constructor(e){super(`Invalid version number '${e}'`),this.#H=e}get number(){return this.#H}}class Pe extends f{#O;constructor(e){super(`Procedure '${e}' not found`),this.#O=e}get fqn(){return this.#O}}class Ae extends y{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class ze extends w{#N;constructor(e){super(`Unknown parameter ${e}`),this.#N=e}get parameterName(){return this.#N}}class Re extends w{#N;constructor(e){super(`Missing value for parameter '${e}'`),this.#N=e}get parameterName(){return this.#N}}class Ce extends w{#N;constructor(e){super(`Invalid value for parameter '${e}'`),this.#N=e}get parameterName(){return this.#N}}class Ee{extract(e,t){const r=this.#T(e,t),s=[];for(const t of e){const e=this.#I(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new ze(e)}return s}#T(e,t){const r=new Map;for(const[s,a]of t){if(this.#j(s)){const t=this.#$(s);!0===this.#L(e,t)&&r.set(t,a);continue}r.set(s,a)}return r}#j(e){return e.startsWith("*")}#$(e){return e.substring(1)}#L(e,t){return void 0!==e.find(e=>e.name===t)}#I(e,t,r){return e instanceof v?this.#F(e,t,r):this.#q(e,t)}#F(e,t,r){const s=t.get(e.name);if(this.#B(e,s,r))throw new Re(e.name);if(this.#W(e,s,r))throw new Ce(e.name);return t.delete(e.name),s}#q(e,t){return e instanceof b?this.#D(e,t):this.#V(e,t)}#D(e,t){const r=this.#K(e,t);return void 0!==r?Object.values(r):void 0}#V(e,t){return this.#K(e,t)}#K(e,t){const r=e instanceof b,s={},a=[];let n=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#I(o,t,e);void 0!==u?n=!0:!1===o.isOptional&&a.push(o.name),s[c]=u}if(!0===n&&a.length>0)throw new Re(a[0]);return n?s:void 0}#B(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#W(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof b&&t instanceof Array==!1||r instanceof M&&t instanceof Object==!1)}}class He{toStatus(e){return e instanceof w?we:e instanceof y?ve:e instanceof f?be:e instanceof x?Se:e instanceof S?ye:e instanceof k?Me:e instanceof P?fe:xe}fromStatus(e,t){switch(e){case we:return new w(t);case ve:return new y(t);case be:return new f(t);case Se:return new x(t);case ye:return new S(t);case Me:return new k(t);case fe:return new P(t);default:return new A(t)}}}const Oe=/^\d+(?:\.\d+){0,2}$/;class Ne{parse(e){if(0===e.trim().length)return z.DEFAULT;if(!1===Oe.test(e))throw new ke(e);const t=e.split(".");switch(t.length){case 1:return new z(Number.parseInt(t[0]));case 2:return new z(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new z(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class Te extends f{#O;#_;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#O=e,this.#_=t}get fqn(){return this.#O}get version(){return this.#_}}class Ie extends A{constructor(){super("Invalid segment")}}class je{#U=new Map;addSegment(e){this.#U.set(e.id,e)}clearSegments(){this.#U.clear()}getClassNames(){const e=new Set;for(const t of this.#U.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.#U.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#U.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#U.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.#U.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class $e{#G;#J;#X=new Ee;#Q=new He;#Z=new je;constructor(e,t=[]){this.#G=e,this.#J=t}async start(){return this.#Y()}async stop(){return this.#ee()}async loadSegment(e){const t=await this.#G.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof R==!1)throw new Ie;this.#Z.addSegment(e)}getClassNames(){return this.#Z.getClassNames()}hasClass(e){return this.#Z.hasClass(e)}getClass(e){return this.#Z.getClass(e)}getClassByImplementation(e){return this.#Z.getClassByImplementation(e)}getProcedureNames(){return this.#Z.getProcedureNames()}hasProcedure(e){return this.#Z.hasProcedure(e)}getProcedure(e){return this.#Z.getProcedure(e)}async run(e){const t=this.#te(e.fqn,e.version),r=this.#X.extract(t.parameters,e.args);return e.mode===me?new C(ge,void 0):this.#re(e,t,r)}async#Y(){await Promise.all(this.#J.map(e=>this.loadSegment(e)))}#ee(){this.#Z.clearSegments()}#te(e,t){const r=this.#Z.getProcedure(e);if(void 0===r)throw new Pe(e);const s=r.getImplementation(t);if(void 0===s)throw new Te(r.fqn,t.toString());return s}async#re(e,t,r){try{const s=await t.executable.call(e,...r);return new C(ge,s)}catch(e){const t=this.#Q.toStatus(e);return new C(t,e)}}}let Le=class{#se;#ae=new E;constructor(e){this.#se=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,a=t.modules.map(e=>this.#ne(e,s,r));await Promise.all(a)}async#ne(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#ie(e,t,r);const a=s.map(s=>this.#oe(e,t,s,r)),n=s[0].getModule(e.filename),i=n?.hasImplementations()?this.#ce(e,s):Promise.resolve();await Promise.all([...a,i]),this.#se.delete(e.filename)}async#ie(e,t,r){const s=e.filename,a=new H(e,t,r).generate();return this.#se.write(s,a)}async#oe(e,t,r,s){const a=this.#ae.addSubExtension(e.filename,r.name),n=new H(e,t,s,r).generate();return this.#se.write(a,n)}async#ce(e,t){const r=this.#ae.addSubExtension(e.filename,"remote"),s=new O(e,t).generate();return this.#se.write(r,s)}};const Fe=["Segment","Class","Procedure","Implementation","Version","NamedParameter","ArrayParameter","ObjectParameter"];class qe{#ue;#ae=new E;#le=new Ne;constructor(e){this.#ue=e}generate(){const e=this.#he(),t=this.#de(),r=this.#pe();return new l([...e,t,r]).toString()}#he(){return[this.#me(),...this.#ge()]}#me(){const e=Fe.map(e=>new T(e));return new N(e,"jitar")}#ge(){const e=[],t=this.#ue.name,r=this.#ue.getSegmentedModules();for(const s of r){const r=`./${this.#ae.addSubExtension(s.filename,t)}`;if(0===s.members.length){const t=new N([],r);e.push(t);continue}const a=s.members.map(e=>new T(e.importKey,e.id)),n=new N(a,r);e.push(n)}return e}#de(){const e=new T("segment","default");return new I([e],void 0)}#pe(){const e=[],t=this.#ue.name,r=this.#ue.classes,s=this.#ue.procedures;e.push(`new Segment("${t}")`);for(const t of r)e.push(`\t.addClass(new Class("${t.fqn}", ${t.id}))`);for(const t of s){e.push(`\t.addProcedure(new Procedure("${t.fqn}")`);for(const r of t.implementations){const t=this.#we(r.version),s=this.#fe(r.model);e.push(`\t\t.addImplementation(new Implementation(${t}, "${r.access}", ${s}, ${r.id}))`)}e.push("\t)")}const a=e.join("\n"),n=new c(a),i=new o("segment");return new u("const",i,n)}#we(e){const t=this.#le.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#fe(e){return`[${this.#ye(e.parameters).join(", ")}]`}#ye(e){const t=[];for(const r of e)t.push(this.#ve(r));return t}#ve(e){return e.binding instanceof j?this.#be(e):e.binding instanceof $?this.#Me(e):this.#xe(e)}#xe(e){return`new NamedParameter("${e.binding}", ${void 0!==e.initializer})`}#be(e){const t=e.binding;return`new ArrayParameter([${this.#ye(t.elements).join(", ")}])`}#Me(e){const t=e.binding;return`new ObjectParameter([${this.#ye(t.elements).join(", ")}])`}}let Be=class{#se;#Se;constructor(e,t){this.#se=e,this.#Se=t}async build(e){const t=e.segmentation.segments.map(e=>this.#ke(e));await Promise.all(t)}async#ke(e){const t=`${e.name}.segment.js`,r=new qe(e).generate();await this.#se.write(t,r),this.#Se.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}};class We{#Pe;#Ae;constructor(e,t){const r=e.target;this.#Pe=new Le(r),this.#Ae=new Be(r,t)}async build(e){await Promise.all([this.#Pe.build(e),this.#Ae.build(e)])}}const De=0,Ve=1,Ke=2,_e=3,Ue=4;class Ge{#ze;#Re;constructor(e=Ve,t=console){this.#ze=e,this.#Re=t}debug(...e){if(this.#ze>De)return;const t=this.#Ce("DEBUG",e);this.#Re.debug(t)}info(...e){if(this.#ze>Ve)return;const t=this.#Ce("INFO",e);this.#Re.info(t)}warn(...e){if(this.#ze>Ke)return;const t=this.#Ce("WARN",e);this.#Re.warn(t)}error(...e){if(this.#ze>_e)return;const t=this.#Ce("ERROR",e);this.#Re.error(t)}fatal(...e){const t=this.#Ce("FATAL",e);this.#Re.error(t)}#Ce(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Ee(e)).join(" ")}`}#Ee(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#He(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#Oe(t)}${r}`}#He(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Ee(e,t)).join(",\n")}\n${this.#Oe(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#Oe(e){return" ".repeat(e)}}class Je extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class Xe{parse(e){switch(e.toUpperCase()){case"DEBUG":return De;case"INFO":return Ve;case"WARN":return Ke;case"ERROR":return _e;case"FATAL":return Ue;default:throw new Je(e)}}}class Qe{#Se;#ae;#M;#Ne;#Te;constructor(e,t){this.#Se=new Ge(t),this.#ae=new E;const r=this.#ae.makePathAbsolute(e.source,e.meta.root),s=this.#ae.makePathAbsolute(e.target,e.meta.root),n=this.#ae.makePathAbsolute(e.resources,e.meta.root),i=this.#ae.makePathAbsolute(e.segments,e.meta.root),o=new a(r),c=new a(s),u=new a(n),l=new a(i);this.#M=new L(o,c,u,l),this.#Ne=new F(this.#M),this.#Te=new We(this.#M,this.#Se)}async build(){const e=this.#M.source,t=this.#M.resource,r=this.#M.segment,s=await e.filter(q.MODULE_PATTERN),a=await t.filter(q.RESOURCE_PATTERN),n=await r.filter(q.SEGMENT_PATTERN),i=await this.#Ne.read(s,a,n);return this.#Te.build(i)}}class Ze{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),a=this.#Ie(s),n=new B;await n.configureEnvironment(t);const i=await n.getRuntimeConfiguration(r);return new Qe(i,a).build()}#Ie(e){if(void 0===e)return;return(new Xe).parse(e)}}const Ye="content-type",et="x-content-type-options",tt="x-jitar-content-type",rt="x-jitar-procedure-version",st="x-powered-by",at="nosniff",nt="application/json",it="application/octet-stream";class ot extends Error{constructor(){super("Invalid worker id")}}class ct{#y;#je;#Q=new He;#$e=new W;constructor(e,t){this.#y=e,this.#je=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#y}/${e}`,r=await this.#Le(t,{method:"GET"}),s=r.headers.get(Ye)??it,a=await r.arrayBuffer(),n=Buffer.from(a);return new D(e,s,n)}async isHealthy(){const e=`${this.#y}/health/status`,t=await this.#Le(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#y}/health`,t=await this.#Le(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#y}/workers`,a={url:e,procedureNames:t,trustKey:r},n={method:"POST",headers:{"Content-Type":nt},body:JSON.stringify(a)},i=await this.#Le(s,n),o=i.headers.get(Ye);if(null===o||!1===o.includes(nt))throw new ot;const c=await i.json();if(!1===this.#$e.validate(c,{id:{type:"string",required:!0}}).valid)throw new ot;return c.id}async reportWorker(e,t){const r=`${this.#y}/workers/${e}/report`,s={state:t},a={method:"POST",headers:{"Content-Type":nt},body:JSON.stringify(s)};await this.#Le(r,a)}async removeWorker(e){const t=`${this.#y}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":nt}};await this.#Le(t,r)}async run(e){e.setHeader(Ye,nt);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[rt]=s;const a=`${this.#y}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:r,body:await this.#Fe(t)},i=await this.#Le(a,n,!1),o=i.status,c=await this.#qe(i),u=this.#Be(i);return new C(o,c,u)}async#Le(e,t,r=!0){const s=await this.#je.execute(e,t);if(r&&this.#We(s)){const e=await this.#qe(s);throw this.#Q.fromStatus(s.status,String(e))}return s}#We(e){return e.status<200||e.status>399}async#Fe(e){return JSON.stringify(e)}async#qe(e){const t=e.headers.get(tt)??e.headers.get(Ye);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}#Be(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class ut{async execute(e,t){return fetch(e,t)}}class lt{#je;constructor(e=new ut){this.#je=e}build(e){return new ct(e,this.#je)}}const ht={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class dt{get url(){throw new x}get state(){return ht.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ht.AVAILABLE}provide(e){throw new x}}class pt{get url(){throw new x}get state(){return ht.AVAILABLE}get trustKey(){throw new x}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ht.AVAILABLE}getProcedureNames(){throw new x}hasProcedure(e){throw new x}run(e){throw new x}}class mt{#De=ht.STOPPED;get state(){return this.#De}set state(e){this.#De=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.#Ve(ht.STOPPED)}isStopped(){return this.#Ke(ht.STOPPED)}isAvailable(){return this.#Ke(ht.AVAILABLE)}setStarting(){this.#De=ht.STARTING}setAvailable(){this.#De=ht.AVAILABLE}setUnavailable(){this.#De=ht.UNAVAILABLE}setAvailability(e){return this.#De=e?ht.AVAILABLE:ht.UNAVAILABLE,this.#De}setStopping(){this.#De=ht.STOPPING}setStopped(){this.#De=ht.STOPPED}#Ke(...e){return e.includes(this.#De)}#Ve(...e){return!1===this.#Ke(...e)}}class gt extends P{constructor(){super("Invalid trust key")}}class wt{#y;#_e;#Ue;#Ge;#Je=new mt;constructor(e){this.#y=e.url,this.#_e=e.trustKey,this.#Ue=e.healthManager,this.#Ge=e.workerManager}get url(){return this.#y}get state(){return this.#Je.state}get trustKey(){return this.#_e}async start(){return this.#Je.start(async()=>{await this.#Ue.start(),this.#Ge.start(),await this.updateState()})}async stop(){return this.#Je.stop(async()=>{this.#Ge.stop(),await this.#Ue.stop()})}async isHealthy(){return this.#Ue.isHealthy()}async getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Je.setAvailability(e)}async addWorker(e){if(this.#Xe(e.trustKey))throw new gt;return await e.start(),this.#Ge.addWorker(e)}getWorker(e){return this.#Ge.getWorker(e)}async reportWorker(e,t){return this.#Ge.reportWorker(e,t)}async removeWorker(e){return this.#Ge.removeWorker(e).stop()}getProcedureNames(){return this.#Ge.getProcedureNames()}hasProcedure(e){return this.#Ge.hasProcedure(e)}async run(e){return this.#Ge.run(e)}#Xe(e){return void 0!==this.#_e&&e!==this.#_e}}class ft{#y;#Qe;#Je=new mt;constructor(e){this.#y=e.url,this.#Qe=e.remote}get url(){return this.#y}get state(){return this.#Je.state}get trustKey(){}async start(){return this.#Je.start(async()=>{await this.#Qe.connect(),await this.updateState()})}async stop(){return this.#Je.stop(async()=>{await this.#Qe.disconnect()})}isHealthy(){return this.#Qe.isHealthy()}getHealth(){return this.#Qe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Je.setAvailability(e)}getProcedureNames(){throw new x}hasProcedure(e){throw new x}addWorker(e){return this.#Qe.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#Qe.reportWorker(e,t)}removeWorker(e){return this.#Qe.removeWorker(e)}run(e){return this.#Qe.run(e)}}class yt extends A{#Ze;constructor(e){super(`No worker available for procedure '${e}'`),this.#Ze=e}get name(){return this.#Ze}}class vt{#Ye=[];#et=0;get workers(){return this.#Ye}addWorker(e){this.#Ye.includes(e)||this.#Ye.push(e)}removeWorker(e){const t=this.#Ye.indexOf(e);-1!==t&&this.#Ye.splice(t,1)}getNextWorker(){const e=this.#Ye.filter(e=>e.isAvailable());if(0!==e.length)return this.#et>=e.length&&(this.#et=0),e[this.#et++];this.#et=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new yt(e.fqn);return t.run(e)}}class bt{generate(){return _.randomUUID()}}class Mt extends A{#tt;constructor(e){super(`Unknown worker id '${e}'`),this.#tt=e}get id(){return this.#tt}}class xt{#Ye=new Map;#rt=new Map;#st=new bt;#at;constructor(e,t){this.#at=e.create(()=>this.#nt(),t)}get workers(){return[...this.#Ye.values()]}get balancers(){return this.#rt}start(){this.#at.start()}stop(){this.#at.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.#st.generate(),this.#Ye.set(e.id,e);for(const t of e.getProcedureNames()){this.#it(t).addWorker(e)}return e.id}getWorker(e){const t=this.#Ye.get(e);if(void 0===t)throw new Mt(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#Ye.delete(e);for(const e of t.getProcedureNames()){const r=this.#ot(e);void 0!==r&&r.removeWorker(t)}return t}#ot(e){return this.#rt.get(e)}#it(e){let t=this.#ot(e);return void 0===t&&(t=new vt,this.#rt.set(e,t)),t}async run(e){const t=this.#ot(e.fqn);if(void 0===t)throw new Pe(e.fqn);return t.run(e)}async#nt(){const e=this.workers.map(e=>this.#ct(e));await Promise.allSettled(e)}async#ct(e){await e.updateState()===ht.STOPPED&&this.removeWorker(e.id)}}class St{#y;#ut;#lt;#Je=new mt;constructor(e){this.#y=e.url,this.#ut=e.provider,this.#lt=e.runner}get url(){return this.#y}get state(){return this.#Je.state}get trustKey(){return this.#lt.trustKey}get provider(){return this.#ut}get runner(){return this.#lt}async start(){return this.#Je.start(async()=>{await Promise.all([this.#ut.start(),this.#lt.start()]),await this.updateState()})}async stop(){return this.#Je.stop(async()=>{await Promise.allSettled([this.#lt.stop(),this.#ut.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#ut.isHealthy(),this.#lt.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#ut.getHealth(),this.#lt.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#Je.setAvailability(e)}provide(e){return this.#ut.provide(e)}getProcedureNames(){return this.#lt.getProcedureNames()}hasProcedure(e){return this.#lt.hasProcedure(e)}run(e){return this.#lt.run(e)}}class kt{#y;#Ue;#ht;#dt;#pt;#mt;#Je=new mt;constructor(e){this.#y=e.url,this.#Ue=e.healthManager,this.#ht=e.sourcingManager,this.#dt=e.assets,this.#pt=e.indexFilename??"index.html",this.#mt=e.serveIndexOnNotFound??false}get url(){return this.#y}get state(){return this.#Je.state}async start(){return this.#Je.start(async()=>{await this.#Ue.start(),await this.updateState()})}async stop(){return this.#Je.stop(async()=>{await this.#Ue.stop()})}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Je.setAvailability(e)}async provide(e){if(this.#gt(e))return this.provide(this.#pt);if(!1===this.#dt.has(e))throw new V(e);return this.#ht.read(e)}#gt(e){return""===e||e!==this.#pt&&(this.#mt&&!1===this.#dt.has(e))}}class Pt{#y;#Qe;#Je=new mt;constructor(e){this.#y=e.url,this.#Qe=e.remote}get url(){return this.#y}get state(){return this.#Je.state}async start(){return this.#Je.start(async()=>{await this.#Qe.connect(),await this.updateState()})}async stop(){return this.#Je.stop(async()=>{await this.#Qe.disconnect()})}isHealthy(){return this.#Qe.isHealthy()}getHealth(){return this.#Qe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Je.setAvailability(e)}provide(e){return this.#Qe.provide(e)}}class At extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class zt extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class Rt extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Ct extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Et{#wt=[];addSerializer(e){e.parent=this,this.#wt.unshift(e)}async serialize(e){const t=this.#wt.find(t=>t.canSerialize(e));if(void 0===t)throw new Ct(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#wt.find(t=>t.canDeserialize(e));if(void 0===t)throw new Rt(typeof e);return t.deserialize(e)}}class Ht extends Error{constructor(){super("Parent serializer not set")}}class Ot{#ft;set parent(e){this.#ft=e}serializeOther(e){if(void 0===this.#ft)throw new Ht;return this.#ft.serialize(e)}deserializeOther(e){if(void 0===this.#ft)throw new Ht;return this.#ft.deserialize(e)}}class Nt extends Ot{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 Tt extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class It extends Ot{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 Tt(e.value)}}}class jt extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class $t extends Ot{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 jt(e.base64)}}}const Lt=new de;class Ft extends Ot{#yt;constructor(e){super(),this.#yt=e}canSerialize(e){return e instanceof Object&&Lt.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=Lt.getClass(e),r=Lt.fromClass(t,!0),s=this.#vt(r),a=this.#yt.resolveKey(t);if(void 0===a)throw new At(t.name);return{serialized:!0,key:a,name:"class",args:await this.#bt(r,s,e),fields:await this.#Mt(r,s,e)}}#vt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#bt(e,t,r){const s={};for(const[a,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(r[n]):void 0;s[a.toString()]=t}return s}async#Mt(e,t,r){const s={};for(const a of e.writable){const n=a.identifier;t.includes(n)||!1===e.canRead(n)||(s[n]=await this.serializeOther(r[n]))}return s}async deserialize(e){const t=await this.#xt(e);if(void 0===t)throw new At(e.key);if(t instanceof Function==!1)throw new zt(e.key);const r=await this.#St(t,e.args),s=Lt.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#St(e,t){const r=Lt.fromClass(e,!0).construct,s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),a=t[s];return this.deserializeOther(a)});return Promise.all(s)}async#xt(e){return globalThis[e.key]??this.#yt.resolveClass(e.key)}}class qt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class Bt extends Ot{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 qt(e.value);return t}}class Wt extends Ot{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 Dt extends Ot{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,a]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(a));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 a=await this.deserializeOther(t[e]),n=await this.deserializeOther(r[e]);s.set(a,n)}return s}}class Vt extends Ot{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 Kt extends Ot{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 _t extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Ut extends Ot{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 _t(e.source,e.flags)}}}class Gt extends Ot{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 Jt=new de;class Xt extends Ot{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),a=new DataView(s);for(let e=0;e<r.length;e++)a.setUint8(e,r[e]);const n=globalThis[t];return Jt.createInstance(n,[s])}}class Qt extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class Zt extends Ot{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 Qt(e.value)}}}class Yt{static build(e){const t=new Et;return t.addSerializer(new Kt),t.addSerializer(new Vt),void 0!==e&&t.addSerializer(new Ft(e)),t.addSerializer(new Wt),t.addSerializer(new Ut),t.addSerializer(new It),t.addSerializer(new Zt),t.addSerializer(new Bt),t.addSerializer(new Gt),t.addSerializer(new Dt),t.addSerializer(new Nt),t.addSerializer(new Xt),"undefined"!=typeof Buffer&&t.addSerializer(new $t),t}}class er{#kt;constructor(e){this.#kt=e}resolveKey(e){const t=this.#kt.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#kt.getClass(e);return t?.implementation}}class tr extends P{constructor(){super("Request not trusted")}}const rr="X-Jitar-Trust-Key",sr="X-Jitar-Data-Encoding",ar="serialized";class nr{#tt;#y;#_e;#Pt;#At;#kt;#Ue;#zt;#Rt;#Je=new mt;constructor(e){this.#y=e.url,this.#_e=e.trustKey,this.#Pt=e.gateway,this.#At=!0===e.registerAtGateway,this.#kt=e.executionManager,this.#Ue=e.healthManager;const t=e.scheduleManager;this.#zt=t.create(()=>this.#Ct(),e.reportInterval);const r=new er(this.#kt);this.#Rt=Yt.build(r)}get id(){return this.#tt}set id(e){this.#tt=e}get state(){return this.#Je.state}get url(){return this.#y}get trustKey(){return this.#_e}async start(){return this.#Je.start(async()=>{await Promise.all([this.#kt.start(),this.#Ue.start()]),void 0!==this.#Pt&&(await this.#Pt.start(),this.#At&&(this.#tt=await this.#Pt.addWorker(this),this.#zt.start())),await this.updateState()})}async stop(){return this.#Je.stop(async()=>{void 0!==this.#Pt&&(void 0!==this.#tt&&(this.#zt.stop(),await this.#Pt.removeWorker(this.#tt)),await this.#Pt.stop()),await Promise.all([this.#Ue.stop(),this.#kt.stop()])})}getProcedureNames(){return this.#kt.getProcedureNames()}hasProcedure(e){return this.#kt.hasProcedure(e)}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}isAvailable(){return this.#Je.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#Je.setAvailability(e)}async reportState(e){if(void 0!==this.#Pt&&void 0!==this.#tt)return this.#Pt.reportWorker(this.#tt,e)}async run(e){return this.#Et(e)?this.#Ht(e):this.#Ot(e)}#Et(e){return void 0===this.#Pt||this.#kt.hasProcedure(e.fqn)}async#Ht(e){const t=this.#kt.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#Nt(r))throw new Pe(e.fqn);if(this.#Tt(e,r))throw new tr;const s=e.getHeader(sr);s===ar&&(e=await this.#It(e)),e.removeHeader(sr);const a=await this.#kt.run(e);return s===ar?this.#jt(a):a}#Nt(e){return void 0===e||e.private}#Tt(e,t){if(t.public)return!1;const r=e.getHeader(rr);return this.#_e!==r}async#Ot(e){(e=await this.#$t(e)).setHeader(sr,ar),void 0!==this.#_e&&e.setHeader(rr,this.#_e);const t=await this.#Pt.run(e);return this.#Lt(t)}async#$t(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Rt.serialize(s);t.set(r,e)}return new K(e.fqn,e.version,t,e.headers,e.mode)}async#It(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Rt.deserialize(s);t.set(r,e)}return new K(e.fqn,e.version,t,e.headers,e.mode)}async#jt(e){const t=await this.#Rt.serialize(e.result);return new C(e.status,t,e.headers)}async#Lt(e){const t=await this.#Rt.deserialize(e.result);return new C(e.status,t,e.headers)}async#Ct(){const e=await this.updateState();return this.reportState(e)}}class ir extends mt{#Ft;#qt;#Bt=Date.now();#Wt=Date.now();constructor(e=6e3,t=18e3){super(),this.#Ft=e,this.#qt=t}report(e){this.#Bt=Date.now(),this.state=e}update(){this.#Wt=Date.now();const e=this.#Wt-this.#Bt;return e>=this.#Ft&&(this.state=e>=this.#qt?ht.STOPPED:ht.UNAVAILABLE),this.state}}class or{#tt;#y;#_e;#Dt;#Qe;#Je;constructor(e){this.#y=e.url,this.#_e=e.trustKey,this.#Dt=e.procedureNames,this.#Qe=e.remote,this.#Je=new ir(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#tt}set id(e){this.#tt=e}get state(){return this.#Je.state}get url(){return this.#y}get trustKey(){return this.#_e}async start(){return this.#Je.start(async()=>{await this.#Qe.connect(),await this.updateState()})}async stop(){return this.#Je.stop(async()=>{await this.#Qe.disconnect()})}getProcedureNames(){return[...this.#Dt.values()]}hasProcedure(e){return this.#Dt.has(e)}isHealthy(){return this.#Qe.isHealthy()}getHealth(){return this.#Qe.getHealth()}isAvailable(){return this.#Je.isAvailable()}async updateState(){return this.#Je.update()}async reportState(e){this.#Je.report(e)}run(e){return this.#Qe.run(e)}}class cr{#Vt;#Ft;#qt;constructor(e,t,r){this.#Vt=e,this.#Ft=t,this.#qt=r}build(e,t,r){const s=this.#Vt.build(e),a=new Set(t),n=this.#Ft,i=this.#qt;return new or({url:e,trustKey:r,remote:s,procedureNames:a,unavailableThreshold:n,stoppedThreshold:i})}}class ur{#lt;constructor(e){this.#lt=e}async handle(e,t){return this.#lt.run(e)}}class lr{#le=new Ne;constructor(){this.#Kt()}#Kt(){const e=globalThis;e.__run=this.#_t.bind(this),e.ProcedureNotAccessible=Ae}async#_t(e,t,r,s){const a=this.#le.parse(t),n=new Map(Object.entries(r)),i=s instanceof K?s.headers:new Map,o=new K(e,a,n,i,pe),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==ge)throw u.result;return u.result}}const hr="starting",dr="started",pr="stopping",mr="stopped";class gr extends A{constructor(){super("Invalid health check")}}class wr{#De=mr;#Ut=new Map;#G;#Gt;constructor(e,t=[]){this.#G=e,this.#Gt=t}get state(){return this.#De}async start(){if(this.#De===mr)try{this.#De=hr,await this.#Jt(),this.#De=dr}catch(e){throw this.#De=mr,e}}async stop(){if(this.#De===dr)try{this.#De=pr,this.clearHealthChecks(),this.#De=mr}catch(e){throw this.#De=dr,e}}async loadHealthCheck(e){const t=await this.#Xt(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new gr;this.#Ut.set(e.name,e)}clearHealthChecks(){this.#Ut.clear()}async isHealthy(){const e=[];for(const t of this.#Ut.values()){const r=this.#Qt(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.#Ut){const s=this.#Qt(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.#Zt(e,t))).then(()=>t)}async#Jt(){(await Promise.all(this.#Gt.map(e=>this.#Xt(e)))).forEach(e=>this.addHealthCheck(e))}async#Xt(e){return(await this.#G.import(e)).default}#Zt(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#Qt(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 fr="starting",yr="started",vr="stopping",br="stopped";class Mr extends A{constructor(){super("Invalid middleware")}}class xr{#De=br;#Yt=[];#G;#er;constructor(e,t=[]){this.#G=e,this.#er=t}get state(){return this.#De}async start(){if(this.#De===br)try{this.#De=fr,await this.#tr(),this.#De=yr}catch(e){throw this.#De=br,e}}async stop(){if(this.#De===yr)try{this.#De=vr,this.clearMiddlewares(),this.#De=br}catch(e){throw this.#De=yr,e}}async loadMiddleware(e){const t=await this.#rr(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Mr;this.#Yt.push(e)}getMiddleware(e){return this.#Yt.find(t=>t instanceof e)}clearMiddlewares(){this.#Yt=[]}handle(e){return this.#sr(e,0)()}async#tr(){(await Promise.all(this.#er.map(e=>this.#rr(e)))).forEach(e=>this.addMiddleware(e))}async#rr(e){return(await this.#G.import(e)).default}#sr(e,t){const r=this.#Yt[t];if(void 0===r)return async()=>new C(ge);const s=this.#sr(e,t+1);return async()=>await r.handle(e,s)}}class Sr{#Se;#ar;#nr;#ir=null;constructor(e,t,r=5e3){this.#Se=e,this.#ar=t,this.#nr=r}start(){this.#or()}stop(){null!==this.#ir&&(clearTimeout(this.#ir),this.#ir=null)}#or(){this.#ir=setTimeout(async()=>{null!==this.#ir&&(await this.#cr(),this.#or())},this.#nr),this.#ir.unref()}async#cr(){try{await this.#ar()}catch(e){this.#Se.warn("Scheduled task failed",e)}}}class kr{#ur=[];#Se;constructor(e){this.#Se=e}create(e,t){const r=new Sr(this.#Se,e,t);return this.#ur.push(r),r}remove(e){const t=this.#ur.indexOf(e);t<0||this.#ur.splice(t,1)}startAll(){this.#ur.forEach(e=>e.start())}stopAll(){this.#ur.forEach(e=>e.stop())}}const Pr="application/null",Ar="application/undefined",zr="application/boolean",Rr="application/number",Cr="application/json",Er="text/plain",Hr=200,Or=400,Nr=401,Tr=402,Ir=403,jr=404,$r=418,Lr=500,Fr=501;class qr extends lr{#lr;#hr;#dr;#pr;#Se;#le=new Ne;constructor(e){super(),this.#lr=e.proxy,this.#hr=e.remoteWorkerBuilder,this.#dr=e.resourceManager,this.#pr=e.middlewareManager,this.#Se=e.logger}get proxy(){return this.#lr}getTrustKey(){return this.#lr.trustKey}async start(){await this.#mr(),this.#Se.info(`Server started at ${this.#lr.url}`),this.#lr.runner instanceof nr&&this.#Se.info("RPC procedures:",this.#lr.runner.getProcedureNames())}async stop(){await this.#gr(),this.#Se.info("Server stopped")}async getHealth(){try{const e=await this.#lr.getHealth();return this.#Se.debug("Got health"),this.#wr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#Se.error("Failed to get health:",t),this.#fr(e)}}async isHealthy(){try{const e=await this.#lr.isHealthy();return this.#Se.debug("Got health status"),this.#yr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#Se.error("Failed to get health status:",t),this.#fr(e)}}async provide(e){try{const t=await this.#lr.provide(e.filename);return this.#Se.info("Provided file:",e.filename),this.#vr(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#Se.warn("Failed to provide file:",t),this.#fr(e)}}async run(e){try{const t=this.#br(e),r=await this.#pr.handle(t);return this.#Se.info("Ran request:",t.fqn),this.#Mr(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#Se.error("Failed run request:",t),this.#fr(e)}}async runInternal(e){return this.#lr.run(e)}async addWorker(e){try{const t=this.#xr(),r=this.#hr.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#Se.info("Added worker:",r.url),this.#Sr({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#Se.error("Failed to add worker:",t),this.#fr(e)}}async reportWorker(e){try{const t=this.#kr(e.state),r=this.#xr();return await r.reportWorker(e.id,t),this.#Se.debug("Reported worker:",e.id),this.#Sr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#Se.error("Failed to report worker:",t),this.#fr(e)}}async removeWorker(e){try{const t=this.#xr();return await t.removeWorker(e.id),this.#Se.info("Removed worker:",e.id),this.#Sr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#Se.error("Failed to remove worker:",t),this.#fr(e)}}async#mr(){await this.#dr.start(),await Promise.all([this.#lr.start(),this.#pr.start()]);const e=new ur(this.#lr);this.#pr.addMiddleware(e)}async#gr(){await Promise.all([this.#pr.stop(),this.#lr.stop()]),await this.#dr.stop()}#br(e){const t=this.#Pr(e.fqn),r=this.#Ar(e.version),s=this.#zr(e.args),a=this.#Rr(e.headers);return new K(t,r,s,a,e.mode)}#Pr(e){if(0===e.length)throw new w("Missing procedure name");if(e.includes(".."))throw new w("Invalid procedure name");return e}#Ar(e){return"string"!=typeof e?z.DEFAULT:this.#le.parse(e)}#zr(e){return new Map(Object.entries(e))}#Rr(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();t.set(e,a)}return t}#kr(e){if(!1===Object.values(ht).includes(e))throw new w("Invalid state value");return e}#wr(e){return{result:Object.fromEntries(e),contentType:Cr,headers:{},status:Hr}}#yr(e){return{result:e,contentType:zr,headers:{},status:Hr}}#vr(e){return{result:e.content,contentType:e.type,headers:{},status:Hr}}#Mr(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Cr(t),headers:this.#Er(e.headers),status:e.status}}#fr(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Cr(t),headers:{},status:this.#Hr(e)}}#Sr(e){return{result:e,contentType:this.#Cr(e),headers:{},status:Hr}}#Cr(e){if(void 0===e)return Ar;if(null===e)return Pr;switch(typeof e){case"boolean":return zr;case"number":return Rr;case"object":return Cr;default:return Er}}#Er(e){return Object.fromEntries(e)}#Hr(e){return e instanceof w?Or:e instanceof y?Ir:e instanceof f?jr:e instanceof x?Fr:e instanceof S?Tr:e instanceof k?$r:e instanceof P?Nr:Lr}#xr(){const e=this.#lr.runner;if(e instanceof wt==!1)throw new w("Cannot remove worker from remote gateway");return e}}class Br extends Error{constructor(){super("Unknown service configured")}}class Wr{#ht;#Or;#Nr;constructor(e,t=[],r=[]){this.#ht=e,this.#Or=t,this.#Nr=r}async start(){return this.#Tr()}async stop(){return this.#Ir()}#Tr(){return this.#jr(this.#Or)}#Ir(){return this.#jr(this.#Nr)}async#jr(e){await Promise.all(e.map(e=>this.#ht.import(e)))}}class Dr{#ht;#Vt;constructor(e,t){this.#ht=e,this.#Vt=t}async build(e,t){const r=e.setUp,s=e.tearDown,a=e.middleware,n=e.healthChecks,i=new Ge(t),o=this.#$r(n),c=this.#Lr(i),u=await this.#Fr(e,o,c),l=this.#ht,h=this.#qr(r,s),d=this.#Br(a),p=this.#Wr(e);return new qr({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:p,logger:i})}#Fr(e,t,r){if(void 0!==e.gateway)return this.#Dr(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#Vr(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Kr(e.url,e.repository,t);if(void 0!==e.proxy)return this.#_r(e.url,e.proxy);if(void 0!==e.standalone)return this.#Ur(e.url,e.standalone,t,r);throw new Br}async#Dr(e,t,r,s){const a=new dt,n=this.#Gr(e,t,r,s);return new St({url:e,provider:a,runner:n})}async#Vr(e,t,r,s){const a=new dt,n=this.#Jr(e,t,r,s);return new St({url:e,provider:a,runner:n})}async#Kr(e,t,r){const s=await this.#Xr(e,t,r),a=new pt;return new St({url:e,provider:s,runner:a})}#Gr(e,t,r,s){const a=t.trustKey,n=t.monitorInterval,i=new xt(s,n);return new wt({url:e,trustKey:a,healthManager:r,workerManager:i})}#Qr(e){const t=this.#Vt.build(e);return new ft({url:e,remote:t})}#Jr(e,t,r,s){const a=t.trustKey,n=t.gateway?this.#Qr(t.gateway):void 0,i=t.reportInterval,o=void 0!==n,c=this.#Zr(t.segments);return new nr({url:e,trustKey:a,reportInterval:i,gateway:n,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#Xr(e,t,r){const s=void 0!==t.assetRoot?this.#ht.fork(t.assetRoot):this.#ht,a=await this.#Yr(s,t.assets),n=t.indexFilename,i=t.serveIndexOnNotFound;return new kt({url:e,sourcingManager:s,assets:a,indexFilename:n,serveIndexOnNotFound:i,healthManager:r})}#es(e){const t=this.#Vt.build(e);return new Pt({url:e,remote:t})}async#_r(e,t){const r=this.#es(t.repository),s=this.#Qr(t.gateway);return new St({url:e,provider:r,runner:s})}async#Ur(e,t,r,s){const a=await this.#Xr(e,t,r),n=this.#Jr(e,t,r,s);return new St({url:e,provider:a,runner:n})}#qr(e=[],t=[]){const r=e.map(e=>this.#ts(e)),s=t.map(e=>this.#ts(e));return new Wr(this.#ht,r,s)}#$r(e=[]){const t=e.map(e=>this.#ts(e));return new wr(this.#ht,t)}#Br(e=[]){const t=e.map(e=>this.#ts(e));return new xr(this.#ht,t)}#Zr(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new $e(this.#ht,t)}#Lr(e){return new kr(e)}#Wr(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new cr(this.#Vt,t,r)}async#Yr(e,t){if(void 0===t)return new Set;const r=await e.filter(...t);return new Set(r)}#ts(e){return e.endsWith(".js")?e:e+".js"}}const Vr="3000",Kr=204800,_r=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class Ur{#rs;#ss;#as;#ns;#$e=new W;constructor(e,t=Vr,r=Kr){this.#rs=e,this.#ss=t,this.#as=U(),this.#is(r),this.#os()}async start(){return await this.#rs.start(),this.#cs()}async stop(){return await this.#us(),this.#rs.stop()}#is(e){this.#as.use(U.json({limit:e})),this.#as.use(U.urlencoded({extended:!0})),this.#as.use(this.#ls.bind(this)),this.#as.disable(st)}#os(){this.#as.get("/health",(e,t)=>{this.#hs(e,t)}),this.#as.get("/health/status",(e,t)=>{this.#ds(e,t)}),this.#as.get("/rpc/*procedure",(e,t)=>{this.#ps(e,t)}),this.#as.post("/rpc/*procedure",(e,t)=>{this.#ms(e,t)}),this.#as.options("/rpc/*procedure",(e,t)=>{this.#gs(e,t)}),this.#as.post("/workers",(e,t)=>{this.#ws(e,t)}),this.#as.post("/workers/:id/report",(e,t)=>{this.#fs(e,t)}),this.#as.delete("/workers/:id",(e,t)=>{this.#ys(e,t)}),this.#as.use((e,t)=>{this.#vs(e,t)})}#cs(){return void 0!==this.#ns?Promise.resolve():new Promise((e,t)=>{this.#ns=this.#as.listen(this.#ss,t),e()})}#us(){return void 0===this.#ns?Promise.resolve():new Promise(e=>{this.#ns.close(()=>e())})}#ls(e,t,r){t.setHeader(et,at),r()}async#hs(e,t){const r=await this.#rs.getHealth();return this.#bs(t,r)}async#ds(e,t){const r=await this.#rs.isHealthy();return this.#bs(t,r)}async#ps(e,t){const r=this.#Ms(e),s=this.#xs(e),a=this.#Ss(e),n=this.#ks(e),i=pe,o=await this.#rs.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#bs(t,o)}async#ms(e,t){const r=this.#Ms(e),s=this.#xs(e),a=this.#Ps(e),n=this.#ks(e),i=pe,o=await this.#rs.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#bs(t,o)}async#gs(e,t){const r=this.#Ms(e),s=this.#xs(e),a=this.#Ps(e),n=this.#ks(e),i=me,o=await this.#rs.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#bs(t,o)}async#ws(e,t){const r=this.#Ps(e),s=this.#$e.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 a=r.url,n=r.procedureNames,i=r.trustKey;try{const e=await this.#rs.addWorker({url:a,procedureNames:n,trustKey:i});return this.#bs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#fs(e,t){const r={id:e.params.id,state:e.body.state},s=this.#$e.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 a=r.id,n=r.state;try{const e=await this.#rs.reportWorker({id:a,state:n});return this.#bs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ys(e,t){const r={id:e.params.id},s=this.#$e.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id;try{const e=await this.#rs.removeWorker({id:a});return this.#bs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#vs(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),a=await this.#rs.provide({filename:s});return this.#bs(t,a)}#Ms(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#xs(e){const t=e.headers[rt];return Array.isArray(t)?t[0]:t}#Ss(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#Ps(e){return e.body}#ks(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();_r.includes(e)||(t[e]=a)}return t}#bs(e,t){const r=this.#As(t),s=this.#zs(t);e.status(r),e.setHeader(Ye,s),e.setHeader(tt,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const a=this.#Rs(t);return e.send(a)}#As(e){return void 0!==e.headers.location?302:e.status}#zs(e){const t=e.contentType.toLowerCase();switch(t){case zr:case Rr:case Ar:case Pr:return Er}return t}#Rs(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class Gr{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"),a=e.getOptionalArgument("--log-level",void 0),n=this.#Ie(a),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Cs(i),c=new B;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#Es(u,l,o,n);return this.#Hs(h)}async#Es(e,t,r,s){const[,,a]=t.url.split(":"),n=new le(e.target),i=new lt,o=new Dr(n,i),c=await o.build(t,s);return new Ur(c,a,r)}#Hs(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()}#Ie(e){if(void 0===e)return;return(new Xe).parse(e)}#Cs(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class Jr extends Error{constructor(e){super(`Command ${e} not found`)}}class Xr{#s=new Set;constructor(){this.#s.add(new X(this.#s)),this.#s.add(new Q),this.#s.add(new Z),this.#s.add(new ae),this.#s.add(new Ze),this.#s.add(new Gr)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new Jr(e)}}class Qr{#Os;#Ns;constructor(){this.#Os=new J(process.argv),this.#Ns=new Xr}start(){const e=this.#Os.getCommand()??"help";return this.#Ns.run(e,this.#Os)}}try{const e=new Qr;await e.start()}catch(e){const t=new Ge,r=e instanceof Error?e.message:String(e);t.fatal(r)}
|
|
2
|
+
import{promises as e}from"node:fs";import t from"node:path";import{fileURLToPath as r}from"node:url";import{L as s,E as a,P as n,a as i,b as o,c,d as u,e as l,f as h,g as d,h as p,i as m,B as g,N as w,F as f,j as y,A as v,O as b,k as M,l as x,T as S,U as k,S as P,V as A,m as z,R,n as C,o as E,p as H,q as O,r as N,s as T,t as I,u as j,v as $,w as L,x as W,C as q,y as B,z as F,D,G as V}from"./ConfigurationManager-B7adTVpS.js";import K from"node:crypto";import U from"express";import"glob";import"mime-types";import"dotenv";class _ extends Error{constructor(e){super(`Missing argument '${e}'`)}}class G{#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 _(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 J{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.#a(t);this.#n()}#n(){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")}#a(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,a=e.defaultValue?`default: ${e.defaultValue}`:"no default value",n=e.required?"required":`optional - ${a}`;console.log(` ${t} ${r} (${n})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class X{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 Q{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class Z extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class Y extends Error{constructor(e){super(`Unknown template: ${e}`)}}const ee=/^[a-zA-Z.\-_]+$/;class te{#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 Y(t);await this.#p(e,t)}#u(){const e=t.dirname(r(import.meta.url));return t.join(e,"templates")}#l(e){return t.resolve(e)}#h(e,t){if(!1===ee.test(e))throw new Z(e,t)}async#d(r){try{const s=t.join(this.#o,r);return(await e.stat(s)).isDirectory()}catch{return!1}}#p(r,s){const a=t.join(this.#o,s),n=t.join(this.#c,r);return e.cp(a,n,{recursive:!0,force:!0})}}class re{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.#m(t,r),await this.#g(t,r,s),this.#w(t)}#m(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#g(e,t,r){return new te(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`)}}class se extends Error{#f;#y;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#f=e,this.#y=t}get url(){return this.#f}get reason(){return this.#y}}class ae{#v;constructor(e){this.#v=e}async import(e){const t=this.#v.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new se(t,r)}}}class ne{#b;constructor(e){this.#b=e}locate(e){return`file://${e.startsWith("/")?this.#b.getAbsoluteLocation(`.${e}`):this.#b.getAbsoluteLocation(e)}`}}class ie extends ae{constructor(e){super(new ne(e))}}class oe{#b;#M;constructor(e,t){this.#b=e,this.#M=t}get fileManager(){return this.#b}get importManager(){return this.#M}async filter(...e){return(await Promise.all(e.map(e=>this.#b.filter(e)))).flat().map(e=>this.#b.getRelativeLocation(e))}exists(e){return this.#b.exists(e)}read(e){return this.#b.read(e)}import(e){return this.#M.import(e)}}class ce extends oe{constructor(e){const t=new s(e);super(t,new ie(t))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new ce(t)}}class ue{merge(e,t){const r=void 0!==e.construct?[e.construct]:[],s=[...this.#x(e.fields,t.fields),...r,...this.#x(e.methods,t.methods),...this.#x(e.getters,t.getters),...this.#x(e.setters,t.setters)];return new a(e.identifier,t.identifier,s)}#x(e,t){const r=new Map;return t.forEach(e=>r.set(e.identifier,e)),e.forEach(e=>r.set(e.identifier,e)),[...r.values()]}}class le{#S=new n;#k=new ue;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,a]of r){if("function"!=typeof a.toString)continue;const r=a.toString();if(r.startsWith("class"))s.push(this.fromClass(a,t));else if(r.startsWith("function"))s.push(this.fromFunction(a));else{const t=new i(e,!1),a=new o(r);s.push(new c("var",t,a))}}return new u(s)}fromClass(e,t=!1){const r=this.isClass(e)?this.#P(e):this.#A(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const a=this.fromClass(s,!0);return this.#k.merge(r,a)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#S.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")}#P(e){const t=e.toString();return this.#S.parseClass(t)}#A(e){const t=this.createInstance(e),r=this.#z(e,t);return new a(e.name,void 0,r)}#z(e,t){return[...this.#R(t),...this.#C(e)]}#R(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],a=void 0!==t?new o(String(t)):void 0,n=new l(e,"public","instance",a);s.push(n)}return s}#C(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],a=s.value;if(a instanceof Function==!1)continue;const n=this.fromFunction(a);"constructor"===n.identifier?r.push(new h(n.parameters,n.body)):void 0!==s.get?r.push(new d(n.identifier,"public","instance",n.body)):void 0!==s.set?r.push(new p(n.identifier,"public","instance",n.parameters[0],n.body)):r.push(new m(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return r}}const he="normal",de="dry",pe=200,me=400,ge=401,we=402,fe=403,ye=404,ve=418,be=500,Me=501;class xe extends g{#E;constructor(e){super(`Invalid version number '${e}'`),this.#E=e}get number(){return this.#E}}class Se extends w{#H;constructor(e){super(`Procedure '${e}' not found`),this.#H=e}get fqn(){return this.#H}}class ke extends f{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class Pe extends g{#O;constructor(e){super(`Unknown parameter ${e}`),this.#O=e}get parameterName(){return this.#O}}class Ae extends g{#O;constructor(e){super(`Missing value for parameter '${e}'`),this.#O=e}get parameterName(){return this.#O}}class ze extends g{#O;constructor(e){super(`Invalid value for parameter '${e}'`),this.#O=e}get parameterName(){return this.#O}}class Re{extract(e,t){const r=this.#N(e,t),s=[];for(const t of e){const e=this.#T(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new Pe(e)}return s}#N(e,t){const r=new Map;for(const[s,a]of t){if(this.#I(s)){const t=this.#j(s);!0===this.#$(e,t)&&r.set(t,a);continue}r.set(s,a)}return r}#I(e){return e.startsWith("*")}#j(e){return e.substring(1)}#$(e,t){return void 0!==e.find(e=>e.name===t)}#T(e,t,r){return e instanceof y?this.#L(e,t,r):this.#W(e,t)}#L(e,t,r){const s=t.get(e.name);if(this.#q(e,s,r))throw new Ae(e.name);if(this.#B(e,s,r))throw new ze(e.name);return t.delete(e.name),s}#W(e,t){return e instanceof v?this.#F(e,t):this.#D(e,t)}#F(e,t){const r=this.#V(e,t);return void 0!==r?Object.values(r):void 0}#D(e,t){return this.#V(e,t)}#V(e,t){const r=e instanceof v,s={},a=[];let n=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#T(o,t,e);void 0!==u?n=!0:!1===o.isOptional&&a.push(o.name),s[c]=u}if(!0===n&&a.length>0)throw new Ae(a[0]);return n?s:void 0}#q(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#B(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof v&&t instanceof Array==!1||r instanceof b&&t instanceof Object==!1)}}class Ce{toStatus(e){return e instanceof g?me:e instanceof f?fe:e instanceof w?ye:e instanceof M?Me:e instanceof x?we:e instanceof S?ve:e instanceof k?ge:be}fromStatus(e,t){switch(e){case me:return new g(t);case fe:return new f(t);case ye:return new w(t);case Me:return new M(t);case we:return new x(t);case ve:return new S(t);case ge:return new k(t);default:return new P(t)}}}const Ee=/^\d+(?:\.\d+){0,2}$/;class He{parse(e){if(0===e.trim().length)return A.DEFAULT;if(!1===Ee.test(e))throw new xe(e);const t=e.split(".");switch(t.length){case 1:return new A(Number.parseInt(t[0]));case 2:return new A(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new A(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class Oe extends w{#H;#K;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#H=e,this.#K=t}get fqn(){return this.#H}get version(){return this.#K}}class Ne extends P{constructor(){super("Invalid segment")}}class Te{#U=new Map;addSegment(e){this.#U.set(e.id,e)}clearSegments(){this.#U.clear()}getClassNames(){const e=new Set;for(const t of this.#U.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.#U.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#U.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#U.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.#U.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class Ie{#_;#G;#J=new Re;#X=new Ce;#Q=new Te;constructor(e,t=[]){this.#_=e,this.#G=t}async start(){return this.#Z()}async stop(){return this.#Y()}async loadSegment(e){const t=await this.#_.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof z==!1)throw new Ne;this.#Q.addSegment(e)}getClassNames(){return this.#Q.getClassNames()}hasClass(e){return this.#Q.hasClass(e)}getClass(e){return this.#Q.getClass(e)}getClassByImplementation(e){return this.#Q.getClassByImplementation(e)}getProcedureNames(){return this.#Q.getProcedureNames()}hasProcedure(e){return this.#Q.hasProcedure(e)}getProcedure(e){return this.#Q.getProcedure(e)}async run(e){const t=this.#ee(e.fqn,e.version),r=this.#J.extract(t.parameters,e.args);return e.mode===de?new R(pe,void 0):this.#te(e,t,r)}async#Z(){await Promise.all(this.#G.map(e=>this.loadSegment(e)))}#Y(){this.#Q.clearSegments()}#ee(e,t){const r=this.#Q.getProcedure(e);if(void 0===r)throw new Se(e);const s=r.getImplementation(t);if(void 0===s)throw new Oe(r.fqn,t.toString());return s}async#te(e,t,r){try{const s=await t.executable.call(e,...r);return new R(pe,s)}catch(e){const t=this.#X.toStatus(e);return new R(t,e)}}}let je=class{#re;#se=new C;constructor(e){this.#re=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,a=t.modules.map(e=>this.#ae(e,s,r));await Promise.all(a)}async#ae(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#ne(e,t,r);const a=s.map(s=>this.#ie(e,t,s,r)),n=s[0].getModule(e.filename),i=n?.hasImplementations()?this.#oe(e,s):Promise.resolve();await Promise.all([...a,i]),this.#re.delete(e.filename)}async#ne(e,t,r){const s=e.filename,a=new E(e,t,r).generate();return this.#re.write(s,a)}async#ie(e,t,r,s){const a=this.#se.addSubExtension(e.filename,r.name),n=new E(e,t,s,r).generate();return this.#re.write(a,n)}async#oe(e,t){const r=this.#se.addSubExtension(e.filename,"remote"),s=new H(e,t).generate();return this.#re.write(r,s)}};const $e=["Segment","Class","Procedure","Implementation","Version","NamedParameter","ArrayParameter","ObjectParameter"];class Le{#ce;#se=new C;#ue=new He;constructor(e){this.#ce=e}generate(){const e=this.#le(),t=this.#he(),r=this.#de();return new u([...e,t,r]).toString()}#le(){return[this.#pe(),...this.#me()]}#pe(){const e=$e.map(e=>new N(e));return new O(e,"jitar")}#me(){const e=[],t=this.#ce.name,r=this.#ce.getSegmentedModules();for(const s of r){const r=`./${this.#se.addSubExtension(s.filename,t)}`;if(0===s.members.length){const t=new O([],r);e.push(t);continue}const a=s.members.map(e=>new N(e.importKey,e.id)),n=new O(a,r);e.push(n)}return e}#he(){const e=new N("segment","default");return new T([e],void 0)}#de(){const e=[],t=this.#ce.name,r=this.#ce.classes,s=this.#ce.procedures;e.push(`new Segment("${t}")`);for(const t of r)e.push(`\t.addClass(new Class("${t.fqn}", ${t.id}))`);for(const t of s){e.push(`\t.addProcedure(new Procedure("${t.fqn}")`);for(const r of t.implementations){const t=this.#ge(r.version),s=this.#we(r.model);e.push(`\t\t.addImplementation(new Implementation(${t}, "${r.access}", ${s}, ${r.id}))`)}e.push("\t)")}const a=e.join("\n"),n=new o(a),u=new i("segment");return new c("const",u,n)}#ge(e){const t=this.#ue.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#we(e){return`[${this.#fe(e.parameters).join(", ")}]`}#fe(e){const t=[];for(const r of e)t.push(this.#ye(r));return t}#ye(e){return e.binding instanceof I?this.#ve(e):e.binding instanceof j?this.#be(e):this.#Me(e)}#Me(e){return`new NamedParameter("${e.binding}", ${void 0!==e.initializer})`}#ve(e){const t=e.binding;return`new ArrayParameter([${this.#fe(t.elements).join(", ")}])`}#be(e){const t=e.binding;return`new ObjectParameter([${this.#fe(t.elements).join(", ")}])`}}let We=class{#re;#xe;constructor(e,t){this.#re=e,this.#xe=t}async build(e){const t=e.segmentation.segments.map(e=>this.#Se(e));await Promise.all(t)}async#Se(e){const t=`${e.name}.segment.js`,r=new Le(e).generate();await this.#re.write(t,r),this.#xe.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}};class qe{#ke;#Pe;constructor(e,t){const r=e.target;this.#ke=new je(r),this.#Pe=new We(r,t)}async build(e){await Promise.all([this.#ke.build(e),this.#Pe.build(e)])}}const Be=0,Fe=1,De=2,Ve=3,Ke=4;class Ue{#Ae;#ze;constructor(e=Fe,t=console){this.#Ae=e,this.#ze=t}debug(...e){if(this.#Ae>Be)return;const t=this.#Re("DEBUG",e);this.#ze.debug(t)}info(...e){if(this.#Ae>Fe)return;const t=this.#Re("INFO",e);this.#ze.info(t)}warn(...e){if(this.#Ae>De)return;const t=this.#Re("WARN",e);this.#ze.warn(t)}error(...e){if(this.#Ae>Ve)return;const t=this.#Re("ERROR",e);this.#ze.error(t)}fatal(...e){const t=this.#Re("FATAL",e);this.#ze.error(t)}#Re(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Ce(e)).join(" ")}`}#Ce(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#Ee(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#He(t)}${r}`}#Ee(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Ce(e,t)).join(",\n")}\n${this.#He(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#He(e){return" ".repeat(e)}}class _e extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class Ge{parse(e){switch(e.toUpperCase()){case"DEBUG":return Be;case"INFO":return Fe;case"WARN":return De;case"ERROR":return Ve;case"FATAL":return Ke;default:throw new _e(e)}}}class Je{#xe;#se;#b;#Oe;#Ne;constructor(e,t){this.#xe=new Ue(t),this.#se=new C;const r=this.#se.makePathAbsolute(e.source,e.meta.root),a=this.#se.makePathAbsolute(e.target,e.meta.root),n=this.#se.makePathAbsolute(e.resources,e.meta.root),i=this.#se.makePathAbsolute(e.segments,e.meta.root);this.#b=new $(new s(r),new s(a),new s(n),new s(i),e.build.ignore),this.#Oe=new L(this.#b),this.#Ne=new qe(this.#b,this.#xe)}async build(){const e=this.#b.source,t=this.#b.resource,r=this.#b.segment,s=await e.filterWithIgnores(W.MODULE_PATTERN,this.#b.sourceIgnores),a=await t.filter(W.RESOURCE_PATTERN),n=await r.filter(W.SEGMENT_PATTERN),i=await this.#Oe.read(s,a,n);return this.#Ne.build(i)}}class Xe{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),a=this.#Te(s),n=new q;await n.configureEnvironment(t);const i=await n.getRuntimeConfiguration(r);return new Je(i,a).build()}#Te(e){if(void 0===e)return;return(new Ge).parse(e)}}const Qe="content-type",Ze="x-content-type-options",Ye="x-jitar-content-type",et="x-jitar-procedure-version",tt="x-powered-by",rt="nosniff",st="application/json",at="application/octet-stream";class nt extends Error{constructor(){super("Invalid worker id")}}class it{#f;#Ie;#X=new Ce;#je=new B;constructor(e,t){this.#f=e,this.#Ie=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#f}/${e}`,r=await this.#$e(t,{method:"GET"}),s=r.headers.get(Qe)??at,a=await r.arrayBuffer(),n=Buffer.from(a);return new F(e,s,n)}async isHealthy(){const e=`${this.#f}/health/status`,t=await this.#$e(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#f}/health`,t=await this.#$e(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#f}/workers`,a={url:e,procedureNames:t,trustKey:r},n={method:"POST",headers:{"Content-Type":st},body:JSON.stringify(a)},i=await this.#$e(s,n),o=i.headers.get(Qe);if(null===o||!1===o.includes(st))throw new nt;const c=await i.json();if(!1===this.#je.validate(c,{id:{type:"string",required:!0}}).valid)throw new nt;return c.id}async reportWorker(e,t){const r=`${this.#f}/workers/${e}/report`,s={state:t},a={method:"POST",headers:{"Content-Type":st},body:JSON.stringify(s)};await this.#$e(r,a)}async removeWorker(e){const t=`${this.#f}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":st}};await this.#$e(t,r)}async run(e){e.setHeader(Qe,st);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[et]=s;const a=`${this.#f}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:r,body:await this.#Le(t)},i=await this.#$e(a,n,!1),o=i.status,c=await this.#We(i),u=this.#qe(i);return new R(o,c,u)}async#$e(e,t,r=!0){const s=await this.#Ie.execute(e,t);if(r&&this.#Be(s)){const e=await this.#We(s);throw this.#X.fromStatus(s.status,String(e))}return s}#Be(e){return e.status<200||e.status>399}async#Le(e){return JSON.stringify(e)}async#We(e){const t=e.headers.get(Ye)??e.headers.get(Qe);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}#qe(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class ot{async execute(e,t){return fetch(e,t)}}class ct{#Ie;constructor(e=new ot){this.#Ie=e}build(e){return new it(e,this.#Ie)}}const ut={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class lt{get url(){throw new M}get state(){return ut.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return ut.AVAILABLE}provide(e){throw new M}}class ht{get url(){throw new M}get state(){return ut.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 ut.AVAILABLE}getProcedureNames(){throw new M}hasProcedure(e){throw new M}run(e){throw new M}}class dt{#Fe=ut.STOPPED;get state(){return this.#Fe}set state(e){this.#Fe=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.#De(ut.STOPPED)}isStopped(){return this.#Ve(ut.STOPPED)}isAvailable(){return this.#Ve(ut.AVAILABLE)}setStarting(){this.#Fe=ut.STARTING}setAvailable(){this.#Fe=ut.AVAILABLE}setUnavailable(){this.#Fe=ut.UNAVAILABLE}setAvailability(e){return this.#Fe=e?ut.AVAILABLE:ut.UNAVAILABLE,this.#Fe}setStopping(){this.#Fe=ut.STOPPING}setStopped(){this.#Fe=ut.STOPPED}#Ve(...e){return e.includes(this.#Fe)}#De(...e){return!1===this.#Ve(...e)}}class pt extends k{constructor(){super("Invalid trust key")}}class mt{#f;#Ke;#Ue;#_e;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#Ue=e.healthManager,this.#_e=e.workerManager}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await this.#Ue.start(),this.#_e.start(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{this.#_e.stop(),await this.#Ue.stop()})}async isHealthy(){return this.#Ue.isHealthy()}async getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async addWorker(e){if(this.#Je(e.trustKey))throw new pt;return await e.start(),this.#_e.addWorker(e)}getWorker(e){return this.#_e.getWorker(e)}async reportWorker(e,t){return this.#_e.reportWorker(e,t)}async removeWorker(e){return this.#_e.removeWorker(e).stop()}getProcedureNames(){return this.#_e.getProcedureNames()}hasProcedure(e){return this.#_e.hasProcedure(e)}async run(e){return this.#_e.run(e)}#Je(e){return void 0!==this.#Ke&&e!==this.#Ke}}class gt{#f;#Xe;#Ge=new dt;constructor(e){this.#f=e.url,this.#Xe=e.remote}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}getProcedureNames(){throw new M}hasProcedure(e){throw new M}addWorker(e){return this.#Xe.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#Xe.reportWorker(e,t)}removeWorker(e){return this.#Xe.removeWorker(e)}run(e){return this.#Xe.run(e)}}class wt extends P{#Qe;constructor(e){super(`No worker available for procedure '${e}'`),this.#Qe=e}get name(){return this.#Qe}}class ft{#Ze=[];#Ye=0;get workers(){return this.#Ze}addWorker(e){this.#Ze.includes(e)||this.#Ze.push(e)}removeWorker(e){const t=this.#Ze.indexOf(e);-1!==t&&this.#Ze.splice(t,1)}getNextWorker(){const e=this.#Ze.filter(e=>e.isAvailable());if(0!==e.length)return this.#Ye>=e.length&&(this.#Ye=0),e[this.#Ye++];this.#Ye=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new wt(e.fqn);return t.run(e)}}class yt{generate(){return K.randomUUID()}}class vt extends P{#et;constructor(e){super(`Unknown worker id '${e}'`),this.#et=e}get id(){return this.#et}}class bt{#Ze=new Map;#tt=new Map;#rt=new yt;#st;constructor(e,t){this.#st=e.create(()=>this.#at(),t)}get workers(){return[...this.#Ze.values()]}get balancers(){return this.#tt}start(){this.#st.start()}stop(){this.#st.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.#rt.generate(),this.#Ze.set(e.id,e);for(const t of e.getProcedureNames()){this.#nt(t).addWorker(e)}return e.id}getWorker(e){const t=this.#Ze.get(e);if(void 0===t)throw new vt(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#Ze.delete(e);for(const e of t.getProcedureNames()){const r=this.#it(e);void 0!==r&&r.removeWorker(t)}return t}#it(e){return this.#tt.get(e)}#nt(e){let t=this.#it(e);return void 0===t&&(t=new ft,this.#tt.set(e,t)),t}async run(e){const t=this.#it(e.fqn);if(void 0===t)throw new Se(e.fqn);return t.run(e)}async#at(){const e=this.workers.map(e=>this.#ot(e));await Promise.allSettled(e)}async#ot(e){await e.updateState()===ut.STOPPED&&this.removeWorker(e.id)}}class Mt{#f;#ct;#ut;#Ge=new dt;constructor(e){this.#f=e.url,this.#ct=e.provider,this.#ut=e.runner}get url(){return this.#f}get state(){return this.#Ge.state}get trustKey(){return this.#ut.trustKey}get provider(){return this.#ct}get runner(){return this.#ut}async start(){return this.#Ge.start(async()=>{await Promise.all([this.#ct.start(),this.#ut.start()]),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await Promise.allSettled([this.#ut.stop(),this.#ct.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#ct.isHealthy(),this.#ut.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#ct.getHealth(),this.#ut.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}provide(e){return this.#ct.provide(e)}getProcedureNames(){return this.#ut.getProcedureNames()}hasProcedure(e){return this.#ut.hasProcedure(e)}run(e){return this.#ut.run(e)}}class xt{#f;#Ue;#lt;#ht;#dt;#pt;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ue=e.healthManager,this.#lt=e.sourcingManager,this.#ht=e.assets,this.#dt=e.indexFilename??"index.html",this.#pt=e.serveIndexOnNotFound??false}get url(){return this.#f}get state(){return this.#Ge.state}async start(){return this.#Ge.start(async()=>{await this.#Ue.start(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Ue.stop()})}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async provide(e){if(this.#mt(e))return this.provide(this.#dt);if(!1===this.#ht.has(e))throw new D(e);return this.#lt.read(e)}#mt(e){return""===e||e!==this.#dt&&(this.#pt&&!1===this.#ht.has(e))}}class St{#f;#Xe;#Ge=new dt;constructor(e){this.#f=e.url,this.#Xe=e.remote}get url(){return this.#f}get state(){return this.#Ge.state}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}provide(e){return this.#Xe.provide(e)}}class kt extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class Pt extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class At extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class zt extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Rt{#gt=[];addSerializer(e){e.parent=this,this.#gt.unshift(e)}async serialize(e){const t=this.#gt.find(t=>t.canSerialize(e));if(void 0===t)throw new zt(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#gt.find(t=>t.canDeserialize(e));if(void 0===t)throw new At(typeof e);return t.deserialize(e)}}class Ct extends Error{constructor(){super("Parent serializer not set")}}class Et{#wt;set parent(e){this.#wt=e}serializeOther(e){if(void 0===this.#wt)throw new Ct;return this.#wt.serialize(e)}deserializeOther(e){if(void 0===this.#wt)throw new Ct;return this.#wt.deserialize(e)}}class Ht extends Et{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 Ot extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Nt extends Et{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 Ot(e.value)}}}class Tt extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class It extends Et{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 Tt(e.base64)}}}const jt=new le;class $t extends Et{#ft;constructor(e){super(),this.#ft=e}canSerialize(e){return e instanceof Object&&jt.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=jt.getClass(e),r=jt.fromClass(t,!0),s=this.#yt(r),a=this.#ft.resolveKey(t);if(void 0===a)throw new kt(t.name);return{serialized:!0,key:a,name:"class",args:await this.#vt(r,s,e),fields:await this.#bt(r,s,e)}}#yt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#vt(e,t,r){const s={};for(const[a,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(r[n]):void 0;s[a.toString()]=t}return s}async#bt(e,t,r){const s={};for(const a of e.writable){const n=a.identifier;t.includes(n)||!1===e.canRead(n)||(s[n]=await this.serializeOther(r[n]))}return s}async deserialize(e){const t=await this.#Mt(e);if(void 0===t)throw new kt(e.key);if(t instanceof Function==!1)throw new Pt(e.key);const r=await this.#xt(t,e.args),s=jt.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#xt(e,t){const r=jt.fromClass(e,!0).construct,s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),a=t[s];return this.deserializeOther(a)});return Promise.all(s)}async#Mt(e){return globalThis[e.key]??this.#ft.resolveClass(e.key)}}class Lt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class Wt extends Et{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 Lt(e.value);return t}}class qt extends Et{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 Bt extends Et{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,a]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(a));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 a=await this.deserializeOther(t[e]),n=await this.deserializeOther(r[e]);s.set(a,n)}return s}}class Ft extends Et{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 Dt extends Et{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 Vt extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class Kt extends Et{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 Vt(e.source,e.flags)}}}class Ut extends Et{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 _t=new le;class Gt extends Et{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),a=new DataView(s);for(let e=0;e<r.length;e++)a.setUint8(e,r[e]);const n=globalThis[t];return _t.createInstance(n,[s])}}class Jt extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class Xt extends Et{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 Jt(e.value)}}}class Qt{static build(e){const t=new Rt;return t.addSerializer(new Dt),t.addSerializer(new Ft),void 0!==e&&t.addSerializer(new $t(e)),t.addSerializer(new qt),t.addSerializer(new Kt),t.addSerializer(new Nt),t.addSerializer(new Xt),t.addSerializer(new Wt),t.addSerializer(new Ut),t.addSerializer(new Bt),t.addSerializer(new Ht),t.addSerializer(new Gt),"undefined"!=typeof Buffer&&t.addSerializer(new It),t}}class Zt{#St;constructor(e){this.#St=e}resolveKey(e){const t=this.#St.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#St.getClass(e);return t?.implementation}}class Yt extends k{constructor(){super("Request not trusted")}}const er="X-Jitar-Trust-Key",tr="X-Jitar-Data-Encoding",rr="serialized";class sr{#et;#f;#Ke;#kt;#Pt;#St;#Ue;#At;#zt;#Ge=new dt;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#kt=e.gateway,this.#Pt=!0===e.registerAtGateway,this.#St=e.executionManager,this.#Ue=e.healthManager;const t=e.scheduleManager;this.#At=t.create(()=>this.#Rt(),e.reportInterval);const r=new Zt(this.#St);this.#zt=Qt.build(r)}get id(){return this.#et}set id(e){this.#et=e}get state(){return this.#Ge.state}get url(){return this.#f}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await Promise.all([this.#St.start(),this.#Ue.start()]),void 0!==this.#kt&&(await this.#kt.start(),this.#Pt&&(this.#et=await this.#kt.addWorker(this),this.#At.start())),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{void 0!==this.#kt&&(void 0!==this.#et&&(this.#At.stop(),await this.#kt.removeWorker(this.#et)),await this.#kt.stop()),await Promise.all([this.#Ue.stop(),this.#St.stop()])})}getProcedureNames(){return this.#St.getProcedureNames()}hasProcedure(e){return this.#St.hasProcedure(e)}isHealthy(){return this.#Ue.isHealthy()}getHealth(){return this.#Ue.getHealth()}isAvailable(){return this.#Ge.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#Ge.setAvailability(e)}async reportState(e){if(void 0!==this.#kt&&void 0!==this.#et)return this.#kt.reportWorker(this.#et,e)}async run(e){return this.#Ct(e)?this.#Et(e):this.#Ht(e)}#Ct(e){return void 0===this.#kt||this.#St.hasProcedure(e.fqn)}async#Et(e){const t=this.#St.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#Ot(r))throw new Se(e.fqn);if(this.#Nt(e,r))throw new Yt;const s=e.getHeader(tr);s===rr&&(e=await this.#Tt(e)),e.removeHeader(tr);const a=await this.#St.run(e);return s===rr?this.#It(a):a}#Ot(e){return void 0===e||e.private}#Nt(e,t){if(t.public)return!1;const r=e.getHeader(er);return this.#Ke!==r}async#Ht(e){(e=await this.#jt(e)).setHeader(tr,rr),void 0!==this.#Ke&&e.setHeader(er,this.#Ke);const t=await this.#kt.run(e);return this.#$t(t)}async#jt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#zt.serialize(s);t.set(r,e)}return new V(e.fqn,e.version,t,e.headers,e.mode)}async#Tt(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#zt.deserialize(s);t.set(r,e)}return new V(e.fqn,e.version,t,e.headers,e.mode)}async#It(e){const t=await this.#zt.serialize(e.result);return new R(e.status,t,e.headers)}async#$t(e){const t=await this.#zt.deserialize(e.result);return new R(e.status,t,e.headers)}async#Rt(){const e=await this.updateState();return this.reportState(e)}}class ar extends dt{#Lt;#Wt;#qt=Date.now();#Bt=Date.now();constructor(e=6e3,t=18e3){super(),this.#Lt=e,this.#Wt=t}report(e){this.#qt=Date.now(),this.state=e}update(){this.#Bt=Date.now();const e=this.#Bt-this.#qt;return e>=this.#Lt&&(this.state=e>=this.#Wt?ut.STOPPED:ut.UNAVAILABLE),this.state}}class nr{#et;#f;#Ke;#Ft;#Xe;#Ge;constructor(e){this.#f=e.url,this.#Ke=e.trustKey,this.#Ft=e.procedureNames,this.#Xe=e.remote,this.#Ge=new ar(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#et}set id(e){this.#et=e}get state(){return this.#Ge.state}get url(){return this.#f}get trustKey(){return this.#Ke}async start(){return this.#Ge.start(async()=>{await this.#Xe.connect(),await this.updateState()})}async stop(){return this.#Ge.stop(async()=>{await this.#Xe.disconnect()})}getProcedureNames(){return[...this.#Ft.values()]}hasProcedure(e){return this.#Ft.has(e)}isHealthy(){return this.#Xe.isHealthy()}getHealth(){return this.#Xe.getHealth()}isAvailable(){return this.#Ge.isAvailable()}async updateState(){return this.#Ge.update()}async reportState(e){this.#Ge.report(e)}run(e){return this.#Xe.run(e)}}class ir{#Dt;#Lt;#Wt;constructor(e,t,r){this.#Dt=e,this.#Lt=t,this.#Wt=r}build(e,t,r){const s=this.#Dt.build(e),a=new Set(t),n=this.#Lt,i=this.#Wt;return new nr({url:e,trustKey:r,remote:s,procedureNames:a,unavailableThreshold:n,stoppedThreshold:i})}}class or{#ut;constructor(e){this.#ut=e}async handle(e,t){return this.#ut.run(e)}}class cr{#ue=new He;constructor(){this.#Vt()}#Vt(){const e=globalThis;e.__run=this.#Kt.bind(this),e.ProcedureNotAccessible=ke}async#Kt(e,t,r,s){const a=this.#ue.parse(t),n=new Map(Object.entries(r)),i=s instanceof V?s.headers:new Map,o=new V(e,a,n,i,he),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==pe)throw u.result;return u.result}}const ur="starting",lr="started",hr="stopping",dr="stopped";class pr extends P{constructor(){super("Invalid health check")}}class mr{#Fe=dr;#Ut=new Map;#_;#_t;constructor(e,t=[]){this.#_=e,this.#_t=t}get state(){return this.#Fe}async start(){if(this.#Fe===dr)try{this.#Fe=ur,await this.#Gt(),this.#Fe=lr}catch(e){throw this.#Fe=dr,e}}async stop(){if(this.#Fe===lr)try{this.#Fe=hr,this.clearHealthChecks(),this.#Fe=dr}catch(e){throw this.#Fe=lr,e}}async loadHealthCheck(e){const t=await this.#Jt(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new pr;this.#Ut.set(e.name,e)}clearHealthChecks(){this.#Ut.clear()}async isHealthy(){const e=[];for(const t of this.#Ut.values()){const r=this.#Xt(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.#Ut){const s=this.#Xt(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.#Qt(e,t))).then(()=>t)}async#Gt(){(await Promise.all(this.#_t.map(e=>this.#Jt(e)))).forEach(e=>this.addHealthCheck(e))}async#Jt(e){return(await this.#_.import(e)).default}#Qt(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#Xt(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 gr="starting",wr="started",fr="stopping",yr="stopped";class vr extends P{constructor(){super("Invalid middleware")}}class br{#Fe=yr;#Zt=[];#_;#Yt;constructor(e,t=[]){this.#_=e,this.#Yt=t}get state(){return this.#Fe}async start(){if(this.#Fe===yr)try{this.#Fe=gr,await this.#er(),this.#Fe=wr}catch(e){throw this.#Fe=yr,e}}async stop(){if(this.#Fe===wr)try{this.#Fe=fr,this.clearMiddlewares(),this.#Fe=yr}catch(e){throw this.#Fe=wr,e}}async loadMiddleware(e){const t=await this.#tr(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new vr;this.#Zt.push(e)}getMiddleware(e){return this.#Zt.find(t=>t instanceof e)}clearMiddlewares(){this.#Zt=[]}handle(e){return this.#rr(e,0)()}async#er(){(await Promise.all(this.#Yt.map(e=>this.#tr(e)))).forEach(e=>this.addMiddleware(e))}async#tr(e){return(await this.#_.import(e)).default}#rr(e,t){const r=this.#Zt[t];if(void 0===r)return async()=>new R(pe);const s=this.#rr(e,t+1);return async()=>await r.handle(e,s)}}class Mr{#xe;#sr;#ar;#nr=null;constructor(e,t,r=5e3){this.#xe=e,this.#sr=t,this.#ar=r}start(){this.#ir()}stop(){null!==this.#nr&&(clearTimeout(this.#nr),this.#nr=null)}#ir(){this.#nr=setTimeout(async()=>{null!==this.#nr&&(await this.#or(),this.#ir())},this.#ar),this.#nr.unref()}async#or(){try{await this.#sr()}catch(e){this.#xe.warn("Scheduled task failed",e)}}}class xr{#cr=[];#xe;constructor(e){this.#xe=e}create(e,t){const r=new Mr(this.#xe,e,t);return this.#cr.push(r),r}remove(e){const t=this.#cr.indexOf(e);t<0||this.#cr.splice(t,1)}startAll(){this.#cr.forEach(e=>e.start())}stopAll(){this.#cr.forEach(e=>e.stop())}}const Sr="application/null",kr="application/undefined",Pr="application/boolean",Ar="application/number",zr="application/json",Rr="text/plain",Cr=200,Er=400,Hr=401,Or=402,Nr=403,Tr=404,Ir=418,jr=500,$r=501;class Lr extends cr{#ur;#lr;#hr;#dr;#xe;#ue=new He;constructor(e){super(),this.#ur=e.proxy,this.#lr=e.remoteWorkerBuilder,this.#hr=e.resourceManager,this.#dr=e.middlewareManager,this.#xe=e.logger}get proxy(){return this.#ur}getTrustKey(){return this.#ur.trustKey}async start(){await this.#pr(),this.#xe.info(`Server started at ${this.#ur.url}`),this.#ur.runner instanceof sr&&this.#xe.info("RPC procedures:",this.#ur.runner.getProcedureNames())}async stop(){await this.#mr(),this.#xe.info("Server stopped")}async getHealth(){try{const e=await this.#ur.getHealth();return this.#xe.debug("Got health"),this.#gr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to get health:",t),this.#wr(e)}}async isHealthy(){try{const e=await this.#ur.isHealthy();return this.#xe.debug("Got health status"),this.#fr(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to get health status:",t),this.#wr(e)}}async provide(e){try{const t=await this.#ur.provide(e.filename);return this.#xe.info("Provided file:",e.filename),this.#yr(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.warn("Failed to provide file:",t),this.#wr(e)}}async run(e){try{const t=this.#vr(e),r=await this.#dr.handle(t);return this.#xe.info("Ran request:",t.fqn),this.#br(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed run request:",t),this.#wr(e)}}async runInternal(e){return this.#ur.run(e)}async addWorker(e){try{const t=this.#Mr(),r=this.#lr.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#xe.info("Added worker:",r.url),this.#xr({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to add worker:",t),this.#wr(e)}}async reportWorker(e){try{const t=this.#Sr(e.state),r=this.#Mr();return await r.reportWorker(e.id,t),this.#xe.debug("Reported worker:",e.id),this.#xr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to report worker:",t),this.#wr(e)}}async removeWorker(e){try{const t=this.#Mr();return await t.removeWorker(e.id),this.#xe.info("Removed worker:",e.id),this.#xr()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#xe.error("Failed to remove worker:",t),this.#wr(e)}}async#pr(){await this.#hr.start(),await Promise.all([this.#ur.start(),this.#dr.start()]);const e=new or(this.#ur);this.#dr.addMiddleware(e)}async#mr(){await Promise.all([this.#dr.stop(),this.#ur.stop()]),await this.#hr.stop()}#vr(e){const t=this.#kr(e.fqn),r=this.#Pr(e.version),s=this.#Ar(e.args),a=this.#zr(e.headers);return new V(t,r,s,a,e.mode)}#kr(e){if(0===e.length)throw new g("Missing procedure name");if(e.includes(".."))throw new g("Invalid procedure name");return e}#Pr(e){return"string"!=typeof e?A.DEFAULT:this.#ue.parse(e)}#Ar(e){return new Map(Object.entries(e))}#zr(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();t.set(e,a)}return t}#Sr(e){if(!1===Object.values(ut).includes(e))throw new g("Invalid state value");return e}#gr(e){return{result:Object.fromEntries(e),contentType:zr,headers:{},status:Cr}}#fr(e){return{result:e,contentType:Pr,headers:{},status:Cr}}#yr(e){return{result:e.content,contentType:e.type,headers:{},status:Cr}}#br(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Rr(t),headers:this.#Cr(e.headers),status:e.status}}#wr(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Rr(t),headers:{},status:this.#Er(e)}}#xr(e){return{result:e,contentType:this.#Rr(e),headers:{},status:Cr}}#Rr(e){if(void 0===e)return kr;if(null===e)return Sr;switch(typeof e){case"boolean":return Pr;case"number":return Ar;case"object":return zr;default:return Rr}}#Cr(e){return Object.fromEntries(e)}#Er(e){return e instanceof g?Er:e instanceof f?Nr:e instanceof w?Tr:e instanceof M?$r:e instanceof x?Or:e instanceof S?Ir:e instanceof k?Hr:jr}#Mr(){const e=this.#ur.runner;if(e instanceof mt==!1)throw new g("Cannot remove worker from remote gateway");return e}}class Wr extends Error{constructor(){super("Unknown service configured")}}class qr{#lt;#Hr;#Or;constructor(e,t=[],r=[]){this.#lt=e,this.#Hr=t,this.#Or=r}async start(){return this.#Nr()}async stop(){return this.#Tr()}#Nr(){return this.#Ir(this.#Hr)}#Tr(){return this.#Ir(this.#Or)}async#Ir(e){await Promise.all(e.map(e=>this.#lt.import(e)))}}class Br{#lt;#Dt;constructor(e,t){this.#lt=e,this.#Dt=t}async build(e,t){const r=e.setUp,s=e.tearDown,a=e.middleware,n=e.healthChecks,i=new Ue(t),o=this.#jr(n),c=this.#$r(i),u=await this.#Lr(e,o,c),l=this.#lt,h=this.#Wr(r,s),d=this.#qr(a),p=this.#Br(e);return new Lr({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:p,logger:i})}#Lr(e,t,r){if(void 0!==e.gateway)return this.#Fr(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#Dr(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Vr(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Kr(e.url,e.proxy);if(void 0!==e.standalone)return this.#Ur(e.url,e.standalone,t,r);throw new Wr}async#Fr(e,t,r,s){const a=new lt,n=this.#_r(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}async#Dr(e,t,r,s){const a=new lt,n=this.#Gr(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}async#Vr(e,t,r){const s=await this.#Jr(e,t,r),a=new ht;return new Mt({url:e,provider:s,runner:a})}#_r(e,t,r,s){const a=t.trustKey,n=t.monitorInterval,i=new bt(s,n);return new mt({url:e,trustKey:a,healthManager:r,workerManager:i})}#Xr(e){const t=this.#Dt.build(e);return new gt({url:e,remote:t})}#Gr(e,t,r,s){const a=t.trustKey,n=t.gateway?this.#Xr(t.gateway):void 0,i=t.reportInterval,o=void 0!==n,c=this.#Qr(t.segments);return new sr({url:e,trustKey:a,reportInterval:i,gateway:n,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#Jr(e,t,r){const s=void 0!==t.assetRoot?this.#lt.fork(t.assetRoot):this.#lt,a=await this.#Zr(s,t.assets),n=t.indexFilename,i=t.serveIndexOnNotFound;return new xt({url:e,sourcingManager:s,assets:a,indexFilename:n,serveIndexOnNotFound:i,healthManager:r})}#Yr(e){const t=this.#Dt.build(e);return new St({url:e,remote:t})}async#Kr(e,t){const r=this.#Yr(t.repository),s=this.#Xr(t.gateway);return new Mt({url:e,provider:r,runner:s})}async#Ur(e,t,r,s){const a=await this.#Jr(e,t,r),n=this.#Gr(e,t,r,s);return new Mt({url:e,provider:a,runner:n})}#Wr(e=[],t=[]){const r=e.map(e=>this.#es(e)),s=t.map(e=>this.#es(e));return new qr(this.#lt,r,s)}#jr(e=[]){const t=e.map(e=>this.#es(e));return new mr(this.#lt,t)}#qr(e=[]){const t=e.map(e=>this.#es(e));return new br(this.#lt,t)}#Qr(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new Ie(this.#lt,t)}#$r(e){return new xr(e)}#Br(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new ir(this.#Dt,t,r)}async#Zr(e,t){if(void 0===t)return new Set;const r=await e.filter(...t);return new Set(r)}#es(e){return e.endsWith(".js")?e:e+".js"}}const Fr="3000",Dr=204800,Vr=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class Kr{#ts;#rs;#ss;#as;#je=new B;constructor(e,t=Fr,r=Dr){this.#ts=e,this.#rs=t,this.#ss=U(),this.#ns(r),this.#is()}async start(){return await this.#ts.start(),this.#os()}async stop(){return await this.#cs(),this.#ts.stop()}#ns(e){this.#ss.use(U.json({limit:e})),this.#ss.use(U.urlencoded({extended:!0})),this.#ss.use(this.#us.bind(this)),this.#ss.disable(tt)}#is(){this.#ss.get("/health",(e,t)=>{this.#ls(e,t)}),this.#ss.get("/health/status",(e,t)=>{this.#hs(e,t)}),this.#ss.get("/rpc/*procedure",(e,t)=>{this.#ds(e,t)}),this.#ss.post("/rpc/*procedure",(e,t)=>{this.#ps(e,t)}),this.#ss.options("/rpc/*procedure",(e,t)=>{this.#ms(e,t)}),this.#ss.post("/workers",(e,t)=>{this.#gs(e,t)}),this.#ss.post("/workers/:id/report",(e,t)=>{this.#ws(e,t)}),this.#ss.delete("/workers/:id",(e,t)=>{this.#fs(e,t)}),this.#ss.use((e,t)=>{this.#ys(e,t)})}#os(){return void 0!==this.#as?Promise.resolve():new Promise((e,t)=>{this.#as=this.#ss.listen(this.#rs,t),e()})}#cs(){return void 0===this.#as?Promise.resolve():new Promise(e=>{this.#as.close(()=>e())})}#us(e,t,r){t.setHeader(Ze,rt),r()}async#ls(e,t){const r=await this.#ts.getHealth();return this.#vs(t,r)}async#hs(e,t){const r=await this.#ts.isHealthy();return this.#vs(t,r)}async#ds(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#xs(e),n=this.#Ss(e),i=he,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#ps(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#ks(e),n=this.#Ss(e),i=he,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#ms(e,t){const r=this.#bs(e),s=this.#Ms(e),a=this.#ks(e),n=this.#Ss(e),i=de,o=await this.#ts.run({fqn:r,version:s,args:a,headers:n,mode:i});return this.#vs(t,o)}async#gs(e,t){const r=this.#ks(e),s=this.#je.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 a=r.url,n=r.procedureNames,i=r.trustKey;try{const e=await this.#ts.addWorker({url:a,procedureNames:n,trustKey:i});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ws(e,t){const r={id:e.params.id,state:e.body.state},s=this.#je.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 a=r.id,n=r.state;try{const e=await this.#ts.reportWorker({id:a,state:n});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#fs(e,t){const r={id:e.params.id},s=this.#je.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const a=r.id;try{const e=await this.#ts.removeWorker({id:a});return this.#vs(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#ys(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),a=await this.#ts.provide({filename:s});return this.#vs(t,a)}#bs(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#Ms(e){const t=e.headers[et];return Array.isArray(t)?t[0]:t}#xs(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#ks(e){return e.body}#Ss(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),a=s.toString();Vr.includes(e)||(t[e]=a)}return t}#vs(e,t){const r=this.#Ps(t),s=this.#As(t);e.status(r),e.setHeader(Qe,s),e.setHeader(Ye,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const a=this.#zs(t);return e.send(a)}#Ps(e){return void 0!==e.headers.location?302:e.status}#As(e){const t=e.contentType.toLowerCase();switch(t){case Pr:case Ar:case kr:case Sr:return Rr}return t}#zs(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class Ur{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"),a=e.getOptionalArgument("--log-level",void 0),n=this.#Te(a),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Rs(i),c=new q;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#Cs(u,l,o,n);return this.#Es(h)}async#Cs(e,t,r,s){const[,,a]=t.url.split(":"),n=new ce(e.target),i=new ct,o=new Br(n,i),c=await o.build(t,s);return new Kr(c,a,r)}#Es(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()}#Te(e){if(void 0===e)return;return(new Ge).parse(e)}#Rs(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class _r extends Error{constructor(e){super(`Command ${e} not found`)}}class Gr{#s=new Set;constructor(){this.#s.add(new J(this.#s)),this.#s.add(new X),this.#s.add(new Q),this.#s.add(new re),this.#s.add(new Xe),this.#s.add(new Ur)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new _r(e)}}class Jr{#Hs;#Os;constructor(){this.#Hs=new G(process.argv),this.#Os=new Gr}start(){const e=this.#Hs.getCommand()??"help";return this.#Os.run(e,this.#Hs)}}try{const e=new Jr;await e.start()}catch(e){const t=new Ue,r=e instanceof Error?e.message:String(e);t.fatal(r)}
|