jitar 0.10.6 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ConfigurationManager-CYD-3rnJ.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/client.js +1 -1
- package/dist/lib.d.ts +76 -1
- package/dist/lib.js +1 -1
- package/package.json +6 -6
- package/dist/Response-DEjrdAZ9.js +0 -1
|
@@ -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))}#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",w=".json",y="default";class S{#l=0;next(){return"$"+ ++this.#l}}const b="js",A=/\.js$/,I=[".","/","http:","https:"];class v{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 I.some(t=>e.startsWith(t))}}let T=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class O{#h;#p;#d=new v;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 T(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 R=class{#t;#g;constructor(e,t){this.#t=e,this.#g=t}get filename(){return this.#t}get model(){return this.#g}};class N{#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 j extends D{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new j(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 B 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 B(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 U 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 U(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 q extends D{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new q(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 q)}get getters(){return this.members.filter(e=>e instanceof j)}get setters(){return this.members.filter(e=>e instanceof B)}get methods(){return this.members.filter(e=>e instanceof U)}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 U{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 we(e){return e===Ee.OPEN||e===Ee.CLOSE}const ye={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(ye),be=[ye.IMPORT,ye.EXPORT,ye.VAR,ye.LET,ye.CONST,ye.FUNCTION,ye.CLASS,ye.ASYNC],Ae=[ye.VAR,ye.LET,ye.CONST,ye.FUNCTION,ye.CLASS,ye.USING],Ie=[ye.AS,ye.ASYNC,ye.GET,ye.SET,ye.OF,ye.YIELD,ye.FROM,ye.STATIC];function ve(e){return be.includes(e)}function Te(e){return Ae.includes(e)}function Oe(e){return Ie.includes(e)}const Re={OPEN:ne,CLOSE:oe};function Ne(e){return e===Re.OPEN||e===Re.CLOSE}const xe=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function Me(e){return xe.includes(e)}const Ce={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:".."},$e=Object.values(Ce);function Le(e){return $e.includes(e)}const Pe={OPEN:ae,CLOSE:ce};function Fe(e){return e===Pe.OPEN||e===Pe.CLOSE}const Ve={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"},De={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},ke=Object.values(De);function je(e){return ke.includes(e)}class Be{#w;#y;constructor(e){this.#w=e,this.#y=0}get items(){return this.#w}get position(){return this.#y}get size(){return this.#w.length}get eol(){return this.#y>=this.#w.length}get current(){return this.#w[this.#y]}get next(){return this.#w[this.#y+1]}get previous(){return this.#w[this.#y-1]}notAtEnd(){return!1===this.eol}get(e){return this.#w[e]}step(e=1){return this.#y+=e,this.current}stepBack(e=1){return this.#y-=e,this.current}hasNext(){return this.#y+1<this.#w.length}insert(...e){this.#w.splice(this.#y,0,...e)}}class Ue 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 Ge extends Be{}const He=["true","false"];const Ke=["0","1","2","3","4","5","6","7","8","9"],_e=[...Ke,"a","b","c","d","e","f","A","B","C","D","E","F"],We=["0","1"];function ze(e){return Ke.includes(e)}const Ye={GENERATOR:"*",PRIVATE:"#"},Xe=Object.values(Ye);class Qe{tokenize(e){const t=new Ue(e),s=[];let r;for(;t.notAtEnd();){const e=this.#I(t,r);if(void 0===e)break;e.isType(Ve.WHITESPACE)||e.isType(Ve.COMMENT)?t.step():(s.push(e),this.#v(e)&&(r=e),t.step())}return new Ge(s)}#v(e){return!1===[Ve.WHITESPACE,Ve.COMMENT].includes(e.type)}#I(e,t){const s=e.current,r=e.position;if(je(s)){const t=e.position;return new qe(Ve.WHITESPACE,s,r,t)}if(function(e){return te.includes(e)}(s+e.next)){const t=this.#T(e),s=e.position;return new qe(Ve.COMMENT,t,r,s)}if(this.#O(s,t)){const t=this.#R(e),s=e.position;return new qe(Ve.REGEX,t,r,s)}if(this.#N(e,t)){const t=this.#x(e),s=e.position;return new qe(Ve.NUMBER,t,r,s)}if(Me(s)){const t=this.#M(e),s=e.position;return new qe(Ve.LITERAL,t,r,s)}if(Le(s)){const t=this.#C(e),s=e.position;return new qe(Ve.OPERATOR,t,r,s)}if(function(e){return Xe.includes(e)}(s)){const t=this.#C(e),s=e.position;return new qe(Ve.INDICATOR,t,r,s)}if(pe(s)){const t=e.position;return new qe(Ve.DIVIDER,s,r,t)}if(we(s)){const t=e.position;return new qe(Ve.GROUP,s,r,t)}if(Fe(s)){const t=e.position;return new qe(Ve.SCOPE,s,r,t)}if(Ne(s)){const t=e.position;return new qe(Ve.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(Ve.KEYWORD,i,r,n):function(e){return He.includes(e)}(i)?new qe(Ve.BOOLEAN,i,r,n):function(e){return me.includes(e)}(i)?new qe(Ve.NOTHING,i,r,n):new qe(Ve.IDENTIFIER,i,r,n)}#T(e){const t=e.current+e.next===ee.MULTI_START,s=t?ee.MULTI_END:De.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===Ce.DIVIDE&&(void 0===t||([Ve.OPERATOR,Ve.DIVIDER,Ve.KEYWORD].includes(t.type)||[Ee.OPEN,Re.OPEN].includes(t.value)))}#L(e){return je(e)||e==se||!1===this.#P(e)}#R(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Ce.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#L(r)){e.stepBack();break}t+=r,e.step()}return t}#N(e,t){const s=e.current,r=e.next;return!!ze(s)||s===Ce.SUBTRACT&&(!t?.isType(Ve.NUMBER)&&ze(r))}#F(e,t,s){return t?!1===(r=e,_e.includes(r))&&e!==ue:s?!1===function(e){return We.includes(e)}(e)&&e!==ue:!1===ze(e)&&e!==se&&e!==ue&&"e"!==e;var r}#x(e){let t=e.current;t===Ce.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)||je(e)||Le(e)||Me(e)||pe(e)||we(e)||Fe(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===Le(s)||!1===Le(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Je extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Ze extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class et extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class tt extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class st extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}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="",t=new qe(Ve.NOTHING,"",0,0);for(const s of this.#V){e+=`${this.#D(t,s)?" ":""}${s.value}`,t=s}return e}#D(e,t){return!(!e.isType(Ve.KEYWORD)||!this.#k(e))||!(!e.isType(Ve.OPERATOR)||!t.isType(Ve.OPERATOR))}#k(e){return Te(e.value)||e.hasValue(ye.RETURN)||e.hasValue(ye.ASYNC)||e.hasValue(ye.AWAIT)||e.hasValue(ye.YIELD)||e.hasValue(ye.NEW)||e.hasValue(ye.THROW)}}const it="default";class nt{#j;constructor(e=new Qe){this.#j=e}parse(e){const t=this.#j.tokenize(e),s=this.#B(t);return new Q(s)}parseStatement(e){const t=this.#j.tokenize(e),s=this.#U(t);if(void 0===s)throw new tt("a statement");return s}parseImport(e){const t=this.#j.tokenize(e),s=this.#q(t);if(s instanceof Y==!1)throw new tt("an import definition");return s}parseExport(e){const t=this.#j.tokenize(e),s=this.#q(t);if(s instanceof H==!1)throw new tt("an export definition");return s}parseVariable(e){const t=this.#j.tokenize(e),s=this.#q(t);if(s instanceof X==!1)throw new tt("a variable definition");return s}parseFunction(e){const t=this.#j.tokenize(e),s=this.#q(t);if(s instanceof L==!1)throw new tt("a function definition");return s}parseClass(e){const t=this.#j.tokenize(e),s=this.#q(t);if(s instanceof G==!1)throw new tt("a class definition");return s}#B(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.#G(s))return this.#H(e);if(s.isType(Ve.IDENTIFIER)){const s=e.next;return s?.hasValue(Ce.ARROW)?this.#K(e,t):this.#H(e)}if(s.isType(Ve.KEYWORD)){if(Oe(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(ye.FUNCTION)||t.hasValue(Ee.OPEN));if(s.hasValue(ye.ASYNC)&&r)return e.step(),this.#U(e,!0);if(void 0===t||this.#_(t))return this.#H(e)}return s.hasValue(ye.RETURN)?this.#H(e):!1===ve(s.value)?this.#H(e):this.#q(e,t)}if(s.isType(Ve.REGEX))return this.#H(e);if(s.hasValue(Ee.OPEN)){const s=this.#W(e,Ee.OPEN,Ee.CLOSE);return s?.hasValue(Ce.ARROW)?this.#K(e,t):this.#H(e)}if(s.hasValue(Pe.OPEN))return this.#H(e);if(s.hasValue(Re.OPEN))return this.#H(e);if(s.hasValue(Ce.NOT)||s.hasValue(Ce.SUBTRACT))return this.#H(e);if(!pe(s.value))throw new st(s.value,s.start);e.step()}#G(e){return e.isType(Ve.LITERAL)||e.isType(Ve.NUMBER)||e.isType(Ve.BOOLEAN)||e.isType(Ve.NOTHING)||e.hasValue(ye.NEW)}#q(e,t=!1){const s=e.current;switch(e.step(),s.value){case ye.IMPORT:return this.#z(e);case ye.EXPORT:return this.#Y(e);case ye.CLASS:return this.#X(e);case ye.FUNCTION:return this.#Q(e,t);case ye.VAR:return this.#J(e,"var");case ye.LET:return this.#J(e,"let");case ye.CONST:return this.#J(e,"const");case ye.ASYNC:return this.#U(e,!0);default:throw new et(s.value,s.start)}}#z(e){const t=[];let s=e.current;if(s.isType(Ve.LITERAL)){const e=this.#Z(s.value);return new Y(t,e)}if(s.hasValue(Ee.OPEN)){s=e.step();const r=this.#Z(s.value);return e.step(2),new Y(t,r)}if(!1===s.hasValue(Pe.OPEN)){const r=s.hasValue(Ce.MULTIPLY)?Ce.MULTIPLY:it;let i=s.value;s=e.step(),s.hasValue(ye.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(Pe.OPEN)){const r=this.#ee(e);t.push(...r),s=e.current}if(!1===s.hasValue(ye.FROM))throw new Je(ye.FROM,s.start);s=e.step();const r=this.#Z(s.value);return e.step(),new Y(t,r)}#Y(e){switch(e.current.value){case ye.DEFAULT:return e.step(),this.#te(e,!0);case Pe.OPEN:return this.#se(e);default:return this.#te(e,!1)}}#te(e,t){let s=e.current,r=0;if(t&&this.#re(e)){const t=`$_EXPORT_${s.start}_${s.end}`;e.insert(new qe(Ve.KEYWORD,ye.CONST,0,0),new qe(Ve.IDENTIFIER,t,0,0),new qe(Ve.OPERATOR,Ce.ASSIGN,0,0)),s=e.current}s.hasValue(ye.ASYNC)&&(s=e.step(),r++),Te(s.value)&&(s=e.step(),r++);const i=this.#P(s)?s.value:"",n=t?it:void 0;let o;s=e.step(),s?.hasValue(ye.FROM)&&(s=e.step(),o=this.#Z(s.value)),r>0&&(r++,e.stepBack(r));const a=new J(i,n);return new H([a],o)}#re(e){const t=e.current;if(this.#G(t))return!0;const s=e.next;return this.#P(t)&&s?.hasValue(Ee.OPEN)}#se(e){const t=this.#ee(e);let s,r=e.current;return r?.hasValue(ye.FROM)&&(r=e.step(),s=this.#Z(r.value)),e.step(),new H(t,s)}#Z(e){return e.slice(1,-1)}#ee(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Pe.CLOSE)){e.step();break}if(s.hasValue(le.SEPARATOR)){s=e.step();continue}const r=this.#ie(e);t.push(r),s=e.step()}return t}#ie(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(ye.AS)&&(t=e.step(2),r=t.value),new J(s,r)}#J(e,t){const s=this.#ne(e),r=this.#oe(e);return new X(t,s,r)}#ne(e){const t=e.current;return t.hasValue(Re.OPEN)?this.#ae(e):t.hasValue(Pe.OPEN)?this.#ce(e):this.#ue(e)}#ae(e){const t=this.#le(e,Re.CLOSE);return new M(t)}#ce(e){const t=this.#le(e,Pe.CLOSE);return new Z(t)}#le(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.#ne(e),n=this.#oe(e),o=new F(i,n);s.push(o)}return s}#ue(e){let t=e.current,s=!1;t.hasValue(Ce.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new z(r,s)}#oe(e){const t=e.current;if(!1!==t.hasValue(Ce.ASSIGN))return e.step(),this.#U(e,!1);t.hasValue(le.TERMINATOR)&&e.step()}#Q(e,t){let s,r=e.current,i=!1;r.hasValue(Ye.GENERATOR)&&(i=!0,r=e.step()),this.#P(r)&&(s=r.value,e.step());const n=this.#le(e,Ee.CLOSE);if(r=e.current,!1===r.hasValue(Pe.OPEN))throw new Ze(Pe.OPEN,r.start);const o=this.#he(e);return i?new _(s,n,o,t):new L(s,n,o,t)}#K(e,t){let s,r,i=e.current;if(i.hasValue(Ee.OPEN))s=this.#le(e,Ee.CLOSE);else{const t=this.#ue(e);s=[new F(t,void 0)]}if(i=e.current,!1===i.hasValue(Ce.ARROW))throw new Ze(Ce.ARROW,i.start);if(i=e.step(),i.hasValue(Pe.OPEN))r=this.#he(e);else{const t=this.#H(e);r=new V(t.code)}return new P(s,r,t)}#X(e){let t,s,r=e.current;if(this.#P(r)&&(t=r.value,r=e.step()),r.hasValue(ye.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(Pe.OPEN))throw new Ze(Pe.OPEN,r.start);const i=this.#pe(e);return new G(t,s,i)}#pe(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Pe.CLOSE)){e.step();break}const r=this.#de(e);s.push(r),t=e.current}return s}#de(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(Ye.PRIVATE))s="private";else if(t.hasValue(ye.STATIC))r="static";else{if(!t.hasValue(ye.ASYNC)){if(t.hasValue(ye.CONSTRUCTOR))return this.#me(e);if(t.hasValue(ye.GET))return this.#fe(e,r);if(t.hasValue(ye.SET))return this.#ge(e,r);if(t.hasValue(Ye.GENERATOR))return e.step(),this.#Ee(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(Ee.OPEN)?this.#Ee(e,s,r,i,!1):this.#we(e,s,r)}#me(e){e.step();const t=this.#le(e,Ee.CLOSE),s=e.current;if(!1===s.hasValue(Pe.OPEN))throw new Ze(Pe.OPEN,s.start);const r=this.#he(e);return new k(t,r)}#fe(e,t){let s="public",r=e.step();r.hasValue(Ye.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#le(e,Ee.CLOSE).length)throw new tt("an empty parameter list");if(r=e.current,!1===r.hasValue(Pe.OPEN))throw new Ze(Pe.OPEN,r.start);const n=this.#he(e);return new j(i,s,t,n)}#ge(e,t){let s="public",r=e.step();r.hasValue(Ye.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#le(e,Ee.CLOSE);if(r=e.current,1!==n.length)throw new tt("exactly one setter parameter");if(!1===r.hasValue(Pe.OPEN))throw new Ze(Pe.OPEN,r.start);const o=this.#he(e);return new B(i,s,t,n[0],o)}#Ee(e,t,s,r,i){let n=e.current;const o=n.value;e.step();const a=this.#le(e,Ee.CLOSE);if(n=e.current,!1===n.hasValue(Pe.OPEN))throw new Ze(Pe.OPEN,n.start);const c=this.#he(e);return i?new W(o,t,s,a,c,r):new U(o,t,s,a,c,r)}#we(e,t,s){const r=e.current.value;e.step();const i=this.#oe(e);return new q(r,t,s,i)}#he(e){const t=this.#ye(e,Pe.OPEN,Pe.CLOSE).generate();return new V(t)}#H(e){const t=new rt;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(Re.OPEN)){const r=this.#ye(e,Re.OPEN,Re.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Ee.OPEN)){const r=this.#ye(e,Ee.OPEN,Ee.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Pe.OPEN)){const r=this.#ye(e,Pe.OPEN,Pe.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#_(s)){s.hasValue(le.TERMINATOR)&&e.step();break}}const r=t.generate();return new K(r)}#ye(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.#ye(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}#W(e,t,s){const r=e.position;this.#ye(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#_(e){return[le.TERMINATOR,le.SEPARATOR].includes(e.value)||[Re.CLOSE,Ee.CLOSE,Pe.CLOSE].includes(e.value)||ve(e.value)}#P(e){return e.isType(Ve.IDENTIFIER)||e.isType(Ve.KEYWORD)&&Oe(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 v;constructor(e){this.#p=e}rewrite(e,t){e.imports.forEach(e=>this.#Se(e,t)),e.exports.forEach(e=>this.#be(e,t))}#Se(e,t){const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Ae(t,s))}#be(e,t){if(void 0===e.from)return;const s=this.#p.normalizeLocation(e.from);!1!==this.#d.isApplicationModule(s)&&(e.from=this.#Ae(t,s))}#Ae(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 N(t)}async read(e){try{const t=this.#p.getRelativeLocation(e),s=await this.#Te(e),r=this.#Ie.parse(s);return this.#ve.rewrite(r,t),new R(t,r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new ot(e,s)}}async#Te(e){return(await this.#p.getContent(e)).toString()}},ut=class{#Oe;#E=new Map;#Re=new Map;#Ne=new Map;constructor(e){this.#Oe=e}get name(){return this.#Oe}get modules(){return[...this.#E.values()]}get classes(){return[...this.#Re.values()]}get procedures(){return[...this.#Ne.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.#Ne.has(e)}getProcedure(e){return this.#Ne.get(e)}setProcedure(e){this.#Ne.set(e.fqn,e)}setClass(e){this.#Re.set(e.fqn,e)}};class lt{#l;#xe;#Me;constructor(e,t,s){this.#l=e,this.#xe=t,this.#Me=s}get id(){return this.#l}get importKey(){return this.#xe}get fqn(){return this.#Me}}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{#Ce;#$e;#g;constructor(e,t,s,r,i,n){super(e,t,s),this.#Ce=r,this.#$e=i,this.#g=n}get access(){return this.#Ce}get version(){return this.#$e}get model(){return this.#g}}class dt{#t;#e;#Le;#Pe=[];#Fe;constructor(e,t,s,r){this.#t=e,this.#e=t,this.#Le=s,this.#Fe=r}get filename(){return this.#t}get location(){return this.#e}get imports(){return this.#Le}get members(){return this.#Pe}get segmented(){return this.#Fe}hasClasses(){return this.#Pe.some(e=>e instanceof ht)}getClasses(){return this.#Pe.filter(e=>e instanceof ht)}hasImplementations(){return this.#Pe.some(e=>e instanceof pt)}getImplementations(){return this.#Pe.filter(e=>e instanceof pt)}addMember(e){this.#Pe.push(e)}addImports(e){const t=Object.keys(e);for(const s of t){const t=s.trim();this.#Le[t]=e[s]}}}class mt{#Me;#Ve=[];constructor(e,t=[]){this.#Me=e,this.#Ve=t}get fqn(){return this.#Me}get implementations(){return this.#Ve}addImplementation(e){this.#Ve.push(e)}}class ft{#De;constructor(e){this.#De=e}get segments(){return this.#De}getSegment(e){return this.#De.find(t=>t.name===e)}isSegmentedModule(e){return this.#De.some(t=>t.hasModule(e))}getSegments(e){return this.#De.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 wt extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class yt 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 v;constructor(e){this.#a=e}locate(e,t){const s=[];return{trace:s,model:this.#ke(e,t,s)}}#ke(e,t,s){s.push({filename:e,importKey:t});const r=this.#je(e);return this.#Be(r,t)?this.#Ue(r,t,s):this.#qe(r,t)}#je(e){const t=this.#a.get(e);if(void 0===t)throw new bt(e);return t}#Be(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.#Ge(e,t)??this.#He(e,t),i=r?.from,n=r?.name,o=this.#d.extractPath(e.filename),a=i,c=this.#d.makePathAbsolute(a,o,"");return this.#ke(c,n,s)}#qe(e,t){const s=this.#He(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}#He(e,t){const s=e.model.getExport(t),r=s?.getMember(t);if(void 0!==r)return{from:s?.from,name:r.identifier}}#Ge(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 It{#Ke;#p;#_e;#d=new v;constructor(e,t,s){this.#Ke=e,this.#p=t,this.#_e=new At(s)}async readAll(e){const t=await Promise.all(e.map(e=>this.#We(e)));return new ft(t)}async#We(e){const t=await this.#ze(e),s=this.#Ye(e),r=new ut(s);return this.#Xe(r,t),this.#Qe(r),r}#Ye(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new Et(e);return t.replace(w,"")}async#ze(e){try{const t=await this.#Ke.getContent(e);return JSON.parse(t.toString())}catch(t){const s=t instanceof Error?t.message:String(t);throw new wt(e,s)}}#Xe(e,t){for(const[s,r]of Object.entries(t))this.#Je(e,s,r,!0)}#Je(e,t,s,r){const i=this.#Ze(t),n=this.#d.extractPath(i),o=e.hasModule(i)?e.getModule(i):new dt(i,n,{},r);o.addImports(s),e.setModule(o)}#Ze(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}#Qe(e){const t=new S;for(const s of e.modules)for(const r in s.imports)this.#et(e,s,r,t)}#et(e,t,s,r){const{model:i,trace:n}=this.#_e.locate(t.filename,s),o=this.#tt(t,i,s,r);this.#st(e,t,i,o),n.shift();for(const t of n){const s={[t.importKey]:{access:o.access}};this.#Je(e,t.filename,s,!1)}}#tt(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.#rt(e,o,s)}}#rt(e,t,s){return this.#it(e)?t:this.#nt(e)&&this.#ot(s)?e.location:`${e.location}/${t}`}#it(e){return""===e.location}#nt(e){return e.filename.endsWith(E)}#ot(e){return e===y}#st(e,t,s,r){if(s instanceof G)return this.#at(e,t,s,r);if(s instanceof L)return this.#ct(e,t,s,r);throw new yt(t.filename,r.importKey)}#at(e,t,s,r){const i=new ht(r.id,r.importKey,r.fqn,s);t.addMember(i),e.setClass(i)}#ct(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.#ut(e,t,i)}#ut(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 vt{#lt;constructor(e){this.#lt=e}async read(e,t,s){const r=this.#lt.source,i=this.#lt.resource,n=this.#lt.segment,o=new ct(r),a=await o.readAll(e),c=new O(i,r),u=await c.readAll(t),l=new It(n,r,a),h=await l.readAll(s);return new d(a,u,h)}}class Tt extends Error{constructor(e){super(`Could not find the rewrite item: ${e}`)}}class Ot{#ht;#c;#u;#pt;#d=new v;constructor(e,t,s,r){this.#ht=e,this.#c=t,this.#u=s,this.#pt=r}generate(){const e=this.#ht.model.clone();return this.#dt(e,e.imports),this.#dt(e,e.exports),e.toString()}#dt(e,t){for(const s of t){const t=this.#mt(s);if(0===t.length)continue;const r=e.statements.indexOf(s);if(-1===r)throw new Tt(s.toString());e.statements.splice(r,1,...t)}}#mt(e){if(this.#ft(e))return[];const t=this.#gt(e);return this.#c.isResourceModule(t)?this.#Et(e,t):this.#wt(e,t)}#ft(e){return void 0===e.from||this.#yt(e)}#yt(e){return!1===this.#d.isApplicationModule(e.from)}#gt(e){const t=e.from,s=this.#d.extractPath(this.#ht.filename);return this.#d.makePathAbsolute(t,s,"")}#Et(e,t){const s=e.clone();return s.from=this.#St(t),[s]}#wt(e,t){if(0===e.members.length)return[this.#bt(t,e,[])];const{segmentKeys:s,remoteKeys:r,commonKeys:i}=this.#At(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.#bt(t,e,i)),n}#At(e,t){const s=this.#Tt(e,this.#pt),r=this.#Ot(e,s),i=this.#Rt(t,s),n=this.#Rt(t,r);return{segmentKeys:i,remoteKeys:n,commonKeys:this.#Nt(t,[...i,...n])}}#Tt(e,t){if(void 0===t)return[];const s=t.getModule(e);return void 0===s?[]:Object.keys(s.imports)}#Ot(e,t){const s=this.#u.getSegments(e).filter(e=>e!==this.#pt).flatMap(t=>this.#Tt(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)}#Nt(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.#St(e,this.#pt?.name),r.members=this.#xt(t.members,s),r}#vt(e,t,s){const r=t.clone();return r.from=this.#St(e,"remote"),r.members=this.#xt(t.members,s),r}#bt(e,t,s){const r=t.clone();return r.from=this.#St(e),r.members=this.#xt(t.members,s),r}#xt(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}#St(e,t){const s=this.#d.extractPath(this.#ht.filename),r=this.#d.makePathRelative(e,s);return void 0!==t?this.#d.addSubExtension(r,t):r}}const Rt={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};class Nt 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;#Ne=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.#Ne.set(e.fqn,e),this}hasProcedure(e){return this.#Ne.has(e)}getProcedure(e){return this.#Ne.get(e)}getExposedProcedures(){return[...this.#Ne.values()].filter(e=>e.public||e.protected)}}class Dt{static get DEFAULT(){return new Dt(0,0,0)}#Mt;#Ct;#$t;constructor(e=0,t=0,s=0){this.#Mt=e,this.#Ct=t,this.#$t=s}get major(){return this.#Mt}get minor(){return this.#Ct}get patch(){return this.#$t}equals(e){return this.#Mt===e.major&&this.#Ct===e.minor&&this.#$t===e.patch}greater(e){return this.#Mt!==e.major?this.#Mt>e.major:this.#Ct!==e.minor?this.#Ct>e.minor:this.#$t!==e.patch&&this.#$t>e.patch}less(e){return this.#Mt!==e.major?this.#Mt<e.major:this.#Ct!==e.minor?this.#Ct<e.minor:this.#$t!==e.patch&&this.#$t<e.patch}toString(){return`${this.#Mt}.${this.#Ct}.${this.#$t}`}}class kt{#Oe;#Lt;constructor(e,t=!1){this.#Oe=e,this.#Lt=t}get name(){return this.#Oe}get isOptional(){return this.#Lt}}class jt extends kt{}class Bt extends kt{#Pt;constructor(e,t,s){super(t??"(anonymous)",s),this.#Pt=e}get variables(){return this.#Pt}}class Ut extends Bt{}class qt extends Bt{}class Gt{#Me;#$e;#Ft;#Vt=new Map;#Dt;constructor(e,t,s,r,i){this.#Me=e,this.#$e=t,this.#Ft=s,this.#Vt=r,this.#Dt=i}get fqn(){return this.#Me}get version(){return this.#$e}get args(){return this.#Ft}get headers(){return this.#Vt}get mode(){return this.#Dt}clearArguments(){this.#Ft.clear()}setArgument(e,t){this.#Ft.set(e,t)}getArgument(e){return this.#Ft.get(e)}hasArgument(e){return this.#Ft.has(e)}removeArgument(e){this.#Ft.delete(e)}clearHeaders(){this.#Vt.clear()}setHeader(e,t){this.#Vt.set(e.toLowerCase(),t)}getHeader(e){return this.#Vt.get(e.toLowerCase())}hasHeader(e){return this.#Vt.has(e.toLowerCase())}removeHeader(e){this.#Vt.delete(e.toLowerCase())}}class Ht{#kt;#jt;#Vt;constructor(e,t=void 0,s=new Map){this.#kt=e,this.#jt=t,this.#Vt=s}get status(){return this.#kt}get result(){return this.#jt}set result(e){this.#jt=e}get headers(){return this.#Vt}clearHeaders(){this.#Vt.clear()}setHeader(e,t){this.#Vt.set(e.toLowerCase(),t)}getHeader(e){return this.#Vt.get(e.toLowerCase())}hasHeader(e){return this.#Vt.has(e.toLowerCase())}removeHeader(e){this.#Vt.delete(e.toLowerCase())}}class Kt{#ht;#De;constructor(e,t){this.#ht=e,this.#De=t}generate(){const e=[],t=this.#Bt();for(const s of t){const t=s.access===Rt.PRIVATE?this.#Ut(s):this.#qt(s);e.push(...t)}return new Q(e).toString()}#Bt(){const e=this.#De.map(e=>e.getModule(this.#ht.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.#Gt(e),this.#Ht(e,t)]}#qt(e){const t=`return __run('${e.fqn}','${e.version}',{${this.#Kt(e.model.parameters)}},this);`;return[this.#Gt(e),this.#Ht(e,t)]}#Gt(e){const t=e.model.identifier,s=e.importKey===y?y:void 0,r=new J(t,s);return new H([r],void 0)}#Ht(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)}#Kt(e){return this.#_t(e).join(",")}#_t(e){const t=[];for(const s of e)if(s.binding instanceof z){const e=this.#Wt(s.binding);t.push(e)}else if(s.binding instanceof M){const e=this.#_t(s.binding.elements);t.push(...e)}else if(s.binding instanceof Z){const e=this.#_t(s.binding.elements);t.push(...e)}return t}#Wt(e){return`'${e.identifier}':${e.toString()}`}}class _t{#zt;#Yt;#Xt;#pt;constructor(e,t,s,r){this.#zt=e,this.#Yt=t,this.#Xt=s,this.#pt=r}get source(){return this.#zt}get target(){return this.#Yt}get resource(){return this.#Xt}get segment(){return this.#pt}}class Wt{#Qt;constructor(e=!0){this.#Qt=e}validate(e,t){const s=[];this.#Jt("",e,t,s);return{valid:0===s.length,errors:s}}#Jt(e,t,s,r){this.#Qt&&this.#Zt(e,t,s,r),this.#es(e,t,s,r)}#Zt(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.#ts(e,t);r.push(`Unknown field '${s}'`)}}#es(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#ts(e,n),o=s[n],a=t[n];this.#ss(i,a,o,r)}}#ss(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#rs(e,t,s,r);case"integer":return this.#is(e,t,s,r);case"real":return this.#ns(e,t,s,r);case"boolean":return this.#os(e,t,s,r);case"url":return this.#as(e,t,s,r);case"group":return this.#cs(e,t,s,r);case"list":return this.#us(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#rs(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#is(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#ns(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#os(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#as(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#cs(e,t,s,r){"object"==typeof t?this.#Jt(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#us(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.#ts(e,t),o=i[t];this.#ss(n,o,s.items,r)}}#ts(e,t){return""===e?t:`${e}.${t}`}}class zt{#ls;constructor(e){this.#ls=e}async configure(e){const t=this.#ls.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={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1}};let ss=class{#hs;#ps;constructor(e,t){this.#hs=e,this.#ps=t}async build(e=Xt){const t=await this.#hs.read(e),s=this.#ps.validate(t,ts);if(!1===s.valid)throw new Yt(s);return t.source??=Qt,t.target??=Jt,t.segments??=Zt,t.resources??=es,t.meta={root:this.#hs.getRootLocation(),configFile:e},t}};const rs="\n => ";class is extends Error{constructor(e){const t=e.errors.join(rs);super(`Invalid server configuration:${rs}${t}`)}}const ns={indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assetRoot:{type:"string",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}},os={gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}},as={url:{type:"url",required:!0},setUp:{type:"list",required:!1,items:{type:"string"}},tearDown:{type:"list",required:!1,items:{type:"string"}},middleware:{type:"list",required:!1,items:{type:"string"}},healthChecks:{type:"list",required:!1,items:{type:"string"}},gateway:{type:"group",required:!1,fields:{monitorInterval:{type:"integer",required:!1},trustKey:{type:"string",required:!1}}},proxy:{type:"group",required:!1,fields:{gateway:{type:"url",required:!0},repository:{type:"url",required:!0}}},repository:{type:"group",required:!1,fields:ns},standalone:{type:"group",required:!1,fields:{...ns,segments:os.segments}},worker:{type:"group",required:!1,fields:os},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class cs{#hs;#ps;constructor(e,t){this.#hs=e,this.#ps=t}async build(e){const t=await this.#hs.read(e),s=this.#ps.validate(t,as);if(!1===s.valid)throw new is(s);return t.meta={root:this.#hs.getRootLocation(),configFile:e},t}}class us extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const ls=/\${([^}]*)}/g;class hs{#ls;constructor(e){this.#ls=e}getRootLocation(){return this.#ls.getAbsoluteLocation(".")}async read(e){if(!1===await this.#ls.exists(e))return{};const t=await this.#ls.read(e);if(!1===t.type.includes("json"))throw new us(e);const s=t.content.toString(),r=this.#ds(s);return this.#ms(r)}#ds(e){return e.replace(ls,(e,t)=>process.env[t]??"null")}#ms(e){return JSON.parse(e)}}class ps{#fs;#gs;#Es;constructor(e="./"){const t=new p(e),s=new hs(t),r=new Wt;this.#fs=new zt(t),this.#gs=new ss(s,r),this.#Es=new cs(s,r)}configureEnvironment(e=".env"){return this.#fs.configure(e)}getRuntimeConfiguration(e){return this.#gs.build(e)}getServerConfiguration(e){return this.#Es.build(e)}}export{Ut as A,Nt as B,ps as C,c as D,G as E,xt as F,Gt as G,Rt as H,p as L,Mt as N,qt 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,q as e,k as f,j as g,B as h,U as i,jt as j,Ct as k,$t as l,Vt as m,v 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,vt 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 e,{promises as t,existsSync as r}from"node:fs";import s from"node:path";import{fileURLToPath as n}from"node:url";import{glob as a}from"glob";import i from"mime-types";import o from"dotenv";import{B as c,N as u,F as l,a as h,A as d,O as m,b as p,P as g,T as f,U as w,S as y,V as v,c as b,R as S,d as M,e as x}from"./Response-DEjrdAZ9.js";import E from"crypto";import A from"express";class P extends Error{constructor(e){super(`Missing argument '${e}'`)}}class I{#e;#t;constructor(e){this.#e=e[2],this.#t=this.#r(e)}getCommand(){return this.#e}containsKey(e){return this.#t.has(e)}getRequiredArgument(e){const t=this.#t.get(e);if(void 0===t)throw new P(e);return t}getOptionalArgument(e,t){return this.#t.get(e)??t}#r(e){const t=e.slice(3),r=new Map;return t.forEach(e=>{const[t,s]=e.split("=");r.set(t.trim(),s?.trim())}),r}}class O{name="help";description="Shows all available commands (this message).";options=[{key:"[command]",required:!1,description:"The command name to show more details for"}];#s;constructor(e){this.#s=e}async execute(e){for(const t of this.#s.values())if(e.containsKey(t.name))return this.#n(t);this.#a()}#a(){console.log("\njitar <command>\n"),console.log("Available commands:");const e=[...this.#s.values()],t=e.map(e=>e.name),r=this.#i(t);for(const t of e){const e=t.name.padEnd(r," "),s=t.description;console.log(` ${e} ${s}`)}console.log("\nFor the options per command, use:"),console.log(" jitar help [command]\n")}#n(e){console.log(`\n${e.description}\n`);const t=e.options;if(0===t.length)return void console.log("No options available.\n");console.log("Options:");const r=t.map(e=>e.key),s=this.#i(r);for(const e of t){const t=e.key.padEnd(s," "),r=e.description,n=e.defaultValue?`default: ${e.defaultValue}`:"no default value",a=e.required?"required":`optional - ${n}`;console.log(` ${t} ${r} (${a})`)}console.log()}#i(e){return e.reduce((e,t)=>t.length>e?t.length:e,0)+3}}class R{name="about";description="Shows information about Jitar.";options=[];async execute(e){console.log("\nJitar is a JavaScript Distributed Runtime created and maintained by Masking Technology.\n\nMore information can be found at:\n- https://jitar.dev\n- https://masking.tech\n")}}class k{name="version";description="Shows the installed version of Jitar.";options=[];async execute(e){console.log("v0.10.4")}}class T extends Error{constructor(e,t){super(`Invalid ${t} name: ${e}`)}}class N extends Error{constructor(e){super(`Unknown template: ${e}`)}}const C=/^[a-zA-Z.\-_]+$/,$={_gitignore:".gitignore","_package.json":"package.json","_tsconfig.json":"tsconfig.json","_vite.config.ts":"vite.config.ts"};class F{#o;#c;constructor(e="./"){this.#o=this.#u(),this.#c=this.#l(e)}async init(e,t){this.#h(e,"project"),this.#h(t,"template");if(!1===await this.#d(t))throw new N(t);await this.#m(e,t),this.#p(e)}#u(){const e=s.dirname(n(import.meta.url));return s.join(e,"templates")}#l(e){return s.resolve(e)}#h(e,t){if(!1===C.test(e))throw new T(e,t)}async#d(e){try{const r=s.join(this.#o,e);return(await t.stat(r)).isDirectory()}catch{return!1}}#m(e,r){const n=s.join(this.#o,r),a=s.join(this.#c,e);return t.cp(n,a,{recursive:!0,force:!0})}async#p(e){const n=s.join(this.#c,e),a=Object.entries($),i=[];for(const[e,o]of a){const a=s.join(n,e),c=s.join(n,o);r(a)&&i.push(t.rename(a,c))}await Promise.all(i)}}class L{name="init";description="Initializes a new Jitar project from a template.";options=[{key:"--name",required:!0,description:"Project name used for creating the project folder"},{key:"--template",required:!0,description:"Template to use [react, vue, backend]"},{key:"--location",required:!1,description:"The root location of the project",defaultValue:"./"}];async execute(e){const t=e.getRequiredArgument("--name"),r=e.getRequiredArgument("--template"),s=e.getOptionalArgument("--location",void 0);this.#g(t,r),await this.#f(t,r,s),this.#w(t)}#g(e,t){console.log(`Initializing project '${e}' with '${t}' template.`)}#f(e,t,r){return new F(r).init(e,t)}#w(e){console.log(`SUCCESS! Run the following commands to continue:\ncd ${e}\nnpm install\nnpm run build\nnpm run standalone`)}}const j=0,z=1,H=2,D=3,q=4;class V{#y;#v;constructor(e=z,t=console){this.#y=e,this.#v=t}debug(...e){if(this.#y>j)return;const t=this.#b("DEBUG",e);this.#v.debug(t)}info(...e){if(this.#y>z)return;const t=this.#b("INFO",e);this.#v.info(t)}warn(...e){if(this.#y>H)return;const t=this.#b("WARN",e);this.#v.warn(t)}error(...e){if(this.#y>D)return;const t=this.#b("ERROR",e);this.#v.error(t)}fatal(...e){const t=this.#b("FATAL",e);this.#v.error(t)}#b(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#S(e)).join(" ")}`}#S(e,t=0){let r;switch(typeof e){case"string":r=e;break;case"object":r=this.#M(e,t+1);break;case"undefined":r="undefined";break;case"function":r="function";break;default:r=String(e)}return`${this.#x(t)}${r}`}#M(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#S(e,t)).join(",\n")}\n${this.#x(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#x(e){return" ".repeat(e)}}class B extends Error{constructor(e){super(`Invalid log level: ${e}`)}}class W{parse(e){switch(e.toUpperCase()){case"DEBUG":return j;case"INFO":return z;case"WARN":return H;case"ERROR":return D;case"FATAL":return q;default:throw new B(e)}}}const K="**/*.js",G="**/*.json",U="**/*.json";class _ extends Error{#E;constructor(e){super(`Invalid location: ${e}`),this.#E=e}get location(){return this.#E}}class J extends Error{#A;constructor(e){super(`The file '${e}' could not be found`),this.#A=e}get filename(){return this.#A}}class Y{#E;#P;#I;constructor(e,t,r){this.#E=e,this.#P=t,this.#I=r}get location(){return this.#E}get type(){return this.#P}get content(){return this.#I}get size(){return this.#I.length}}class X{#E;#O;#R;constructor(e,t){const r=t.resolve(e);this.#E=t.normalize(e),this.#O=t.normalize(r),this.#R=t}getAbsoluteLocation(e){const t=this.#R.isAbsolute(e)?e:this.#R.join(this.#E,e),r=this.#R.resolve(t),s=this.#R.normalize(r);return this.#k(s,e),s}getRelativeLocation(e){const t=this.#R.relative(this.#E,e);return this.#R.normalize(t)}normalizeLocation(e){return this.#R.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#R.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#R.exists(t))throw new J(e);return this.#R.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#R.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#R.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),r=await this.getType(t),s=await this.getContent(t);return new Y(e,r,s)}async write(e,t){const r=this.getAbsoluteLocation(e);return this.#R.write(r,t)}async copy(e,t){const r=this.getAbsoluteLocation(e),s=this.getAbsoluteLocation(t);return this.#R.copy(r,s)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#R.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),r=this.#R.normalize(e);return(await this.#R.filter(t,r)).map(e=>this.#R.normalize(e))}#k(e,t){if(!1===e.startsWith(this.#O))throw new _(t)}}class Q{copy(e,r){return t.cp(e,r,{recursive:!0,force:!0})}delete(e){return t.rm(e,{recursive:!0,force:!0})}async exists(e){try{return await t.stat(e),!0}catch{return!1}}isAbsolute(e){return s.isAbsolute(e)}isDirectory(t){try{return e.statSync(t).isDirectory()}catch{return!1}}filter(e,t){return a(`${e}/${t}`)}join(...e){return s.join(...e)}read(e){return t.readFile(e)}resolve(e){return s.resolve(e)}relative(e,t){return s.relative(e,t)}normalize(e){return e.replaceAll(s.win32.sep,s.posix.sep)}async mimeType(e){const t=i.lookup(e);if(!1!==t)return t}async write(r,n){const a=s.dirname(r);return e.mkdirSync(a,{recursive:!0}),t.writeFile(r,n)}}class Z extends X{constructor(e){super(e,new Q)}}let ee=class extends Error{#T;#N;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#T=e,this.#N=t}get url(){return this.#T}get reason(){return this.#N}};class te{#C;constructor(e){this.#C=e}async import(e){const t=this.#C.locate(e);try{return await import(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new ee(t,r)}}}class re{#$;constructor(e){this.#$=e}locate(e){return`file://${e.startsWith("/")?this.#$.getAbsoluteLocation(`.${e}`):this.#$.getAbsoluteLocation(e)}`}}class se extends te{constructor(e){super(new re(e))}}class ne{#$;#F;constructor(e,t){this.#$=e,this.#F=t}async filter(...e){return(await Promise.all(e.map(e=>this.#$.filter(e)))).flat().map(e=>this.#$.getRelativeLocation(e))}exists(e){return this.#$.exists(e)}read(e){return this.#$.read(e)}import(e){return this.#F.import(e)}}class ae extends ne{constructor(e){const t=new Z(e);super(t,new se(t))}}let ie=class{#L;#j;#z;constructor(e,t,r){this.#L=e,this.#j=t,this.#z=r}get resources(){return this.#j}get repository(){return this.#L}get segmentation(){return this.#z}};class oe{#j;constructor(e){this.#j=e}isResourceModule(e){return this.#j.includes(e)}}const ce="private",ue="0.0.0",le="index.js",he=".json",de="default",me=/import\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,pe=/export\s(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/._-]+)["'\s].*/g,ge="*";let fe=class{#H=0;next(){return"$"+ ++this.#H}};const we="js",ye=/\.js$/,ve=[".","/","http:","https:"];class be{translatePath(e){const t=e.split("/"),r=[];for(const e of t){switch(e.trim()){case"":case".":continue;case"..":r.pop();continue}r.push(e)}return r.join("/")}makePathRelative(e,t){if(""===t)return`./${e}`;const r=e.split("/"),s=t.split("/");for(;r[0]===s[0];)r.shift(),s.shift();const n=s.map(()=>"..").join("/");return`${s.length>0?n:"."}/${r.join("/")}`}makePathAbsolute(e,t){const r=""!==t?`${t}/${e}`:e;return this.translatePath(r)}extractPath(e){return e.split("/").slice(0,-1).join("/")}stripPath(e){return e.substring(1,e.length-1)}extractFilename(e){return e.split("/").pop()}assureExtension(e){return e.endsWith(`.${we}`)?e:`${e}.${we}`}addSubExtension(e,t){return e.replace(ye,`.${t}.${we}`)}isApplicationModule(e){return ve.some(t=>e.startsWith(t))}}let Se=class extends Error{constructor(e,t){super(`Failed to load resource file '${e}' because of: ${t}`)}};class Me{#D;#q;#V=new be;constructor(e,t){this.#D=e,this.#q=t}async readAll(e){const t=await Promise.all(e.map(e=>this.#B(e)));return new oe(t.flat())}async#B(e){try{const t=await this.#D.getContent(e);return JSON.parse(t.toString()).map(e=>this.#W(e))}catch(t){const r=t instanceof Error?t.message:String(t);throw new Se(e,r)}}#W(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${le}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}}let xe=class{#A;#K;#G;constructor(e,t,r){this.#K=t,this.#A=e,this.#G=r}get filename(){return this.#A}get code(){return this.#K}get model(){return this.#G}};class Ee{#U;constructor(e){this.#U=e}get modules(){return this.#U}get(e){return this.#U.find(t=>t.filename===e)}}class Ae{#_;#J;constructor(e,t){this.#_=e,this.#J=t}get name(){return this.#_}get as(){return this.#J}toString(){return`${this.#_} as ${this.#J}`}}class Pe{#Y;constructor(e){this.#Y=e}get definition(){return this.#Y}toString(){return this.#Y}}class Ie extends Pe{}class Oe{#_;#X;#Q;constructor(e,t=!1,r=!1){this.#_=e,this.#X=t,this.#Q=r}get name(){return this.#_}get isStatic(){return this.#X}get isPrivate(){return this.#Q}get isPublic(){return!1===this.#Q}}class Re extends Oe{#Z;#ee;constructor(e,t,r){super(e),this.#Z=t,this.#ee=r}get parentName(){return this.#Z}get scope(){return this.#ee}get members(){return this.#ee.members}get declarations(){return this.#ee.declarations}get functions(){return this.#ee.functions}get getters(){return this.#ee.getters}get setters(){return this.#ee.setters}get generators(){return this.#ee.generators}get readable(){const e=new Map;return this.getters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get writable(){const e=new Map;return this.setters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get callable(){return this.functions.filter(e=>e.isPublic)}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGetter(e){return this.#ee.getGetter(e)}getSetter(e){return this.#ee.getSetter(e)}getGenerator(e){return this.#ee.getGenerator(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGetter(e){return this.#ee.hasGetter(e)}hasSetter(e){return this.#ee.hasSetter(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}canRead(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasGetter(e)}canWrite(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasSetter(e)}canCall(e){const t=this.getFunction(e);return t?.isPublic??!1}toString(){const e=void 0!==this.#Z?` extends ${this.#Z}`:"";return`class ${this.name}${e} { ${this.#ee.toString()} }`}}class ke extends Oe{#te;#re;constructor(e,t,r=!1,s=!1){super(e.toString(),r,s),this.#te=e,this.#re=t}get identifier(){return this.#te}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class Te{#se;constructor(e){this.#se=e}get members(){return this.#se}toString(){return this.#se.map(e=>e.toString()).join(" , ")}}class Ne extends Te{toString(){return`[ ${super.toString()} ]`}}class Ce extends Te{toString(){return`{ ${super.toString()} }`}}class $e extends Oe{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){const e=this.#ne?` from '${this.#ne}'`:"";return`export { ${this.#se.join(", ")} }${e}`}}class Fe extends Pe{}class Le{#_;#re;constructor(e,t){this.#_=e,this.#re=t}get name(){return this.#_}get value(){return this.#re}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class je extends Oe{#ae;#ie;#oe;constructor(e,t,r,s=!1,n=!1,a=!1){super(e,s,a),this.#ae=t,this.#ie=r,this.#oe=n}get parameters(){return this.#ae}get body(){return this.#ie}get isAsync(){return this.#oe}toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}(${e.join(", ")}) { ${this.body} }`}}class ze extends je{toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}*(${e.join(", ")}) { ${this.body} }`}}class He extends je{toString(){return`get ${super.toString()}`}}class De extends Oe{#se;#ne;constructor(e,t){super(""),this.#se=e,this.#ne=t}get members(){return this.#se}get from(){return this.#ne}hasMember(e){return this.#se.some(t=>t.as===e)}getMember(e){return this.#se.find(t=>t.as===e)}toString(){return`import { ${this.#se.map(e=>e.toString()).join(", ")} } from '${this.#ne}';`}}class qe{#ee;constructor(e){this.#ee=e}get scope(){return this.#ee}get members(){return this.#ee.members}get exportedMembers(){return this.#ce(this.#ee.members)}get imports(){return this.#ee.imports}get exports(){return this.#ee.exports}get declarations(){return this.#ee.declarations}get exportedDeclarations(){return this.#ce(this.#ee.declarations)}get functions(){return this.#ee.functions}get exportedFunctions(){return this.#ce(this.#ee.functions)}get generators(){return this.#ee.generators}get exportedGenerators(){return this.#ce(this.#ee.generators)}get classes(){return this.#ee.classes}get exportedClasses(){return this.#ce(this.#ee.classes)}get exported(){const e=new Map;for(const t of this.exports)for(const r of t.members){const t=this.getMember(r.name);void 0!==t&&e.set(r.as,t)}return e}getMember(e){return this.#ee.getMember(e)}getDeclaration(e){return this.#ee.getDeclaration(e)}getFunction(e){return this.#ee.getFunction(e)}getGenerator(e){return this.#ee.getGenerator(e)}getClass(e){return this.#ee.getClass(e)}hasMember(e){return this.#ee.hasMember(e)}hasDeclaration(e){return this.#ee.hasDeclaration(e)}hasFunction(e){return this.#ee.hasFunction(e)}hasGenerator(e){return this.#ee.hasGenerator(e)}hasClass(e){return this.#ee.hasClass(e)}getImport(e){return this.imports.find(t=>t.hasMember(e))}getImported(e){for(const t of this.imports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}isExported(e){for(const t of this.exports)for(const r of t.members)if(r.name===e.name)return!0;return!1}getExport(e){return this.exports.find(t=>t.hasMember(e))}getExported(e){for(const t of this.exports)for(const r of t.members)if(r.as===e)return this.getMember(r.name)}#ce(e){return e.filter(e=>this.isExported(e))}}class Ve extends Pe{}class Be extends je{toString(){return`set ${super.toString()}`}}const We=De.name,Ke=$e.name,Ge=ke.name,Ue=je.name,_e=He.name,Je=Be.name,Ye=ze.name,Xe=Re.name;class Qe{#se;constructor(e){this.#se=e}get members(){return this.#se}get imports(){return this.#se.filter(e=>e.constructor.name===We)}get exports(){return this.#se.filter(e=>e.constructor.name===Ke)}get declarations(){return this.#se.filter(e=>e.constructor.name===Ge)}get functions(){return this.#se.filter(e=>e.constructor.name===Ue)}get getters(){return this.#se.filter(e=>e.constructor.name===_e)}get setters(){return this.#se.filter(e=>e.constructor.name===Je)}get generators(){return this.#se.filter(e=>e.constructor.name===Ye)}get classes(){return this.#se.filter(e=>e.constructor.name===Xe)}getMember(e){return this.#se.find(t=>t.name===e)}getDeclaration(e){return this.declarations.find(t=>t.name===e)}getFunction(e){return this.functions.find(t=>t.name===e)}getGetter(e){return this.getters.find(t=>t.name===e)}getSetter(e){return this.setters.find(t=>t.name===e)}getGenerator(e){return this.generators.find(t=>t.name===e)}getClass(e){return this.classes.find(t=>t.name===e)}hasMember(e){return void 0!==this.getMember(e)}hasDeclaration(e){return void 0!==this.getDeclaration(e)}hasFunction(e){return void 0!==this.getFunction(e)}hasGetter(e){return void 0!==this.getGetter(e)}hasSetter(e){return void 0!==this.getSetter(e)}hasGenerator(e){return void 0!==this.getGenerator(e)}hasClass(e){return void 0!==this.getClass(e)}toString(){return this.#se.map(e=>e.toString()).join("\n")}}const Ze={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},et=Object.values(Ze);const tt=".",rt="(",st=")",nt="[",at="]",it="{",ot="}",ct={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},ut=Object.values(ct);function lt(e){return ut.includes(e)}const ht={UNDEFINED:void 0,NULL:null,STRING:""},dt=Object.values(ht);function mt(e){return dt.includes(e)}const pt={OPEN:rt,CLOSE:st};function gt(e){return e===pt.OPEN||e===pt.CLOSE}const ft={EXPORT:"export",DEFAULT:"default",CLASS:"class",FUNCTION:"function",CONST:"const",LET:"let",VAR:"var",AS:"as",FROM:"from",IMPORT:"import",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",ASYNC:"async",RETURN:"return"},wt=Object.values(ft);function yt(e){return wt.includes(e)}function vt(e){return e===ft.AS||e===ft.ASYNC||e===ft.FROM||e===ft.GET||e===ft.SET}const bt={OPEN:nt,CLOSE:at};function St(e){return e===bt.OPEN||e===bt.CLOSE}const Mt=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function xt(e){return Mt.includes(e)}const Et={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_DIVIDE:"/=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_MODULO:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",ASSIGN_XOR:"^=",BITWISE_AND:"&",BITWISE_OR:"|",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",MODULO:"%",MULTIPLY:"*",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",XOR:"^"},At=Object.values(Et);function Pt(e){return At.includes(e)}const It={OPEN:it,CLOSE:ot};function Ot(e){return e===It.OPEN||e===It.CLOSE}const Rt={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},kt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Tt=Object.values(kt);function Nt(e){return Tt.includes(e)}class Ct{#ue;#le;constructor(e){this.#ue=e,this.#le=0}get items(){return this.#ue}get position(){return this.#le}get size(){return this.#ue.length}get eol(){return this.#le>=this.#ue.length}get current(){return this.#ue[this.#le]}get next(){return this.#ue[this.#le+1]}get previous(){return this.#ue[this.#le-1]}notAtEnd(){return!1===this.eol}get(e){return this.#ue[e]}step(e=1){return this.#le+=e,this.current}stepBack(e=1){return this.#le-=e,this.current}hasNext(){return this.#le+1<this.#ue.length}}class $t extends Ct{constructor(e){super(e.split(""))}}class Ft{#P;#re;#he;#de;constructor(e,t,r,s){this.#P=e,this.#re=t,this.#he=r,this.#de=s}get type(){return this.#P}get value(){return this.#re}get start(){return this.#he}get end(){return this.#de}isType(e){return this.#P===e}hasValue(e){return this.#re===e}toString(){return`${this.#re}`}}class Lt extends Ct{}class jt{tokenize(e){const t=new $t(e),r=[];let s;for(;t.notAtEnd();){const e=this.#me(t,s);if(void 0===e)break;e.isType(Rt.WHITESPACE)||e.isType(Rt.COMMENT)?t.step():(r.push(e),this.#pe(e)&&(s=e),t.step())}return new Lt(r)}#pe(e){return!1===[Rt.WHITESPACE,Rt.COMMENT].includes(e.type)}#me(e,t){const r=e.current,s=e.position;if(Nt(r)){const t=e.position;return new Ft(Rt.WHITESPACE,r,s,t)}if(function(e){return et.includes(e)}(r+e.next)){const t=this.#ge(e),r=e.position;return new Ft(Rt.COMMENT,t,s,r)}if(this.#fe(r,t)){const t=this.#we(e),r=e.position;return new Ft(Rt.REGEX,t,s,r)}if(xt(r)){const t=this.#ye(e),r=e.position;return new Ft(Rt.LITERAL,t,s,r)}if(Pt(r)){const t=this.#ve(e),r=e.position;return new Ft(Rt.OPERATOR,t,s,r)}if(lt(r)){const t=e.position;return new Ft(Rt.DIVIDER,r,s,t)}if(gt(r)){const t=e.position;return new Ft(Rt.GROUP,r,s,t)}if(Ot(r)){const t=e.position;return new Ft(Rt.SCOPE,r,s,t)}if(St(r)){const t=e.position;return new Ft(Rt.LIST,r,s,t)}if(mt(r))return;const n=this.#be(e),a=yt(n)?Rt.KEYWORD:Rt.IDENTIFIER,i=e.position;return new Ft(a,n,s,i)}#ge(e){const t=e.current+e.next===Ze.MULTI_START,r=t?Ze.MULTI_END:kt.NEWLINE;let s=t?Ze.MULTI_START:Ze.SINGLE;for(e.step(2);e.notAtEnd();){const n=e.current;if((t?n+e.next:n)===r){e.step(r.length-1);break}s+=n,e.step()}return t?s+Ze.MULTI_END:s.trim()}#fe(e,t){return e===Et.DIVIDE&&(void 0===t||([Rt.OPERATOR,Rt.DIVIDER,Rt.KEYWORD].includes(t.type)||[pt.OPEN,bt.OPEN].includes(t.value)))}#Se(e){return Nt(e)||e==tt||!1===this.#Me(e)}#we(e){let t=e.current,r=!1;for(e.step();e.notAtEnd();){const s=e.current,n=e.previous;if(s===Et.DIVIDE&&"\\"!==n)r=!0;else if(!0===r&&this.#Se(s)){e.stepBack();break}t+=s,e.step()}return t}#ye(e){const t=e.current;let r=t,s=!1;for(e.step();e.notAtEnd();){const n=e.current;if(!1===s){if(n===t){r+=n;break}"\\"===n&&(s=!0)}else s=!1;r+=n,e.step()}return r}#Me(e){return!1===(mt(e)||Nt(e)||Pt(e)||xt(e)||lt(e)||gt(e)||Ot(e)||St(e))}#be(e){let t="";for(;e.notAtEnd();){const r=e.current;if(!1===this.#Me(r)){e.stepBack();break}t+=r,e.step()}return t}#ve(e){let t=e.current;for(e.step();e.notAtEnd();){const r=e.current;if(!1===Pt(r)||!1===Pt(t+r)){e.stepBack();break}t+=r,e.step()}return t}}class zt extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Ht extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Dt extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class qt extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class Vt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const Bt="default",Wt=" ";class Kt{#xe;constructor(e=new jt){this.#xe=e}parse(e){const t=this.#xe.tokenize(e),r=this.#Ee(t);return new qe(r)}parseFirst(e){const t=this.#xe.tokenize(e);return this.#Ae(t)}parseValue(e){const t=this.parseFirst(e);if(t instanceof Pe==!1)throw new qt("a value definition");return t}parseImport(e){const t=this.parseFirst(e);if(t instanceof De==!1)throw new qt("an import definition");return t}parseExport(e){const t=this.parseFirst(e);if(t instanceof $e==!1)throw new qt("an export definition");return t}parseDeclaration(e){const t=this.parseFirst(e);if(t instanceof ke==!1)throw new qt("a declaration definition");return t}parseFunction(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof je==!1)throw new qt("a function definition");return r}parseClass(e){const t=this.#xe.tokenize(e),r=this.#Pe(t);if(r instanceof Re==!1)throw new qt("a class definition");return r}#Ee(e){const t=[];for(;e.notAtEnd();){const r=this.#Ae(e);r instanceof Oe&&t.push(r)}return new Qe(t)}#Ae(e,t=!1){const r=e.current;if(r.isType(Rt.LITERAL))return this.#Ie(e);if(r.isType(Rt.IDENTIFIER)){const r=e.next;return r?.hasValue(Et.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.isType(Rt.KEYWORD)){if(vt(r.value)){const t=e.next,s=void 0!==t&&(t.hasValue(ft.FUNCTION)||t.hasValue(pt.OPEN));if(r.hasValue(ft.ASYNC)&&s)return e.step(),this.#Ae(e,!0);if(void 0===t||this.#Re(t))return this.#Ie(e)}return r.hasValue(ft.RETURN)?this.#Ie(e):this.#Pe(e,t)}if(r.isType(Rt.REGEX))return this.#Ie(e);if(r.hasValue(pt.OPEN)){const r=this.#ke(e,pt.OPEN,pt.CLOSE);return r?.hasValue(Et.ARROW)?this.#Oe(e,t):this.#Ie(e)}if(r.hasValue(It.OPEN))return this.#Te(e);if(r.hasValue(bt.OPEN))return this.#Ne(e);if(r.hasValue(Et.NOT)||r.hasValue(Et.SUBTRACT))return this.#Ie(e);if(!lt(r.value))throw new Vt(r.value,r.start);e.step()}#Pe(e,t=!1){const r=e.current;switch(e.step(),r.value){case ft.IMPORT:return this.#Ce(e);case ft.EXPORT:return this.#$e(e);case ft.CLASS:return this.#Fe(e);case ft.FUNCTION:return this.#Le(e,t);case ft.VAR:case ft.LET:case ft.CONST:return this.#je(e,!1,!0);case ft.ASYNC:return this.#Pe(e,!0);default:throw new Dt(r.value,r.start)}}#Ce(e){const t=[];let r=e.current;if(r.isType(Rt.LITERAL))return new De(t,r.value);if(r.hasValue(pt.OPEN)){r=e.step();const s=r.value;return e.step(2),new De(t,s)}if(!1===r.hasValue(It.OPEN)){const s=r.hasValue(Et.MULTIPLY)?Et.MULTIPLY:Bt;let n=r.value;r=e.step(),r.hasValue(ft.AS)&&(r=e.step(),n=r.value,r=e.step()),t.push(new Ae(s,n))}if(r.hasValue(ct.SEPARATOR)&&(r=e.step()),r.hasValue(It.OPEN)){const s=this.#ze(e);t.push(...s),r=e.current}if(!1===r.hasValue(ft.FROM))throw new zt(ft.FROM,r.start);r=e.step();const s=r.value;return e.step(),new De(t,s)}#$e(e){switch(e.current.value){case ft.DEFAULT:return e.step(),this.#He(e,!0);case It.OPEN:return this.#De(e);default:return this.#He(e,!1)}}#He(e,t){let r=e.current,s=0;var n;r.hasValue(ft.ASYNC)&&(r=e.step(),s++),((n=r.value)===ft.CLASS||n===ft.FUNCTION||n===ft.CONST||n===ft.LET||n===ft.VAR)&&(r=e.step(),s++);const a=this.#Me(r)?r.value:"",i=t?Bt:a;let o;r=e.step(),r?.hasValue(ft.FROM)&&(r=e.step(),o=r.value),s>0&&(s++,e.stepBack(s));const c=new Ae(a,i);return new $e([c],o)}#De(e){const t=this.#ze(e);let r,s=e.current;return s?.hasValue(ft.FROM)&&(s=e.step(),r=s.value),e.step(),new $e(t,r)}#ze(e){const t=[];let r=e.step();for(;e.notAtEnd();){if(r.hasValue(It.CLOSE)){e.step();break}if(r.hasValue(ct.SEPARATOR)){r=e.step();continue}const s=this.#qe(e);t.push(s),r=e.step()}return t}#qe(e){let t=e.current;const r=t.value;let s=r;return e.next.hasValue(ft.AS)&&(t=e.step(2),s=t.value),new Ae(r,s)}#je(e,t,r=!1){let s,n,a=e.current,i=!1;return a.hasValue(bt.OPEN)?(s=this.#Ve(e),a=e.current):a.hasValue(It.OPEN)?(s=this.#Be(e),a=e.current):(i=a.value.startsWith("#"),s=i?a.value.substring(1):a.value,a=e.step()),a.hasValue(Et.ASSIGN)&&(e.step(),n=this.#Ae(e,!1),a=e.current),void 0!==a&&(a.hasValue(ct.TERMINATOR)?e.step():!0===r&&a.hasValue(ct.SEPARATOR)&&(e.step(),this.#je(e,t,!0))),n instanceof ze?new ze(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof je?new je(s.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof Re?new Re(s.toString(),n.parentName,n.scope):new ke(s,n,t,i)}#Le(e,t,r=!1,s=!1,n=!1){let a=e.current,i="",o=!1,c=!1;a.hasValue(Et.MULTIPLY)&&(o=!0,a=e.step()),this.#Me(a)&&(c=a.value.startsWith("#"),i=c?a.value.substring(1):a.value,a=e.step());const u=this.#We(e,pt.CLOSE);if(a=e.current,!1===a.hasValue(It.OPEN))throw new Ht(It.OPEN,a.start);const l=this.#Ke(e,It.OPEN,It.CLOSE);return o?new ze(i,u,l,r,t,c):s?new He(i,u,l,r,t,c):n?new Be(i,u,l,r,t,c):new je(i,u,l,r,t,c)}#Oe(e,t){let r,s=e.current;if(s.hasValue(pt.OPEN)?(r=this.#We(e,pt.CLOSE),s=e.current):(r=[new Le(s.value,void 0)],s=e.step()),!1===s.hasValue(Et.ARROW))throw new Ht(Et.ARROW,s.start);s=e.step();const n=s.hasValue(It.OPEN)?this.#Ke(e,It.OPEN,It.CLOSE):this.#Ie(e).definition;return new je("",r,n,!1,t,!1)}#We(e,t){const r=[];for(e.step();e.notAtEnd();){const s=e.current;if(s.hasValue(t)){e.step();break}if(s.hasValue(ct.SEPARATOR)){e.step();continue}let n;n=s.hasValue(It.OPEN)?this.#Be(e):s.hasValue(bt.OPEN)?this.#Ve(e):this.#Ge(e),r.push(n)}return r}#Fe(e){let t,r=e.current,s="";if(this.#Me(r)&&(s=r.value,r=e.step()),r.hasValue(ft.EXTENDS)&&(r=e.step(),t=r.value,r=e.step()),!1===r.hasValue(It.OPEN))throw new Ht(It.OPEN,r.start);const n=this.#Ue(e);return new Re(s,t,n)}#Ue(e){let t=e.step();const r=[];for(;e.notAtEnd();){if(t.hasValue(It.CLOSE)){e.step();break}const s=this.#_e(e);r.push(s),t=e.current}return new Qe(r)}#_e(e){let t=e.current,r=!1,s=!1,n=!1,a=!1;for(;e.notAtEnd();){if(t.hasValue(ft.STATIC))s=!0;else if(t.hasValue(ft.ASYNC))r=!0;else if(t.hasValue(ft.GET))n=!0;else{if(!t.hasValue(ft.SET)){if(t.hasValue(Et.MULTIPLY))return this.#Le(e,r,s,!1,!1);break}a=!0}t=e.step()}return e.next.hasValue(pt.OPEN)?this.#Le(e,r,s,n,a):this.#je(e,s)}#Ne(e){const t=this.#Ke(e,bt.OPEN,bt.CLOSE);return new Ie(t)}#Ve(e){const t=this.#We(e,bt.CLOSE);return new Ne(t)}#Te(e){const t=this.#Ke(e,It.OPEN,It.CLOSE);return new Ve(t)}#Be(e){const t=this.#We(e,It.CLOSE);return new Ce(t)}#Ge(e){let t=e.current;const r=t.value;let s;return t=e.step(),t.hasValue(Et.ASSIGN)&&(e.step(),s=this.#Ae(e,!1)),new Le(r,s)}#Ie(e){let t=e.current,r="";for(;e.notAtEnd();){if(t.hasValue(bt.OPEN)){r+=this.#Ke(e,bt.OPEN,bt.CLOSE)+Wt,t=e.current}else if(t.hasValue(pt.OPEN)){r+=this.#Ke(e,pt.OPEN,pt.CLOSE)+Wt,t=e.current}else if(t.hasValue(It.OPEN)){r+=this.#Ke(e,It.OPEN,It.CLOSE)+Wt,t=e.current}else r+=t.toString()+Wt,t=e.step();if(void 0===t||this.#Re(t))break}return new Fe(r.trim())}#Ke(e,t,r){let s=e.step(),n=t+Wt;for(;e.notAtEnd();)if(s.hasValue(t))n+=this.#Ke(e,t,r)+Wt,s=e.current;else{if(s.hasValue(r))return e.step(),n+=r,n;n+=s.toString()+Wt,s=e.step()}return n}#ke(e,t,r){const s=e.position;this.#Ke(e,t,r);const n=e.current,a=e.position;return e.stepBack(a-s),n}#Re(e){return[ct.TERMINATOR,ct.SEPARATOR].includes(e.value)||[bt.CLOSE,pt.CLOSE,It.CLOSE].includes(e.value)||yt(e.value)}#Me(e){return e.isType(Rt.IDENTIFIER)||e.isType(Rt.KEYWORD)&&vt(e.value)}}class Gt{merge(e,t){const r=this.#Je(e.declarations,t.declarations),s=this.#Ye(e.functions,t.functions),n=this.#Ye(e.getters,t.getters),a=this.#Ye(e.setters,t.setters),i=[...r.values(),...s.values(),...n.values(),...a.values()];return new Re(e.name,t.name,new Qe(i))}#Je(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}#Ye(e,t){const r=new Map;return t.forEach(e=>r.set(e.name,e)),e.forEach(e=>r.set(e.name,e)),[...r.values()]}}class Ut{#Xe=new Kt;#Qe=new Gt;fromModule(e,t=!1){const r=Object.entries(e),s=[];for(const[e,n]of r){if("function"!=typeof n.toString)continue;const r=n.toString();if(r.startsWith("class"))s.push(this.fromClass(n,t));else if(r.startsWith("function"))s.push(this.fromFunction(n));else{const t=new Fe(r);s.push(new ke(e,t))}}return new qe(new Qe(s))}fromClass(e,t=!1){const r=this.isClass(e)?this.#Ze(e):this.#et(e);if(!1===t)return r;const s=this.getParentClass(e);if(""===s.name)return r;const n=this.fromClass(s,!0);return this.#Qe.merge(r,n)}fromObject(e,t=!0){const r=this.getClass(e);return this.fromClass(r,t)}fromFunction(e){const t=e.toString();return this.#Xe.parseFunction(t)}createInstance(e,t=[]){return new e(...t)}getClass(e){return e.constructor}getParentClass(e){return Object.getPrototypeOf(e)}isClassObject(e){return this.isClass(e.constructor)}isFunctionObject(e){return this.isFunction(e.constructor)}isClass(e){return e.toString().startsWith("class")}isFunction(e){return e.toString().startsWith("function")||e.toString().startsWith("async function")}#Ze(e){const t=e.toString();return this.#Xe.parseClass(t)}#et(e){const t=this.createInstance(e),r=this.#tt(e,t),s=new Qe(r);return new Re(e.name,void 0,s)}#tt(e,t){return[...this.#rt(t),...this.#st(e)]}#rt(e){const t=Object.getOwnPropertyNames(e),r=e,s=[];for(const e of t){const t=r[e],n=void 0!==t?new Pe(String(t)):void 0,a=new ke(e,n);s.push(a)}return s}#st(e){const t=Object.getOwnPropertyDescriptors(e.prototype),r=[];for(const e in t){const s=t[e],n=s.value;if(n instanceof Function==!1)continue;const a=this.fromFunction(n);void 0!==s.get?r.push(new He(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):void 0!==s.set?r.push(new Be(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):r.push(a)}return r}}let _t=class extends Error{constructor(e,t){super(`Failed to load module file '${e}' because of: ${t}`)}},Jt=class{#q;#Xe=new Kt;#V=new be;constructor(e){this.#q=e}rewrite(e,t){const r=this.#nt(e,t);return this.#at(e,r)}#nt(e,t){return t.replaceAll(me,t=>this.#it(e,t))}#at(e,t){return t.replaceAll(pe,t=>this.#ot(e,t))}#it(e,t){const r=this.#Xe.parseImport(t),s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ot(e,t){const r=this.#Xe.parseExport(t);if(void 0===r.from)return t;const s=this.#V.stripPath(r.from),n=this.#q.normalizeLocation(s);if(!1===this.#V.isApplicationModule(n))return t;const a=this.#ct(e,n);return t.replace(s,a)}#ct(e,t){const r=this.#V.extractPath(e),s=this.#V.makePathAbsolute(t,r);return this.#q.isDirectory(s)?`${t}/${le}`:this.#V.assureExtension(t)}},Yt=class{#q;#Xe;#ut;constructor(e,t=new Kt){this.#q=e,this.#Xe=t,this.#ut=new Jt(e)}async readAll(e){const t=await Promise.all(e.map(e=>this.read(e)));return new Ee(t)}async read(e){const t=this.#q.getRelativeLocation(e),r=await this.#lt(e),s=this.#ut.rewrite(t,r),n=this.#Xe.parse(s);return new xe(t,s,n)}async#lt(e){try{return(await this.#q.getContent(e)).toString()}catch(t){const r=t instanceof Error?t.message:String(t);throw new _t(e,r)}}};class Xt{#_;#U=new Map;#ht=new Map;#dt=new Map;constructor(e){this.#_=e}get name(){return this.#_}get modules(){return[...this.#U.values()]}get classes(){return[...this.#ht.values()]}get procedures(){return[...this.#dt.values()]}hasModule(e){return this.#U.has(e)}getModule(e){return this.#U.get(e)}getSegmentedModules(){return this.modules.filter(e=>e.segmented)}setModule(e){this.#U.set(e.filename,e)}hasProcedure(e){return this.#dt.has(e)}getProcedure(e){return this.#dt.get(e)}setProcedure(e){this.#dt.set(e.fqn,e)}setClass(e){this.#ht.set(e.fqn,e)}}class Qt{#H;#mt;#pt;constructor(e,t,r){this.#H=e,this.#mt=t,this.#pt=r}get id(){return this.#H}get importKey(){return this.#mt}get fqn(){return this.#pt}}class Zt extends Qt{#G;constructor(e,t,r,s){super(e,t,r),this.#G=s}get model(){return this.#G}}class er extends Qt{#gt;#ft;#G;constructor(e,t,r,s,n,a){super(e,t,r),this.#gt=s,this.#ft=n,this.#G=a}get access(){return this.#gt}get version(){return this.#ft}get model(){return this.#G}}class tr{#A;#E;#wt;#se=[];#yt;constructor(e,t,r,s){this.#A=e,this.#E=t,this.#wt=r,this.#yt=s}get filename(){return this.#A}get location(){return this.#E}get imports(){return this.#wt}get members(){return this.#se}get segmented(){return this.#yt}hasClasses(){return this.#se.some(e=>e instanceof Zt)}getClasses(){return this.#se.filter(e=>e instanceof Zt)}hasImplementations(){return this.#se.some(e=>e instanceof er)}getImplementations(){return this.#se.filter(e=>e instanceof er)}addMember(e){this.#se.push(e)}addImports(e){const t=Object.keys(e);for(const r of t)this.#wt[r]=e[r]}}class rr{#pt;#vt=[];constructor(e,t=[]){this.#pt=e,this.#vt=t}get fqn(){return this.#pt}get implementations(){return this.#vt}addImplementation(e){this.#vt.push(e)}}class sr{#bt;constructor(e){this.#bt=e}get segments(){return this.#bt}getSegment(e){return this.#bt.find(t=>t.name===e)}isSegmentedModule(e){return this.#bt.some(t=>t.hasModule(e))}getSegments(e){return this.#bt.filter(t=>t.hasModule(e))}}class nr extends Error{constructor(e,t){super(`Function '${t}' from file '${e}' is not async`)}}class ar extends Error{constructor(e){super(`Segment filename '${e}' is invalid`)}}class ir extends Error{constructor(e,t){super(`Failed to load segment file '${e}' because of: ${t}`)}}class or extends Error{constructor(e,t){super(`The export '${t}' from file '${e}' is not a function or a class.`)}}class cr extends Error{constructor(e,t){super(`Module '${e}' does not export '${t}'`)}}class ur extends Error{constructor(e){super(`Segmented module not found '${e}'`)}}class lr{#L;#V=new be;constructor(e){this.#L=e}locate(e,t){const r=[];return{trace:r,model:this.#St(e,t,r)}}#St(e,t,r){r.push({filename:e,importKey:t});const s=this.#Mt(e);return this.#xt(s,t)?this.#Et(s,t,r):this.#At(s,t)}#Mt(e){const t=this.#L.get(e);if(void 0===t)throw new ur(e);return t}#xt(e,t){const r=e.model.getImport(t),s=e.model.getExport(t);return void 0!==r||void 0!==s?.from}#Et(e,t,r){const s=this.#Pt(e,t)??this.#It(e,t),n=s?.from,a=s?.name,i=this.#V.extractPath(e.filename),o=this.#V.stripPath(n),c=this.#V.makePathAbsolute(o,i);return this.#St(c,a,r)}#At(e,t){const r=this.#It(e,t);if(void 0===r)throw new cr(e.filename,t);const s=e.model.getMember(r.name);if(void 0===s)throw new cr(e.filename,r.name);return s}#It(e,t){const r=e.model.getExport(t),s=r?.getMember(t);if(void 0!==s)return{from:r?.from,name:s.name}}#Pt(e,t){const r=e.model.getImport(t),s=r?.getMember(t);if(void 0!==r&&void 0!==s)return{from:r.from,name:s.name}}}class hr{#Ot;#q;#Rt;#V=new be;constructor(e,t,r){this.#Ot=e,this.#q=t,this.#Rt=new lr(r)}async readAll(e){const t=await Promise.all(e.map(e=>this.#kt(e)));return new sr(t)}async#kt(e){const t=await this.#Tt(e),r=this.#Nt(e),s=new Xt(r);return this.#Ct(s,t),this.#$t(s),s}#Nt(e){const t=e.split("/").pop();if(void 0===t||""===t)throw new ar(e);return t.replace(he,"")}async#Tt(e){try{const t=await this.#Ot.getContent(e);return JSON.parse(t.toString())}catch(t){const r=t instanceof Error?t.message:String(t);throw new ir(e,r)}}#Ct(e,t){for(const[r,s]of Object.entries(t))this.#Ft(e,r,s,!0)}#Ft(e,t,r,s){const n=this.#Lt(t),a=this.#V.extractPath(n),i=e.hasModule(n)?e.getModule(n):new tr(n,a,{},s);i.addImports(r),e.setModule(i)}#Lt(e){const t=this.#q.normalizeLocation(e),r=this.#q.isDirectory(t)?`${t}/${le}`:this.#V.assureExtension(t);return r.startsWith("./")?r.substring(2):r.startsWith("/")?r.substring(1):r}#$t(e){const t=new fe;for(const r of e.modules)for(const s in r.imports)this.#jt(e,r,s,t)}#jt(e,t,r,s){const{model:n,trace:a}=this.#Rt.locate(t.filename,r),i=this.#zt(t,n,r,s);this.#Ht(e,t,n,i),a.shift();for(const t of a){const r={[t.importKey]:{access:i.access}};this.#Ft(e,t.filename,r,!1)}}#zt(e,t,r,s){const n=e.imports[r],a=s.next(),i=n.as??t.name;return{id:a,importKey:r,name:i,access:n.access??ce,version:n.version??ue,fqn:this.#Dt(e,i,r)}}#Dt(e,t,r){return this.#qt(e)?t:this.#Vt(e)&&this.#Bt(r)?e.location:`${e.location}/${t}`}#qt(e){return""===e.location}#Vt(e){return e.filename.endsWith(le)}#Bt(e){return e===de}#Ht(e,t,r,s){if(r instanceof Re)return this.#Wt(e,t,r,s);if(r instanceof je)return this.#Kt(e,t,r,s);throw new or(t.filename,s.importKey)}#Wt(e,t,r,s){const n=new Zt(s.id,s.importKey,s.fqn,r);t.addMember(n),e.setClass(n)}#Kt(e,t,r,s){if(!1===r.isAsync)throw new nr(t.filename,s.name);const n=new er(s.id,s.importKey,s.fqn,s.access,s.version,r);this.#Gt(e,t,n)}#Gt(e,t,r){const s=e.hasProcedure(r.fqn)?e.getProcedure(r.fqn):new rr(r.fqn);s.addImplementation(r),t.addMember(r),e.setProcedure(s)}}class dr{#Ut;constructor(e){this.#Ut=e}async read(e,t,r){const s=this.#Ut.source,n=this.#Ut.resource,a=this.#Ut.segment,i=new Yt(s),o=await i.readAll(e),c=new Me(n,s),u=await c.readAll(t),l=new hr(a,s,o),h=await l.readAll(r);return new ie(o,u,h)}}class mr{#_t;#j;#z;#Jt;#Xe=new Kt;#V=new be;constructor(e,t,r,s){this.#_t=e,this.#j=t,this.#z=r,this.#Jt=s}get parser(){return this.#Xe}rewrite(e){return e.replaceAll(this.replacementPattern,e=>this.replaceStatement(e))}replaceStatement(e){const t=this.parseStatement(e);return void 0===t.from?e:this.#Yt(t)?this.#Xt(t):this.#Qt(t)}#Xt(e){const t=this.#Zt(e);return this.#j.isResourceModule(t)?this.#er(t,e):this.#tr(t,e)}#Qt(e){const t=this.#rr(e),r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#tr(e,t){if(0===t.members.length)return this.#sr(e,t,[]);const{segmentKeys:r,remoteKeys:s,commonKeys:n}=this.#nr(e,t),a=[];return r.length>0&&a.push(this.#ar(e,t,r)),s.length>0&&a.push(this.#ir(e,t,s)),n.length>0&&a.push(this.#sr(e,t,n)),a.filter(e=>e.length>0).join("\n")}#er(e,t){const r=this.#or(e);return this.excludeFromBundle(t,r)}#ar(e,t,r){const s=this.#or(e,this.#Jt?.name);return this.includeInBundle(t,s,r)}#ir(e,t,r){const s=this.#or(e,"remote");return this.includeInBundle(t,s,r)}#sr(e,t,r){const s=this.#or(e);return this.includeInBundle(t,s,r)}#Yt(e){const t=this.#V.stripPath(e.from);return this.#V.isApplicationModule(t)}#Zt(e){const t=this.#V.stripPath(e.from),r=this.#V.extractPath(this.#_t.filename);return this.#V.makePathAbsolute(t,r)}#nr(e,t){const r=this.#cr(e,this.#Jt),s=this.#ur(e,r),n=this.#lr(t,r),a=this.#lr(t,s);return{segmentKeys:n,remoteKeys:a,commonKeys:this.#hr(t,[...n,...a])}}#cr(e,t){if(void 0===t)return[];const r=t.getModule(e);return void 0!==r?Object.keys(r.imports):[]}#ur(e,t){const r=this.#z.getSegments(e).filter(e=>e!==this.#Jt).map(t=>this.#cr(e,t)).flat();return[...new Set(r)].filter(e=>!1===t.includes(e))}#lr(e,t){return e.members.filter(e=>t.includes(e.name)).map(e=>e.name)}#hr(e,t){return e.members.filter(e=>!1===t.includes(e.name)).map(e=>e.name)}#or(e,t){const r=this.#V.extractPath(this.#_t.filename),s=this.#V.makePathRelative(e,r);return void 0!==t?this.#V.addSubExtension(s,t):s}#rr(e){return this.#V.stripPath(e.from)}}class pr extends mr{get replacementPattern(){return me}parseStatement(e){return this.parser.parseImport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`import "${t}";`;return`import ${this.#dr(e,r)} from "${t}";`}excludeFromBundle(e,t){if(0===e.members.length)return`await import("${t}");`;return`const ${this.#mr(e)} = await import("${t}");`}#dr(e,t){const r=e.members.filter(e=>t.includes(e.name)),s=r.find(e=>e.name===de),n=void 0!==s,a=n?s.as:"",i=r.filter(e=>e.name!==de).map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name),o=i.length>0;return`${a}${n&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#mr(e){if(this.#pr(e))return e.members[0].as;return`{ ${e.members.map(e=>e.name!==e.as?`${e.name} : ${e.as}`:e.name).join(", ")} }`}#pr(e){return 1===e.members.length&&e.members[0].name===ge}}class gr extends mr{get replacementPattern(){return pe}parseStatement(e){return this.parser.parseExport(e)}includeInBundle(e,t,r){if(0===e.members.length)return`export "${t}";`;return`export ${this.#gr(e,r)} from "${t}";`}excludeFromBundle(e,t){const r=e.members.map(e=>e.name);return this.includeInBundle(e,t,r)}#gr(e,t){const r=e.members.filter(e=>t.includes(e.name));if(1===r.length&&""===r[0].name){const e=r[0];return e.name!==e.as?`${ge} as ${e.as}`:ge}return`{ ${r.map(e=>e.name!==e.as?`${e.name} as ${e.as}`:e.name).join(", ")} }`}}class fr{build(e,t,r,s){const n=new pr(e,t,r,s),a=new gr(e,t,r,s),i=n.rewrite(e.code);return a.rewrite(i)}}const wr="normal",yr="dry",vr=200,br=400,Sr=401,Mr=402,xr=403,Er=404,Ar=418,Pr=500,Ir=501;class Or extends c{#fr;constructor(e){super(`Invalid version number '${e}'`),this.#fr=e}get number(){return this.#fr}}class Rr extends u{#pt;constructor(e){super(`Procedure '${e}' not found`),this.#pt=e}get fqn(){return this.#pt}}class kr extends l{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class Tr extends c{#wr;constructor(e){super(`Unknown parameter ${e}`),this.#wr=e}get parameterName(){return this.#wr}}class Nr extends c{#wr;constructor(e){super(`Missing value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class Cr extends c{#wr;constructor(e){super(`Invalid value for parameter '${e}'`),this.#wr=e}get parameterName(){return this.#wr}}class $r{extract(e,t){const r=this.#yr(e,t),s=[];for(const t of e){const e=this.#vr(t,r);s.push(e)}if(r.size>0){const e=r.keys().next().value;throw new Tr(e)}return s}#yr(e,t){const r=new Map;for(const[s,n]of t){if(this.#br(s)){const t=this.#Sr(s);!0===this.#Mr(e,t)&&r.set(t,n);continue}r.set(s,n)}return r}#br(e){return e.startsWith("*")}#Sr(e){return e.substring(1)}#Mr(e,t){return void 0!==e.find(e=>e.name===t)}#vr(e,t,r){return e instanceof h?this.#xr(e,t,r):this.#Er(e,t)}#xr(e,t,r){const s=t.get(e.name);if(this.#Ar(e,s,r))throw new Nr(e.name);if(this.#Pr(e,s,r))throw new Cr(e.name);return t.delete(e.name),s}#Er(e,t){return e instanceof d?this.#Ir(e,t):this.#Or(e,t)}#Ir(e,t){const r=this.#Rr(e,t);return void 0!==r?Object.values(r):void 0}#Or(e,t){return this.#Rr(e,t)}#Rr(e,t){const r=e instanceof d,s={},n=[];let a=!1,i=0;for(const o of e.variables){const c=r?i++:o.name,u=this.#vr(o,t,e);void 0!==u?a=!0:!1===o.isOptional&&n.push(o.name),s[c]=u}if(!0===a&&n.length>0)throw new Nr(n[0]);return a?s:void 0}#Ar(e,t,r){return void 0===t&&(!0!==e.isOptional&&!0!==r?.isOptional)}#Pr(e,t,r){return!1!==e.name.startsWith("...")&&(void 0===r&&t instanceof Array==!1||r instanceof d&&t instanceof Array==!1||r instanceof m&&t instanceof Object==!1)}}class Fr{toStatus(e){return e instanceof c?br:e instanceof l?xr:e instanceof u?Er:e instanceof p?Ir:e instanceof g?Mr:e instanceof f?Ar:e instanceof w?Sr:Pr}fromStatus(e,t){switch(e){case br:return new c(t);case xr:return new l(t);case Er:return new u(t);case Ir:return new p(t);case Mr:return new g(t);case Ar:return new f(t);case Sr:return new w(t);default:return new y(t)}}}const Lr=/^\d+(?:\.\d+){0,2}$/;class jr{parse(e){if(0===e.trim().length)return v.DEFAULT;if(!1===Lr.test(e))throw new Or(e);const t=e.split(".");switch(t.length){case 1:return new v(Number.parseInt(t[0]));case 2:return new v(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new v(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class zr extends u{#pt;#ft;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#pt=e,this.#ft=t}get fqn(){return this.#pt}get version(){return this.#ft}}class Hr extends y{constructor(){super("Invalid segment")}}class Dr{#bt=new Map;addSegment(e){this.#bt.set(e.id,e)}clearSegments(){this.#bt.clear()}getClassNames(){const e=new Set;for(const t of this.#bt.values()){t.getClasses().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasClass(e){return this.getClassNames().includes(e)}getClass(e){for(const t of this.#bt.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#bt.values()){const r=t.getClassByImplementation(e);if(void 0!==r)return r}}getProcedureNames(){const e=new Set;for(const t of this.#bt.values()){t.getExposedProcedures().forEach(t=>e.add(t.fqn))}return[...e.values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}getProcedure(e){for(const t of this.#bt.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class qr{#kr;#Tr;#Nr=new $r;#Cr=new Fr;#$r=new Dr;constructor(e,t=[]){this.#kr=e,this.#Tr=t}async start(){return this.#Fr()}async stop(){return this.#Lr()}async loadSegment(e){const t=await this.#kr.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof b==!1)throw new Hr;this.#$r.addSegment(e)}getClassNames(){return this.#$r.getClassNames()}hasClass(e){return this.#$r.hasClass(e)}getClass(e){return this.#$r.getClass(e)}getClassByImplementation(e){return this.#$r.getClassByImplementation(e)}getProcedureNames(){return this.#$r.getProcedureNames()}hasProcedure(e){return this.#$r.hasProcedure(e)}getProcedure(e){return this.#$r.getProcedure(e)}async run(e){const t=this.#jr(e.fqn,e.version),r=this.#Nr.extract(t.parameters,e.args);return e.mode===yr?new S(vr,void 0):this.#zr(e,t,r)}async#Fr(){await Promise.all(this.#Tr.map(e=>this.loadSegment(e)))}#Lr(){this.#$r.clearSegments()}#jr(e,t){const r=this.#$r.getProcedure(e);if(void 0===r)throw new Rr(e);const s=r.getImplementation(t);if(void 0===s)throw new zr(r.fqn,t.toString());return s}async#zr(e,t,r){try{const s=await t.executable.call(e,...r);return new S(vr,s)}catch(e){const t=this.#Cr.toStatus(e);return new S(t,e)}}}class Vr{build(e){let t="";for(const r of e)t+=r.access===M.PRIVATE?this.#Hr(r):this.#Dr(r);return t.trim()}#Hr(e){const t=e.fqn,r=e.version,s=this.#qr(e),n=`throw new ProcedureNotAccessible('${t}', '${r}');`;return this.#Vr(s,n)}#Dr(e){const t=e.fqn,r=e.version,s=this.#Br(e.model.parameters),n=this.#qr(e),a=`return __run('${t}', '${r}', { ${s} }, this);`;return this.#Vr(n,a)}#Wr(e){const t=[];for(const r of e)r instanceof Le?t.push(r.name):(r instanceof Ne||r instanceof Ce)&&t.push(r.toString());return t.join(", ")}#Br(e){return this.#Kr(e).join(", ")}#Kr(e){const t=[];for(const r of e)if(r instanceof Te){const e=this.#Kr(r.members);t.push(...e)}else if(r instanceof Le){const e=this.#Gr(r);t.push(e)}return t}#Gr(e){const t=e.name,r=t.startsWith("...")?t.substring(3):t;return`'${t}': ${r}`}#qr(e){const t=e.model.name,r=this.#Wr(e.model.parameters);return`\nexport ${e.importKey===de?`${de} `:""}async function ${t}(${r})`}#Vr(e,t){return`${e} {\n\t${t}\n}\n`}}let Br=class{#Ur;#_r=new fr;#Jr=new Vr;#V=new be;constructor(e){this.#Ur=e}async build(e){const t=e.repository,r=e.segmentation,s=e.resources,n=t.modules.map(e=>this.#Yr(e,s,r));await Promise.all(n)}async#Yr(e,t,r){const s=r.getSegments(e.filename);if(0===s.length)return this.#Xr(e,t,r);const n=s.map(s=>this.#Qr(e,t,s,r)),a=s[0].getModule(e.filename),i=a?.hasImplementations()?this.#Zr(e,s):Promise.resolve();await Promise.all([...n,i]),this.#Ur.delete(e.filename)}async#Xr(e,t,r){const s=e.filename,n=this.#_r.build(e,t,r);return this.#Ur.write(s,n)}async#Qr(e,t,r,s){const n=this.#V.addSubExtension(e.filename,r.name),a=this.#_r.build(e,t,s,r);return this.#Ur.write(n,a)}async#Zr(e,t){const r=this.#es(e,t),s=this.#V.addSubExtension(e.filename,"remote"),n=this.#Jr.build(r);return this.#Ur.write(s,n)}#es(e,t){const r=t.map(t=>t.getModule(e.filename)).flatMap(e=>e.getImplementations()),s=new Map;for(const e of r){const t=`${e.fqn}:${e.version.toString()}`;s.set(t,e)}return[...s.values()]}};let Wr=class{#Ur;#ts;#V=new be;#rs=new jr;constructor(e,t){this.#Ur=e,this.#ts=t}async build(e){const t=e.segmentation.segments.map(e=>this.#ss(e));await Promise.all(t)}async#ss(e){const t=`${e.name}.segment.js`,r=this.#ns(e);await this.#Ur.write(t,r),this.#ts.info(`Built ${e.name} segment (${e.modules.length} modules, ${e.procedures.length} procedures, ${e.classes.length} classes)`)}#ns(e){return`${this.#as(e)}\n${this.#is(e)}`}#as(e){return`import { Segment, Class, Procedure, Implementation, Version, NamedParameter, ArrayParameter, ObjectParameter } from "jitar";\n${this.#os(e)}`}#os(e){const t=[];for(const r of e.getSegmentedModules()){if(0===r.members.length)continue;const s=this.#V.addSubExtension(r.filename,e.name),n=`import ${this.#cs(r)} from "./${s}";`;t.push(n)}return t.join("\n")}#cs(e){const t=e.members,r=t.find(e=>e.importKey===de),s=void 0!==r,n=s?r.id:"",a=t.filter(e=>e.importKey!==de),i=a.map(e=>`${e.importKey} as ${e.id}`),o=a.length>0;return`${n}${s&&o?", ":""}${o?`{ ${i.join(", ")} }`:""}`}#is(e){const t=[];t.push(`export default new Segment("${e.name}")`);for(const r of e.classes)t.push(`\t.addClass(new Class("${r.fqn}", ${r.id}))`);for(const r of e.procedures){t.push(`\t.addProcedure(new Procedure("${r.fqn}")`);for(const e of r.implementations){const r=this.#us(e.version),s=this.#ls(e.model);t.push(`\t\t.addImplementation(new Implementation(${r}, "${e.access}", ${s}, ${e.id}))`)}t.push("\t)")}return t.join("\n")}#us(e){const t=this.#rs.parse(e);return`new Version(${t.major}, ${t.minor}, ${t.patch})`}#ls(e){return`[${this.#hs(e.parameters).join(", ")}]`}#hs(e){const t=[];for(const r of e)t.push(this.#ds(r));return t}#ds(e){return e instanceof Ne?this.#ms(e):e instanceof Ce?this.#ps(e):this.#gs(e)}#gs(e){return`new NamedParameter("${e.name}", ${void 0!==e.value})`}#ms(e){return`new ArrayParameter([${this.#hs(e.members).join(", ")}])`}#ps(e){return`new ObjectParameter([${this.#hs(e.members).join(", ")}])`}};class Kr{#fs;#ws;constructor(e,t){const r=e.target;this.#fs=new Br(r),this.#ws=new Wr(r,t)}async build(e){await Promise.all([this.#fs.build(e),this.#ws.build(e)])}}class Gr{#ys;#vs;#bs;#Jt;constructor(e,t,r,s){this.#ys=e,this.#vs=t,this.#bs=r,this.#Jt=s}get source(){return this.#ys}get target(){return this.#vs}get resource(){return this.#bs}get segment(){return this.#Jt}}class Ur{#ts;#$;#Ss;#Ms;constructor(e,t){this.#ts=new V(t);const r=new Z(e.source),s=new Z(e.target),n=new Z(e.resources),a=new Z(e.segments);this.#$=new Gr(r,s,n,a),this.#Ss=new dr(this.#$),this.#Ms=new Kr(this.#$,this.#ts)}async build(){const e=this.#$.source,t=this.#$.resource,r=this.#$.segment,s=await e.filter(K),n=await t.filter(G),a=await r.filter(U),i=await this.#Ss.read(s,n,a);return this.#Ms.build(i)}}class _r{#xs;constructor(e=!0){this.#xs=e}validate(e,t){const r=[];this.#Es("",e,t,r);return{valid:0===r.length,errors:r}}#Es(e,t,r,s){this.#xs&&this.#As(e,t,r,s),this.#Ps(e,t,r,s)}#As(e,t,r,s){const n=Object.keys(t),a=Object.keys(r);for(const t of n)if(!1===a.includes(t)){const r=this.#Is(e,t);s.push(`Unknown field '${r}'`)}}#Ps(e,t,r,s){const n=Object.keys(r);for(const a of n){const n=this.#Is(e,a),i=r[a],o=t[a];this.#Os(n,o,i,s)}}#Os(e,t,r,s){if(void 0!==t)switch(r.type){case"string":return this.#Rs(e,t,r,s);case"integer":return this.#ks(e,t,r,s);case"real":return this.#Ts(e,t,r,s);case"boolean":return this.#Ns(e,t,r,s);case"url":return this.#Cs(e,t,r,s);case"group":return this.#$s(e,t,r,s);case"list":return this.#Fs(e,t,r,s)}else!0===r.required&&s.push(`Field '${e}' is required`)}#Rs(e,t,r,s){"string"!=typeof t&&s.push(`Field '${e}' is not a string`)}#ks(e,t,r,s){"number"==typeof t&&!1!==Number.isInteger(t)||s.push(`Field '${e}' is not an integer`)}#Ts(e,t,r,s){"number"!=typeof t&&s.push(`Field '${e}' is not a real number`)}#Ns(e,t,r,s){"boolean"!=typeof t&&s.push(`Field '${e}' is not a boolean`)}#Cs(e,t,r,s){"string"==typeof t&&!1!==t.startsWith("http")||s.push(`Field '${e}' is not a valid URL`)}#$s(e,t,r,s){"object"==typeof t?this.#Es(e,t,r.fields,s):s.push(`Field '${e}' is not an object`)}#Fs(e,t,r,s){if(!Array.isArray(t))return void s.push(`Field '${e}' is not a list`);const n=t;for(const t in n){const a=this.#Is(e,t),i=n[t];this.#Os(a,i,r.items,s)}}#Is(e,t){return""===e?t:`${e}.${t}`}}class Jr{async configure(e){o.config({path:e})}}class Yr extends Error{constructor(e){super(`Runtime configuration is invalid:\n${e.errors.join("\n")}`)}}const Xr="./jitar.json",Qr="./src",Zr="./dist",es="./segments",ts="./resources",rs={source:{type:"string",required:!1},target:{type:"string",required:!1},segments:{type:"string",required:!1},resources:{type:"string",required:!1}};let ss=class{#Ls;#js;constructor(e,t){this.#Ls=e,this.#js=t}async build(e=Xr){const t=await this.#Ls.read(e),r=this.#js.validate(t,rs);if(!1===r.valid)throw new Yr(r);return t.source??=Qr,t.target??=Zr,t.segments??=es,t.resources??=ts,t}};const ns="\n => ";class as extends Error{constructor(e){const t=e.errors.join(ns);super(`Invalid server configuration:${ns}${t}`)}}const is={url:{type:"url",required:!0},setUp:{type:"list",required:!1,items:{type:"string"}},tearDown:{type:"list",required:!1,items:{type:"string"}},middleware:{type:"list",required:!1,items:{type:"string"}},healthChecks:{type:"list",required:!1,items:{type:"string"}},gateway:{type:"group",required:!1,fields:{monitorInterval:{type:"integer",required:!1},trustKey:{type:"string",required:!1}}},proxy:{type:"group",required:!1,fields:{gateway:{type:"url",required:!0},repository:{type:"url",required:!0}}},repository:{type:"group",required:!1,fields:{indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},standalone:{type:"group",required:!1,fields:{segments:{type:"list",required:!0,items:{type:"string"}},indexFilename:{type:"string",required:!1},serveIndexOnNotFound:{type:"boolean",required:!1},assets:{type:"list",required:!1,items:{type:"string"}}}},worker:{type:"group",required:!1,fields:{gateway:{type:"url",required:!1},segments:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1},reportInterval:{type:"integer",required:!1}}},remoteWorker:{type:"group",required:!1,fields:{unavailableThreshold:{type:"integer",required:!1},stoppedThreshold:{type:"integer",required:!1}}}};class os{#Ls;#js;constructor(e,t){this.#Ls=e,this.#js=t}async build(e){const t=await this.#Ls.read(e),r=this.#js.validate(t,is);if(!1===r.valid)throw new as(r);return t}}class cs extends Error{constructor(e){super(`${e} is not a valid configuration file.`)}}const us=/\${([^}]*)}/g;class ls{#$;constructor(e){this.#$=e}async read(e){if(!1===await this.#$.exists(e))return{};const t=await this.#$.read(e);if(!1===t.type.includes("json"))throw new cs(e);const r=t.content.toString(),s=this.#zs(r);return this.#Hs(s)}#zs(e){return e.replace(us,(e,t)=>process.env[t]??"null")}#Hs(e){return JSON.parse(e)}}class hs{#Ds;#qs;#Vs;constructor(e="./"){const t=new Z(e),r=new ls(t),s=new _r;this.#Ds=new Jr,this.#qs=new ss(r,s),this.#Vs=new os(r,s)}configureEnvironment(e=".env"){return this.#Ds.configure(e)}getRuntimeConfiguration(e){return this.#qs.build(e)}getServerConfiguration(e){return this.#Vs.build(e)}}class ds{name="build";description="Builds the application (creates segment bundles).";options=[{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getOptionalArgument("--log-level",void 0),n=this.#Bs(s),a=new hs;await a.configureEnvironment(t);const i=await a.getRuntimeConfiguration(r);return new Ur(i,n).build()}#Bs(e){if(void 0===e)return;return(new W).parse(e)}}const ms="content-type",ps="x-content-type-options",gs="x-jitar-content-type",fs="x-jitar-procedure-version",ws="x-powered-by",ys="nosniff",vs="application/json",bs="application/octet-stream";class Ss extends Error{constructor(){super("Invalid worker id")}}class Ms{#T;#Ws;#Cr=new Fr;#js=new _r;constructor(e,t){this.#T=e,this.#Ws=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#T}/${e}`,r=await this.#Ks(t,{method:"GET"}),s=r.headers.get(ms)??bs,n=await r.arrayBuffer(),a=Buffer.from(n);return new Y(e,s,a)}async isHealthy(){const e=`${this.#T}/health/status`,t=await this.#Ks(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#T}/health`,t=await this.#Ks(e,{method:"GET"}),r=await t.json();return new Map(Object.entries(r))}async addWorker(e,t,r){const s=`${this.#T}/workers`,n={url:e,procedureNames:t,trustKey:r},a={method:"POST",headers:{"Content-Type":vs},body:JSON.stringify(n)},i=await this.#Ks(s,a),o=i.headers.get(ms);if(null===o||!1===o.includes(vs))throw new Ss;const c=await i.json();if(!1===this.#js.validate(c,{id:{type:"string",required:!0}}).valid)throw new Ss;return c.id}async reportWorker(e,t){const r=`${this.#T}/workers/${e}/report`,s={state:t},n={method:"POST",headers:{"Content-Type":vs},body:JSON.stringify(s)};await this.#Ks(r,n)}async removeWorker(e){const t=`${this.#T}/workers/${e}`,r={method:"DELETE",headers:{"Content-Type":vs}};await this.#Ks(t,r)}async run(e){e.setHeader(ms,vs);const t=Object.fromEntries(e.args),r=Object.fromEntries(e.headers),s=e.version.toString();r[fs]=s;const n=`${this.#T}/rpc/${e.fqn}`,a={method:"POST",redirect:"manual",headers:r,body:await this.#Gs(t)},i=await this.#Ks(n,a,!1),o=i.status,c=await this.#Us(i),u=this.#_s(i);return new S(o,c,u)}async#Ks(e,t,r=!0){const s=await this.#Ws.execute(e,t);if(r&&this.#Js(s)){const e=await this.#Us(s);throw this.#Cr.fromStatus(s.status,String(e))}return s}#Js(e){return e.status<200||e.status>399}async#Gs(e){return JSON.stringify(e)}async#Us(e){const t=e.headers.get(gs)??e.headers.get(ms);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const r=await e.text();return t?.includes("boolean")?"true"===r:t?.includes("number")?Number(r):r}#_s(e){const t=new Map;for(const[r,s]of e.headers)t.set(r,s);return t}}class xs{async execute(e,t){return fetch(e,t)}}class Es{#Ws;constructor(e=new xs){this.#Ws=e}build(e){return new Ms(e,this.#Ws)}}const As={STARTING:"starting",AVAILABLE:"available",UNAVAILABLE:"unavailable",STOPPING:"stopping",STOPPED:"stopped"};class Ps{get url(){throw new p}get state(){return As.AVAILABLE}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return As.AVAILABLE}provide(e){throw new p}}class Is{get url(){throw new p}get state(){return As.AVAILABLE}get trustKey(){throw new p}start(){return Promise.resolve()}stop(){return Promise.resolve()}async isHealthy(){return!0}async getHealth(){return new Map}async updateState(){return As.AVAILABLE}getProcedureNames(){throw new p}hasProcedure(e){throw new p}run(e){throw new p}}class Os{#Ys=As.STOPPED;get state(){return this.#Ys}set state(e){this.#Ys=e}async start(e){if(!this.isStarted())try{this.setStarting(),await e()}catch(e){throw this.setStopped(),e}}async stop(e){this.isStopped()||(this.setStopping(),await e(),this.setStopped())}isStarted(){return this.#Xs(As.STOPPED)}isStopped(){return this.#Qs(As.STOPPED)}isAvailable(){return this.#Qs(As.AVAILABLE)}setStarting(){this.#Ys=As.STARTING}setAvailable(){this.#Ys=As.AVAILABLE}setUnavailable(){this.#Ys=As.UNAVAILABLE}setAvailability(e){return this.#Ys=e?As.AVAILABLE:As.UNAVAILABLE,this.#Ys}setStopping(){this.#Ys=As.STOPPING}setStopped(){this.#Ys=As.STOPPED}#Qs(...e){return e.includes(this.#Ys)}#Xs(...e){return!1===this.#Qs(...e)}}class Rs extends w{constructor(){super("Invalid trust key")}}class ks{#T;#Zs;#en;#tn;#rn=new Os;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#en=e.healthManager,this.#tn=e.workerManager}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await Promise.all([this.#en.start(),this.#tn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.all([this.#tn.stop(),this.#en.stop()])})}async isHealthy(){return this.#en.isHealthy()}async getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async addWorker(e){if(this.#sn(e.trustKey))throw new Rs;return await e.start(),this.#tn.addWorker(e)}getWorker(e){return this.#tn.getWorker(e)}async reportWorker(e,t){return this.#tn.reportWorker(e,t)}async removeWorker(e){return this.#tn.removeWorker(e).stop()}getProcedureNames(){return this.#tn.getProcedureNames()}hasProcedure(e){return this.#tn.hasProcedure(e)}async run(e){return this.#tn.run(e)}#sn(e){return void 0!==this.#Zs&&e!==this.#Zs}}class Ts{#T;#nn;#rn=new Os;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}getProcedureNames(){throw new p}hasProcedure(e){throw new p}addWorker(e){return this.#nn.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#nn.reportWorker(e,t)}removeWorker(e){return this.#nn.removeWorker(e)}run(e){return this.#nn.run(e)}}class Ns extends y{#_;constructor(e){super(`No worker available for procedure '${e}'`),this.#_=e}get name(){return this.#_}}class Cs{#an=[];#in=0;get workers(){return this.#an}addWorker(e){this.#an.includes(e)||this.#an.push(e)}removeWorker(e){const t=this.#an.indexOf(e);-1!==t&&this.#an.splice(t,1)}getNextWorker(){const e=this.#an.filter(e=>e.isAvailable());if(0!==e.length)return this.#in>=e.length&&(this.#in=0),e[this.#in++];this.#in=0}async run(e){const t=this.getNextWorker();if(void 0===t)throw new Ns(e.fqn);return t.run(e)}}class $s{generate(){return E.randomUUID()}}class Fs extends y{#H;constructor(e){super(`Unknown worker id '${e}'`),this.#H=e}get id(){return this.#H}}class Ls{#an=new Map;#on=new Map;#cn=new $s;#un;constructor(e,t){this.#un=e.create(()=>this.#ln(),t)}get workers(){return[...this.#an.values()]}get balancers(){return this.#on}start(){this.#un.start()}stop(){this.#un.stop()}getProcedureNames(){const e=this.workers.map(e=>e.getProcedureNames());return[...new Set(e.flat()).values()]}hasProcedure(e){return this.getProcedureNames().includes(e)}addWorker(e){e.id=this.#cn.generate(),this.#an.set(e.id,e);for(const t of e.getProcedureNames()){this.#hn(t).addWorker(e)}return e.id}getWorker(e){const t=this.#an.get(e);if(void 0===t)throw new Fs(e);return t}reportWorker(e,t){this.getWorker(e).reportState(t)}removeWorker(e){const t=this.getWorker(e);this.#an.delete(e);for(const e of t.getProcedureNames()){const r=this.#dn(e);void 0!==r&&r.removeWorker(t)}return t}#dn(e){return this.#on.get(e)}#hn(e){let t=this.#dn(e);return void 0===t&&(t=new Cs,this.#on.set(e,t)),t}async run(e){const t=this.#dn(e.fqn);if(void 0===t)throw new Rr(e.fqn);return t.run(e)}async#ln(){const e=this.workers.map(e=>this.#mn(e));await Promise.allSettled(e)}async#mn(e){await e.updateState()===As.STOPPED&&this.removeWorker(e.id)}}class js{#T;#pn;#gn;#rn=new Os;constructor(e){this.#T=e.url,this.#pn=e.provider,this.#gn=e.runner}get url(){return this.#T}get state(){return this.#rn.state}get trustKey(){return this.#gn.trustKey}get provider(){return this.#pn}get runner(){return this.#gn}async start(){return this.#rn.start(async()=>{await Promise.all([this.#pn.start(),this.#gn.start()]),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await Promise.allSettled([this.#gn.stop(),this.#pn.stop()])})}async isHealthy(){const[e,t]=await Promise.all([this.#pn.isHealthy(),this.#gn.isHealthy()]);return e&&t}async getHealth(){const[e,t]=await Promise.all([this.#pn.getHealth(),this.#gn.getHealth()]);return new Map([...e,...t])}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#pn.provide(e)}getProcedureNames(){return this.#gn.getProcedureNames()}hasProcedure(e){return this.#gn.hasProcedure(e)}run(e){return this.#gn.run(e)}}class zs{#T;#en;#fn;#wn;#yn;#vn;#rn=new Os;constructor(e){this.#T=e.url,this.#en=e.healthManager,this.#fn=e.sourcingManager,this.#wn=e.assets,this.#yn=e.indexFilename??"index.html",this.#vn=e.serveIndexOnNotFound??false}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#en.start(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#en.stop()})}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async provide(e){if(this.#bn(e))return this.provide(this.#yn);if(!1===this.#wn.has(e))throw new J(e);return this.#fn.read(e)}#bn(e){return""===e||e!==this.#yn&&(this.#vn&&!1===this.#wn.has(e))}}class Hs{#T;#nn;#rn=new Os;constructor(e){this.#T=e.url,this.#nn=e.remote}get url(){return this.#T}get state(){return this.#rn.state}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}provide(e){return this.#nn.provide(e)}}class Ds extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class qs extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class Vs extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Bs extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Ws{#Sn=[];addSerializer(e){e.parent=this,this.#Sn.unshift(e)}async serialize(e){const t=this.#Sn.find(t=>t.canSerialize(e));if(void 0===t)throw new Bs(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Sn.find(t=>t.canDeserialize(e));if(void 0===t)throw new Vs(typeof e);return t.deserialize(e)}}class Ks extends Error{constructor(){super("Parent serializer not set")}}class Gs{#Mn;set parent(e){this.#Mn=e}serializeOther(e){if(void 0===this.#Mn)throw new Ks;return this.#Mn.serialize(e)}deserializeOther(e){if(void 0===this.#Mn)throw new Ks;return this.#Mn.deserialize(e)}}class Us extends Gs{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const r of e)t.push(await this.serializeOther(r));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class _s extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Js extends Gs{canSerialize(e){return"bigint"==typeof e}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"BigInt"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"BigInt",value:e.toString()}}async deserialize(e){try{return BigInt(e.value)}catch{throw new _s(e.value)}}}class Ys extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Xs extends Gs{canSerialize(e){return e instanceof Buffer}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Buffer"===t.name&&"string"==typeof t.base64}async serialize(e){return{serialized:!0,name:"Buffer",base64:e.toString("base64")}}async deserialize(e){try{return Buffer.from(e.base64,"base64")}catch{throw new Ys(e.base64)}}}const Qs=new Ut;class Zs extends Gs{#xn;constructor(e){super(),this.#xn=e}canSerialize(e){return e instanceof Object&&Qs.isClassObject(e)}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"class"===t.name&&"string"==typeof t.key&&t.args instanceof Object&&t.args.constructor===Object&&t.fields instanceof Object&&t.fields.constructor===Object}async serialize(e){const t=Qs.getClass(e),r=Qs.fromClass(t,!0),s=this.#En(r),n=this.#xn.resolveKey(t);if(void 0===n)throw new Ds(t.name);return{serialized:!0,key:n,name:"class",args:await this.#An(r,s,e),fields:await this.#Pn(r,s,e)}}#En(e){const t=e.getFunction("constructor");return(t?.parameters??[]).map(e=>e.name)}async#An(e,t,r){const s={};for(const[n,a]of t.entries()){const t=e.canRead(a)?await this.serializeOther(r[a]):void 0;s[n.toString()]=t}return s}async#Pn(e,t,r){const s={};for(const n of e.writable){const a=n.name;t.includes(a)||!1===e.canRead(a)||(s[a]=await this.serializeOther(r[a]))}return s}async deserialize(e){const t=await this.#In(e);if(void 0===t)throw new Ds(e.key);if(t instanceof Function==!1)throw new qs(e.key);const r=await this.#On(t,e.args),s=Qs.createInstance(t,r);for(const t in e.fields){const r=e.fields[t];s[t]=await this.deserializeOther(r)}return s}async#On(e,t){const r=Qs.fromClass(e,!0).getFunction("constructor"),s=(r?.parameters??[]).map((e,r)=>{const s=r.toString(),n=t[s];return this.deserializeOther(n)});return Promise.all(s)}async#In(e){return globalThis[e.key]??this.#xn.resolveClass(e.key)}}class en extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class tn extends Gs{canSerialize(e){return e instanceof Date}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Date"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Date",value:e.toISOString()}}async deserialize(e){const t=new Date(e.value);if("Invalid Date"===t.toString())throw new en(e.value);return t}}class rn extends Gs{canSerialize(e){if(e instanceof Object==!1)return!1;const t=e;return t.constructor===Error||t.constructor===EvalError||t.constructor===RangeError||t.constructor===ReferenceError||t.constructor===SyntaxError||t.constructor===TypeError||t.constructor===URIError||t.constructor===AggregateError}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Error"===t.name&&t.type in globalThis}async serialize(e){return{serialized:!0,name:"Error",type:e.constructor.name,stack:e.stack,message:e.message,cause:e.cause}}async deserialize(e){const t=new(0,globalThis[e.type])(e.message,{cause:e.cause});return t.stack=e.stack,t}}class sn extends Gs{canSerialize(e){return e instanceof Map}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Map"===t.name&&t.entries instanceof Object&&t.entries.keys instanceof Array&&t.entries.values instanceof Array}async serialize(e){const t=[],r=[];for(const[s,n]of e)t.push(await this.serializeOther(s)),r.push(await this.serializeOther(n));return{serialized:!0,name:"Map",entries:{keys:t,values:r}}}async deserialize(e){const t=e.entries.keys,r=e.entries.values,s=new Map;for(let e=0;e<t.length;e++){const n=await this.deserializeOther(t[e]),a=await this.deserializeOther(r[e]);s.set(n,a)}return s}}class nn extends Gs{canSerialize(e){return e instanceof Object&&e.constructor===Object}canDeserialize(e){return e instanceof Object&&e.constructor===Object}async serialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.serializeOther(s)}return t}async deserialize(e){const t={};for(const r in e){const s=e[r];t[r]=await this.deserializeOther(s)}return t}}class an extends Gs{canSerialize(e){return e instanceof Object==!1}canDeserialize(e){return e instanceof Object==!1}async serialize(e){return e}async deserialize(e){return e}}class on extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class cn extends Gs{canSerialize(e){return e instanceof RegExp}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"RegExp"===t.name&&"string"==typeof t.source&&"string"==typeof t.flags}async serialize(e){return{serialized:!0,name:"RegExp",source:e.source,flags:e.flags}}async deserialize(e){try{return new RegExp(e.source,e.flags)}catch{throw new on(e.source,e.flags)}}}class un extends Gs{canSerialize(e){return e instanceof Set}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Set"===t.name&&t.values instanceof Array}async serialize(e){const t=[];for(const r of e.values())t.push(await this.serializeOther(r));return{serialized:!0,name:"Set",values:t}}async deserialize(e){const t=await Promise.all(e.values.map(async e=>this.deserializeOther(e)));return new Set([...t])}}const ln=new Ut;class hn extends Gs{canSerialize(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof BigInt64Array||e instanceof BigUint64Array}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"TypedArray"===t.name&&t.type in globalThis&&t.bytes instanceof Array}async serialize(e){const t=e.constructor.name,r=new DataView(e.buffer),s=[];for(let e=0;e<r.byteLength;e++)s.push(r.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:s}}async deserialize(e){const t=e.type,r=e.bytes,s=new ArrayBuffer(r.length),n=new DataView(s);for(let e=0;e<r.length;e++)n.setUint8(e,r[e]);const a=globalThis[t];return ln.createInstance(a,[s])}}class dn extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class mn extends Gs{canSerialize(e){return e instanceof URL}canDeserialize(e){const t=e;return t instanceof Object&&!0===t.serialized&&"Url"===t.name&&"string"==typeof t.value}async serialize(e){return{serialized:!0,name:"Url",value:e.toString()}}async deserialize(e){try{return new URL(e.value)}catch{throw new dn(e.value)}}}class pn{static build(e){const t=new Ws;return t.addSerializer(new an),t.addSerializer(new nn),void 0!==e&&t.addSerializer(new Zs(e)),t.addSerializer(new rn),t.addSerializer(new cn),t.addSerializer(new Js),t.addSerializer(new mn),t.addSerializer(new tn),t.addSerializer(new un),t.addSerializer(new sn),t.addSerializer(new Us),t.addSerializer(new hn),"undefined"!=typeof Buffer&&t.addSerializer(new Xs),t}}class gn{#Rn;constructor(e){this.#Rn=e}resolveKey(e){const t=this.#Rn.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Rn.getClass(e);return t?.implementation}}class fn extends w{constructor(){super("Request not trusted")}}const wn="X-Jitar-Trust-Key",yn="X-Jitar-Data-Encoding",vn="serialized";class bn{#H;#T;#Zs;#kn;#Tn;#Rn;#en;#Nn;#Cn;#rn=new Os;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#kn=e.gateway,this.#Tn=!0===e.registerAtGateway,this.#Rn=e.executionManager,this.#en=e.healthManager;const t=e.scheduleManager;this.#Nn=t.create(()=>this.#$n(),e.reportInterval);const r=new gn(this.#Rn);this.#Cn=pn.build(r)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await Promise.all([this.#Rn.start(),this.#en.start()]),void 0!==this.#kn&&(await this.#kn.start(),this.#Tn&&(this.#H=await this.#kn.addWorker(this),this.#Nn.start())),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{void 0!==this.#kn&&(void 0!==this.#H&&(this.#Nn.stop(),await this.#kn.removeWorker(this.#H)),await this.#kn.stop()),await Promise.all([this.#en.stop(),this.#Rn.stop()])})}getProcedureNames(){return this.#Rn.getProcedureNames()}hasProcedure(e){return this.#Rn.hasProcedure(e)}isHealthy(){return this.#en.isHealthy()}getHealth(){return this.#en.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#rn.setAvailability(e)}async reportState(e){if(void 0!==this.#kn&&void 0!==this.#H)return this.#kn.reportWorker(this.#H,e)}async run(e){return this.#Fn(e)?this.#Ln(e):this.#jn(e)}#Fn(e){return void 0===this.#kn||this.#Rn.hasProcedure(e.fqn)}async#Ln(e){const t=this.#Rn.getProcedure(e.fqn),r=t?.getImplementation(e.version);if(this.#zn(r))throw new Rr(e.fqn);if(this.#Hn(e,r))throw new fn;const s=e.getHeader(yn);s===vn&&(e=await this.#Dn(e)),e.removeHeader(yn);const n=await this.#Rn.run(e);return s===vn?this.#qn(n):n}#zn(e){return void 0===e||e.private}#Hn(e,t){if(t.public)return!1;const r=e.getHeader(wn);return this.#Zs!==r}async#jn(e){(e=await this.#Vn(e)).setHeader(yn,vn),void 0!==this.#Zs&&e.setHeader(wn,this.#Zs);const t=await this.#kn.run(e);return this.#Bn(t)}async#Vn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.serialize(s);t.set(r,e)}return new x(e.fqn,e.version,t,e.headers,e.mode)}async#Dn(e){const t=new Map;for(const[r,s]of e.args){const e=await this.#Cn.deserialize(s);t.set(r,e)}return new x(e.fqn,e.version,t,e.headers,e.mode)}async#qn(e){const t=await this.#Cn.serialize(e.result);return new S(e.status,t,e.headers)}async#Bn(e){const t=await this.#Cn.deserialize(e.result);return new S(e.status,t,e.headers)}async#$n(){const e=await this.updateState();return this.reportState(e)}}class Sn extends Os{#Wn;#Kn;#Gn=Date.now();#Un=Date.now();constructor(e=6e3,t=18e3){super(),this.#Wn=e,this.#Kn=t}report(e){this.#Gn=Date.now(),this.state=e}update(){this.#Un=Date.now();const e=this.#Un-this.#Gn;return e>=this.#Wn&&(this.state=e>=this.#Kn?As.STOPPED:As.UNAVAILABLE),this.state}}class Mn{#H;#T;#Zs;#_n;#nn;#rn;constructor(e){this.#T=e.url,this.#Zs=e.trustKey,this.#_n=e.procedureNames,this.#nn=e.remote,this.#rn=new Sn(e.unavailableThreshold,e.stoppedThreshold)}get id(){return this.#H}set id(e){this.#H=e}get state(){return this.#rn.state}get url(){return this.#T}get trustKey(){return this.#Zs}async start(){return this.#rn.start(async()=>{await this.#nn.connect(),await this.updateState()})}async stop(){return this.#rn.stop(async()=>{await this.#nn.disconnect()})}getProcedureNames(){return[...this.#_n.values()]}hasProcedure(e){return this.#_n.has(e)}isHealthy(){return this.#nn.isHealthy()}getHealth(){return this.#nn.getHealth()}isAvailable(){return this.#rn.isAvailable()}async updateState(){return this.#rn.update()}async reportState(e){this.#rn.report(e)}run(e){return this.#nn.run(e)}}class xn{#Jr;#Wn;#Kn;constructor(e,t,r){this.#Jr=e,this.#Wn=t,this.#Kn=r}build(e,t,r){const s=this.#Jr.build(e),n=new Set(t),a=this.#Wn,i=this.#Kn;return new Mn({url:e,trustKey:r,remote:s,procedureNames:n,unavailableThreshold:a,stoppedThreshold:i})}}class En{#gn;constructor(e){this.#gn=e}async handle(e,t){return this.#gn.run(e)}}class An{#rs=new jr;constructor(){this.#Jn()}#Jn(){const e=globalThis;e.__run=this.#Yn.bind(this),e.ProcedureNotAccessible=kr}async#Yn(e,t,r,s){const n=this.#rs.parse(t),a=new Map(Object.entries(r)),i=s instanceof x?s.headers:new Map,o=new x(e,n,a,i,wr),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==vr)throw u.result;return u.result}}const Pn="starting",In="started",On="stopping",Rn="stopped";class kn extends y{constructor(){super("Invalid health check")}}class Tn{#Ys=Rn;#Xn=new Map;#kr;#Qn;constructor(e,t=[]){this.#kr=e,this.#Qn=t}get state(){return this.#Ys}async start(){if(this.#Ys===Rn)try{this.#Ys=Pn,await this.#Zn(),this.#Ys=In}catch(e){throw this.#Ys=Rn,e}}async stop(){if(this.#Ys===In)try{this.#Ys=On,this.clearHealthChecks(),this.#Ys=Rn}catch(e){throw this.#Ys=In,e}}async loadHealthCheck(e){const t=await this.#ea(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new kn;this.#Xn.set(e.name,e)}clearHealthChecks(){this.#Xn.clear()}async isHealthy(){const e=[];for(const t of this.#Xn.values()){const r=this.#ta(t);e.push(r)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,r]of this.#Xn){const s=this.#ta(r).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(s)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#ra(e,t))).then(()=>t)}async#Zn(){(await Promise.all(this.#Qn.map(e=>this.#ea(e)))).forEach(e=>this.addHealthCheck(e))}async#ea(e){return(await this.#kr.import(e)).default}#ra(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#ta(e){const t=e.isHealthy(),r=e.timeout;if(void 0===r)return t;const s=new Promise(e=>{setTimeout(e,r)}).then(()=>!1);return Promise.race([s,t])}}const Nn="starting",Cn="started",$n="stopping",Fn="stopped";class Ln extends y{constructor(){super("Invalid middleware")}}class jn{#Ys=Fn;#sa=[];#kr;#na;constructor(e,t=[]){this.#kr=e,this.#na=t}get state(){return this.#Ys}async start(){if(this.#Ys===Fn)try{this.#Ys=Nn,await this.#aa(),this.#Ys=Cn}catch(e){throw this.#Ys=Fn,e}}async stop(){if(this.#Ys===Cn)try{this.#Ys=$n,this.clearMiddlewares(),this.#Ys=Fn}catch(e){throw this.#Ys=Cn,e}}async loadMiddleware(e){const t=await this.#ia(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Ln;this.#sa.push(e)}getMiddleware(e){return this.#sa.find(t=>t instanceof e)}clearMiddlewares(){this.#sa=[]}handle(e){return this.#oa(e,0)()}async#aa(){(await Promise.all(this.#na.map(e=>this.#ia(e)))).forEach(e=>this.addMiddleware(e))}async#ia(e){return(await this.#kr.import(e)).default}#oa(e,t){const r=this.#sa[t];if(void 0===r)return async()=>new S(vr);const s=this.#oa(e,t+1);return async()=>await r.handle(e,s)}}class zn{#ts;#ca;#ua;#la=null;constructor(e,t,r=5e3){this.#ts=e,this.#ca=t,this.#ua=r}start(){this.#ha()}stop(){null!==this.#la&&(clearTimeout(this.#la),this.#la=null)}#ha(){this.#la=setTimeout(async()=>{null!==this.#la&&(await this.#da(),this.#ha())},this.#ua),this.#la.unref()}async#da(){try{await this.#ca()}catch(e){this.#ts.warn("Scheduled task failed",e)}}}class Hn{#ma=[];#ts;constructor(e){this.#ts=e}create(e,t){const r=new zn(this.#ts,e,t);return this.#ma.push(r),r}remove(e){const t=this.#ma.indexOf(e);t<0||this.#ma.splice(t,1)}startAll(){this.#ma.forEach(e=>e.start())}stopAll(){this.#ma.forEach(e=>e.stop())}}const Dn="application/null",qn="application/undefined",Vn="application/boolean",Bn="application/number",Wn="application/json",Kn="text/plain",Gn=200,Un=400,_n=401,Jn=402,Yn=403,Xn=404,Qn=418,Zn=500,ea=501;class ta extends An{#pa;#ga;#fa;#wa;#ts;#rs=new jr;constructor(e){super(),this.#pa=e.proxy,this.#ga=e.remoteWorkerBuilder,this.#fa=e.resourceManager,this.#wa=e.middlewareManager,this.#ts=e.logger}get proxy(){return this.#pa}getTrustKey(){return this.#pa.trustKey}async start(){await this.#ya(),this.#ts.info(`Server started at ${this.#pa.url}`),this.#pa.runner instanceof bn&&this.#ts.info("RPC procedures:",this.#pa.runner.getProcedureNames())}async stop(){await this.#va(),this.#ts.info("Server stopped")}async getHealth(){try{const e=await this.#pa.getHealth();return this.#ts.debug("Got health"),this.#ba(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health:",t),this.#Sa(e)}}async isHealthy(){try{const e=await this.#pa.isHealthy();return this.#ts.debug("Got health status"),this.#Ma(e)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to get health status:",t),this.#Sa(e)}}async provide(e){try{const t=await this.#pa.provide(e.filename);return this.#ts.info("Provided file:",e.filename),this.#xa(t)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.warn("Failed to provide file:",t),this.#Sa(e)}}async run(e){try{const t=this.#Ea(e),r=await this.#wa.handle(t);return this.#ts.info("Ran request:",t.fqn),this.#Aa(r)}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed run request:",t),this.#Sa(e)}}async runInternal(e){return this.#pa.run(e)}async addWorker(e){try{const t=this.#Pa(),r=this.#ga.build(e.url,e.procedureNames,e.trustKey),s=await t.addWorker(r);return this.#ts.info("Added worker:",r.url),this.#Ia({id:s})}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to add worker:",t),this.#Sa(e)}}async reportWorker(e){try{const t=this.#Oa(e.state),r=this.#Pa();return await r.reportWorker(e.id,t),this.#ts.debug("Reported worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to report worker:",t),this.#Sa(e)}}async removeWorker(e){try{const t=this.#Pa();return await t.removeWorker(e.id),this.#ts.info("Removed worker:",e.id),this.#Ia()}catch(e){const t=e instanceof Error?e.message:String(e);return this.#ts.error("Failed to remove worker:",t),this.#Sa(e)}}async#ya(){await this.#fa.start(),await Promise.all([this.#pa.start(),this.#wa.start()]);const e=new En(this.#pa);this.#wa.addMiddleware(e)}async#va(){await Promise.all([this.#wa.stop(),this.#pa.stop()]),await this.#fa.stop()}#Ea(e){const t=this.#Ra(e.fqn),r=this.#ka(e.version),s=this.#Ta(e.args),n=this.#Na(e.headers);return new x(t,r,s,n,e.mode)}#Ra(e){if(0===e.length)throw new c("Missing procedure name");if(e.includes(".."))throw new c("Invalid procedure name");return e}#ka(e){return"string"!=typeof e?v.DEFAULT:this.#rs.parse(e)}#Ta(e){return new Map(Object.entries(e))}#Na(e){const t=new Map;for(const[r,s]of Object.entries(e)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();t.set(e,n)}return t}#Oa(e){if(!1===Object.values(As).includes(e))throw new c("Invalid state value");return e}#ba(e){return{result:Object.fromEntries(e),contentType:Wn,headers:{},status:Gn}}#Ma(e){return{result:e,contentType:Vn,headers:{},status:Gn}}#xa(e){return{result:e.content,contentType:e.type,headers:{},status:Gn}}#Aa(e){const t=e.result instanceof Error?e.result.message:e.result;return{result:t,contentType:this.#Ca(t),headers:this.#$a(e.headers),status:e.status}}#Sa(e){const t=e instanceof Error?e.message:String(e);return{result:t,contentType:this.#Ca(t),headers:{},status:this.#Fa(e)}}#Ia(e){return{result:e,contentType:this.#Ca(e),headers:{},status:Gn}}#Ca(e){if(void 0===e)return qn;if(null===e)return Dn;switch(typeof e){case"boolean":return Vn;case"number":return Bn;case"object":return Wn;default:return Kn}}#$a(e){return Object.fromEntries(e)}#Fa(e){return e instanceof c?Un:e instanceof l?Yn:e instanceof u?Xn:e instanceof p?ea:e instanceof g?Jn:e instanceof f?Qn:e instanceof w?_n:Zn}#Pa(){const e=this.#pa.runner;if(e instanceof ks==!1)throw new c("Cannot remove worker from remote gateway");return e}}class ra extends Error{constructor(){super("Unknown service configured")}}class sa{#fn;#La;#ja;constructor(e,t=[],r=[]){this.#fn=e,this.#La=t,this.#ja=r}async start(){return this.#za()}async stop(){return this.#Ha()}#za(){return this.#Da(this.#La)}#Ha(){return this.#Da(this.#ja)}async#Da(e){await Promise.all(e.map(e=>this.#fn.import(e)))}}class na{#fn;#Jr;constructor(e,t){this.#fn=e,this.#Jr=t}async build(e,t){const r=e.setUp,s=e.tearDown,n=e.middleware,a=e.healthChecks,i=new V(t),o=this.#qa(a),c=this.#Va(i),u=await this.#Ba(e,o,c),l=this.#fn,h=this.#Wa(r,s),d=this.#Ka(n),m=this.#Ga(e);return new ta({proxy:u,sourcingManager:l,resourceManager:h,middlewareManager:d,remoteWorkerBuilder:m,logger:i})}#Ba(e,t,r){if(void 0!==e.gateway)return this.#Ua(e.url,e.gateway,t,r);if(void 0!==e.worker)return this.#_a(e.url,e.worker,t,r);if(void 0!==e.repository)return this.#Ja(e.url,e.repository,t);if(void 0!==e.proxy)return this.#Ya(e.url,e.proxy);if(void 0!==e.standalone)return this.#Xa(e.url,e.standalone,t,r);throw new ra}async#Ua(e,t,r,s){const n=new Ps,a=this.#Qa(e,t,r,s);return new js({url:e,provider:n,runner:a})}async#_a(e,t,r,s){const n=new Ps,a=this.#Za(e,t,r,s);return new js({url:e,provider:n,runner:a})}async#Ja(e,t,r){const s=await this.#ei(e,t,r),n=new Is;return new js({url:e,provider:s,runner:n})}#Qa(e,t,r,s){const n=t.trustKey,a=t.monitorInterval,i=new Ls(s,a);return new ks({url:e,trustKey:n,healthManager:r,workerManager:i})}#ti(e){const t=this.#Jr.build(e);return new Ts({url:e,remote:t})}#Za(e,t,r,s){const n=t.trustKey,a=t.gateway?this.#ti(t.gateway):void 0,i=t.reportInterval,o=void 0!==a,c=this.#ri(t.segments);return new bn({url:e,trustKey:n,reportInterval:i,gateway:a,registerAtGateway:o,executionManager:c,healthManager:r,scheduleManager:s})}async#ei(e,t,r){const s=this.#fn,n=await this.#si(t.assets),a=t.indexFilename,i=t.serveIndexOnNotFound;return new zs({url:e,sourcingManager:s,assets:n,indexFilename:a,serveIndexOnNotFound:i,healthManager:r})}#ni(e){const t=this.#Jr.build(e);return new Hs({url:e,remote:t})}async#Ya(e,t){const r=this.#ni(t.repository),s=this.#ti(t.gateway);return new js({url:e,provider:r,runner:s})}async#Xa(e,t,r,s){const n=await this.#ei(e,t,r),a=this.#Za(e,t,r,s);return new js({url:e,provider:n,runner:a})}#Wa(e=[],t=[]){const r=e.map(e=>this.#ai(e)),s=t.map(e=>this.#ai(e));return new sa(this.#fn,r,s)}#qa(e=[]){const t=e.map(e=>this.#ai(e));return new Tn(this.#fn,t)}#Ka(e=[]){const t=e.map(e=>this.#ai(e));return new jn(this.#fn,t)}#ri(e=[]){const t=e.map(e=>`./${e}.segment.js`);return new qr(this.#fn,t)}#Va(e){return new Hn(e)}#Ga(e){const t=e.remoteWorker?.unavailableThreshold,r=e.remoteWorker?.stoppedThreshold;return new xn(this.#Jr,t,r)}async#si(e){if(void 0===e)return new Set;const t=await this.#fn.filter(...e);return new Set(t)}#ai(e){return e.endsWith(".js")?e:e+".js"}}const aa="3000",ia=204800,oa=["host","connection","content-length","accept-encoding","user-agent","keep-alive"];class ca{#ii;#oi;#ci;#ui;#js=new _r;constructor(e,t=aa,r=ia){this.#ii=e,this.#oi=t,this.#ci=A(),this.#li(r),this.#hi()}async start(){return await this.#ii.start(),this.#di()}async stop(){return await this.#mi(),this.#ii.stop()}#li(e){this.#ci.use(A.json({limit:e})),this.#ci.use(A.urlencoded({extended:!0})),this.#ci.use(this.#pi.bind(this)),this.#ci.disable(ws)}#hi(){this.#ci.get("/health",(e,t)=>{this.#gi(e,t)}),this.#ci.get("/health/status",(e,t)=>{this.#fi(e,t)}),this.#ci.get("/rpc/*procedure",(e,t)=>{this.#wi(e,t)}),this.#ci.post("/rpc/*procedure",(e,t)=>{this.#yi(e,t)}),this.#ci.options("/rpc/*procedure",(e,t)=>{this.#vi(e,t)}),this.#ci.post("/workers",(e,t)=>{this.#bi(e,t)}),this.#ci.post("/workers/:id/report",(e,t)=>{this.#Si(e,t)}),this.#ci.delete("/workers/:id",(e,t)=>{this.#Mi(e,t)}),this.#ci.use((e,t)=>{this.#xi(e,t)})}#di(){return void 0!==this.#ui?Promise.resolve():new Promise((e,t)=>{this.#ui=this.#ci.listen(this.#oi,t),e()})}#mi(){return void 0===this.#ui?Promise.resolve():new Promise(e=>{this.#ui.close(()=>e())})}#pi(e,t,r){t.setHeader(ps,ys),r()}async#gi(e,t){const r=await this.#ii.getHealth();return this.#Ei(t,r)}async#fi(e,t){const r=await this.#ii.isHealthy();return this.#Ei(t,r)}async#wi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ii(e),a=this.#Oi(e),i=wr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#yi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=wr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#vi(e,t){const r=this.#Ai(e),s=this.#Pi(e),n=this.#Ri(e),a=this.#Oi(e),i=yr,o=await this.#ii.run({fqn:r,version:s,args:n,headers:a,mode:i});return this.#Ei(t,o)}async#bi(e,t){const r=this.#Ri(e),s=this.#js.validate(r,{url:{type:"url",required:!0},procedureNames:{type:"list",required:!0,items:{type:"string"}},trustKey:{type:"string",required:!1}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.url,a=r.procedureNames,i=r.trustKey;try{const e=await this.#ii.addWorker({url:n,procedureNames:a,trustKey:i});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Si(e,t){const r={id:e.params.id,state:e.body.state},s=this.#js.validate(r,{id:{type:"string",required:!0},state:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.id,a=r.state;try{const e=await this.#ii.reportWorker({id:n,state:a});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#Mi(e,t){const r={id:e.params.id},s=this.#js.validate(r,{id:{type:"string",required:!0}});if(!1===s.valid)return t.status(400).send(s.errors.join("\n"));const n=r.id;try{const e=await this.#ii.removeWorker({id:n});return this.#Ei(t,e)}catch(e){const r=e instanceof Error?e.message:"Server error";return t.status(500).send(r)}}async#xi(e,t){const r=e.path.substring(1).trim(),s=decodeURIComponent(r),n=await this.#ii.provide({filename:s});return this.#Ei(t,n)}#Ai(e){return decodeURIComponent(e.path.trim()).substring(5).trim()}#Pi(e){const t=e.headers[fs];return Array.isArray(t)?t[0]:t}#Ii(e){const t={};for(const[r,s]of Object.entries(e.query))t[r]=s;return t}#Ri(e){return e.body}#Oi(e){const t={};for(const[r,s]of Object.entries(e.headers)){if(void 0===s)continue;const e=r.toLowerCase(),n=s.toString();oa.includes(e)||(t[e]=n)}return t}#Ei(e,t){const r=this.#ki(t),s=this.#Ti(t);e.status(r),e.setHeader(ms,s),e.setHeader(gs,t.contentType);for(const[r,s]of Object.entries(t.headers))e.setHeader(r,s);const n=this.#Ni(t);return e.send(n)}#ki(e){return void 0!==e.headers.location?302:e.status}#Ti(e){const t=e.contentType.toLowerCase();switch(t){case Vn:case Bn:case qn:case Dn:return Kn}return t}#Ni(e){const t=e.result;return"number"==typeof t||"boolean"==typeof t?String(t):t}}class ua{name="start";description="Starts a server with the configured service.";options=[{key:"--service",required:!0,description:"Path to the service configuration file"},{key:"--env-file",required:!1,description:"Path to the environment file"},{key:"--config",required:!1,description:"Path to the configuration file",defaultValue:"jitar.json"},{key:"--log-level",required:!1,description:"Level of logging [info, debug, warn, error, fatal]",defaultValue:"info"},{key:"--http-body-limit",required:!1,description:"Maximum HTTP body size in bytes",defaultValue:204800}];async execute(e){const t=e.getOptionalArgument("--env-file",void 0),r=e.getOptionalArgument("--config",void 0),s=e.getRequiredArgument("--service"),n=e.getOptionalArgument("--log-level",void 0),a=this.#Bs(n),i=e.getOptionalArgument("--http-body-limit",void 0),o=this.#Ci(i),c=new hs;await c.configureEnvironment(t);const u=await c.getRuntimeConfiguration(r),l=await c.getServerConfiguration(s),h=await this.#$i(u,l,o,a);return this.#Fi(h)}async#$i(e,t,r,s){const[,,n]=t.url.split(":"),a=new ae(e.target),i=new Es,o=new na(a,i),c=await o.build(t,s);return new ca(c,n,r)}#Fi(e){let t=!1;return process.on("SIGINT",async()=>{t||(t=!0,e.stop())}),console.log("\n ██╗██╗████████╗ █████╗ ██████╗ \n ██║██║╚══██╔══╝██╔══██╗██╔══██╗\n ██║██║ ██║ ███████║██████╔╝\n██ ██║██║ ██║ ██╔══██║██╔══██╗\n╚█████╔╝██║ ██║ ██║ ██║██║ ██║\n ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n ~ Distributed JavaScript Runtime ~\n____________________________________\n"),e.start()}#Bs(e){if(void 0===e)return;return(new W).parse(e)}#Ci(e){const t=Number.parseInt(e);return Number.isNaN(t)?void 0:t}}class la extends Error{constructor(e){super(`Command ${e} not found`)}}class ha{#s=new Set;constructor(){this.#s.add(new O(this.#s)),this.#s.add(new R),this.#s.add(new k),this.#s.add(new L),this.#s.add(new ds),this.#s.add(new ua)}run(e,t){for(const r of this.#s)if(r.name===e)return r.execute(t);throw new la(e)}}class da{#Li;#ji;constructor(){this.#Li=new I(process.argv),this.#ji=new ha}start(){const e=this.#Li.getCommand()??"help";return this.#ji.run(e,this.#Li)}}try{const e=new da;await e.start()}catch(e){const t=new V,r=e instanceof Error?e.message:String(e);t.fatal(r)}
|
|
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)}
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{constructor(e="Invalid request"){super(e)}}class t extends Error{constructor(e="Forbidden"){super(e)}}class s extends Error{constructor(e="Not found"){super(e)}}class r extends Error{constructor(e="Not implemented"){super(e)}}class n extends Error{constructor(e="Payment required"){super(e)}}class a extends Error{constructor(e="Server error"){super(e)}}class i extends Error{constructor(e="I'm a teapot"){super(e)}}class o extends Error{constructor(e="Unauthorized"){super(e)}}const c="private",u="protected",l="public",h="normal",d="dry",p=200,m=400,g=401,f=402,w=403,y=404,v=418,S=500,E=501;class b extends e{#e;constructor(e){super(`Invalid version number '${e}'`),this.#e=e}get number(){return this.#e}}class x extends s{#t;constructor(e){super(`Procedure '${e}' not found`),this.#t=e}get fqn(){return this.#t}}class O extends t{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class A{#s;#r=new Map;#n=new Map;constructor(e){this.#s=e}get id(){return this.#s}addClass(e){return this.#r.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#r.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#r.values()]}addProcedure(e){return this.#n.set(e.fqn,e),this}hasProcedure(e){return this.#n.has(e)}getProcedure(e){return this.#n.get(e)}getExposedProcedures(){return[...this.#n.values()].filter(e=>e.public||e.protected)}}class C{#t;#a;constructor(e,t){this.#t=e,this.#a=t}get fqn(){return this.#t}get implementation(){return this.#a}}class I{static get DEFAULT(){return new I(0,0,0)}#i;#o;#c;constructor(e=0,t=0,s=0){this.#i=e,this.#o=t,this.#c=s}get major(){return this.#i}get minor(){return this.#o}get patch(){return this.#c}equals(e){return this.#i===e.major&&this.#o===e.minor&&this.#c===e.patch}greater(e){return this.#i!==e.major?this.#i>e.major:this.#o!==e.minor?this.#o>e.minor:this.#c!==e.patch&&this.#c>e.patch}less(e){return this.#i!==e.major?this.#i<e.major:this.#o!==e.minor?this.#o<e.minor:this.#c!==e.patch&&this.#c<e.patch}toString(){return`${this.#i}.${this.#o}.${this.#c}`}}class N{#t;#u=new Map;#l;constructor(e){this.#t=e}get fqn(){return this.#t}get public(){return[...this.#u.values()].some(e=>e.public)}get protected(){return[...this.#u.values()].some(e=>e.protected)}addImplementation(e){return this.#u.set(e.version,e),this.#h(e)&&(this.#l=e),this}#h(e){return void 0===this.#l||e.version.greater(this.#l.version)}getImplementation(e){const t=this.#d(e);return this.#u.get(t)}#d(e){let t=I.DEFAULT;for(const s of this.#u.keys()){if(s.equals(e))return s;s.greater(e)||t.less(s)&&(t=s)}return t}}class M{#p;#m;#g;#f;constructor(e,t,s,r){this.#p=e,this.#m=t,this.#g=s,this.#f=r}get version(){return this.#p}get public(){return this.#m===l}get protected(){return this.#m===u}get private(){return this.#m===c}get parameters(){return this.#g}get executable(){return this.#f}}class T{#w;#y;constructor(e,t=!1){this.#w=e,this.#y=t}get name(){return this.#w}get isOptional(){return this.#y}}class R extends T{}class z extends T{#v;constructor(e,t,s){super(t??"(anonymous)",s),this.#v=e}get variables(){return this.#v}}class P extends z{}class L extends z{}class k{#t;#p;#S;#E=new Map;#b;constructor(e,t,s,r,n){this.#t=e,this.#p=t,this.#S=s,this.#E=r,this.#b=n}get fqn(){return this.#t}get version(){return this.#p}get args(){return this.#S}get headers(){return this.#E}get mode(){return this.#b}clearArguments(){this.#S.clear()}setArgument(e,t){this.#S.set(e,t)}getArgument(e){return this.#S.get(e)}hasArgument(e){return this.#S.has(e)}removeArgument(e){this.#S.delete(e)}clearHeaders(){this.#E.clear()}setHeader(e,t){this.#E.set(e.toLowerCase(),t)}getHeader(e){return this.#E.get(e.toLowerCase())}hasHeader(e){return this.#E.has(e.toLowerCase())}removeHeader(e){this.#E.delete(e.toLowerCase())}}class D{#x;#O;#E;constructor(e,t=void 0,s=new Map){this.#x=e,this.#O=t,this.#E=s}get status(){return this.#x}get result(){return this.#O}set result(e){this.#O=e}get headers(){return this.#E}clearHeaders(){this.#E.clear()}setHeader(e,t){this.#E.set(e.toLowerCase(),t)}getHeader(e){return this.#E.get(e.toLowerCase())}hasHeader(e){return this.#E.has(e.toLowerCase())}removeHeader(e){this.#E.delete(e.toLowerCase())}}class F extends e{#A;constructor(e){super(`Unknown parameter ${e}`),this.#A=e}get parameterName(){return this.#A}}class V extends e{#A;constructor(e){super(`Missing value for parameter '${e}'`),this.#A=e}get parameterName(){return this.#A}}class j extends e{#A;constructor(e){super(`Invalid value for parameter '${e}'`),this.#A=e}get parameterName(){return this.#A}}class ${extract(e,t){const s=this.#C(e,t),r=[];for(const t of e){const e=this.#I(t,s);r.push(e)}if(s.size>0){const e=s.keys().next().value;throw new F(e)}return r}#C(e,t){const s=new Map;for(const[r,n]of t){if(this.#N(r)){const t=this.#M(r);!0===this.#T(e,t)&&s.set(t,n);continue}s.set(r,n)}return s}#N(e){return e.startsWith("*")}#M(e){return e.substring(1)}#T(e,t){return void 0!==e.find(e=>e.name===t)}#I(e,t,s){return e instanceof R?this.#R(e,t,s):this.#z(e,t)}#R(e,t,s){const r=t.get(e.name);if(this.#P(e,r,s))throw new V(e.name);if(this.#L(e,r,s))throw new j(e.name);return t.delete(e.name),r}#z(e,t){return e instanceof P?this.#k(e,t):this.#D(e,t)}#k(e,t){const s=this.#F(e,t);return void 0!==s?Object.values(s):void 0}#D(e,t){return this.#F(e,t)}#F(e,t){const s=e instanceof P,r={},n=[];let a=!1,i=0;for(const o of e.variables){const c=s?i++:o.name,u=this.#I(o,t,e);void 0!==u?a=!0:!1===o.isOptional&&n.push(o.name),r[c]=u}if(!0===a&&n.length>0)throw new V(n[0]);return a?r:void 0}#P(e,t,s){return void 0===t&&(!0!==e.isOptional&&!0!==s?.isOptional)}#L(e,t,s){return!1!==e.name.startsWith("...")&&(void 0===s&&t instanceof Array==!1||s instanceof P&&t instanceof Array==!1||s instanceof L&&t instanceof Object==!1)}}class H{toStatus(a){return a instanceof e?m:a instanceof t?w:a instanceof s?y:a instanceof r?E:a instanceof n?f:a instanceof i?v:a instanceof o?g:S}fromStatus(c,u){switch(c){case m:return new e(u);case w:return new t(u);case y:return new s(u);case E:return new r(u);case f:return new n(u);case v:return new i(u);case g:return new o(u);default:return new a(u)}}}const U=/^\d+(?:\.\d+){0,2}$/;class G{parse(e){if(0===e.trim().length)return I.DEFAULT;if(!1===U.test(e))throw new b(e);const t=e.split(".");switch(t.length){case 1:return new I(Number.parseInt(t[0]));case 2:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new I(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class q extends s{#t;#p;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#t=e,this.#p=t}get fqn(){return this.#t}get version(){return this.#p}}class B extends a{constructor(){super("Invalid segment")}}class W{#V=new Map;addSegment(e){this.#V.set(e.id,e)}clearSegments(){this.#V.clear()}getClassNames(){const e=new Set;for(const t of this.#V.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.#V.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#V.values()){const s=t.getClassByImplementation(e);if(void 0!==s)return s}}getProcedureNames(){const e=new Set;for(const t of this.#V.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.#V.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class _{#j;#$;#H=new $;#U=new H;#G=new W;constructor(e,t=[]){this.#j=e,this.#$=t}async start(){return this.#q()}async stop(){return this.#B()}async loadSegment(e){const t=await this.#j.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof A==!1)throw new B;this.#G.addSegment(e)}getClassNames(){return this.#G.getClassNames()}hasClass(e){return this.#G.hasClass(e)}getClass(e){return this.#G.getClass(e)}getClassByImplementation(e){return this.#G.getClassByImplementation(e)}getProcedureNames(){return this.#G.getProcedureNames()}hasProcedure(e){return this.#G.hasProcedure(e)}getProcedure(e){return this.#G.getProcedure(e)}async run(e){const t=this.#W(e.fqn,e.version),s=this.#H.extract(t.parameters,e.args);return e.mode===d?new D(p,void 0):this.#_(e,t,s)}async#q(){await Promise.all(this.#$.map(e=>this.loadSegment(e)))}#B(){this.#G.clearSegments()}#W(e,t){const s=this.#G.getProcedure(e);if(void 0===s)throw new x(e);const r=s.getImplementation(t);if(void 0===r)throw new q(s.fqn,t.toString());return r}async#_(e,t,s){try{const r=await t.executable.call(e,...s);return new D(p,r)}catch(e){const t=this.#U.toStatus(e);return new D(t,e)}}}class K extends a{constructor(){super("Request cancelled")}}class Y{#K;#Y;#X=[];#J=!1;#Q=0;constructor(e,t=20){this.#K=e,this.#Y=t}start(){this.#J=!0,this.#Z()}stop(){this.#J=!1,this.#ee()}run(e){return new Promise((t,s)=>{this.#X.push({request:e,resolve:t,reject:s}),this.#Z()})}#Z(){if(this.#te())return;const e=this.#X.length,t=this.#Y-this.#Q,s=Math.min(e,t);this.#se(s)}#te(){return this.#re()||this.#ne()||this.#ae()}#re(){return!1===this.#J}#ne(){return 0===this.#X.length}#ae(){return this.#Q>=this.#Y}#se(e){const t=this.#X.splice(0,e);this.#Q+=e,t.forEach(e=>this.#ie(e))}async#ie(e){try{const t=await this.#K.run(e.request);e.resolve(t)}catch(t){e.reject(t)}finally{this.#Q--,this.#Z()}}#ee(){for(;this.#X.length>0;){const e=this.#X.shift();void 0!==e&&this.#oe(e)}}#oe(e){e.reject(new K)}}const X="starting",J="available",Q="unavailable",Z="stopping",ee="stopped";class te{#ce=ee;get state(){return this.#ce}set state(e){this.#ce=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.#ue(ee)}isStopped(){return this.#le(ee)}isAvailable(){return this.#le(J)}setStarting(){this.#ce=X}setAvailable(){this.#ce=J}setUnavailable(){this.#ce=Q}setAvailability(e){return this.#ce=e?J:Q,this.#ce}setStopping(){this.#ce=Z}setStopped(){this.#ce=ee}#le(...e){return e.includes(this.#ce)}#ue(...e){return!1===this.#le(...e)}}class se{#he;#de;#pe=new te;constructor(e){this.#he=e.url,this.#de=e.remote}get url(){return this.#he}get state(){return this.#pe.state}get trustKey(){}async start(){return this.#pe.start(async()=>{await this.#de.connect(),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{await this.#de.disconnect()})}isHealthy(){return this.#de.isHealthy()}getHealth(){return this.#de.getHealth()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}getProcedureNames(){throw new r}hasProcedure(e){throw new r}addWorker(e){return this.#de.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#de.reportWorker(e,t)}removeWorker(e){return this.#de.removeWorker(e)}run(e){return this.#de.run(e)}}class re extends Error{#me;constructor(e){super(`Invalid location: ${e}`),this.#me=e}get location(){return this.#me}}class ne extends Error{#ge;constructor(e){super(`The file '${e}' could not be found`),this.#ge=e}get filename(){return this.#ge}}class ae{#me;#fe;#we;constructor(e,t,s){this.#me=e,this.#fe=t,this.#we=s}get location(){return this.#me}get type(){return this.#fe}get content(){return this.#we}get size(){return this.#we.length}}class ie{#me;#ye;#ve;constructor(e,t){const s=t.resolve(e);this.#me=t.normalize(e),this.#ye=t.normalize(s),this.#ve=t}getAbsoluteLocation(e){const t=this.#ve.isAbsolute(e)?e:this.#ve.join(this.#me,e),s=this.#ve.resolve(t),r=this.#ve.normalize(s);return this.#Se(r,e),r}getRelativeLocation(e){const t=this.#ve.relative(this.#me,e);return this.#ve.normalize(t)}normalizeLocation(e){return this.#ve.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#ve.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#ve.exists(t))throw new ne(e);return this.#ve.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#ve.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#ve.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new ae(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#ve.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#ve.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#ve.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#ve.normalize(e);return(await this.#ve.filter(t,s)).map(e=>this.#ve.normalize(e))}#Se(e,t){if(!1===e.startsWith(this.#ye))throw new re(t)}}class oe extends Error{constructor(){super("Remote files are not supported")}}class ce{copy(e,t){throw new oe}delete(e){throw new oe}exists(e){throw new oe}async filter(e,t){return[]}isAbsolute(e){return e.startsWith("/")}isDirectory(e){throw new oe}join(...e){throw new oe}read(e){throw new oe}resolve(e){return e}relative(e,t){throw new oe}normalize(e){return e}mimeType(e){throw new oe}write(e,t){throw new oe}}class ue extends ie{constructor(e){super(e,new ce)}}class le extends Error{#he;#Ee;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#he=e,this.#Ee=t}get url(){return this.#he}get reason(){return this.#Ee}}class he{#be;constructor(e){this.#be=e}async import(e){const t=this.#be.locate(e);try{return await import(t)}catch(e){const s=e instanceof Error?e.message:String(e);throw new le(t,s)}}}class de{constructor(e){}locate(e){throw new le(e,"Remote module loading is not allowed")}}class pe extends he{constructor(e){super(new de(e))}}class me{#xe;#Oe;constructor(e,t){this.#xe=e,this.#Oe=t}async filter(...e){return(await Promise.all(e.map(e=>this.#xe.filter(e)))).flat().map(e=>this.#xe.getRelativeLocation(e))}exists(e){return this.#xe.exists(e)}read(e){return this.#xe.read(e)}import(e){return this.#Oe.import(e)}}class ge extends me{constructor(e){super(new ue(e),new pe(e))}}class fe extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class we extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class ye extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class ve extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Se{#Ae=[];addSerializer(e){e.parent=this,this.#Ae.unshift(e)}async serialize(e){const t=this.#Ae.find(t=>t.canSerialize(e));if(void 0===t)throw new ve(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Ae.find(t=>t.canDeserialize(e));if(void 0===t)throw new ye(typeof e);return t.deserialize(e)}}class Ee extends Error{constructor(){super("Parent serializer not set")}}class be{#Ce;set parent(e){this.#Ce=e}serializeOther(e){if(void 0===this.#Ce)throw new Ee;return this.#Ce.serialize(e)}deserializeOther(e){if(void 0===this.#Ce)throw new Ee;return this.#Ce.deserialize(e)}}class xe extends be{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const s of e)t.push(await this.serializeOther(s));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Oe extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Ae extends be{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 Oe(e.value)}}}class Ce extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Ie extends be{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 Ce(e.base64)}}}class Ne{#w;#Ie;constructor(e,t){this.#w=e,this.#Ie=t}get name(){return this.#w}get as(){return this.#Ie}toString(){return`${this.#w} as ${this.#Ie}`}}class Me{#Ne;constructor(e){this.#Ne=e}get definition(){return this.#Ne}toString(){return this.#Ne}}class Te extends Me{}class Re{#w;#Me;#Te;constructor(e,t=!1,s=!1){this.#w=e,this.#Me=t,this.#Te=s}get name(){return this.#w}get isStatic(){return this.#Me}get isPrivate(){return this.#Te}get isPublic(){return!1===this.#Te}}class ze extends Re{#Re;#ze;constructor(e,t,s){super(e),this.#Re=t,this.#ze=s}get parentName(){return this.#Re}get scope(){return this.#ze}get members(){return this.#ze.members}get declarations(){return this.#ze.declarations}get functions(){return this.#ze.functions}get getters(){return this.#ze.getters}get setters(){return this.#ze.setters}get generators(){return this.#ze.generators}get readable(){const e=new Map;return this.getters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get writable(){const e=new Map;return this.setters.forEach(t=>{e.set(t.name,t)}),this.declarations.forEach(t=>{t.isPublic&&e.set(t.name,t)}),[...e.values()]}get callable(){return this.functions.filter(e=>e.isPublic)}getMember(e){return this.#ze.getMember(e)}getDeclaration(e){return this.#ze.getDeclaration(e)}getFunction(e){return this.#ze.getFunction(e)}getGetter(e){return this.#ze.getGetter(e)}getSetter(e){return this.#ze.getSetter(e)}getGenerator(e){return this.#ze.getGenerator(e)}hasMember(e){return this.#ze.hasMember(e)}hasDeclaration(e){return this.#ze.hasDeclaration(e)}hasFunction(e){return this.#ze.hasFunction(e)}hasGetter(e){return this.#ze.hasGetter(e)}hasSetter(e){return this.#ze.hasSetter(e)}hasGenerator(e){return this.#ze.hasGenerator(e)}canRead(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasGetter(e)}canWrite(e){const t=this.getDeclaration(e);return t?.isPublic||this.hasSetter(e)}canCall(e){const t=this.getFunction(e);return t?.isPublic??!1}toString(){const e=void 0!==this.#Re?` extends ${this.#Re}`:"";return`class ${this.name}${e} { ${this.#ze.toString()} }`}}class Pe extends Re{#Pe;#Le;constructor(e,t,s=!1,r=!1){super(e.toString(),s,r),this.#Pe=e,this.#Le=t}get identifier(){return this.#Pe}get value(){return this.#Le}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class Le{#ke;constructor(e){this.#ke=e}get members(){return this.#ke}toString(){return this.#ke.map(e=>e.toString()).join(" , ")}}class ke extends Le{toString(){return`[ ${super.toString()} ]`}}class De extends Le{toString(){return`{ ${super.toString()} }`}}class Fe extends Re{#ke;#De;constructor(e,t){super(""),this.#ke=e,this.#De=t}get members(){return this.#ke}get from(){return this.#De}hasMember(e){return this.#ke.some(t=>t.as===e)}getMember(e){return this.#ke.find(t=>t.as===e)}toString(){const e=this.#De?` from '${this.#De}'`:"";return`export { ${this.#ke.join(", ")} }${e}`}}class Ve extends Me{}class je{#w;#Le;constructor(e,t){this.#w=e,this.#Le=t}get name(){return this.#w}get value(){return this.#Le}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class $e extends Re{#g;#Fe;#Ve;constructor(e,t,s,r=!1,n=!1,a=!1){super(e,r,a),this.#g=t,this.#Fe=s,this.#Ve=n}get parameters(){return this.#g}get body(){return this.#Fe}get isAsync(){return this.#Ve}toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}(${e.join(", ")}) { ${this.body} }`}}class He extends $e{toString(){const e=this.parameters.map(e=>e.toString());return`${this.isAsync?"async ":""}${this.name}*(${e.join(", ")}) { ${this.body} }`}}class Ue extends $e{toString(){return`get ${super.toString()}`}}class Ge extends Re{#ke;#De;constructor(e,t){super(""),this.#ke=e,this.#De=t}get members(){return this.#ke}get from(){return this.#De}hasMember(e){return this.#ke.some(t=>t.as===e)}getMember(e){return this.#ke.find(t=>t.as===e)}toString(){return`import { ${this.#ke.map(e=>e.toString()).join(", ")} } from '${this.#De}';`}}class qe{#ze;constructor(e){this.#ze=e}get scope(){return this.#ze}get members(){return this.#ze.members}get exportedMembers(){return this.#je(this.#ze.members)}get imports(){return this.#ze.imports}get exports(){return this.#ze.exports}get declarations(){return this.#ze.declarations}get exportedDeclarations(){return this.#je(this.#ze.declarations)}get functions(){return this.#ze.functions}get exportedFunctions(){return this.#je(this.#ze.functions)}get generators(){return this.#ze.generators}get exportedGenerators(){return this.#je(this.#ze.generators)}get classes(){return this.#ze.classes}get exportedClasses(){return this.#je(this.#ze.classes)}get exported(){const e=new Map;for(const t of this.exports)for(const s of t.members){const t=this.getMember(s.name);void 0!==t&&e.set(s.as,t)}return e}getMember(e){return this.#ze.getMember(e)}getDeclaration(e){return this.#ze.getDeclaration(e)}getFunction(e){return this.#ze.getFunction(e)}getGenerator(e){return this.#ze.getGenerator(e)}getClass(e){return this.#ze.getClass(e)}hasMember(e){return this.#ze.hasMember(e)}hasDeclaration(e){return this.#ze.hasDeclaration(e)}hasFunction(e){return this.#ze.hasFunction(e)}hasGenerator(e){return this.#ze.hasGenerator(e)}hasClass(e){return this.#ze.hasClass(e)}getImport(e){return this.imports.find(t=>t.hasMember(e))}getImported(e){for(const t of this.imports)for(const s of t.members)if(s.as===e)return this.getMember(s.name)}isExported(e){for(const t of this.exports)for(const s of t.members)if(s.name===e.name)return!0;return!1}getExport(e){return this.exports.find(t=>t.hasMember(e))}getExported(e){for(const t of this.exports)for(const s of t.members)if(s.as===e)return this.getMember(s.name)}#je(e){return e.filter(e=>this.isExported(e))}}class Be extends Me{}class We extends $e{toString(){return`set ${super.toString()}`}}const _e=Ge.name,Ke=Fe.name,Ye=Pe.name,Xe=$e.name,Je=Ue.name,Qe=We.name,Ze=He.name,et=ze.name;class tt{#ke;constructor(e){this.#ke=e}get members(){return this.#ke}get imports(){return this.#ke.filter(e=>e.constructor.name===_e)}get exports(){return this.#ke.filter(e=>e.constructor.name===Ke)}get declarations(){return this.#ke.filter(e=>e.constructor.name===Ye)}get functions(){return this.#ke.filter(e=>e.constructor.name===Xe)}get getters(){return this.#ke.filter(e=>e.constructor.name===Je)}get setters(){return this.#ke.filter(e=>e.constructor.name===Qe)}get generators(){return this.#ke.filter(e=>e.constructor.name===Ze)}get classes(){return this.#ke.filter(e=>e.constructor.name===et)}getMember(e){return this.#ke.find(t=>t.name===e)}getDeclaration(e){return this.declarations.find(t=>t.name===e)}getFunction(e){return this.functions.find(t=>t.name===e)}getGetter(e){return this.getters.find(t=>t.name===e)}getSetter(e){return this.setters.find(t=>t.name===e)}getGenerator(e){return this.generators.find(t=>t.name===e)}getClass(e){return this.classes.find(t=>t.name===e)}hasMember(e){return void 0!==this.getMember(e)}hasDeclaration(e){return void 0!==this.getDeclaration(e)}hasFunction(e){return void 0!==this.getFunction(e)}hasGetter(e){return void 0!==this.getGetter(e)}hasSetter(e){return void 0!==this.getSetter(e)}hasGenerator(e){return void 0!==this.getGenerator(e)}hasClass(e){return void 0!==this.getClass(e)}toString(){return this.#ke.map(e=>e.toString()).join("\n")}}const st={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},rt=Object.values(st);const nt=".",at="(",it=")",ot="[",ct="]",ut="{",lt="}",ht={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},dt=Object.values(ht);function pt(e){return dt.includes(e)}const mt={UNDEFINED:void 0,NULL:null,STRING:""},gt=Object.values(mt);function ft(e){return gt.includes(e)}const wt={OPEN:at,CLOSE:it};function yt(e){return e===wt.OPEN||e===wt.CLOSE}const vt={EXPORT:"export",DEFAULT:"default",CLASS:"class",FUNCTION:"function",CONST:"const",LET:"let",VAR:"var",AS:"as",FROM:"from",IMPORT:"import",GET:"get",SET:"set",EXTENDS:"extends",STATIC:"static",ASYNC:"async",RETURN:"return"},St=Object.values(vt);function Et(e){return St.includes(e)}function bt(e){return e===vt.AS||e===vt.ASYNC||e===vt.FROM||e===vt.GET||e===vt.SET}const xt={OPEN:ot,CLOSE:ct};function Ot(e){return e===xt.OPEN||e===xt.CLOSE}const At=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function Ct(e){return At.includes(e)}const It={ADD:"+",ARROW:"=>",ASSIGN:"=",ASSIGN_ADD:"+=",ASSIGN_BITWISE_AND:"&=",ASSIGN_BITWISE_OR:"|=",ASSIGN_DIVIDE:"/=",ASSIGN_LEFT_SHIFT:"<<=",ASSIGN_LOGICAL_AND:"&&=",ASSIGN_LOGICAL_OR:"||=",ASSIGN_MODULO:"%=",ASSIGN_MULTIPLY:"*=",ASSIGN_RIGHT_SHIFT:">>=",ASSIGN_SUBTRACT:"-=",ASSIGN_XOR:"^=",BITWISE_AND:"&",BITWISE_OR:"|",DECREMENT:"--",DIVIDE:"/",EQUAL:"==",EQUAL_STRICT:"===",GREATER:">",GREATER_EQUAL:">=",INCREMENT:"++",LEFT_SHIFT:"<<",LESS:"<",LESS_EQUAL:"<=",LOGICAL_AND:"&&",LOGICAL_OR:"||",MODULO:"%",MULTIPLY:"*",NOT:"!",NOT_EQUAL:"!=",NOT_EQUAL_STRICT:"!==",RIGHT_SHIFT:">>",SUBTRACT:"-",TERNARY:"?",XOR:"^"},Nt=Object.values(It);function Mt(e){return Nt.includes(e)}const Tt={OPEN:ut,CLOSE:lt};function Rt(e){return e===Tt.OPEN||e===Tt.CLOSE}const zt={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},Pt={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Lt=Object.values(Pt);function kt(e){return Lt.includes(e)}class Dt{#$e;#He;constructor(e){this.#$e=e,this.#He=0}get items(){return this.#$e}get position(){return this.#He}get size(){return this.#$e.length}get eol(){return this.#He>=this.#$e.length}get current(){return this.#$e[this.#He]}get next(){return this.#$e[this.#He+1]}get previous(){return this.#$e[this.#He-1]}notAtEnd(){return!1===this.eol}get(e){return this.#$e[e]}step(e=1){return this.#He+=e,this.current}stepBack(e=1){return this.#He-=e,this.current}hasNext(){return this.#He+1<this.#$e.length}}class Ft extends Dt{constructor(e){super(e.split(""))}}class Vt{#fe;#Le;#Ue;#Ge;constructor(e,t,s,r){this.#fe=e,this.#Le=t,this.#Ue=s,this.#Ge=r}get type(){return this.#fe}get value(){return this.#Le}get start(){return this.#Ue}get end(){return this.#Ge}isType(e){return this.#fe===e}hasValue(e){return this.#Le===e}toString(){return`${this.#Le}`}}class jt extends Dt{}class $t{tokenize(e){const t=new Ft(e),s=[];let r;for(;t.notAtEnd();){const e=this.#qe(t,r);if(void 0===e)break;e.isType(zt.WHITESPACE)||e.isType(zt.COMMENT)?t.step():(s.push(e),this.#Be(e)&&(r=e),t.step())}return new jt(s)}#Be(e){return!1===[zt.WHITESPACE,zt.COMMENT].includes(e.type)}#qe(e,t){const s=e.current,r=e.position;if(kt(s)){const t=e.position;return new Vt(zt.WHITESPACE,s,r,t)}if(function(e){return rt.includes(e)}(s+e.next)){const t=this.#We(e),s=e.position;return new Vt(zt.COMMENT,t,r,s)}if(this.#_e(s,t)){const t=this.#Ke(e),s=e.position;return new Vt(zt.REGEX,t,r,s)}if(Ct(s)){const t=this.#Ye(e),s=e.position;return new Vt(zt.LITERAL,t,r,s)}if(Mt(s)){const t=this.#Xe(e),s=e.position;return new Vt(zt.OPERATOR,t,r,s)}if(pt(s)){const t=e.position;return new Vt(zt.DIVIDER,s,r,t)}if(yt(s)){const t=e.position;return new Vt(zt.GROUP,s,r,t)}if(Rt(s)){const t=e.position;return new Vt(zt.SCOPE,s,r,t)}if(Ot(s)){const t=e.position;return new Vt(zt.LIST,s,r,t)}if(ft(s))return;const n=this.#Je(e),a=Et(n)?zt.KEYWORD:zt.IDENTIFIER,i=e.position;return new Vt(a,n,r,i)}#We(e){const t=e.current+e.next===st.MULTI_START,s=t?st.MULTI_END:Pt.NEWLINE;let r=t?st.MULTI_START:st.SINGLE;for(e.step(2);e.notAtEnd();){const n=e.current;if((t?n+e.next:n)===s){e.step(s.length-1);break}r+=n,e.step()}return t?r+st.MULTI_END:r.trim()}#_e(e,t){return e===It.DIVIDE&&(void 0===t||([zt.OPERATOR,zt.DIVIDER,zt.KEYWORD].includes(t.type)||[wt.OPEN,xt.OPEN].includes(t.value)))}#Qe(e){return kt(e)||e==nt||!1===this.#Ze(e)}#Ke(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,n=e.previous;if(r===It.DIVIDE&&"\\"!==n)s=!0;else if(!0===s&&this.#Qe(r)){e.stepBack();break}t+=r,e.step()}return t}#Ye(e){const t=e.current;let s=t,r=!1;for(e.step();e.notAtEnd();){const n=e.current;if(!1===r){if(n===t){s+=n;break}"\\"===n&&(r=!0)}else r=!1;s+=n,e.step()}return s}#Ze(e){return!1===(ft(e)||kt(e)||Mt(e)||Ct(e)||pt(e)||yt(e)||Rt(e)||Ot(e))}#Je(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#Ze(s)){e.stepBack();break}t+=s,e.step()}return t}#Xe(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===Mt(s)||!1===Mt(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Ht extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Ut extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Gt extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class qt extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class Bt extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}const Wt="default",_t=" ";class Kt{#et;constructor(e=new $t){this.#et=e}parse(e){const t=this.#et.tokenize(e),s=this.#tt(t);return new qe(s)}parseFirst(e){const t=this.#et.tokenize(e);return this.#st(t)}parseValue(e){const t=this.parseFirst(e);if(t instanceof Me==!1)throw new qt("a value definition");return t}parseImport(e){const t=this.parseFirst(e);if(t instanceof Ge==!1)throw new qt("an import definition");return t}parseExport(e){const t=this.parseFirst(e);if(t instanceof Fe==!1)throw new qt("an export definition");return t}parseDeclaration(e){const t=this.parseFirst(e);if(t instanceof Pe==!1)throw new qt("a declaration definition");return t}parseFunction(e){const t=this.#et.tokenize(e),s=this.#rt(t);if(s instanceof $e==!1)throw new qt("a function definition");return s}parseClass(e){const t=this.#et.tokenize(e),s=this.#rt(t);if(s instanceof ze==!1)throw new qt("a class definition");return s}#tt(e){const t=[];for(;e.notAtEnd();){const s=this.#st(e);s instanceof Re&&t.push(s)}return new tt(t)}#st(e,t=!1){const s=e.current;if(s.isType(zt.LITERAL))return this.#nt(e);if(s.isType(zt.IDENTIFIER)){const s=e.next;return s?.hasValue(It.ARROW)?this.#at(e,t):this.#nt(e)}if(s.isType(zt.KEYWORD)){if(bt(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(vt.FUNCTION)||t.hasValue(wt.OPEN));if(s.hasValue(vt.ASYNC)&&r)return e.step(),this.#st(e,!0);if(void 0===t||this.#it(t))return this.#nt(e)}return s.hasValue(vt.RETURN)?this.#nt(e):this.#rt(e,t)}if(s.isType(zt.REGEX))return this.#nt(e);if(s.hasValue(wt.OPEN)){const s=this.#ot(e,wt.OPEN,wt.CLOSE);return s?.hasValue(It.ARROW)?this.#at(e,t):this.#nt(e)}if(s.hasValue(Tt.OPEN))return this.#ct(e);if(s.hasValue(xt.OPEN))return this.#ut(e);if(s.hasValue(It.NOT)||s.hasValue(It.SUBTRACT))return this.#nt(e);if(!pt(s.value))throw new Bt(s.value,s.start);e.step()}#rt(e,t=!1){const s=e.current;switch(e.step(),s.value){case vt.IMPORT:return this.#lt(e);case vt.EXPORT:return this.#ht(e);case vt.CLASS:return this.#dt(e);case vt.FUNCTION:return this.#pt(e,t);case vt.VAR:case vt.LET:case vt.CONST:return this.#mt(e,!1,!0);case vt.ASYNC:return this.#rt(e,!0);default:throw new Gt(s.value,s.start)}}#lt(e){const t=[];let s=e.current;if(s.isType(zt.LITERAL))return new Ge(t,s.value);if(s.hasValue(wt.OPEN)){s=e.step();const r=s.value;return e.step(2),new Ge(t,r)}if(!1===s.hasValue(Tt.OPEN)){const r=s.hasValue(It.MULTIPLY)?It.MULTIPLY:Wt;let n=s.value;s=e.step(),s.hasValue(vt.AS)&&(s=e.step(),n=s.value,s=e.step()),t.push(new Ne(r,n))}if(s.hasValue(ht.SEPARATOR)&&(s=e.step()),s.hasValue(Tt.OPEN)){const r=this.#gt(e);t.push(...r),s=e.current}if(!1===s.hasValue(vt.FROM))throw new Ht(vt.FROM,s.start);s=e.step();const r=s.value;return e.step(),new Ge(t,r)}#ht(e){switch(e.current.value){case vt.DEFAULT:return e.step(),this.#ft(e,!0);case Tt.OPEN:return this.#wt(e);default:return this.#ft(e,!1)}}#ft(e,t){let s=e.current,r=0;var n;s.hasValue(vt.ASYNC)&&(s=e.step(),r++),((n=s.value)===vt.CLASS||n===vt.FUNCTION||n===vt.CONST||n===vt.LET||n===vt.VAR)&&(s=e.step(),r++);const a=this.#Ze(s)?s.value:"",i=t?Wt:a;let o;s=e.step(),s?.hasValue(vt.FROM)&&(s=e.step(),o=s.value),r>0&&(r++,e.stepBack(r));const c=new Ne(a,i);return new Fe([c],o)}#wt(e){const t=this.#gt(e);let s,r=e.current;return r?.hasValue(vt.FROM)&&(r=e.step(),s=r.value),e.step(),new Fe(t,s)}#gt(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Tt.CLOSE)){e.step();break}if(s.hasValue(ht.SEPARATOR)){s=e.step();continue}const r=this.#yt(e);t.push(r),s=e.step()}return t}#yt(e){let t=e.current;const s=t.value;let r=s;return e.next.hasValue(vt.AS)&&(t=e.step(2),r=t.value),new Ne(s,r)}#mt(e,t,s=!1){let r,n,a=e.current,i=!1;return a.hasValue(xt.OPEN)?(r=this.#vt(e),a=e.current):a.hasValue(Tt.OPEN)?(r=this.#St(e),a=e.current):(i=a.value.startsWith("#"),r=i?a.value.substring(1):a.value,a=e.step()),a.hasValue(It.ASSIGN)&&(e.step(),n=this.#st(e,!1),a=e.current),void 0!==a&&(a.hasValue(ht.TERMINATOR)?e.step():!0===s&&a.hasValue(ht.SEPARATOR)&&(e.step(),this.#mt(e,t,!0))),n instanceof He?new He(r.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof $e?new $e(r.toString(),n.parameters,n.body,t,n.isAsync,i):n instanceof ze?new ze(r.toString(),n.parentName,n.scope):new Pe(r,n,t,i)}#pt(e,t,s=!1,r=!1,n=!1){let a=e.current,i="",o=!1,c=!1;a.hasValue(It.MULTIPLY)&&(o=!0,a=e.step()),this.#Ze(a)&&(c=a.value.startsWith("#"),i=c?a.value.substring(1):a.value,a=e.step());const u=this.#Et(e,wt.CLOSE);if(a=e.current,!1===a.hasValue(Tt.OPEN))throw new Ut(Tt.OPEN,a.start);const l=this.#bt(e,Tt.OPEN,Tt.CLOSE);return o?new He(i,u,l,s,t,c):r?new Ue(i,u,l,s,t,c):n?new We(i,u,l,s,t,c):new $e(i,u,l,s,t,c)}#at(e,t){let s,r=e.current;if(r.hasValue(wt.OPEN)?(s=this.#Et(e,wt.CLOSE),r=e.current):(s=[new je(r.value,void 0)],r=e.step()),!1===r.hasValue(It.ARROW))throw new Ut(It.ARROW,r.start);r=e.step();const n=r.hasValue(Tt.OPEN)?this.#bt(e,Tt.OPEN,Tt.CLOSE):this.#nt(e).definition;return new $e("",s,n,!1,t,!1)}#Et(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(ht.SEPARATOR)){e.step();continue}let n;n=r.hasValue(Tt.OPEN)?this.#St(e):r.hasValue(xt.OPEN)?this.#vt(e):this.#xt(e),s.push(n)}return s}#dt(e){let t,s=e.current,r="";if(this.#Ze(s)&&(r=s.value,s=e.step()),s.hasValue(vt.EXTENDS)&&(s=e.step(),t=s.value,s=e.step()),!1===s.hasValue(Tt.OPEN))throw new Ut(Tt.OPEN,s.start);const n=this.#Ot(e);return new ze(r,t,n)}#Ot(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Tt.CLOSE)){e.step();break}const r=this.#At(e);s.push(r),t=e.current}return new tt(s)}#At(e){let t=e.current,s=!1,r=!1,n=!1,a=!1;for(;e.notAtEnd();){if(t.hasValue(vt.STATIC))r=!0;else if(t.hasValue(vt.ASYNC))s=!0;else if(t.hasValue(vt.GET))n=!0;else{if(!t.hasValue(vt.SET)){if(t.hasValue(It.MULTIPLY))return this.#pt(e,s,r,!1,!1);break}a=!0}t=e.step()}return e.next.hasValue(wt.OPEN)?this.#pt(e,s,r,n,a):this.#mt(e,r)}#ut(e){const t=this.#bt(e,xt.OPEN,xt.CLOSE);return new Te(t)}#vt(e){const t=this.#Et(e,xt.CLOSE);return new ke(t)}#ct(e){const t=this.#bt(e,Tt.OPEN,Tt.CLOSE);return new Be(t)}#St(e){const t=this.#Et(e,Tt.CLOSE);return new De(t)}#xt(e){let t=e.current;const s=t.value;let r;return t=e.step(),t.hasValue(It.ASSIGN)&&(e.step(),r=this.#st(e,!1)),new je(s,r)}#nt(e){let t=e.current,s="";for(;e.notAtEnd();){if(t.hasValue(xt.OPEN)){s+=this.#bt(e,xt.OPEN,xt.CLOSE)+_t,t=e.current}else if(t.hasValue(wt.OPEN)){s+=this.#bt(e,wt.OPEN,wt.CLOSE)+_t,t=e.current}else if(t.hasValue(Tt.OPEN)){s+=this.#bt(e,Tt.OPEN,Tt.CLOSE)+_t,t=e.current}else s+=t.toString()+_t,t=e.step();if(void 0===t||this.#it(t))break}return new Ve(s.trim())}#bt(e,t,s){let r=e.step(),n=t+_t;for(;e.notAtEnd();)if(r.hasValue(t))n+=this.#bt(e,t,s)+_t,r=e.current;else{if(r.hasValue(s))return e.step(),n+=s,n;n+=r.toString()+_t,r=e.step()}return n}#ot(e,t,s){const r=e.position;this.#bt(e,t,s);const n=e.current,a=e.position;return e.stepBack(a-r),n}#it(e){return[ht.TERMINATOR,ht.SEPARATOR].includes(e.value)||[xt.CLOSE,wt.CLOSE,Tt.CLOSE].includes(e.value)||Et(e.value)}#Ze(e){return e.isType(zt.IDENTIFIER)||e.isType(zt.KEYWORD)&&bt(e.value)}}class Yt{merge(e,t){const s=this.#Ct(e.declarations,t.declarations),r=this.#It(e.functions,t.functions),n=this.#It(e.getters,t.getters),a=this.#It(e.setters,t.setters),i=[...s.values(),...r.values(),...n.values(),...a.values()];return new ze(e.name,t.name,new tt(i))}#Ct(e,t){const s=new Map;return t.forEach(e=>s.set(e.name,e)),e.forEach(e=>s.set(e.name,e)),[...s.values()]}#It(e,t){const s=new Map;return t.forEach(e=>s.set(e.name,e)),e.forEach(e=>s.set(e.name,e)),[...s.values()]}}class Xt{#Nt=new Kt;#Mt=new Yt;fromModule(e,t=!1){const s=Object.entries(e),r=[];for(const[e,n]of s){if("function"!=typeof n.toString)continue;const s=n.toString();if(s.startsWith("class"))r.push(this.fromClass(n,t));else if(s.startsWith("function"))r.push(this.fromFunction(n));else{const t=new Ve(s);r.push(new Pe(e,t))}}return new qe(new tt(r))}fromClass(e,t=!1){const s=this.isClass(e)?this.#Tt(e):this.#Rt(e);if(!1===t)return s;const r=this.getParentClass(e);if(""===r.name)return s;const n=this.fromClass(r,!0);return this.#Mt.merge(s,n)}fromObject(e,t=!0){const s=this.getClass(e);return this.fromClass(s,t)}fromFunction(e){const t=e.toString();return this.#Nt.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")}#Tt(e){const t=e.toString();return this.#Nt.parseClass(t)}#Rt(e){const t=this.createInstance(e),s=this.#zt(e,t),r=new tt(s);return new ze(e.name,void 0,r)}#zt(e,t){return[...this.#Pt(t),...this.#Lt(e)]}#Pt(e){const t=Object.getOwnPropertyNames(e),s=e,r=[];for(const e of t){const t=s[e],n=void 0!==t?new Me(String(t)):void 0,a=new Pe(e,n);r.push(a)}return r}#Lt(e){const t=Object.getOwnPropertyDescriptors(e.prototype),s=[];for(const e in t){const r=t[e],n=r.value;if(n instanceof Function==!1)continue;const a=this.fromFunction(n);void 0!==r.get?s.push(new Ue(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):void 0!==r.set?s.push(new We(a.name,a.parameters,a.body,a.isStatic,a.isAsync,a.isPrivate)):s.push(a)}return s}}const Jt=new Xt;class Qt extends be{#kt;constructor(e){super(),this.#kt=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),s=Jt.fromClass(t,!0),r=this.#Dt(s),n=this.#kt.resolveKey(t);if(void 0===n)throw new fe(t.name);return{serialized:!0,key:n,name:"class",args:await this.#Ft(s,r,e),fields:await this.#Vt(s,r,e)}}#Dt(e){const t=e.getFunction("constructor");return(t?.parameters??[]).map(e=>e.name)}async#Ft(e,t,s){const r={};for(const[n,a]of t.entries()){const t=e.canRead(a)?await this.serializeOther(s[a]):void 0;r[n.toString()]=t}return r}async#Vt(e,t,s){const r={};for(const n of e.writable){const a=n.name;t.includes(a)||!1===e.canRead(a)||(r[a]=await this.serializeOther(s[a]))}return r}async deserialize(e){const t=await this.#jt(e);if(void 0===t)throw new fe(e.key);if(t instanceof Function==!1)throw new we(e.key);const s=await this.#$t(t,e.args),r=Jt.createInstance(t,s);for(const t in e.fields){const s=e.fields[t];r[t]=await this.deserializeOther(s)}return r}async#$t(e,t){const s=Jt.fromClass(e,!0).getFunction("constructor"),r=(s?.parameters??[]).map((e,s)=>{const r=s.toString(),n=t[r];return this.deserializeOther(n)});return Promise.all(r)}async#jt(e){return globalThis[e.key]??this.#kt.resolveClass(e.key)}}class Zt extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class es extends be{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 Zt(e.value);return t}}class ts extends be{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 ss extends be{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=[],s=[];for(const[r,n]of e)t.push(await this.serializeOther(r)),s.push(await this.serializeOther(n));return{serialized:!0,name:"Map",entries:{keys:t,values:s}}}async deserialize(e){const t=e.entries.keys,s=e.entries.values,r=new Map;for(let e=0;e<t.length;e++){const n=await this.deserializeOther(t[e]),a=await this.deserializeOther(s[e]);r.set(n,a)}return r}}class rs extends be{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 s in e){const r=e[s];t[s]=await this.serializeOther(r)}return t}async deserialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.deserializeOther(r)}return t}}class ns extends be{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 as extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class is extends be{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 as(e.source,e.flags)}}}class os extends be{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 s of e.values())t.push(await this.serializeOther(s));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 cs=new Xt;class us extends be{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,s=new DataView(e.buffer),r=[];for(let e=0;e<s.byteLength;e++)r.push(s.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:r}}async deserialize(e){const t=e.type,s=e.bytes,r=new ArrayBuffer(s.length),n=new DataView(r);for(let e=0;e<s.length;e++)n.setUint8(e,s[e]);const a=globalThis[t];return cs.createInstance(a,[r])}}class ls extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class hs extends be{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 ls(e.value)}}}class ds{static build(e){const t=new Se;return t.addSerializer(new ns),t.addSerializer(new rs),void 0!==e&&t.addSerializer(new Qt(e)),t.addSerializer(new ts),t.addSerializer(new is),t.addSerializer(new Ae),t.addSerializer(new hs),t.addSerializer(new es),t.addSerializer(new os),t.addSerializer(new ss),t.addSerializer(new xe),t.addSerializer(new us),"undefined"!=typeof Buffer&&t.addSerializer(new Ie),t}}class ps{#Ht;constructor(e){this.#Ht=e}resolveKey(e){const t=this.#Ht.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Ht.getClass(e);return t?.implementation}}class ms extends o{constructor(){super("Request not trusted")}}const gs="X-Jitar-Trust-Key",fs="X-Jitar-Data-Encoding",ws="serialized";class ys{#s;#he;#Ut;#Gt;#qt;#Ht;#Bt;#Wt;#_t;#pe=new te;constructor(e){this.#he=e.url,this.#Ut=e.trustKey,this.#Gt=e.gateway,this.#qt=!0===e.registerAtGateway,this.#Ht=e.executionManager,this.#Bt=e.healthManager;const t=e.scheduleManager;this.#Wt=t.create(()=>this.#Kt(),e.reportInterval);const s=new ps(this.#Ht);this.#_t=ds.build(s)}get id(){return this.#s}set id(e){this.#s=e}get state(){return this.#pe.state}get url(){return this.#he}get trustKey(){return this.#Ut}async start(){return this.#pe.start(async()=>{await Promise.all([this.#Ht.start(),this.#Bt.start()]),void 0!==this.#Gt&&(await this.#Gt.start(),this.#qt&&(this.#s=await this.#Gt.addWorker(this),this.#Wt.start())),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{void 0!==this.#Gt&&(void 0!==this.#s&&(this.#Wt.stop(),await this.#Gt.removeWorker(this.#s)),await this.#Gt.stop()),await Promise.all([this.#Bt.stop(),this.#Ht.stop()])})}getProcedureNames(){return this.#Ht.getProcedureNames()}hasProcedure(e){return this.#Ht.hasProcedure(e)}isHealthy(){return this.#Bt.isHealthy()}getHealth(){return this.#Bt.getHealth()}isAvailable(){return this.#pe.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}async reportState(e){if(void 0!==this.#Gt&&void 0!==this.#s)return this.#Gt.reportWorker(this.#s,e)}async run(e){return this.#Yt(e)?this.#Xt(e):this.#Jt(e)}#Yt(e){return void 0===this.#Gt||this.#Ht.hasProcedure(e.fqn)}async#Xt(e){const t=this.#Ht.getProcedure(e.fqn),s=t?.getImplementation(e.version);if(this.#Qt(s))throw new x(e.fqn);if(this.#Zt(e,s))throw new ms;const r=e.getHeader(fs);r===ws&&(e=await this.#es(e)),e.removeHeader(fs);const n=await this.#Ht.run(e);return r===ws?this.#ts(n):n}#Qt(e){return void 0===e||e.private}#Zt(e,t){if(t.public)return!1;const s=e.getHeader(gs);return this.#Ut!==s}async#Jt(e){(e=await this.#ss(e)).setHeader(fs,ws),void 0!==this.#Ut&&e.setHeader(gs,this.#Ut);const t=await this.#Gt.run(e);return this.#rs(t)}async#ss(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#_t.serialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#es(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#_t.deserialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#ts(e){const t=await this.#_t.serialize(e.result);return new D(e.status,t,e.headers)}async#rs(e){const t=await this.#_t.deserialize(e.result);return new D(e.status,t,e.headers)}async#Kt(){const e=await this.updateState();return this.reportState(e)}}class vs{#K;constructor(e){this.#K=e}async handle(e,t){return this.#K.run(e)}}class Ss{#ns=new G;constructor(){this.#as()}#as(){const e=globalThis;e.__run=this.#is.bind(this),e.ProcedureNotAccessible=O}async#is(e,t,s,r){const n=this.#ns.parse(t),a=new Map(Object.entries(s)),i=r instanceof k?r.headers:new Map,o=new k(e,n,a,i,h),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const u=await this.runInternal(o);if(u.status!==p)throw u.result;return u.result}}class Es extends Ss{#os;#cs;#us=new Y(this);constructor(e){super(),this.#os=new ys({url:e.remoteUrl,gateway:new se({url:e.remoteUrl,remote:e.remote}),healthManager:e.healthManager,executionManager:e.executionManager,scheduleManager:e.scheduleManager}),this.#cs=e.middlewareManager}get worker(){return this.#os}async start(){await this.#ls(),this.#us.start()}async stop(){this.#us.stop(),await this.#hs()}getTrustKey(){}run(e){return this.#cs.handle(e)}async runInternal(e){return this.#us.run(e)}async#ls(){await Promise.all([this.#os.start(),this.#cs.start()]);const e=new vs(this.#os);this.#cs.addMiddleware(e)}async#hs(){await Promise.all([this.#cs.stop(),this.#os.stop()])}}const bs="starting",xs="started",Os="stopping",As="stopped";class Cs extends a{constructor(){super("Invalid health check")}}class Is{#ce=As;#ds=new Map;#j;#ps;constructor(e,t=[]){this.#j=e,this.#ps=t}get state(){return this.#ce}async start(){if(this.#ce===As)try{this.#ce=bs,await this.#ms(),this.#ce=xs}catch(e){throw this.#ce=As,e}}async stop(){if(this.#ce===xs)try{this.#ce=Os,this.clearHealthChecks(),this.#ce=As}catch(e){throw this.#ce=xs,e}}async loadHealthCheck(e){const t=await this.#gs(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new Cs;this.#ds.set(e.name,e)}clearHealthChecks(){this.#ds.clear()}async isHealthy(){const e=[];for(const t of this.#ds.values()){const s=this.#fs(t);e.push(s)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,s]of this.#ds){const r=this.#fs(s).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(r)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#ws(e,t))).then(()=>t)}async#ms(){(await Promise.all(this.#ps.map(e=>this.#gs(e)))).forEach(e=>this.addHealthCheck(e))}async#gs(e){return(await this.#j.import(e)).default}#ws(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#fs(e){const t=e.isHealthy(),s=e.timeout;if(void 0===s)return t;const r=new Promise(e=>{setTimeout(e,s)}).then(()=>!1);return Promise.race([r,t])}}const Ns=0,Ms=1,Ts=2,Rs=3;class zs{#ys;#vs;constructor(e=Ms,t=console){this.#ys=e,this.#vs=t}debug(...e){if(this.#ys>Ns)return;const t=this.#Ss("DEBUG",e);this.#vs.debug(t)}info(...e){if(this.#ys>Ms)return;const t=this.#Ss("INFO",e);this.#vs.info(t)}warn(...e){if(this.#ys>Ts)return;const t=this.#Ss("WARN",e);this.#vs.warn(t)}error(...e){if(this.#ys>Rs)return;const t=this.#Ss("ERROR",e);this.#vs.error(t)}fatal(...e){const t=this.#Ss("FATAL",e);this.#vs.error(t)}#Ss(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Es(e)).join(" ")}`}#Es(e,t=0){let s;switch(typeof e){case"string":s=e;break;case"object":s=this.#bs(e,t+1);break;case"undefined":s="undefined";break;case"function":s="function";break;default:s=String(e)}return`${this.#xs(t)}${s}`}#bs(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Es(e,t)).join(",\n")}\n${this.#xs(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#xs(e){return" ".repeat(e)}}const Ps="starting",Ls="started",ks="stopping",Ds="stopped";class Fs extends a{constructor(){super("Invalid middleware")}}class Vs{#ce=Ds;#Os=[];#j;#As;constructor(e,t=[]){this.#j=e,this.#As=t}get state(){return this.#ce}async start(){if(this.#ce===Ds)try{this.#ce=Ps,await this.#Cs(),this.#ce=Ls}catch(e){throw this.#ce=Ds,e}}async stop(){if(this.#ce===Ls)try{this.#ce=ks,this.clearMiddlewares(),this.#ce=Ds}catch(e){throw this.#ce=Ls,e}}async loadMiddleware(e){const t=await this.#Is(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new Fs;this.#Os.push(e)}getMiddleware(e){return this.#Os.find(t=>t instanceof e)}clearMiddlewares(){this.#Os=[]}handle(e){return this.#Ns(e,0)()}async#Cs(){(await Promise.all(this.#As.map(e=>this.#Is(e)))).forEach(e=>this.addMiddleware(e))}async#Is(e){return(await this.#j.import(e)).default}#Ns(e,t){const s=this.#Os[t];if(void 0===s)return async()=>new D(p);const r=this.#Ns(e,t+1);return async()=>await s.handle(e,r)}}class js{#Ms;#Ts;#Rs;#zs=null;constructor(e,t,s=5e3){this.#Ms=e,this.#Ts=t,this.#Rs=s}start(){this.#Ps()}stop(){null!==this.#zs&&(clearTimeout(this.#zs),this.#zs=null)}#Ps(){this.#zs=setTimeout(async()=>{null!==this.#zs&&(await this.#Ls(),this.#Ps())},this.#Rs),this.#zs.unref()}async#Ls(){try{await this.#Ts()}catch(e){this.#Ms.warn("Scheduled task failed",e)}}}class $s{#ks=[];#Ms;constructor(e){this.#Ms=e}create(e,t){const s=new js(this.#Ms,e,t);return this.#ks.push(s),s}remove(e){const t=this.#ks.indexOf(e);t<0||this.#ks.splice(t,1)}startAll(){this.#ks.forEach(e=>e.start())}stopAll(){this.#ks.forEach(e=>e.stop())}}class Hs{#Ds;constructor(e){this.#Ds=e}build(e){const t=e.remoteUrl,s=e.middleware,r=e.segments,n=new zs(e.logLevel??Ts),a=this.#Ds.build(t),i=new ge(t),o=this.#Fs(i),c=this.#Vs(i,s),u=this.#js(i,r),l=this.#$s(n);return new Es({remoteUrl:t,remote:a,healthManager:o,middlewareManager:c,executionManager:u,scheduleManager:l})}#Fs(e){return new Is(e)}#Vs(e,t=[]){const s=new Vs(e);return t.forEach(e=>s.addMiddleware(e)),s}#js(e,t=[]){const s=new _(e);return t.forEach(e=>s.addSegment(e)),s}#$s(e){return new $s(e)}}class Us{#Hs;constructor(e=!0){this.#Hs=e}validate(e,t){const s=[];this.#Us("",e,t,s);return{valid:0===s.length,errors:s}}#Us(e,t,s,r){this.#Hs&&this.#Gs(e,t,s,r),this.#qs(e,t,s,r)}#Gs(e,t,s,r){const n=Object.keys(t),a=Object.keys(s);for(const t of n)if(!1===a.includes(t)){const s=this.#Bs(e,t);r.push(`Unknown field '${s}'`)}}#qs(e,t,s,r){const n=Object.keys(s);for(const a of n){const n=this.#Bs(e,a),i=s[a],o=t[a];this.#Ws(n,o,i,r)}}#Ws(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#_s(e,t,s,r);case"integer":return this.#Ks(e,t,s,r);case"real":return this.#Ys(e,t,s,r);case"boolean":return this.#Xs(e,t,s,r);case"url":return this.#Js(e,t,s,r);case"group":return this.#Qs(e,t,s,r);case"list":return this.#Zs(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#_s(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#Ks(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#Ys(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#Xs(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#Js(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#Qs(e,t,s,r){"object"==typeof t?this.#Us(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#Zs(e,t,s,r){if(!Array.isArray(t))return void r.push(`Field '${e}' is not a list`);const n=t;for(const t in n){const a=this.#Bs(e,t),i=n[t];this.#Ws(a,i,s.items,r)}}#Bs(e,t){return""===e?t:`${e}.${t}`}}const Gs="content-type",qs="x-jitar-content-type",Bs="x-jitar-procedure-version",Ws="application/json",_s="application/octet-stream";class Ks extends Error{constructor(){super("Invalid worker id")}}class Ys{#he;#er;#U=new H;#tr=new Us;constructor(e,t){this.#he=e,this.#er=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#he}/${e}`,s=await this.#sr(t,{method:"GET"}),r=s.headers.get(Gs)??_s,n=await s.arrayBuffer(),a=Buffer.from(n);return new ae(e,r,a)}async isHealthy(){const e=`${this.#he}/health/status`,t=await this.#sr(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#he}/health`,t=await this.#sr(e,{method:"GET"}),s=await t.json();return new Map(Object.entries(s))}async addWorker(e,t,s){const r=`${this.#he}/workers`,n={url:e,procedureNames:t,trustKey:s},a={method:"POST",headers:{"Content-Type":Ws},body:JSON.stringify(n)},i=await this.#sr(r,a),o=i.headers.get(Gs);if(null===o||!1===o.includes(Ws))throw new Ks;const c=await i.json();if(!1===this.#tr.validate(c,{id:{type:"string",required:!0}}).valid)throw new Ks;return c.id}async reportWorker(e,t){const s=`${this.#he}/workers/${e}/report`,r={state:t},n={method:"POST",headers:{"Content-Type":Ws},body:JSON.stringify(r)};await this.#sr(s,n)}async removeWorker(e){const t=`${this.#he}/workers/${e}`,s={method:"DELETE",headers:{"Content-Type":Ws}};await this.#sr(t,s)}async run(e){e.setHeader(Gs,Ws);const t=Object.fromEntries(e.args),s=Object.fromEntries(e.headers),r=e.version.toString();s[Bs]=r;const n=`${this.#he}/rpc/${e.fqn}`,a={method:"POST",redirect:"manual",headers:s,body:await this.#rr(t)},i=await this.#sr(n,a,!1),o=i.status,c=await this.#nr(i),u=this.#ar(i);return new D(o,c,u)}async#sr(e,t,s=!0){const r=await this.#er.execute(e,t);if(s&&this.#ir(r)){const e=await this.#nr(r);throw this.#U.fromStatus(r.status,String(e))}return r}#ir(e){return e.status<200||e.status>399}async#rr(e){return JSON.stringify(e)}async#nr(e){const t=e.headers.get(qs)??e.headers.get(Gs);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const s=await e.text();return t?.includes("boolean")?"true"===s:t?.includes("number")?Number(s):s}#ar(e){const t=new Map;for(const[s,r]of e.headers)t.set(s,r);return t}}class Xs{async execute(e,t){return fetch(e,t)}}class Js{#er;constructor(e=new Xs){this.#er=e}build(e){return new Ys(e,this.#er)}}export{P as ArrayParameter,e as BadRequest,C as Class,Hs as ClientBuilder,t as Forbidden,Js as HttpRemoteBuilder,M as Implementation,R as NamedParameter,s as NotFound,r as NotImplemented,L as ObjectParameter,n as PaymentRequired,N as Procedure,k as Request,D as Response,A as Segment,a as ServerError,i as Teapot,o as Unauthorized,I as Version};
|
|
1
|
+
class e extends Error{constructor(e="Invalid request"){super(e)}}class t extends Error{constructor(e="Forbidden"){super(e)}}class s extends Error{constructor(e="Not found"){super(e)}}class r extends Error{constructor(e="Not implemented"){super(e)}}class i extends Error{constructor(e="Payment required"){super(e)}}class n extends Error{constructor(e="Server error"){super(e)}}class a extends Error{constructor(e="I'm a teapot"){super(e)}}class o extends Error{constructor(e="Unauthorized"){super(e)}}const c="private",l="protected",u="public",h="normal",d="dry",p=200,m=400,f=401,g=402,w=403,y=404,E=418,S=500,v=501;class b extends e{#e;constructor(e){super(`Invalid version number '${e}'`),this.#e=e}get number(){return this.#e}}class O extends s{#t;constructor(e){super(`Procedure '${e}' not found`),this.#t=e}get fqn(){return this.#t}}class A extends t{constructor(e,t){super(`Procedure '${e}' (v${t}) is not accessible`)}}class I{#s;#r=new Map;#i=new Map;constructor(e){this.#s=e}get id(){return this.#s}addClass(e){return this.#r.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#r.get(e)}getClassByImplementation(e){return this.getClasses().find(t=>t.implementation===e)}getClasses(){return[...this.#r.values()]}addProcedure(e){return this.#i.set(e.fqn,e),this}hasProcedure(e){return this.#i.has(e)}getProcedure(e){return this.#i.get(e)}getExposedProcedures(){return[...this.#i.values()].filter(e=>e.public||e.protected)}}class N{#t;#n;constructor(e,t){this.#t=e,this.#n=t}get fqn(){return this.#t}get implementation(){return this.#n}}class T{static get DEFAULT(){return new T(0,0,0)}#a;#o;#c;constructor(e=0,t=0,s=0){this.#a=e,this.#o=t,this.#c=s}get major(){return this.#a}get minor(){return this.#o}get patch(){return this.#c}equals(e){return this.#a===e.major&&this.#o===e.minor&&this.#c===e.patch}greater(e){return this.#a!==e.major?this.#a>e.major:this.#o!==e.minor?this.#o>e.minor:this.#c!==e.patch&&this.#c>e.patch}less(e){return this.#a!==e.major?this.#a<e.major:this.#o!==e.minor?this.#o<e.minor:this.#c!==e.patch&&this.#c<e.patch}toString(){return`${this.#a}.${this.#o}.${this.#c}`}}class x{#t;#l=new Map;#u;constructor(e){this.#t=e}get fqn(){return this.#t}get public(){return[...this.#l.values()].some(e=>e.public)}get protected(){return[...this.#l.values()].some(e=>e.protected)}addImplementation(e){return this.#l.set(e.version,e),this.#h(e)&&(this.#u=e),this}#h(e){return void 0===this.#u||e.version.greater(this.#u.version)}getImplementation(e){const t=this.#d(e);return this.#l.get(t)}#d(e){let t=T.DEFAULT;for(const s of this.#l.keys()){if(s.equals(e))return s;s.greater(e)||t.less(s)&&(t=s)}return t}}class C{#p;#m;#f;#g;constructor(e,t,s,r){this.#p=e,this.#m=t,this.#f=s,this.#g=r}get version(){return this.#p}get public(){return this.#m===u}get protected(){return this.#m===l}get private(){return this.#m===c}get parameters(){return this.#f}get executable(){return this.#g}}class R{#w;#y;constructor(e,t=!1){this.#w=e,this.#y=t}get name(){return this.#w}get isOptional(){return this.#y}}class M extends R{}class z extends R{#E;constructor(e,t,s){super(t??"(anonymous)",s),this.#E=e}get variables(){return this.#E}}class L extends z{}class P extends z{}class k{#t;#p;#S;#v=new Map;#b;constructor(e,t,s,r,i){this.#t=e,this.#p=t,this.#S=s,this.#v=r,this.#b=i}get fqn(){return this.#t}get version(){return this.#p}get args(){return this.#S}get headers(){return this.#v}get mode(){return this.#b}clearArguments(){this.#S.clear()}setArgument(e,t){this.#S.set(e,t)}getArgument(e){return this.#S.get(e)}hasArgument(e){return this.#S.has(e)}removeArgument(e){this.#S.delete(e)}clearHeaders(){this.#v.clear()}setHeader(e,t){this.#v.set(e.toLowerCase(),t)}getHeader(e){return this.#v.get(e.toLowerCase())}hasHeader(e){return this.#v.has(e.toLowerCase())}removeHeader(e){this.#v.delete(e.toLowerCase())}}class ${#O;#A;#v;constructor(e,t=void 0,s=new Map){this.#O=e,this.#A=t,this.#v=s}get status(){return this.#O}get result(){return this.#A}set result(e){this.#A=e}get headers(){return this.#v}clearHeaders(){this.#v.clear()}setHeader(e,t){this.#v.set(e.toLowerCase(),t)}getHeader(e){return this.#v.get(e.toLowerCase())}hasHeader(e){return this.#v.has(e.toLowerCase())}removeHeader(e){this.#v.delete(e.toLowerCase())}}class V extends e{#I;constructor(e){super(`Unknown parameter ${e}`),this.#I=e}get parameterName(){return this.#I}}class D extends e{#I;constructor(e){super(`Missing value for parameter '${e}'`),this.#I=e}get parameterName(){return this.#I}}class j extends e{#I;constructor(e){super(`Invalid value for parameter '${e}'`),this.#I=e}get parameterName(){return this.#I}}class F{extract(e,t){const s=this.#N(e,t),r=[];for(const t of e){const e=this.#T(t,s);r.push(e)}if(s.size>0){const e=s.keys().next().value;throw new V(e)}return r}#N(e,t){const s=new Map;for(const[r,i]of t){if(this.#x(r)){const t=this.#C(r);!0===this.#R(e,t)&&s.set(t,i);continue}s.set(r,i)}return s}#x(e){return e.startsWith("*")}#C(e){return e.substring(1)}#R(e,t){return void 0!==e.find(e=>e.name===t)}#T(e,t,s){return e instanceof M?this.#M(e,t,s):this.#z(e,t)}#M(e,t,s){const r=t.get(e.name);if(this.#L(e,r,s))throw new D(e.name);if(this.#P(e,r,s))throw new j(e.name);return t.delete(e.name),r}#z(e,t){return e instanceof L?this.#k(e,t):this.#$(e,t)}#k(e,t){const s=this.#V(e,t);return void 0!==s?Object.values(s):void 0}#$(e,t){return this.#V(e,t)}#V(e,t){const s=e instanceof L,r={},i=[];let n=!1,a=0;for(const o of e.variables){const c=s?a++:o.name,l=this.#T(o,t,e);void 0!==l?n=!0:!1===o.isOptional&&i.push(o.name),r[c]=l}if(!0===n&&i.length>0)throw new D(i[0]);return n?r:void 0}#L(e,t,s){return void 0===t&&(!0!==e.isOptional&&!0!==s?.isOptional)}#P(e,t,s){return!1!==e.name.startsWith("...")&&(void 0===s&&t instanceof Array==!1||s instanceof L&&t instanceof Array==!1||s instanceof P&&t instanceof Object==!1)}}class B{toStatus(n){return n instanceof e?m:n instanceof t?w:n instanceof s?y:n instanceof r?v:n instanceof i?g:n instanceof a?E:n instanceof o?f:S}fromStatus(c,l){switch(c){case m:return new e(l);case w:return new t(l);case y:return new s(l);case v:return new r(l);case g:return new i(l);case E:return new a(l);case f:return new o(l);default:return new n(l)}}}const H=/^\d+(?:\.\d+){0,2}$/;class U{parse(e){if(0===e.trim().length)return T.DEFAULT;if(!1===H.test(e))throw new b(e);const t=e.split(".");switch(t.length){case 1:return new T(Number.parseInt(t[0]));case 2:return new T(Number.parseInt(t[0]),Number.parseInt(t[1]));default:return new T(Number.parseInt(t[0]),Number.parseInt(t[1]),Number.parseInt(t[2]))}}}class G extends s{#t;#p;constructor(e,t){super(`No implementation found for procedure '${e}' with version '${t}'`),this.#t=e,this.#p=t}get fqn(){return this.#t}get version(){return this.#p}}class q extends n{constructor(){super("Invalid segment")}}class W{#D=new Map;addSegment(e){this.#D.set(e.id,e)}clearSegments(){this.#D.clear()}getClassNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasClass(e))return t.getClass(e)}getClassByImplementation(e){for(const t of this.#D.values()){const s=t.getClassByImplementation(e);if(void 0!==s)return s}}getProcedureNames(){const e=new Set;for(const t of this.#D.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.#D.values())if(t.hasProcedure(e))return t.getProcedure(e)}}class _{#j;#F;#B=new F;#H=new B;#U=new W;constructor(e,t=[]){this.#j=e,this.#F=t}async start(){return this.#G()}async stop(){return this.#q()}async loadSegment(e){const t=await this.#j.import(e);this.addSegment(t.default)}async addSegment(e){if(e instanceof I==!1)throw new q;this.#U.addSegment(e)}getClassNames(){return this.#U.getClassNames()}hasClass(e){return this.#U.hasClass(e)}getClass(e){return this.#U.getClass(e)}getClassByImplementation(e){return this.#U.getClassByImplementation(e)}getProcedureNames(){return this.#U.getProcedureNames()}hasProcedure(e){return this.#U.hasProcedure(e)}getProcedure(e){return this.#U.getProcedure(e)}async run(e){const t=this.#W(e.fqn,e.version),s=this.#B.extract(t.parameters,e.args);return e.mode===d?new $(p,void 0):this.#_(e,t,s)}async#G(){await Promise.all(this.#F.map(e=>this.loadSegment(e)))}#q(){this.#U.clearSegments()}#W(e,t){const s=this.#U.getProcedure(e);if(void 0===s)throw new O(e);const r=s.getImplementation(t);if(void 0===r)throw new G(s.fqn,t.toString());return r}async#_(e,t,s){try{const r=await t.executable.call(e,...s);return new $(p,r)}catch(e){const t=this.#H.toStatus(e);return new $(t,e)}}}class K extends n{constructor(){super("Request cancelled")}}class Y{#K;#Y;#X=[];#J=!1;#Q=0;constructor(e,t=20){this.#K=e,this.#Y=t}start(){this.#J=!0,this.#Z()}stop(){this.#J=!1,this.#ee()}run(e){return new Promise((t,s)=>{this.#X.push({request:e,resolve:t,reject:s}),this.#Z()})}#Z(){if(this.#te())return;const e=this.#X.length,t=this.#Y-this.#Q,s=Math.min(e,t);this.#se(s)}#te(){return this.#re()||this.#ie()||this.#ne()}#re(){return!1===this.#J}#ie(){return 0===this.#X.length}#ne(){return this.#Q>=this.#Y}#se(e){const t=this.#X.splice(0,e);this.#Q+=e,t.forEach(e=>this.#ae(e))}async#ae(e){try{const t=await this.#K.run(e.request);e.resolve(t)}catch(t){e.reject(t)}finally{this.#Q--,this.#Z()}}#ee(){for(;this.#X.length>0;){const e=this.#X.shift();void 0!==e&&this.#oe(e)}}#oe(e){e.reject(new K)}}const X="starting",J="available",Q="unavailable",Z="stopping",ee="stopped";class te{#ce=ee;get state(){return this.#ce}set state(e){this.#ce=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.#le(ee)}isStopped(){return this.#ue(ee)}isAvailable(){return this.#ue(J)}setStarting(){this.#ce=X}setAvailable(){this.#ce=J}setUnavailable(){this.#ce=Q}setAvailability(e){return this.#ce=e?J:Q,this.#ce}setStopping(){this.#ce=Z}setStopped(){this.#ce=ee}#ue(...e){return e.includes(this.#ce)}#le(...e){return!1===this.#ue(...e)}}class se{#he;#de;#pe=new te;constructor(e){this.#he=e.url,this.#de=e.remote}get url(){return this.#he}get state(){return this.#pe.state}get trustKey(){}async start(){return this.#pe.start(async()=>{await this.#de.connect(),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{await this.#de.disconnect()})}isHealthy(){return this.#de.isHealthy()}getHealth(){return this.#de.getHealth()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}getProcedureNames(){throw new r}hasProcedure(e){throw new r}addWorker(e){return this.#de.addWorker(e.url,e.getProcedureNames(),e.trustKey)}reportWorker(e,t){return this.#de.reportWorker(e,t)}removeWorker(e){return this.#de.removeWorker(e)}run(e){return this.#de.run(e)}}class re extends Error{#me;constructor(e){super(`Invalid location: ${e}`),this.#me=e}get location(){return this.#me}}class ie extends Error{#fe;constructor(e){super(`The file '${e}' could not be found`),this.#fe=e}get filename(){return this.#fe}}class ne{#me;#ge;#we;constructor(e,t,s){this.#me=e,this.#ge=t,this.#we=s}get location(){return this.#me}get type(){return this.#ge}get content(){return this.#we}get size(){return this.#we.length}}class ae{#me;#ye;#Ee;constructor(e,t){const s=t.resolve(e);this.#me=t.normalize(e),this.#ye=t.normalize(s),this.#Ee=t}getAbsoluteLocation(e){const t=this.#Ee.isAbsolute(e)?e:this.#Ee.join(this.#me,e),s=this.#Ee.resolve(t),r=this.#Ee.normalize(s);return this.#Se(r,e),r}getRelativeLocation(e){const t=this.#Ee.relative(this.#me,e);return this.#Ee.normalize(t)}normalizeLocation(e){return this.#Ee.normalize(e)}async getType(e){const t=this.getAbsoluteLocation(e);return await this.#Ee.mimeType(t)??"application/octet-stream"}async getContent(e){const t=this.getAbsoluteLocation(e);if(!1===await this.#Ee.exists(t))throw new ie(e);return this.#Ee.read(t)}async exists(e){const t=this.getAbsoluteLocation(e);return this.#Ee.exists(t)}isDirectory(e){const t=this.getAbsoluteLocation(e);return this.#Ee.isDirectory(t)}async read(e){const t=this.getAbsoluteLocation(e),s=await this.getType(t),r=await this.getContent(t);return new ne(e,s,r)}async write(e,t){const s=this.getAbsoluteLocation(e);return this.#Ee.write(s,t)}async copy(e,t){const s=this.getAbsoluteLocation(e),r=this.getAbsoluteLocation(t);return this.#Ee.copy(s,r)}async delete(e){const t=this.getAbsoluteLocation(e);return this.#Ee.delete(t)}async filter(e){const t=this.getAbsoluteLocation("./"),s=this.#Ee.normalize(e);return(await this.#Ee.filter(t,s)).map(e=>this.#Ee.normalize(e))}#Se(e,t){if(!1===e.startsWith(this.#ye))throw new re(t)}}class oe extends Error{constructor(){super("Remote files are not supported")}}class ce{copy(e,t){throw new oe}delete(e){throw new oe}exists(e){throw new oe}async filter(e,t){return[]}isAbsolute(e){return e.startsWith("/")}isDirectory(e){throw new oe}join(...e){throw new oe}read(e){throw new oe}resolve(e){return e}relative(e,t){throw new oe}normalize(e){return e}mimeType(e){throw new oe}write(e,t){throw new oe}}class le extends ae{constructor(e){super(e,new ce)}}class ue extends Error{#he;#ve;constructor(e,t){super(`Module '${e}' could not be loaded${void 0!==t?` | ${t}`:""}`),this.#he=e,this.#ve=t}get url(){return this.#he}get reason(){return this.#ve}}class he{#be;constructor(e){this.#be=e}async import(e){const t=this.#be.locate(e);try{return await import(t)}catch(e){const s=e instanceof Error?e.message:String(e);throw new ue(t,s)}}}class de{constructor(e){}locate(e){throw new ue(e,"Remote module loading is not allowed")}}class pe extends he{constructor(e){super(new de(e))}}class me{#Oe;#Ae;constructor(e,t){this.#Oe=e,this.#Ae=t}get fileManager(){return this.#Oe}get importManager(){return this.#Ae}async filter(...e){return(await Promise.all(e.map(e=>this.#Oe.filter(e)))).flat().map(e=>this.#Oe.getRelativeLocation(e))}exists(e){return this.#Oe.exists(e)}read(e){return this.#Oe.read(e)}import(e){return this.#Ae.import(e)}}class fe extends me{constructor(e){super(new le(e),new pe(e))}fork(e){const t=this.fileManager.getAbsoluteLocation(e);return new fe(t)}}class ge extends Error{constructor(e){super(`The class '${e}' could not be found`)}}class we extends Error{constructor(e){super(`The class '${e}' is invalid`)}}class ye extends Error{constructor(e){super(`No deserializer found for value of type '${e}'`)}}class Ee extends Error{constructor(e){super(`No serializer found for value of type '${e}'`)}}class Se{#Ie=[];addSerializer(e){e.parent=this,this.#Ie.unshift(e)}async serialize(e){const t=this.#Ie.find(t=>t.canSerialize(e));if(void 0===t)throw new Ee(typeof e);return t.serialize(e)}async deserialize(e){const t=this.#Ie.find(t=>t.canDeserialize(e));if(void 0===t)throw new ye(typeof e);return t.deserialize(e)}}class ve extends Error{constructor(){super("Parent serializer not set")}}class be{#Ne;set parent(e){this.#Ne=e}serializeOther(e){if(void 0===this.#Ne)throw new ve;return this.#Ne.serialize(e)}deserializeOther(e){if(void 0===this.#Ne)throw new ve;return this.#Ne.deserialize(e)}}class Oe extends be{canSerialize(e){return e instanceof Array}canDeserialize(e){return e instanceof Array}async serialize(e){const t=[];for(const s of e)t.push(await this.serializeOther(s));return t}async deserialize(e){return Promise.all(e.map(async e=>this.deserializeOther(e)))}}class Ae extends Error{constructor(e){super(`Invalid BigInt string '${e}'`)}}class Ie extends be{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 Ae(e.value)}}}class Ne extends Error{constructor(e){super(`Invalid Buffer string '${e}'`)}}class Te extends be{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 Ne(e.base64)}}}class xe{}class Ce extends xe{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Ce(e)}toString(){return`[${this.elements.map(e=>e.toString()).join(",")}]`}}class Re{}class Me extends Re{identifier;constructor(e){super(),this.identifier=e}is(e){return this.identifier===e}}class ze extends Me{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 ze(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 Le extends ze{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 Le(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 Pe{binding;initializer;constructor(e,t){this.binding=e,this.initializer=t}clone(){const e=this.binding.clone(),t=this.initializer?.clone();return new Pe(e,t)}toString(){return`${this.binding.toString()}${void 0!==this.initializer?`=${this.initializer.toString(!1)}`:""}`}}class ke extends Re{code;constructor(e){super(),this.code=e}clone(){return new ke(this.code)}toString(){return this.code}}class $e{identifier;visibility;location;constructor(e,t,s){this.identifier=e,this.visibility=t,this.location=s}is(e){return this.identifier===e}}class Ve extends $e{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 Ve(e,t)}toString(){const e=this.parameters.map(e=>e.toString()),t=this.body.toString();return`${this.identifier}(${e.join(",")}) ${t}`}}class De extends $e{body;constructor(e,t,s,r){super(e,t,s),this.body=r}clone(){const e=this.body.clone();return new De(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 je extends $e{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 je(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 Fe extends $e{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 Fe(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 Be extends $e{initializer;constructor(e,t,s,r){super(e,t,s),this.initializer=r}clone(){const e=this.initializer?.clone();return new Be(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 He extends Me{parent;members;constructor(e,t,s){super(e),this.parent=t,this.members=s}get construct(){return this.members.find(e=>e instanceof Ve)}get fields(){return this.members.filter(e=>e instanceof Be)}get getters(){return this.members.filter(e=>e instanceof De)}get setters(){return this.members.filter(e=>e instanceof je)}get methods(){return this.members.filter(e=>e instanceof Fe)}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 He(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 Ue extends Re{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 Ue(e,this.from)}toString(){const e=this.members.map(e=>e.toString()),t=this.from?` from '${this.from}'`:"";return`export {${e.join(",")}}${t};`}}class Ge extends Re{code;constructor(e){super(),this.code=e}clone(){return new Ge(this.code)}toString(e=!0){const t=!1===e||this.code.endsWith("}")?"":";";return`${this.code}${t}`}}class qe extends ze{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new qe(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 We extends Fe{clone(){const e=this.parameters.map(e=>e.clone()),t=this.body.clone();return new We(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 _e extends xe{identifier;isRest;constructor(e,t=!1){super(),this.identifier=e,this.isRest=t}clone(){return new _e(this.identifier,this.isRest)}toString(){return`${this.isRest?"...":""}${this.identifier}`}}class Ke extends Re{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 Ke(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 Ye extends Me{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 Ye(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 Xe{statements;constructor(e){this.statements=e}get exports(){return this.statements.filter(e=>e instanceof Ue)}get imports(){return this.statements.filter(e=>e instanceof Ke)}get expressions(){return this.statements.filter(e=>e instanceof Ge)}get declarations(){return this.statements.filter(e=>e instanceof Me)}get variables(){return this.statements.filter(e=>e instanceof Ye)}get functions(){return this.statements.filter(e=>e instanceof ze)}get classes(){return this.statements.filter(e=>e instanceof He)}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 Ye)}get exportedFunctions(){return this.exported.filter(e=>e instanceof ze)}get exportedClasses(){return this.exported.filter(e=>e instanceof He)}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 Xe(e)}toString(){return this.statements.map(e=>e.toString(!0)).join("\n")}}class Je{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 Je(this.identifier,this.alias)}toString(){return void 0===this.alias?this.identifier:`${this.identifier} as ${this.alias}`}}class Qe extends xe{elements;constructor(e){super(),this.elements=e}clone(){const e=this.elements.map(e=>e.clone());return new Qe(e)}toString(){return`{${this.elements.map(e=>e.toString()).join(",")}}`}}const Ze={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},et=Object.values(Ze);const tt=".",st="(",rt=")",it="[",nt="]",at="{",ot="}",ct="_",lt={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},ut=Object.values(lt);function ht(e){return ut.includes(e)}const dt={UNDEFINED:void 0,NULL:null,STRING:""},pt=["null","undefined"],mt=Object.values(dt);function ft(e){return mt.includes(e)}const gt={OPEN:st,CLOSE:rt};function wt(e){return e===gt.OPEN||e===gt.CLOSE}const yt={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"},Et=Object.values(yt),St=[yt.IMPORT,yt.EXPORT,yt.VAR,yt.LET,yt.CONST,yt.FUNCTION,yt.CLASS,yt.ASYNC],vt=[yt.VAR,yt.LET,yt.CONST,yt.FUNCTION,yt.CLASS,yt.USING],bt=[yt.AS,yt.ASYNC,yt.GET,yt.SET,yt.OF,yt.YIELD,yt.FROM,yt.STATIC];function Ot(e){return St.includes(e)}function At(e){return vt.includes(e)}function It(e){return bt.includes(e)}const Nt={OPEN:it,CLOSE:nt};function Tt(e){return e===Nt.OPEN||e===Nt.CLOSE}const xt=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function Ct(e){return xt.includes(e)}const Rt={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:".."},Mt=Object.values(Rt);function zt(e){return Mt.includes(e)}const Lt={OPEN:at,CLOSE:ot};function Pt(e){return e===Lt.OPEN||e===Lt.CLOSE}const kt={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"},$t={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Vt=Object.values($t);function Dt(e){return Vt.includes(e)}class jt{#Te;#xe;constructor(e){this.#Te=e,this.#xe=0}get items(){return this.#Te}get position(){return this.#xe}get size(){return this.#Te.length}get eol(){return this.#xe>=this.#Te.length}get current(){return this.#Te[this.#xe]}get next(){return this.#Te[this.#xe+1]}get previous(){return this.#Te[this.#xe-1]}notAtEnd(){return!1===this.eol}get(e){return this.#Te[e]}step(e=1){return this.#xe+=e,this.current}stepBack(e=1){return this.#xe-=e,this.current}hasNext(){return this.#xe+1<this.#Te.length}insert(...e){this.#Te.splice(this.#xe,0,...e)}}class Ft extends jt{constructor(e){super(e.split(""))}}class Bt{#ge;#Ce;#Re;#Me;constructor(e,t,s,r){this.#ge=e,this.#Ce=t,this.#Re=s,this.#Me=r}get type(){return this.#ge}get value(){return this.#Ce}get start(){return this.#Re}get end(){return this.#Me}isType(e){return this.#ge===e}hasValue(e){return this.#Ce===e}toString(){return`${this.#Ce}`}}class Ht extends jt{}const Ut=["true","false"];const Gt=["0","1","2","3","4","5","6","7","8","9"],qt=[...Gt,"a","b","c","d","e","f","A","B","C","D","E","F"],Wt=["0","1"];function _t(e){return Gt.includes(e)}const Kt={GENERATOR:"*",PRIVATE:"#"},Yt=Object.values(Kt);class Xt{tokenize(e){const t=new Ft(e),s=[];let r;for(;t.notAtEnd();){const e=this.#ze(t,r);if(void 0===e)break;e.isType(kt.WHITESPACE)||e.isType(kt.COMMENT)?t.step():(s.push(e),this.#Le(e)&&(r=e),t.step())}return new Ht(s)}#Le(e){return!1===[kt.WHITESPACE,kt.COMMENT].includes(e.type)}#ze(e,t){const s=e.current,r=e.position;if(Dt(s)){const t=e.position;return new Bt(kt.WHITESPACE,s,r,t)}if(function(e){return et.includes(e)}(s+e.next)){const t=this.#Pe(e),s=e.position;return new Bt(kt.COMMENT,t,r,s)}if(this.#ke(s,t)){const t=this.#$e(e),s=e.position;return new Bt(kt.REGEX,t,r,s)}if(this.#Ve(e,t)){const t=this.#De(e),s=e.position;return new Bt(kt.NUMBER,t,r,s)}if(Ct(s)){const t=this.#je(e),s=e.position;return new Bt(kt.LITERAL,t,r,s)}if(zt(s)){const t=this.#Fe(e),s=e.position;return new Bt(kt.OPERATOR,t,r,s)}if(function(e){return Yt.includes(e)}(s)){const t=this.#Fe(e),s=e.position;return new Bt(kt.INDICATOR,t,r,s)}if(ht(s)){const t=e.position;return new Bt(kt.DIVIDER,s,r,t)}if(wt(s)){const t=e.position;return new Bt(kt.GROUP,s,r,t)}if(Pt(s)){const t=e.position;return new Bt(kt.SCOPE,s,r,t)}if(Tt(s)){const t=e.position;return new Bt(kt.LIST,s,r,t)}if(ft(s))return;const i=this.#Be(e),n=e.position;return function(e){return Et.includes(e)}(i)?new Bt(kt.KEYWORD,i,r,n):function(e){return Ut.includes(e)}(i)?new Bt(kt.BOOLEAN,i,r,n):function(e){return pt.includes(e)}(i)?new Bt(kt.NOTHING,i,r,n):new Bt(kt.IDENTIFIER,i,r,n)}#Pe(e){const t=e.current+e.next===Ze.MULTI_START,s=t?Ze.MULTI_END:$t.NEWLINE;let r=t?Ze.MULTI_START:Ze.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+Ze.MULTI_END:r.trim()}#ke(e,t){return e===Rt.DIVIDE&&(void 0===t||([kt.OPERATOR,kt.DIVIDER,kt.KEYWORD].includes(t.type)||[gt.OPEN,Nt.OPEN].includes(t.value)))}#He(e){return Dt(e)||e==tt||!1===this.#Ue(e)}#$e(e){let t=e.current,s=!1;for(e.step();e.notAtEnd();){const r=e.current,i=e.previous;if(r===Rt.DIVIDE&&"\\"!==i)s=!0;else if(!0===s&&this.#He(r)){e.stepBack();break}t+=r,e.step()}return t}#Ve(e,t){const s=e.current,r=e.next;return!!_t(s)||s===Rt.SUBTRACT&&(!t?.isType(kt.NUMBER)&&_t(r))}#Ge(e,t,s){return t?!1===(r=e,qt.includes(r))&&e!==ct:s?!1===function(e){return Wt.includes(e)}(e)&&e!==ct:!1===_t(e)&&e!==tt&&e!==ct&&"e"!==e;var r}#De(e){let t=e.current;t===Rt.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.#Ge(i,s,r)){e.stepBack();break}t+=i,e.step()}return t}#je(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}#Ue(e){return!1===(ft(e)||Dt(e)||zt(e)||Ct(e)||ht(e)||wt(e)||Pt(e)||Tt(e))}#Be(e){let t="";for(;e.notAtEnd();){const s=e.current;if(!1===this.#Ue(s)){e.stepBack();break}t+=s,e.step()}return t}#Fe(e){let t=e.current;for(e.step();e.notAtEnd();){const s=e.current;if(!1===zt(s)||!1===zt(t+s)){e.stepBack();break}t+=s,e.step()}return t}}class Jt extends Error{constructor(e,t){super(`Expected keyword '${e}' at position ${t}`)}}class Qt extends Error{constructor(e,t){super(`Expected token '${e}' at position ${t}`)}}class Zt extends Error{constructor(e,t){super(`Unexpected keyword '${e}' at position ${t}`)}}class es extends Error{constructor(e){super(`The given code does not contain ${e}`)}}class ts extends Error{constructor(e,t){super(`Unexpected token '${e}' at position ${t}`)}}class ss{#qe;constructor(e=[]){this.#qe=e}get tokens(){return this.#qe}append(...e){this.#qe.push(...e)}merge(e){this.append(...e.tokens)}generate(){let e="",t=new Bt(kt.NOTHING,"",0,0);for(const s of this.#qe){e+=`${this.#We(t,s)?" ":""}${s.value}`,t=s}return e}#We(e,t){return!(!e.isType(kt.KEYWORD)||!this.#_e(e))||!(!e.isType(kt.OPERATOR)||!t.isType(kt.OPERATOR))}#_e(e){return At(e.value)||e.hasValue(yt.RETURN)||e.hasValue(yt.ASYNC)||e.hasValue(yt.AWAIT)||e.hasValue(yt.YIELD)||e.hasValue(yt.NEW)||e.hasValue(yt.THROW)}}const rs="default";class is{#Ke;constructor(e=new Xt){this.#Ke=e}parse(e){const t=this.#Ke.tokenize(e),s=this.#Ye(t);return new Xe(s)}parseStatement(e){const t=this.#Ke.tokenize(e),s=this.#Xe(t);if(void 0===s)throw new es("a statement");return s}parseImport(e){const t=this.#Ke.tokenize(e),s=this.#Je(t);if(s instanceof Ke==!1)throw new es("an import definition");return s}parseExport(e){const t=this.#Ke.tokenize(e),s=this.#Je(t);if(s instanceof Ue==!1)throw new es("an export definition");return s}parseVariable(e){const t=this.#Ke.tokenize(e),s=this.#Je(t);if(s instanceof Ye==!1)throw new es("a variable definition");return s}parseFunction(e){const t=this.#Ke.tokenize(e),s=this.#Je(t);if(s instanceof ze==!1)throw new es("a function definition");return s}parseClass(e){const t=this.#Ke.tokenize(e),s=this.#Je(t);if(s instanceof He==!1)throw new es("a class definition");return s}#Ye(e){const t=[];for(;e.notAtEnd();){const s=this.#Xe(e);void 0!==s&&t.push(s)}return t}#Xe(e,t=!1){const s=e.current;if(this.#Qe(s))return this.#Ze(e);if(s.isType(kt.IDENTIFIER)){const s=e.next;return s?.hasValue(Rt.ARROW)?this.#et(e,t):this.#Ze(e)}if(s.isType(kt.KEYWORD)){if(It(s.value)){const t=e.next,r=void 0!==t&&(t.hasValue(yt.FUNCTION)||t.hasValue(gt.OPEN));if(s.hasValue(yt.ASYNC)&&r)return e.step(),this.#Xe(e,!0);if(void 0===t||this.#tt(t))return this.#Ze(e)}return s.hasValue(yt.RETURN)?this.#Ze(e):!1===Ot(s.value)?this.#Ze(e):this.#Je(e,t)}if(s.isType(kt.REGEX))return this.#Ze(e);if(s.hasValue(gt.OPEN)){const s=this.#st(e,gt.OPEN,gt.CLOSE);return s?.hasValue(Rt.ARROW)?this.#et(e,t):this.#Ze(e)}if(s.hasValue(Lt.OPEN))return this.#Ze(e);if(s.hasValue(Nt.OPEN))return this.#Ze(e);if(s.hasValue(Rt.NOT)||s.hasValue(Rt.SUBTRACT))return this.#Ze(e);if(!ht(s.value))throw new ts(s.value,s.start);e.step()}#Qe(e){return e.isType(kt.LITERAL)||e.isType(kt.NUMBER)||e.isType(kt.BOOLEAN)||e.isType(kt.NOTHING)||e.hasValue(yt.NEW)}#Je(e,t=!1){const s=e.current;switch(e.step(),s.value){case yt.IMPORT:return this.#rt(e);case yt.EXPORT:return this.#it(e);case yt.CLASS:return this.#nt(e);case yt.FUNCTION:return this.#at(e,t);case yt.VAR:return this.#ot(e,"var");case yt.LET:return this.#ot(e,"let");case yt.CONST:return this.#ot(e,"const");case yt.ASYNC:return this.#Xe(e,!0);default:throw new Zt(s.value,s.start)}}#rt(e){const t=[];let s=e.current;if(s.isType(kt.LITERAL)){const e=this.#ct(s.value);return new Ke(t,e)}if(s.hasValue(gt.OPEN)){s=e.step();const r=this.#ct(s.value);return e.step(2),new Ke(t,r)}if(!1===s.hasValue(Lt.OPEN)){const r=s.hasValue(Rt.MULTIPLY)?Rt.MULTIPLY:rs;let i=s.value;s=e.step(),s.hasValue(yt.AS)&&(s=e.step(),i=s.value,s=e.step()),t.push(new Je(r,i))}if(s.hasValue(lt.SEPARATOR)&&(s=e.step()),s.hasValue(Lt.OPEN)){const r=this.#lt(e);t.push(...r),s=e.current}if(!1===s.hasValue(yt.FROM))throw new Jt(yt.FROM,s.start);s=e.step();const r=this.#ct(s.value);return e.step(),new Ke(t,r)}#it(e){switch(e.current.value){case yt.DEFAULT:return e.step(),this.#ut(e,!0);case Lt.OPEN:return this.#ht(e);default:return this.#ut(e,!1)}}#ut(e,t){let s=e.current,r=0;if(t&&this.#dt(e)){const t=`$_EXPORT_${s.start}_${s.end}`;e.insert(new Bt(kt.KEYWORD,yt.CONST,0,0),new Bt(kt.IDENTIFIER,t,0,0),new Bt(kt.OPERATOR,Rt.ASSIGN,0,0)),s=e.current}s.hasValue(yt.ASYNC)&&(s=e.step(),r++),At(s.value)&&(s=e.step(),r++);const i=this.#Ue(s)?s.value:"",n=t?rs:void 0;let a;s=e.step(),s?.hasValue(yt.FROM)&&(s=e.step(),a=this.#ct(s.value)),r>0&&(r++,e.stepBack(r));const o=new Je(i,n);return new Ue([o],a)}#dt(e){const t=e.current;if(this.#Qe(t))return!0;const s=e.next;return this.#Ue(t)&&s?.hasValue(gt.OPEN)}#ht(e){const t=this.#lt(e);let s,r=e.current;return r?.hasValue(yt.FROM)&&(r=e.step(),s=this.#ct(r.value)),e.step(),new Ue(t,s)}#ct(e){return e.slice(1,-1)}#lt(e){const t=[];let s=e.step();for(;e.notAtEnd();){if(s.hasValue(Lt.CLOSE)){e.step();break}if(s.hasValue(lt.SEPARATOR)){s=e.step();continue}const r=this.#pt(e);t.push(r),s=e.step()}return t}#pt(e){let t=e.current;const s=t.value;let r;return e.next.hasValue(yt.AS)&&(t=e.step(2),r=t.value),new Je(s,r)}#ot(e,t){const s=this.#mt(e),r=this.#ft(e);return new Ye(t,s,r)}#mt(e){const t=e.current;return t.hasValue(Nt.OPEN)?this.#gt(e):t.hasValue(Lt.OPEN)?this.#wt(e):this.#yt(e)}#gt(e){const t=this.#Et(e,Nt.CLOSE);return new Ce(t)}#wt(e){const t=this.#Et(e,Lt.CLOSE);return new Qe(t)}#Et(e,t){const s=[];for(e.step();e.notAtEnd();){const r=e.current;if(r.hasValue(t)){e.step();break}if(r.hasValue(lt.SEPARATOR)){e.step();continue}const i=this.#mt(e),n=this.#ft(e),a=new Pe(i,n);s.push(a)}return s}#yt(e){let t=e.current,s=!1;t.hasValue(Rt.SPREAD)&&(s=!0,t=e.step());const r=t.value;return e.step(),new _e(r,s)}#ft(e){const t=e.current;if(!1!==t.hasValue(Rt.ASSIGN))return e.step(),this.#Xe(e,!1);t.hasValue(lt.TERMINATOR)&&e.step()}#at(e,t){let s,r=e.current,i=!1;r.hasValue(Kt.GENERATOR)&&(i=!0,r=e.step()),this.#Ue(r)&&(s=r.value,e.step());const n=this.#Et(e,gt.CLOSE);if(r=e.current,!1===r.hasValue(Lt.OPEN))throw new Qt(Lt.OPEN,r.start);const a=this.#St(e);return i?new qe(s,n,a,t):new ze(s,n,a,t)}#et(e,t){let s,r,i=e.current;if(i.hasValue(gt.OPEN))s=this.#Et(e,gt.CLOSE);else{const t=this.#yt(e);s=[new Pe(t,void 0)]}if(i=e.current,!1===i.hasValue(Rt.ARROW))throw new Qt(Rt.ARROW,i.start);if(i=e.step(),i.hasValue(Lt.OPEN))r=this.#St(e);else{const t=this.#Ze(e);r=new ke(t.code)}return new Le(s,r,t)}#nt(e){let t,s,r=e.current;if(this.#Ue(r)&&(t=r.value,r=e.step()),r.hasValue(yt.EXTENDS)&&(r=e.step(),s=r.value,r=e.step()),!1===r.hasValue(Lt.OPEN))throw new Qt(Lt.OPEN,r.start);const i=this.#vt(e);return new He(t,s,i)}#vt(e){let t=e.step();const s=[];for(;e.notAtEnd();){if(t.hasValue(Lt.CLOSE)){e.step();break}const r=this.#bt(e);s.push(r),t=e.current}return s}#bt(e){let t=e.current,s="public",r="instance",i=!1;for(;e.notAtEnd();){if(t.hasValue(Kt.PRIVATE))s="private";else if(t.hasValue(yt.STATIC))r="static";else{if(!t.hasValue(yt.ASYNC)){if(t.hasValue(yt.CONSTRUCTOR))return this.#Ot(e);if(t.hasValue(yt.GET))return this.#At(e,r);if(t.hasValue(yt.SET))return this.#It(e,r);if(t.hasValue(Kt.GENERATOR))return e.step(),this.#Nt(e,s,r,i,!0);break}i=!0}t=e.step()}return e.next.hasValue(gt.OPEN)?this.#Nt(e,s,r,i,!1):this.#Tt(e,s,r)}#Ot(e){e.step();const t=this.#Et(e,gt.CLOSE),s=e.current;if(!1===s.hasValue(Lt.OPEN))throw new Qt(Lt.OPEN,s.start);const r=this.#St(e);return new Ve(t,r)}#At(e,t){let s="public",r=e.step();r.hasValue(Kt.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();if(0!==this.#Et(e,gt.CLOSE).length)throw new es("an empty parameter list");if(r=e.current,!1===r.hasValue(Lt.OPEN))throw new Qt(Lt.OPEN,r.start);const n=this.#St(e);return new De(i,s,t,n)}#It(e,t){let s="public",r=e.step();r.hasValue(Kt.PRIVATE)&&(s="private",r=e.step());const i=r.value;e.step();const n=this.#Et(e,gt.CLOSE);if(r=e.current,1!==n.length)throw new es("exactly one setter parameter");if(!1===r.hasValue(Lt.OPEN))throw new Qt(Lt.OPEN,r.start);const a=this.#St(e);return new je(i,s,t,n[0],a)}#Nt(e,t,s,r,i){let n=e.current;const a=n.value;e.step();const o=this.#Et(e,gt.CLOSE);if(n=e.current,!1===n.hasValue(Lt.OPEN))throw new Qt(Lt.OPEN,n.start);const c=this.#St(e);return i?new We(a,t,s,o,c,r):new Fe(a,t,s,o,c,r)}#Tt(e,t,s){const r=e.current.value;e.step();const i=this.#ft(e);return new Be(r,t,s,i)}#St(e){const t=this.#xt(e,Lt.OPEN,Lt.CLOSE).generate();return new ke(t)}#Ze(e){const t=new ss;let s=e.current;for(;e.notAtEnd();){if(s.hasValue(Nt.OPEN)){const r=this.#xt(e,Nt.OPEN,Nt.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(gt.OPEN)){const r=this.#xt(e,gt.OPEN,gt.CLOSE);t.merge(r),s=e.current}else if(s.hasValue(Lt.OPEN)){const r=this.#xt(e,Lt.OPEN,Lt.CLOSE);t.merge(r),s=e.current}else t.append(s),s=e.step();if(void 0===s)break;if(this.#tt(s)){s.hasValue(lt.TERMINATOR)&&e.step();break}}const r=t.generate();return new Ge(r)}#xt(e,t,s){let r=e.current;const i=new ss([r]);for(r=e.step();e.notAtEnd();){if(r.hasValue(t)){const n=this.#xt(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}#st(e,t,s){const r=e.position;this.#xt(e,t,s);const i=e.current,n=e.position;return e.stepBack(n-r),i}#tt(e){return[lt.TERMINATOR,lt.SEPARATOR].includes(e.value)||[Nt.CLOSE,gt.CLOSE,Lt.CLOSE].includes(e.value)||Ot(e.value)}#Ue(e){return e.isType(kt.IDENTIFIER)||e.isType(kt.KEYWORD)&&It(e.value)}}class ns{merge(e,t){const s=void 0!==e.construct?[e.construct]:[],r=[...this.#Ct(e.fields,t.fields),...s,...this.#Ct(e.methods,t.methods),...this.#Ct(e.getters,t.getters),...this.#Ct(e.setters,t.setters)];return new He(e.identifier,t.identifier,r)}#Ct(e,t){const s=new Map;return t.forEach(e=>s.set(e.identifier,e)),e.forEach(e=>s.set(e.identifier,e)),[...s.values()]}}class as{#Rt=new is;#Mt=new ns;fromModule(e,t=!1){const s=Object.entries(e),r=[];for(const[e,i]of s){if("function"!=typeof i.toString)continue;const s=i.toString();if(s.startsWith("class"))r.push(this.fromClass(i,t));else if(s.startsWith("function"))r.push(this.fromFunction(i));else{const t=new _e(e,!1),i=new Ge(s);r.push(new Ye("var",t,i))}}return new Xe(r)}fromClass(e,t=!1){const s=this.isClass(e)?this.#zt(e):this.#Lt(e);if(!1===t)return s;const r=this.getParentClass(e);if(""===r.name)return s;const i=this.fromClass(r,!0);return this.#Mt.merge(s,i)}fromObject(e,t=!0){const s=this.getClass(e);return this.fromClass(s,t)}fromFunction(e){const t=e.toString();return this.#Rt.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")}#zt(e){const t=e.toString();return this.#Rt.parseClass(t)}#Lt(e){const t=this.createInstance(e),s=this.#Pt(e,t);return new He(e.name,void 0,s)}#Pt(e,t){return[...this.#kt(t),...this.#$t(e)]}#kt(e){const t=Object.getOwnPropertyNames(e),s=e,r=[];for(const e of t){const t=s[e],i=void 0!==t?new Ge(String(t)):void 0,n=new Be(e,"public","instance",i);r.push(n)}return r}#$t(e){const t=Object.getOwnPropertyDescriptors(e.prototype),s=[];for(const e in t){const r=t[e],i=r.value;if(i instanceof Function==!1)continue;const n=this.fromFunction(i);"constructor"===n.identifier?s.push(new Ve(n.parameters,n.body)):void 0!==r.get?s.push(new De(n.identifier,"public","instance",n.body)):void 0!==r.set?s.push(new je(n.identifier,"public","instance",n.parameters[0],n.body)):s.push(new Fe(n.identifier,"public","instance",n.parameters,n.body,n.isAsync))}return s}}const os=new as;class cs extends be{#Vt;constructor(e){super(),this.#Vt=e}canSerialize(e){return e instanceof Object&&os.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=os.getClass(e),s=os.fromClass(t,!0),r=this.#Dt(s),i=this.#Vt.resolveKey(t);if(void 0===i)throw new ge(t.name);return{serialized:!0,key:i,name:"class",args:await this.#jt(s,r,e),fields:await this.#Ft(s,r,e)}}#Dt(e){const t=e.construct;return(t?.parameters??[]).map(e=>e.binding.identifier)}async#jt(e,t,s){const r={};for(const[i,n]of t.entries()){const t=e.canRead(n)?await this.serializeOther(s[n]):void 0;r[i.toString()]=t}return r}async#Ft(e,t,s){const r={};for(const i of e.writable){const n=i.identifier;t.includes(n)||!1===e.canRead(n)||(r[n]=await this.serializeOther(s[n]))}return r}async deserialize(e){const t=await this.#Bt(e);if(void 0===t)throw new ge(e.key);if(t instanceof Function==!1)throw new we(e.key);const s=await this.#Ht(t,e.args),r=os.createInstance(t,s);for(const t in e.fields){const s=e.fields[t];r[t]=await this.deserializeOther(s)}return r}async#Ht(e,t){const s=os.fromClass(e,!0).construct,r=(s?.parameters??[]).map((e,s)=>{const r=s.toString(),i=t[r];return this.deserializeOther(i)});return Promise.all(r)}async#Bt(e){return globalThis[e.key]??this.#Vt.resolveClass(e.key)}}class ls extends Error{constructor(e){super(`Invalid date string '${e}'`)}}class us extends be{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 ls(e.value);return t}}class hs extends be{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 ds extends be{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=[],s=[];for(const[r,i]of e)t.push(await this.serializeOther(r)),s.push(await this.serializeOther(i));return{serialized:!0,name:"Map",entries:{keys:t,values:s}}}async deserialize(e){const t=e.entries.keys,s=e.entries.values,r=new Map;for(let e=0;e<t.length;e++){const i=await this.deserializeOther(t[e]),n=await this.deserializeOther(s[e]);r.set(i,n)}return r}}class ps extends be{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 s in e){const r=e[s];t[s]=await this.serializeOther(r)}return t}async deserialize(e){const t={};for(const s in e){const r=e[s];t[s]=await this.deserializeOther(r)}return t}}class ms extends be{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 fs extends Error{constructor(e,t){super(`Invalid regular expression '${e}' with flags '${t}'`)}}class gs extends be{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 fs(e.source,e.flags)}}}class ws extends be{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 s of e.values())t.push(await this.serializeOther(s));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 ys=new as;class Es extends be{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,s=new DataView(e.buffer),r=[];for(let e=0;e<s.byteLength;e++)r.push(s.getUint8(e));return{serialized:!0,name:"TypedArray",type:t,bytes:r}}async deserialize(e){const t=e.type,s=e.bytes,r=new ArrayBuffer(s.length),i=new DataView(r);for(let e=0;e<s.length;e++)i.setUint8(e,s[e]);const n=globalThis[t];return ys.createInstance(n,[r])}}class Ss extends Error{constructor(e){super(`Invalid url string '${e}'`)}}class vs extends be{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 Ss(e.value)}}}class bs{static build(e){const t=new Se;return t.addSerializer(new ms),t.addSerializer(new ps),void 0!==e&&t.addSerializer(new cs(e)),t.addSerializer(new hs),t.addSerializer(new gs),t.addSerializer(new Ie),t.addSerializer(new vs),t.addSerializer(new us),t.addSerializer(new ws),t.addSerializer(new ds),t.addSerializer(new Oe),t.addSerializer(new Es),"undefined"!=typeof Buffer&&t.addSerializer(new Te),t}}class Os{#Ut;constructor(e){this.#Ut=e}resolveKey(e){const t=this.#Ut.getClassByImplementation(e);return t?.fqn}resolveClass(e){const t=this.#Ut.getClass(e);return t?.implementation}}class As extends o{constructor(){super("Request not trusted")}}const Is="X-Jitar-Trust-Key",Ns="X-Jitar-Data-Encoding",Ts="serialized";class xs{#s;#he;#Gt;#qt;#Wt;#Ut;#_t;#Kt;#Yt;#pe=new te;constructor(e){this.#he=e.url,this.#Gt=e.trustKey,this.#qt=e.gateway,this.#Wt=!0===e.registerAtGateway,this.#Ut=e.executionManager,this.#_t=e.healthManager;const t=e.scheduleManager;this.#Kt=t.create(()=>this.#Xt(),e.reportInterval);const s=new Os(this.#Ut);this.#Yt=bs.build(s)}get id(){return this.#s}set id(e){this.#s=e}get state(){return this.#pe.state}get url(){return this.#he}get trustKey(){return this.#Gt}async start(){return this.#pe.start(async()=>{await Promise.all([this.#Ut.start(),this.#_t.start()]),void 0!==this.#qt&&(await this.#qt.start(),this.#Wt&&(this.#s=await this.#qt.addWorker(this),this.#Kt.start())),await this.updateState()})}async stop(){return this.#pe.stop(async()=>{void 0!==this.#qt&&(void 0!==this.#s&&(this.#Kt.stop(),await this.#qt.removeWorker(this.#s)),await this.#qt.stop()),await Promise.all([this.#_t.stop(),this.#Ut.stop()])})}getProcedureNames(){return this.#Ut.getProcedureNames()}hasProcedure(e){return this.#Ut.hasProcedure(e)}isHealthy(){return this.#_t.isHealthy()}getHealth(){return this.#_t.getHealth()}isAvailable(){return this.#pe.isAvailable()}async updateState(){const e=await this.isHealthy();return this.#pe.setAvailability(e)}async reportState(e){if(void 0!==this.#qt&&void 0!==this.#s)return this.#qt.reportWorker(this.#s,e)}async run(e){return this.#Jt(e)?this.#Qt(e):this.#Zt(e)}#Jt(e){return void 0===this.#qt||this.#Ut.hasProcedure(e.fqn)}async#Qt(e){const t=this.#Ut.getProcedure(e.fqn),s=t?.getImplementation(e.version);if(this.#es(s))throw new O(e.fqn);if(this.#ts(e,s))throw new As;const r=e.getHeader(Ns);r===Ts&&(e=await this.#ss(e)),e.removeHeader(Ns);const i=await this.#Ut.run(e);return r===Ts?this.#rs(i):i}#es(e){return void 0===e||e.private}#ts(e,t){if(t.public)return!1;const s=e.getHeader(Is);return this.#Gt!==s}async#Zt(e){(e=await this.#is(e)).setHeader(Ns,Ts),void 0!==this.#Gt&&e.setHeader(Is,this.#Gt);const t=await this.#qt.run(e);return this.#ns(t)}async#is(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#Yt.serialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#ss(e){const t=new Map;for(const[s,r]of e.args){const e=await this.#Yt.deserialize(r);t.set(s,e)}return new k(e.fqn,e.version,t,e.headers,e.mode)}async#rs(e){const t=await this.#Yt.serialize(e.result);return new $(e.status,t,e.headers)}async#ns(e){const t=await this.#Yt.deserialize(e.result);return new $(e.status,t,e.headers)}async#Xt(){const e=await this.updateState();return this.reportState(e)}}class Cs{#K;constructor(e){this.#K=e}async handle(e,t){return this.#K.run(e)}}class Rs{#as=new U;constructor(){this.#os()}#os(){const e=globalThis;e.__run=this.#cs.bind(this),e.ProcedureNotAccessible=A}async#cs(e,t,s,r){const i=this.#as.parse(t),n=new Map(Object.entries(s)),a=r instanceof k?r.headers:new Map,o=new k(e,i,n,a,h),c=this.getTrustKey();void 0!==c&&o.setHeader("X-Jitar-Trust-Key",c);const l=await this.runInternal(o);if(l.status!==p)throw l.result;return l.result}}class Ms extends Rs{#ls;#us;#hs=new Y(this);constructor(e){super(),this.#ls=new xs({url:e.remoteUrl,gateway:new se({url:e.remoteUrl,remote:e.remote}),healthManager:e.healthManager,executionManager:e.executionManager,scheduleManager:e.scheduleManager}),this.#us=e.middlewareManager}get worker(){return this.#ls}async start(){await this.#ds(),this.#hs.start()}async stop(){this.#hs.stop(),await this.#ps()}getTrustKey(){}run(e){return this.#us.handle(e)}async runInternal(e){return this.#hs.run(e)}async#ds(){await Promise.all([this.#ls.start(),this.#us.start()]);const e=new Cs(this.#ls);this.#us.addMiddleware(e)}async#ps(){await Promise.all([this.#us.stop(),this.#ls.stop()])}}const zs="starting",Ls="started",Ps="stopping",ks="stopped";class $s extends n{constructor(){super("Invalid health check")}}class Vs{#ce=ks;#ms=new Map;#j;#fs;constructor(e,t=[]){this.#j=e,this.#fs=t}get state(){return this.#ce}async start(){if(this.#ce===ks)try{this.#ce=zs,await this.#gs(),this.#ce=Ls}catch(e){throw this.#ce=ks,e}}async stop(){if(this.#ce===Ls)try{this.#ce=Ps,this.clearHealthChecks(),this.#ce=ks}catch(e){throw this.#ce=Ls,e}}async loadHealthCheck(e){const t=await this.#ws(e);this.addHealthCheck(t)}addHealthCheck(e){if(void 0===e.isHealthy)throw new $s;this.#ms.set(e.name,e)}clearHealthChecks(){this.#ms.clear()}async isHealthy(){const e=[];for(const t of this.#ms.values()){const s=this.#ys(t);e.push(s)}return Promise.all(e).then(e=>e.every(e=>e)).catch(()=>!1)}async getHealth(){const e=[];for(const[t,s]of this.#ms){const r=this.#ys(s).then(e=>({name:t,isHealthy:e})).catch(()=>({name:t,isHealthy:!1}));e.push(r)}const t=new Map;return Promise.allSettled(e).then(e=>e.forEach(e=>this.#Es(e,t))).then(()=>t)}async#gs(){(await Promise.all(this.#fs.map(e=>this.#ws(e)))).forEach(e=>this.addHealthCheck(e))}async#ws(e){return(await this.#j.import(e)).default}#Es(e,t){"fulfilled"===e.status?t.set(e.value.name,e.value.isHealthy):t.set(e.reason.name,!1)}async#ys(e){const t=e.isHealthy(),s=e.timeout;if(void 0===s)return t;const r=new Promise(e=>{setTimeout(e,s)}).then(()=>!1);return Promise.race([r,t])}}const Ds=0,js=1,Fs=2,Bs=3;class Hs{#Ss;#vs;constructor(e=js,t=console){this.#Ss=e,this.#vs=t}debug(...e){if(this.#Ss>Ds)return;const t=this.#bs("DEBUG",e);this.#vs.debug(t)}info(...e){if(this.#Ss>js)return;const t=this.#bs("INFO",e);this.#vs.info(t)}warn(...e){if(this.#Ss>Fs)return;const t=this.#bs("WARN",e);this.#vs.warn(t)}error(...e){if(this.#Ss>Bs)return;const t=this.#bs("ERROR",e);this.#vs.error(t)}fatal(...e){const t=this.#bs("FATAL",e);this.#vs.error(t)}#bs(e,t){return`[${e}][${(new Date).toISOString()}] ${t.map(e=>this.#Os(e)).join(" ")}`}#Os(e,t=0){let s;switch(typeof e){case"string":s=e;break;case"object":s=this.#As(e,t+1);break;case"undefined":s="undefined";break;case"function":s="function";break;default:s=String(e)}return`${this.#Is(t)}${s}`}#As(e,t){if(null===e)return"null";if(Array.isArray(e)){return`[\n${e.map(e=>this.#Os(e,t)).join(",\n")}\n${this.#Is(t-1)}]`}return e instanceof Error?e.stack??e.message:JSON.stringify(e)}#Is(e){return" ".repeat(e)}}const Us="starting",Gs="started",qs="stopping",Ws="stopped";class _s extends n{constructor(){super("Invalid middleware")}}class Ks{#ce=Ws;#Ns=[];#j;#Ts;constructor(e,t=[]){this.#j=e,this.#Ts=t}get state(){return this.#ce}async start(){if(this.#ce===Ws)try{this.#ce=Us,await this.#xs(),this.#ce=Gs}catch(e){throw this.#ce=Ws,e}}async stop(){if(this.#ce===Gs)try{this.#ce=qs,this.clearMiddlewares(),this.#ce=Ws}catch(e){throw this.#ce=Gs,e}}async loadMiddleware(e){const t=await this.#Cs(e);this.addMiddleware(t)}addMiddleware(e){if(void 0===e?.handle)throw new _s;this.#Ns.push(e)}getMiddleware(e){return this.#Ns.find(t=>t instanceof e)}clearMiddlewares(){this.#Ns=[]}handle(e){return this.#Rs(e,0)()}async#xs(){(await Promise.all(this.#Ts.map(e=>this.#Cs(e)))).forEach(e=>this.addMiddleware(e))}async#Cs(e){return(await this.#j.import(e)).default}#Rs(e,t){const s=this.#Ns[t];if(void 0===s)return async()=>new $(p);const r=this.#Rs(e,t+1);return async()=>await s.handle(e,r)}}class Ys{#Ms;#zs;#Ls;#Ps=null;constructor(e,t,s=5e3){this.#Ms=e,this.#zs=t,this.#Ls=s}start(){this.#ks()}stop(){null!==this.#Ps&&(clearTimeout(this.#Ps),this.#Ps=null)}#ks(){this.#Ps=setTimeout(async()=>{null!==this.#Ps&&(await this.#$s(),this.#ks())},this.#Ls),this.#Ps.unref()}async#$s(){try{await this.#zs()}catch(e){this.#Ms.warn("Scheduled task failed",e)}}}class Xs{#Vs=[];#Ms;constructor(e){this.#Ms=e}create(e,t){const s=new Ys(this.#Ms,e,t);return this.#Vs.push(s),s}remove(e){const t=this.#Vs.indexOf(e);t<0||this.#Vs.splice(t,1)}startAll(){this.#Vs.forEach(e=>e.start())}stopAll(){this.#Vs.forEach(e=>e.stop())}}class Js{#Ds;constructor(e){this.#Ds=e}build(e){const t=e.remoteUrl,s=e.middleware,r=e.segments,i=new Hs(e.logLevel??Fs),n=this.#Ds.build(t),a=new fe(t),o=this.#js(a),c=this.#Fs(a,s),l=this.#Bs(a,r),u=this.#Hs(i);return new Ms({remoteUrl:t,remote:n,healthManager:o,middlewareManager:c,executionManager:l,scheduleManager:u})}#js(e){return new Vs(e)}#Fs(e,t=[]){const s=new Ks(e);return t.forEach(e=>s.addMiddleware(e)),s}#Bs(e,t=[]){const s=new _(e);return t.forEach(e=>s.addSegment(e)),s}#Hs(e){return new Xs(e)}}class Qs{#Us;constructor(e=!0){this.#Us=e}validate(e,t){const s=[];this.#Gs("",e,t,s);return{valid:0===s.length,errors:s}}#Gs(e,t,s,r){this.#Us&&this.#qs(e,t,s,r),this.#Ws(e,t,s,r)}#qs(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.#_s(e,t);r.push(`Unknown field '${s}'`)}}#Ws(e,t,s,r){const i=Object.keys(s);for(const n of i){const i=this.#_s(e,n),a=s[n],o=t[n];this.#Ks(i,o,a,r)}}#Ks(e,t,s,r){if(void 0!==t)switch(s.type){case"string":return this.#Ys(e,t,s,r);case"integer":return this.#Xs(e,t,s,r);case"real":return this.#Js(e,t,s,r);case"boolean":return this.#Qs(e,t,s,r);case"url":return this.#Zs(e,t,s,r);case"group":return this.#er(e,t,s,r);case"list":return this.#tr(e,t,s,r)}else!0===s.required&&r.push(`Field '${e}' is required`)}#Ys(e,t,s,r){"string"!=typeof t&&r.push(`Field '${e}' is not a string`)}#Xs(e,t,s,r){"number"==typeof t&&!1!==Number.isInteger(t)||r.push(`Field '${e}' is not an integer`)}#Js(e,t,s,r){"number"!=typeof t&&r.push(`Field '${e}' is not a real number`)}#Qs(e,t,s,r){"boolean"!=typeof t&&r.push(`Field '${e}' is not a boolean`)}#Zs(e,t,s,r){"string"==typeof t&&!1!==t.startsWith("http")||r.push(`Field '${e}' is not a valid URL`)}#er(e,t,s,r){"object"==typeof t?this.#Gs(e,t,s.fields,r):r.push(`Field '${e}' is not an object`)}#tr(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.#_s(e,t),a=i[t];this.#Ks(n,a,s.items,r)}}#_s(e,t){return""===e?t:`${e}.${t}`}}const Zs="content-type",er="x-jitar-content-type",tr="x-jitar-procedure-version",sr="application/json",rr="application/octet-stream";class ir extends Error{constructor(){super("Invalid worker id")}}class nr{#he;#sr;#H=new B;#rr=new Qs;constructor(e,t){this.#he=e,this.#sr=t}connect(){return Promise.resolve()}disconnect(){return Promise.resolve()}async provide(e){const t=`${this.#he}/${e}`,s=await this.#ir(t,{method:"GET"}),r=s.headers.get(Zs)??rr,i=await s.arrayBuffer(),n=Buffer.from(i);return new ne(e,r,n)}async isHealthy(){const e=`${this.#he}/health/status`,t=await this.#ir(e,{method:"GET"});return"true"===await t.text()}async getHealth(){const e=`${this.#he}/health`,t=await this.#ir(e,{method:"GET"}),s=await t.json();return new Map(Object.entries(s))}async addWorker(e,t,s){const r=`${this.#he}/workers`,i={url:e,procedureNames:t,trustKey:s},n={method:"POST",headers:{"Content-Type":sr},body:JSON.stringify(i)},a=await this.#ir(r,n),o=a.headers.get(Zs);if(null===o||!1===o.includes(sr))throw new ir;const c=await a.json();if(!1===this.#rr.validate(c,{id:{type:"string",required:!0}}).valid)throw new ir;return c.id}async reportWorker(e,t){const s=`${this.#he}/workers/${e}/report`,r={state:t},i={method:"POST",headers:{"Content-Type":sr},body:JSON.stringify(r)};await this.#ir(s,i)}async removeWorker(e){const t=`${this.#he}/workers/${e}`,s={method:"DELETE",headers:{"Content-Type":sr}};await this.#ir(t,s)}async run(e){e.setHeader(Zs,sr);const t=Object.fromEntries(e.args),s=Object.fromEntries(e.headers),r=e.version.toString();s[tr]=r;const i=`${this.#he}/rpc/${e.fqn}`,n={method:"POST",redirect:"manual",headers:s,body:await this.#nr(t)},a=await this.#ir(i,n,!1),o=a.status,c=await this.#ar(a),l=this.#or(a);return new $(o,c,l)}async#ir(e,t,s=!0){const r=await this.#sr.execute(e,t);if(s&&this.#cr(r)){const e=await this.#ar(r);throw this.#H.fromStatus(r.status,String(e))}return r}#cr(e){return e.status<200||e.status>399}async#nr(e){return JSON.stringify(e)}async#ar(e){const t=e.headers.get(er)??e.headers.get(Zs);if(t?.includes("undefined"))return;if(t?.includes("null"))return null;if(t?.includes("json"))return e.json();const s=await e.text();return t?.includes("boolean")?"true"===s:t?.includes("number")?Number(s):s}#or(e){const t=new Map;for(const[s,r]of e.headers)t.set(s,r);return t}}class ar{async execute(e,t){return fetch(e,t)}}class or{#sr;constructor(e=new ar){this.#sr=e}build(e){return new nr(e,this.#sr)}}export{L as ArrayParameter,e as BadRequest,N as Class,Js as ClientBuilder,t as Forbidden,or as HttpRemoteBuilder,C as Implementation,M as NamedParameter,s as NotFound,r as NotImplemented,P as ObjectParameter,i as PaymentRequired,x as Procedure,k as Request,$ as Response,I as Segment,n as ServerError,a as Teapot,o as Unauthorized,T as Version};
|
package/dist/lib.d.ts
CHANGED
|
@@ -1,3 +1,78 @@
|
|
|
1
|
+
type RuntimeConfiguration = {
|
|
2
|
+
source: string;
|
|
3
|
+
target: string;
|
|
4
|
+
segments: string;
|
|
5
|
+
resources: string;
|
|
6
|
+
meta: {
|
|
7
|
+
root: string;
|
|
8
|
+
configFile: string;
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
type GatewayConfiguration = {
|
|
13
|
+
monitorInterval?: number;
|
|
14
|
+
trustKey?: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type ProxyConfiguration = {
|
|
18
|
+
gateway: string;
|
|
19
|
+
repository: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type RepositoryConfiguration = {
|
|
23
|
+
indexFilename?: string;
|
|
24
|
+
serveIndexOnNotFound?: boolean;
|
|
25
|
+
assetRoot?: string;
|
|
26
|
+
assets?: string[];
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
type WorkerConfiguration = {
|
|
30
|
+
gateway?: string;
|
|
31
|
+
segments: string[];
|
|
32
|
+
trustKey?: string;
|
|
33
|
+
reportInterval?: number;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
type StandaloneConfiguration = RepositoryConfiguration & Pick<WorkerConfiguration, 'segments'>;
|
|
37
|
+
|
|
38
|
+
type RemoteWorkerConfiguration = {
|
|
39
|
+
unavailableThreshold?: number;
|
|
40
|
+
stoppedThreshold?: number;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type ServerConfiguration = {
|
|
44
|
+
url: string;
|
|
45
|
+
setUp?: string[];
|
|
46
|
+
tearDown?: string[];
|
|
47
|
+
middleware?: string[];
|
|
48
|
+
healthChecks?: string[];
|
|
49
|
+
gateway?: GatewayConfiguration;
|
|
50
|
+
proxy?: ProxyConfiguration;
|
|
51
|
+
repository?: RepositoryConfiguration;
|
|
52
|
+
standalone?: StandaloneConfiguration;
|
|
53
|
+
worker?: WorkerConfiguration;
|
|
54
|
+
remoteWorker?: RemoteWorkerConfiguration;
|
|
55
|
+
meta: {
|
|
56
|
+
root: string;
|
|
57
|
+
configFile: string;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
declare class ConfigurationManager {
|
|
62
|
+
#private;
|
|
63
|
+
constructor(rootPath?: string);
|
|
64
|
+
configureEnvironment(filename?: string): Promise<void>;
|
|
65
|
+
getRuntimeConfiguration(filename?: string): Promise<RuntimeConfiguration>;
|
|
66
|
+
getServerConfiguration(filename: string): Promise<ServerConfiguration>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
declare class BuildHelper {
|
|
70
|
+
#private;
|
|
71
|
+
constructor(configuration: RuntimeConfiguration);
|
|
72
|
+
readApplication(): Promise<void>;
|
|
73
|
+
generateModuleCode(filename: string, segmentNames?: string[]): string;
|
|
74
|
+
}
|
|
75
|
+
|
|
1
76
|
declare class BadRequest extends Error {
|
|
2
77
|
constructor(message?: string);
|
|
3
78
|
}
|
|
@@ -168,5 +243,5 @@ interface HealthCheck {
|
|
|
168
243
|
isHealthy(): Promise<boolean>;
|
|
169
244
|
}
|
|
170
245
|
|
|
171
|
-
export { ArrayParameter, BadRequest, Class, Forbidden, Implementation, NamedParameter, NotFound, NotImplemented, ObjectParameter, PaymentRequired, Procedure, Request, Response, Segment, ServerError, Teapot, Unauthorized, Version };
|
|
246
|
+
export { ArrayParameter, BadRequest, BuildHelper, Class, ConfigurationManager, Forbidden, Implementation, NamedParameter, NotFound, NotImplemented, ObjectParameter, PaymentRequired, Procedure, Request, Response, Segment, ServerError, Teapot, Unauthorized, Version };
|
|
172
247
|
export type { HealthCheck, Middleware, NextHandler };
|
package/dist/lib.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{V as t,
|
|
1
|
+
import{V as e,H as t,n as a,L as s,v as i,w as r,x as n,o,p}from"./ConfigurationManager-CYD-3rnJ.js";export{A as ArrayParameter,B as BadRequest,C as ConfigurationManager,F as Forbidden,j as NamedParameter,N as NotFound,k as NotImplemented,O as ObjectParameter,l as PaymentRequired,G as Request,R as Response,m as Segment,S as ServerError,T as Teapot,U as Unauthorized}from"./ConfigurationManager-CYD-3rnJ.js";import"node:fs";import"node:path";import"glob";import"mime-types";import"dotenv";class c{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get fqn(){return this.#e}get implementation(){return this.#t}}class u{#e;#a=new Map;#s;constructor(e){this.#e=e}get fqn(){return this.#e}get public(){return[...this.#a.values()].some(e=>e.public)}get protected(){return[...this.#a.values()].some(e=>e.protected)}addImplementation(e){return this.#a.set(e.version,e),this.#i(e)&&(this.#s=e),this}#i(e){return void 0===this.#s||e.version.greater(this.#s.version)}getImplementation(e){const t=this.#r(e);return this.#a.get(t)}#r(t){let a=e.DEFAULT;for(const e of this.#a.keys()){if(e.equals(t))return e;e.greater(t)||a.less(e)&&(a=e)}return a}}class h{#n;#o;#l;#p;constructor(e,t,a,s){this.#n=e,this.#o=t,this.#l=a,this.#p=s}get version(){return this.#n}get public(){return this.#o===t.PUBLIC}get protected(){return this.#o===t.PROTECTED}get private(){return this.#o===t.PRIVATE}get parameters(){return this.#l}get executable(){return this.#p}}class g extends Error{constructor(){super("Application not read")}}class f extends Error{constructor(e){super(`Application module not found '${e}'`)}}class d{#m=new a;#c;#u;#h;constructor(e){const t=this.#m.makePathAbsolute(e.source,e.meta.root),a=this.#m.makePathAbsolute(e.target,e.meta.root),n=this.#m.makePathAbsolute(e.resources,e.meta.root),o=this.#m.makePathAbsolute(e.segments,e.meta.root),l=new s(t),p=new s(a),m=new s(n),c=new s(o);this.#c=new i(l,p,m,c),this.#u=new r(this.#c)}async readApplication(){const e=this.#c.source,t=this.#c.resource,a=this.#c.segment,s=await e.filter(n.MODULE_PATTERN),i=await t.filter(n.RESOURCE_PATTERN),r=await a.filter(n.SEGMENT_PATTERN);this.#h=await this.#u.read(s,i,r)}generateModuleCode(e,t=[]){if(void 0===this.#h)throw new g;const a=this.#h.repository.get(e);if(void 0===a)throw new f(e);const s=this.#h.resources,i=this.#h.segmentation,r=i.getSegments(e);if(0===r.length){return new o(a,s,i).generate()}if(void 0===r.find(e=>t.includes(e.name))){return new p(a,r).generate()}return new o(a,s,i).generate()}}export{d as BuildHelper,c as Class,h as Implementation,u as Procedure,e as Version};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jitar",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Distributed runtime for JavaScript and TypeScript to chop monolithic applications into micros.",
|
|
5
5
|
"author": "Masking Technology <info@masking.tech> (https://jitar.dev)",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,9 +30,9 @@
|
|
|
30
30
|
"prepublishOnly": "npm run clean && npm run build"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"dotenv": "17.2
|
|
33
|
+
"dotenv": "17.4.2",
|
|
34
34
|
"express": "5.2.1",
|
|
35
|
-
"glob": "13.0.
|
|
35
|
+
"glob": "13.0.6",
|
|
36
36
|
"mime-types": "3.0.2"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"@jitar/runtime": "*",
|
|
47
47
|
"@rollup/plugin-node-resolve": "16.0.3",
|
|
48
48
|
"@rollup/plugin-replace": "6.0.3",
|
|
49
|
-
"@rollup/plugin-terser": "0.
|
|
49
|
+
"@rollup/plugin-terser": "1.0.0",
|
|
50
50
|
"@rollup/plugin-typescript": "12.3.0",
|
|
51
|
-
"rollup": "4.
|
|
52
|
-
"rollup-plugin-dts": "6.
|
|
51
|
+
"rollup": "4.60.3",
|
|
52
|
+
"rollup-plugin-dts": "6.4.1"
|
|
53
53
|
},
|
|
54
54
|
"engines": {
|
|
55
55
|
"node": ">=20.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};class s extends Error{constructor(e="Invalid request"){super(e)}}class r extends Error{constructor(e="Forbidden"){super(e)}}class t extends Error{constructor(e="Not found"){super(e)}}class a extends Error{constructor(e="Not implemented"){super(e)}}class i extends Error{constructor(e="Payment required"){super(e)}}class o extends Error{constructor(e="Server error"){super(e)}}class n extends Error{constructor(e="I'm a teapot"){super(e)}}class h extends Error{constructor(e="Unauthorized"){super(e)}}class u{#e;#s=new Map;#r=new Map;constructor(e){this.#e=e}get id(){return this.#e}addClass(e){return this.#s.set(e.fqn,e),this}hasClass(e){return void 0!==this.getClass(e)}getClass(e){return this.#s.get(e)}getClassByImplementation(e){return this.getClasses().find(s=>s.implementation===e)}getClasses(){return[...this.#s.values()]}addProcedure(e){return this.#r.set(e.fqn,e),this}hasProcedure(e){return this.#r.has(e)}getProcedure(e){return this.#r.get(e)}getExposedProcedures(){return[...this.#r.values()].filter(e=>e.public||e.protected)}}class c{static get DEFAULT(){return new c(0,0,0)}#t;#a;#i;constructor(e=0,s=0,r=0){this.#t=e,this.#a=s,this.#i=r}get major(){return this.#t}get minor(){return this.#a}get patch(){return this.#i}equals(e){return this.#t===e.major&&this.#a===e.minor&&this.#i===e.patch}greater(e){return this.#t!==e.major?this.#t>e.major:this.#a!==e.minor?this.#a>e.minor:this.#i!==e.patch&&this.#i>e.patch}less(e){return this.#t!==e.major?this.#t<e.major:this.#a!==e.minor?this.#a<e.minor:this.#i!==e.patch&&this.#i<e.patch}toString(){return`${this.#t}.${this.#a}.${this.#i}`}}class d{#o;#n;constructor(e,s=!1){this.#o=e,this.#n=s}get name(){return this.#o}get isOptional(){return this.#n}}class l extends d{}class m extends d{#h;constructor(e,s,r){super(s??"(anonymous)",r),this.#h=e}get variables(){return this.#h}}class p extends m{}class g extends m{}class v{#u;#c;#d;#l=new Map;#m;constructor(e,s,r,t,a){this.#u=e,this.#c=s,this.#d=r,this.#l=t,this.#m=a}get fqn(){return this.#u}get version(){return this.#c}get args(){return this.#d}get headers(){return this.#l}get mode(){return this.#m}clearArguments(){this.#d.clear()}setArgument(e,s){this.#d.set(e,s)}getArgument(e){return this.#d.get(e)}hasArgument(e){return this.#d.has(e)}removeArgument(e){this.#d.delete(e)}clearHeaders(){this.#l.clear()}setHeader(e,s){this.#l.set(e.toLowerCase(),s)}getHeader(e){return this.#l.get(e.toLowerCase())}hasHeader(e){return this.#l.has(e.toLowerCase())}removeHeader(e){this.#l.delete(e.toLowerCase())}}class C{#p;#g;#l;constructor(e,s=void 0,r=new Map){this.#p=e,this.#g=s,this.#l=r}get status(){return this.#p}get result(){return this.#g}set result(e){this.#g=e}get headers(){return this.#l}clearHeaders(){this.#l.clear()}setHeader(e,s){this.#l.set(e.toLowerCase(),s)}getHeader(e){return this.#l.get(e.toLowerCase())}hasHeader(e){return this.#l.has(e.toLowerCase())}removeHeader(e){this.#l.delete(e.toLowerCase())}}export{p as A,s as B,r as F,t as N,g as O,i as P,C as R,o as S,n as T,h as U,c as V,l as a,a as b,u as c,e as d,v as e};
|