jitar 0.7.7 → 0.8.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.
@@ -1 +0,0 @@
1
- const AccessLevels={PRIVATE:"private",PROTECTED:"protected",PUBLIC:"public"};Object.freeze(AccessLevels);const Files={MODULE_PATTERN:"**/*.js",SEGMENT_PATTERN:"**/*.segment.json",WORKER_SEGMENT_PATTERN:"**/*.segment.worker.js",REPOSITORY_SEGMENT_PATTERN:"**/*.segment.repository.js"};Object.freeze(Files);const EXTENSION_PATTERN=/\.js$/;function convertToLocalFilename(filename){return filename.replace(EXTENSION_PATTERN,".local.js")}function convertToRemoteFilename(filename){return filename.replace(EXTENSION_PATTERN,".remote.js")}function createWorkerFilename(name){return`./${name}.segment.worker.js`}function createRepositoryFilename(name){return`./${name}.segment.repository.js`}function isSegmentFilename(filename){return filename.includes(".segment.")}const ExecutionScopes={APPLICATION:"application",RUNTIME:"runtime"};Object.freeze(ExecutionScopes);class BadRequest extends Error{constructor(message="Invalid request"){super(message)}}BadRequest.source="/jitar/client.js";class Forbidden extends Error{constructor(message="Forbidden"){super(message)}}Forbidden.source="/jitar/client.js";class NotFound extends Error{constructor(message="Not found"){super(message)}}NotFound.source="/jitar/client.js";class NotImplemented extends Error{constructor(message="Not implemented"){super(message)}}NotImplemented.source="/jitar/client.js";class PaymentRequired extends Error{constructor(message="Payment required"){super(message)}}PaymentRequired.source="/jitar/client.js";class ServerError extends Error{constructor(message="Server error"){super(message)}}ServerError.source="/jitar/client.js";class Teapot extends Error{constructor(){super("I'm a teapot")}}Teapot.source="/jitar/client.js";class Unauthorized extends Error{constructor(message="Unauthorized"){super(message)}}Unauthorized.source="/jitar/client.js";class ClientNotFound extends BadRequest{#clientId;constructor(clientId){super(`Client not found for id '${clientId}'`),this.#clientId=clientId}get clientId(){return this.#clientId}}ClientNotFound.source="/jitar/client.js";class FileNotFound extends NotFound{#filename;constructor(filename){super(`The file '${filename}' could not be found`),this.#filename=filename}get filename(){return this.#filename}}FileNotFound.source="/jitar/client.js";class ImplementationNotFound extends NotFound{#fqn;#version;constructor(fqn,version){super(`No implementation found for procedure '${fqn}' with version '${version}'`),this.#fqn=fqn,this.#version=version}get fqn(){return this.#fqn}get version(){return this.#version}}ImplementationNotFound.source="/jitar/client.js";class InvalidClientId extends BadRequest{#clientId;constructor(clientId){super(`Invalid client id '${clientId}'`),this.#clientId=clientId}get clientId(){return this.#clientId}}InvalidClientId.source="/jitar/client.js";class InvalidParameterValue extends BadRequest{#parameterName;constructor(parameterName){super(`Invalid value for parameter '${parameterName}'`),this.#parameterName=parameterName}get parameterName(){return this.#parameterName}}InvalidParameterValue.source="/jitar/client.js";class InvalidSegmentFile extends ServerError{#filename;constructor(filename){super(`Missing files array in segment file '${filename}'`),this.#filename=filename}get filename(){return this.#filename}}InvalidSegmentFile.source="/jitar/client.js";class InvalidVersionNumber extends BadRequest{#number;constructor(number){super(`Invalid version number '${number}'`),this.#number=number}get number(){return this.#number}}InvalidVersionNumber.source="/jitar/client.js";class MissingParameterValue extends BadRequest{#parameterName;constructor(parameterName){super(`Missing value for parameter '${parameterName}'`),this.#parameterName=parameterName}get parameterName(){return this.#parameterName}}MissingParameterValue.source="/jitar/client.js";class ModuleNotAccessible extends Forbidden{#url;constructor(url){super(`Module '${url}' is not accessible`),this.#url=url}get url(){return this.#url}}ModuleNotAccessible.source="/jitar/client.js";class ModuleNotLoaded extends ServerError{#url;#reason;constructor(url,reason){super(`Module '${url}' could not be loaded${void 0!==reason?` | ${reason}`:""}`),this.#url=url,this.#reason=reason}get url(){return this.#url}get reason(){return this.#reason}}ModuleNotLoaded.source="/jitar/client.js";class NoWorkerAvailable extends ServerError{#name;constructor(name){super(`No worker available for procedure '${name}'`),this.#name=name}get name(){return this.#name}}NoWorkerAvailable.source="/jitar/client.js";class ProcedureNotAccessible extends Forbidden{#fqn;#versionNumber;constructor(fqn,versionNumber){super(`Procedure '${fqn}' (v${versionNumber}) is not accessible`),this.#fqn=fqn,this.#versionNumber=versionNumber}get fqn(){return this.#fqn}get versionNumber(){return this.#versionNumber}}ProcedureNotAccessible.source="/jitar/client.js";class ProcedureNotFound extends NotFound{#fqn;constructor(fqn){super(`Procedure '${fqn}' not found`),this.#fqn=fqn}get fqn(){return this.#fqn}}ProcedureNotFound.source="/jitar/client.js";class RepositoryNotAvailable extends ServerError{constructor(){super("Repository not available")}}RepositoryNotAvailable.source="/jitar/client.js";class RuntimeNotAvailable extends ServerError{constructor(){super("Runtime not available")}}RuntimeNotAvailable.source="/jitar/client.js";class SegmentNotFound extends ServerError{#source;constructor(source){super(`Segment found for '${source}'`),this.#source=source}get source(){return this.#source}}SegmentNotFound.source="/jitar/client.js";class UnknownParameter extends BadRequest{#parameterName;constructor(parameterName){super(`Unknown parameter ${parameterName}`),this.#parameterName=parameterName}get parameterName(){return this.#parameterName}}UnknownParameter.source="/jitar/client.js";class Parameter{#name;#isOptional;constructor(name,isOptional=!1){this.#name=name,this.#isOptional=isOptional}get name(){return this.#name}get isOptional(){return this.#isOptional}}class DestructuredParameter extends Parameter{#variables;constructor(variables,name,isOptional){super(name??"(anonymous)",isOptional),this.#variables=variables}get variables(){return this.#variables}}class ArrayParameter extends DestructuredParameter{}class File{#location;#type;#content;constructor(location,type,content){this.#location=location,this.#type=type,this.#content=content}get location(){return this.#location}get type(){return this.#type}get content(){return this.#content}get size(){return this.#content.length}}class NamedParameter extends Parameter{}class ObjectParameter extends DestructuredParameter{}class Version{static get DEFAULT(){return new Version(0,0,0)}#major;#minor;#patch;constructor(major=0,minor=0,patch=0){this.#major=major,this.#minor=minor,this.#patch=patch}get major(){return this.#major}get minor(){return this.#minor}get patch(){return this.#patch}equals(version){return this.#major===version.major&&this.#minor===version.minor&&this.#patch===version.patch}greater(version){return this.#major!==version.major?this.#major>version.major:this.#minor!==version.minor?this.#minor>version.minor:this.#patch!==version.patch&&this.#patch>version.patch}less(version){return this.#major!==version.major?this.#major<version.major:this.#minor!==version.minor?this.#minor<version.minor:this.#patch!==version.patch&&this.#patch<version.patch}toString(){return`${this.#major}.${this.#minor}.${this.#patch}`}}class Request{#fqn;#version;#args;#headers=new Map;constructor(fqn,version,args,headers){this.#fqn=fqn,this.#version=version,this.#args=args,this.#headers=headers}get fqn(){return this.#fqn}get version(){return this.#version}get args(){return this.#args}get headers(){return this.#headers}clearArguments(){this.#args.clear()}setArgument(name,value){this.#args.set(name,value)}getArgument(name){return this.#args.get(name)}hasArgument(name){return this.#args.has(name)}removeArgument(name){this.#args.delete(name)}clearHeaders(){this.#headers.clear()}setHeader(name,value){this.#headers.set(name.toLowerCase(),value)}getHeader(name){return this.#headers.get(name.toLowerCase())}hasHeader(name){return this.#headers.has(name.toLowerCase())}removeHeader(name){this.#headers.delete(name.toLowerCase())}}class Response{#result;#headers;constructor(result=void 0,headers=new Map){this.#result=result,this.#headers=headers}get result(){return this.#result}set result(value){this.#result=value}get headers(){return this.#headers}clearHeaders(){this.#headers.clear()}setHeader(name,value){this.#headers.set(name.toLowerCase(),value)}getHeader(name){return this.#headers.get(name.toLowerCase())}hasHeader(name){return this.#headers.has(name.toLowerCase())}removeHeader(name){this.#headers.delete(name.toLowerCase())}}class InvalidMiddleware extends ServerError{#url;constructor(url){super(`Module '${url}' does not export valid middleware`),this.#url=url}get url(){return this.#url}}InvalidMiddleware.source="/jitar/client.js";class ProcedureRunner{#runner;constructor(runner){this.#runner=runner}async handle(request,next){return this.#runner.run(request)}}class InvalidHealthCheck extends ServerError{#url;constructor(url){super(`Module '${url}' does not export a valid health check`),this.#url=url}get url(){return this.#url}}InvalidHealthCheck.source="/jitar/client.js";class Runtime{#url;#healthCheckFiles=new Set;#healthChecks=new Map;constructor(url){this.#url=url}get url(){return this.#url}set healthCheckFiles(filenames){this.#healthCheckFiles=filenames}start(){return this.#importHealthChecks()}async stop(){this.#clearHealthChecks()}addHealthCheck(healthCheck){this.#healthChecks.set(healthCheck.name,healthCheck)}async isHealthy(){const promises=[];for(const healthCheck of this.#healthChecks.values()){const promise=this.#executeHealthCheck(healthCheck);promises.push(promise)}return Promise.all(promises).then((results=>results.every((result=>result)))).catch((()=>!1))}async getHealth(){const promises=[];for(const[name,healthCheck]of this.#healthChecks){const promise=this.#executeHealthCheck(healthCheck).then((result=>({name:name,isHealthy:result}))).catch((()=>({name:name,isHealthy:!1})));promises.push(promise)}const healthChecks=new Map;return Promise.allSettled(promises).then((results=>results.forEach((result=>{"fulfilled"===result.status?healthChecks.set(result.value.name,result.value.isHealthy):healthChecks.set(result.reason.name,!1)})))).then((()=>healthChecks))}async#importHealthChecks(){for(const filename of this.#healthCheckFiles)await this.#importHealthCheck(filename)}async#importHealthCheck(url){const healthCheck=(await this.import(url,ExecutionScopes.APPLICATION)).default;if(void 0===healthCheck?.isHealthy)throw new InvalidHealthCheck(url);this.addHealthCheck(healthCheck)}#clearHealthChecks(){this.#healthChecks.clear()}async#executeHealthCheck(healthCheck){const health=healthCheck.isHealthy(),milliseconds=healthCheck.timeout;if(void 0===milliseconds)return health;const timeout=new Promise((resolve=>{setTimeout(resolve,milliseconds)})).then((()=>!1));return Promise.race([timeout,health])}}class ProcedureRuntime extends Runtime{#repository;#middlewareFiles=new Set;#middlewares=[];constructor(repository,url){super(url),this.#repository=repository,this.#middlewares.push(new ProcedureRunner(this))}get repository(){return this.#repository}set middlewareFiles(filenames){this.#middlewareFiles=filenames}async start(){await this.#repository.start(),await super.start(),await this.#importMiddlewares()}async stop(){this.#clearMiddlewares(),await this.#repository.stop(),await super.stop()}import(url,scope){return this.#repository.import(url,scope)}addMiddleware(middleware){const index=this.#middlewares.length-1;this.#middlewares.splice(index,0,middleware)}getMiddleware(type){return this.#middlewares.find((middleware=>middleware instanceof type))}handle(request){return this.#getNextHandler(request,0)()}#getNextHandler(request,index){const next=this.#middlewares[index];if(void 0===next)return async()=>new Response;const nextHandler=this.#getNextHandler(request,index+1);return async()=>next.handle(request,nextHandler)}async#importMiddlewares(){for(const url of this.#middlewareFiles)await this.#importMiddleware(url)}async#importMiddleware(url){const middleware=(await this.import(url,ExecutionScopes.APPLICATION)).default;if(void 0===middleware?.handle)throw new InvalidMiddleware(url);this.addMiddleware(middleware)}#clearMiddlewares(){this.#middlewares=[]}}class Gateway extends ProcedureRuntime{}class InvalidTrustKey extends Unauthorized{constructor(){super("Invalid trust key")}}InvalidTrustKey.source="/jitar/client.js";const VERSION_EXPRESSION=/^\d+(?:\.\d+){0,2}$/;class VersionParser{static parse(number){if(0===number.trim().length)return Version.DEFAULT;if(!1===VERSION_EXPRESSION.test(number))throw new InvalidVersionNumber(number);const parts=number.split(".");switch(parts.length){case 1:return new Version(Number.parseInt(parts[0]));case 2:return new Version(Number.parseInt(parts[0]),Number.parseInt(parts[1]));default:return new Version(Number.parseInt(parts[0]),Number.parseInt(parts[1]),Number.parseInt(parts[2]))}}}const RUNS_IN_BROWSER="undefined"!=typeof window;let _runtime;function setRuntime(runtime){_runtime=runtime}function getRuntime(){if(void 0===_runtime)throw new RuntimeNotAvailable;return _runtime}class ArgumentExtractor{extract(parameters,args){const argsCopy=this.#copyArguments(parameters,args),values=[];for(const parameter of parameters){const value=this.#extractArgumentValue(parameter,argsCopy);values.push(value)}if(argsCopy.size>0){const name=argsCopy.keys().next().value;throw new UnknownParameter(name)}return values}#copyArguments(parameters,args){const copy=new Map;for(const[key,value]of args)if(this.#isOptionalArgument(key)){const name=this.#getParameterName(key);!0===this.#containsParameter(parameters,name)&&copy.set(name,value)}else copy.set(key,value);return copy}#isOptionalArgument(argument){return argument.startsWith("*")}#getParameterName(argument){return argument.substring(1)}#containsParameter(parameters,name){return void 0!==parameters.find((parameter=>parameter.name===name))}#extractArgumentValue(parameter,args,parent){return parameter instanceof NamedParameter?this.#extractNamedArgumentValue(parameter,args,parent):this.#extractDestructedArgumentValue(parameter,args)}#extractNamedArgumentValue(parameter,args,parent){const value=args.get(parameter.name);if(this.#isMissingParameterValue(parameter,value,parent))throw new MissingParameterValue(parameter.name);if(this.#isInvalidRestParameter(parameter,value,parent))throw new InvalidParameterValue(parameter.name);return args.delete(parameter.name),value}#extractDestructedArgumentValue(parameter,args){return parameter instanceof ArrayParameter?this.#extractArrayArgumentValue(parameter,args):this.#extractObjectArgumentValue(parameter,args)}#extractArrayArgumentValue(parameter,args){const values=this.#extractVariableValues(parameter,args);return void 0!==values?Object.values(values):void 0}#extractObjectArgumentValue(parameter,args){return this.#extractVariableValues(parameter,args)}#extractVariableValues(parameter,args){const useIndex=parameter instanceof ArrayParameter,values={},missingValues=[];let containsValues=!1,index=0;for(const variable of parameter.variables){const key=useIndex?index++:variable.name,value=this.#extractArgumentValue(variable,args,parameter);void 0!==value?containsValues=!0:!1===variable.isOptional&&missingValues.push(variable.name),values[key]=value}if(!0===containsValues&&missingValues.length>0)throw new MissingParameterValue(missingValues[0]);return containsValues?values:void 0}#isMissingParameterValue(parameter,value,parent){return void 0===value&&(!0!==parameter.isOptional&&!0!==parent?.isOptional)}#isInvalidRestParameter(parameter,value,parent){return!1!==parameter.name.startsWith("...")&&(void 0===parent&&value instanceof Array==!1||parent instanceof ArrayParameter&&value instanceof Array==!1||parent instanceof ObjectParameter&&value instanceof Object==!1)}}class Worker extends ProcedureRuntime{}class LocalWorker extends Worker{#gateway;#trustKey;#argumentConstructor;#segmentNames=new Set;#segments=new Map;constructor(repository,gateway,url,trustKey,argumentConstructor=new ArgumentExtractor){super(repository,url),this.#gateway=gateway,this.#trustKey=trustKey,this.#argumentConstructor=argumentConstructor,setRuntime(this)}get trustKey(){return this.#trustKey}set segmentNames(names){this.#segmentNames=names}async start(){await super.start(),await this.#loadSegments(),void 0!==this.#gateway&&await this.#gateway.start()}async stop(){this.#unloadSegments(),void 0!==this.#gateway&&await this.#gateway.stop(),await super.stop()}getProcedureNames(){const names=new Set;for(const segment of this.#segments.values()){segment.getExposedProcedures().forEach((procedure=>names.add(procedure.fqn)))}return[...names.values()]}addSegment(segment){this.#segments.set(segment.id,segment)}hasProcedure(fqn){return this.getProcedureNames().includes(fqn)}run(request){const procedure=this.#getProcedure(request.fqn);return void 0===procedure?this.#useGateway(request):this.#runProcedure(procedure,request)}async#loadSegments(){for(const segmentName of this.#segmentNames)await this.#loadSegment(segmentName)}async#loadSegment(name){const filename=createWorkerFilename(name),segment=(await this.import(filename,ExecutionScopes.APPLICATION)).segment;this.addSegment(segment)}#unloadSegments(){this.#segments.clear()}#useGateway(request){if(void 0===this.#gateway)throw new ProcedureNotFound(request.fqn);if(void 0!==this.#trustKey){request.headers.set("X-Jitar-Trust-Key",this.#trustKey)}return this.#gateway.run(request)}async#runProcedure(procedure,request){const trustKey=request.getHeader("X-Jitar-Trust-Key");if(void 0!==trustKey&&this.#trustKey!==trustKey)throw new InvalidTrustKey;if(void 0===trustKey&&procedure.protected)throw new Unauthorized;const implementation=procedure.getImplementation(request.version);if(void 0===implementation)throw new ImplementationNotFound(procedure.fqn,request.version.toString());const values=this.#argumentConstructor.extract(implementation.parameters,request.args),result=await implementation.executable.call(request,...values);return new Response(result)}#getProcedure(fqn){for(const segment of this.#segments.values())if(segment.hasProcedure(fqn))return segment.getProcedure(fqn)}}const hasWindowObject="undefined"!=typeof window;class Environment{static isBrowser(){return hasWindowObject}static isServer(){return!1===hasWindowObject}}class UrlRewriter{static addBase(url,base){if(url.startsWith(base))return url;const parts=`${base}/${url}`.split("://"),protocol=parts.length>1?`${parts[0]}://`:"",address=parts.length>1?parts[1]:parts[0];return`${protocol}${this.#translateAddress(address)}`}static removeBase(url,base){return!1===url.startsWith(base)?url:url.substring(base.length)}static#translateAddress(address){const parts=address.split("/"),translated=[];translated.push(parts[0]);for(let index=1;index<parts.length;index++){const part=parts[index].trim();switch(part){case"":case".":continue;case"..":translated.pop();continue}translated.push(part)}return translated.join("/")}}const APPLICATION_MODULE_INDICATORS=[".","/","http:","https:"];let _baseUrl="",_import=async name=>import(name);class ModuleLoader{static setBaseUrl(baseUrl){_baseUrl=baseUrl}static setImporter(importer){_import=importer}static async load(specifier){if(this.#isSystemModule(specifier))return this.#import(specifier);if(specifier.startsWith("/jitar"))return Environment.isServer()?this.#import("jitar"):this.#import(specifier);const filename=this.assureExtension(specifier),url=UrlRewriter.addBase(filename,_baseUrl);if(!1===url.startsWith(_baseUrl))throw new ModuleNotAccessible(specifier);return this.#import(url)}static assureExtension(specifier){return specifier.endsWith(".js")?specifier:`${specifier}.js`}static#isSystemModule(specifier){return!1===APPLICATION_MODULE_INDICATORS.some((indicator=>specifier.startsWith(indicator)))}static async#import(specifier){try{return await _import(specifier)}catch(error){const safeUrl=UrlRewriter.removeBase(specifier,_baseUrl),message=error instanceof Error?error.message:String(error);throw new ModuleNotLoaded(safeUrl,message)}}}class Repository extends Runtime{async import(url,scope){return scope===ExecutionScopes.RUNTIME?ModuleLoader.load(url):this.loadModule(url)}}class ClassNotFound extends Error{constructor(name){super(`The class '${name}' could not be found`)}}class InvalidClass extends Error{constructor(name){super(`The class '${name}' is invalid`)}}class NoDeserializerFound extends Error{constructor(type){super(`No deserializer found for value of type '${type}'`)}}class NoSerializerFound extends Error{constructor(type){super(`No serializer found for value of type '${type}'`)}}class Serializer{#serializers=[];addSerializer(serializer){serializer.parent=this,this.#serializers.unshift(serializer)}async serialize(value){const serializer=this.#serializers.find((serializer=>serializer.canSerialize(value)));if(void 0===serializer)throw new NoSerializerFound(typeof value);return serializer.serialize(value)}async deserialize(value){const serializer=this.#serializers.find((serializer=>serializer.canDeserialize(value)));if(void 0===serializer)throw new NoDeserializerFound(typeof value);return serializer.deserialize(value)}}class ParentSerializerNotSet extends Error{constructor(){super("Parent serializer not set")}}class ValueSerializer{#parent;set parent(parent){this.#parent=parent}serializeOther(value){if(void 0===this.#parent)throw new ParentSerializerNotSet;return this.#parent.serialize(value)}deserializeOther(value){if(void 0===this.#parent)throw new ParentSerializerNotSet;return this.#parent.deserialize(value)}}class ArraySerializer extends ValueSerializer{canSerialize(value){return value instanceof Array}canDeserialize(value){return value instanceof Array}async serialize(array){const values=[];for(const value of array)values.push(await this.serializeOther(value));return values}async deserialize(array){return Promise.all(array.map((async value=>this.deserializeOther(value))))}}class InvalidBigIntString extends Error{constructor(bigIntString){super(`Invalid BigInt string '${bigIntString}'`)}}class BigIntSerializer extends ValueSerializer{canSerialize(value){return"bigint"==typeof value}canDeserialize(value){const bigInt=value;return bigInt instanceof Object&&!0===bigInt.serialized&&"BigInt"===bigInt.name&&"string"==typeof bigInt.value}async serialize(bigInt){return{serialized:!0,name:"BigInt",value:bigInt.toString()}}async deserialize(object){try{return BigInt(object.value)}catch(error){throw new InvalidBigIntString(object.value)}}}class ReflectionAlias{#name;#as;constructor(name,as){this.#name=name,this.#as=as}get name(){return this.#name}get as(){return this.#as}toString(){return`${this.#name} as ${this.#as}`}}class ReflectionValue{#definition;constructor(definition){this.#definition=definition}get definition(){return this.#definition}toString(){return this.#definition}}class ReflectionArray extends ReflectionValue{}class ReflectionMember{#name;#isStatic;#isPrivate;constructor(name,isStatic=!1,isPrivate=!1){this.#name=name,this.#isStatic=isStatic,this.#isPrivate=isPrivate}get name(){return this.#name}get isStatic(){return this.#isStatic}get isPrivate(){return this.#isPrivate}get isPublic(){return!1===this.#isPrivate}}class ReflectionClass extends ReflectionMember{#parentName;#scope;constructor(name,parentName,scope){super(name),this.#parentName=parentName,this.#scope=scope}get parentName(){return this.#parentName}get scope(){return this.#scope}get members(){return this.#scope.members}get declarations(){return this.#scope.declarations}get functions(){return this.#scope.functions}get getters(){return this.#scope.getters}get setters(){return this.#scope.setters}get generators(){return this.#scope.generators}get readable(){const members=new Map;return this.getters.forEach((getter=>{members.set(getter.name,getter)})),this.declarations.forEach((declaration=>{declaration.isPublic&&members.set(declaration.name,declaration)})),[...members.values()]}get writable(){const members=new Map;return this.setters.forEach((setter=>{members.set(setter.name,setter)})),this.declarations.forEach((declaration=>{declaration.isPublic&&members.set(declaration.name,declaration)})),[...members.values()]}get callable(){return this.functions.filter((funktion=>funktion.isPublic))}getMember(name){return this.#scope.getMember(name)}getDeclaration(name){return this.#scope.getDeclaration(name)}getFunction(name){return this.#scope.getFunction(name)}getGetter(name){return this.#scope.getGetter(name)}getSetter(name){return this.#scope.getSetter(name)}getGenerator(name){return this.#scope.getGenerator(name)}hasMember(name){return this.#scope.hasMember(name)}hasDeclaration(name){return this.#scope.hasDeclaration(name)}hasFunction(name){return this.#scope.hasFunction(name)}hasGetter(name){return this.#scope.hasGetter(name)}hasSetter(name){return this.#scope.hasSetter(name)}hasGenerator(name){return this.#scope.hasGenerator(name)}canRead(name){const declaration=this.getDeclaration(name);return declaration?.isPublic||this.hasGetter(name)}canWrite(name){const declaration=this.getDeclaration(name);return declaration?.isPublic||this.hasSetter(name)}canCall(name){const funktion=this.getFunction(name);return funktion?.isPublic??!1}toString(){const infix=void 0!==this.#parentName?` extends ${this.#parentName}`:"";return`class ${this.name}${infix} { ${this.#scope.toString()} }`}}class ReflectionDeclaration extends ReflectionMember{#identifier;#value;constructor(identifier,value,isStatic=!1,isPrivate=!1){super(identifier.toString(),isStatic,isPrivate),this.#identifier=identifier,this.#value=value}get identifier(){return this.#identifier}get value(){return this.#value}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class ReflectionDestructuredValue{#members;constructor(members){this.#members=members}get members(){return this.#members}toString(){return this.#members.map((member=>member.toString())).join(" , ")}}class ReflectionDestructuredArray extends ReflectionDestructuredValue{toString(){return`[ ${super.toString()} ]`}}class ReflectionDestructuredObject extends ReflectionDestructuredValue{toString(){return`{ ${super.toString()} }`}}class ReflectionExport extends ReflectionMember{#members;#from;constructor(members,from){super(""),this.#members=members,this.#from=from}get members(){return this.#members}get from(){return this.#from}toString(){const postfix=this.#from?` from '${this.#from}'`:"";return`export { ${this.#members.join(", ")} }${postfix}`}}class ReflectionExpression extends ReflectionValue{}class ReflectionField{#name;#value;constructor(name,value){this.#name=name,this.#value=value}get name(){return this.#name}get value(){return this.#value}toString(){return`${this.name}${this.value?" = "+this.value.toString():""}`}}class ReflectionFunction extends ReflectionMember{#parameters;#body;#isAsync;constructor(name,parameters,body,isStatic=!1,isAsync=!1,isPrivate=!1){super(name,isStatic,isPrivate),this.#parameters=parameters,this.#body=body,this.#isAsync=isAsync}get parameters(){return this.#parameters}get body(){return this.#body}get isAsync(){return this.#isAsync}toString(){const parameters=this.parameters.map((parameter=>parameter.toString()));return`${this.isAsync?"async ":""}${this.name}(${parameters.join(", ")}) { ${this.body} }`}}class ReflectionGenerator extends ReflectionFunction{toString(){const parameters=this.parameters.map((parameter=>parameter.toString()));return`${this.isAsync?"async ":""}${this.name}*(${parameters.join(", ")}) { ${this.body} }`}}class ReflectionGetter extends ReflectionFunction{toString(){return`get ${super.toString()}`}}class ReflectionImport extends ReflectionMember{#members;#from;constructor(members,from){super(""),this.#members=members,this.#from=from}get members(){return this.#members}get from(){return this.#from}toString(){return`import { ${this.#members.map((member=>member.toString())).join(", ")} } from '${this.#from}';`}}class ReflectionModule{#scope;constructor(scope){this.#scope=scope}get scope(){return this.#scope}get members(){return this.#scope.members}get exportedMembers(){return this.#filterExported(this.#scope.members)}get imports(){return this.#scope.imports}get exports(){return this.#scope.exports}get declarations(){return this.#scope.declarations}get exportedDeclarations(){return this.#filterExported(this.#scope.declarations)}get functions(){return this.#scope.functions}get exportedFunctions(){return this.#filterExported(this.#scope.functions)}get generators(){return this.#scope.generators}get exportedGenerators(){return this.#filterExported(this.#scope.generators)}get classes(){return this.#scope.classes}get exportedClasses(){return this.#filterExported(this.#scope.classes)}get exported(){const exported=new Map;for(const exportItem of this.exports)for(const alias of exportItem.members){const member=this.getMember(alias.name);void 0!==member&&exported.set(alias.as,member)}return exported}getMember(name){return this.#scope.getMember(name)}getDeclaration(name){return this.#scope.getDeclaration(name)}getFunction(name){return this.#scope.getFunction(name)}getGenerator(name){return this.#scope.getGenerator(name)}getClass(name){return this.#scope.getClass(name)}hasMember(name){return this.#scope.hasMember(name)}hasDeclaration(name){return this.#scope.hasDeclaration(name)}hasFunction(name){return this.#scope.hasFunction(name)}hasGenerator(name){return this.#scope.hasGenerator(name)}hasClass(name){return this.#scope.hasClass(name)}isExported(member){for(const exportItem of this.exports)for(const alias of exportItem.members)if(alias.name===member.name)return!0;return!1}getExported(name){for(const exportItem of this.exports)for(const alias of exportItem.members)if(alias.as===name)return this.getMember(alias.name)}#filterExported(members){return members.filter((member=>this.isExported(member)))}}class ReflectionObject extends ReflectionValue{}class ReflectionSetter extends ReflectionFunction{toString(){return`set ${super.toString()}`}}class ItemList{#items;#position;constructor(items){this.#items=items,this.#position=0}get items(){return this.#items}get position(){return this.#position}get size(){return this.#items.length}get eol(){return this.#position>=this.#items.length}get current(){return this.#items[this.#position]}get next(){return this.#items[this.#position+1]}get previous(){return this.#items[this.#position-1]}notAtEnd(){return!1===this.eol}get(index){return this.#items[index]}step(amount=1){return this.#position+=amount,this.current}stepBack(amount=1){return this.#position-=amount,this.current}hasNext(){return this.#position+1<this.#items.length}}class CharList extends ItemList{constructor(code){super(code.split(""))}}class Token{#type;#value;#start;#end;constructor(type,value,start,end){this.#type=type,this.#value=value,this.#start=start,this.#end=end}get type(){return this.#type}get value(){return this.#value}get start(){return this.#start}get end(){return this.#end}isType(type){return this.#type===type}hasValue(value){return this.#value===value}toString(){return`${this.#value}`}}class TokenList extends ItemList{}const Comment={SINGLE:"//",MULTI_START:"/*",MULTI_END:"*/"},Comments=Object.values(Comment);const Punctuation_DOT=".",Punctuation_LEFT_PARENTHESIS="(",Punctuation_RIGHT_PARENTHESIS=")",Punctuation_LEFT_BRACKET="[",Punctuation_RIGHT_BRACKET="]",Punctuation_LEFT_BRACE="{",Punctuation_RIGHT_BRACE="}",Divider={SCOPE:":",SEPARATOR:",",TERMINATOR:";"},Divisions=Object.values(Divider);function isDivider(value){return Divisions.includes(value)}const Empty={UNDEFINED:void 0,NULL:null,STRING:""},Empties=Object.values(Empty);function isEmpty(value){return Empties.includes(value)}const Group={OPEN:Punctuation_LEFT_PARENTHESIS,CLOSE:Punctuation_RIGHT_PARENTHESIS};function isGroup(value){return value===Group.OPEN||value===Group.CLOSE}const Keyword={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"},Keywords=Object.values(Keyword);function isKeyword(value){return Keywords.includes(value)}function isNotReserved(value){return value===Keyword.AS||value===Keyword.ASYNC||value===Keyword.FROM||value===Keyword.GET||value===Keyword.SET}const List={OPEN:Punctuation_LEFT_BRACKET,CLOSE:Punctuation_RIGHT_BRACKET};function isList(value){return value===List.OPEN||value===List.CLOSE}const Literals=Object.values({SINGLE:"'",DOUBLE:'"',BACKTICK:"`"});function isLiteral(value){return Literals.includes(value)}const Operator={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:"^"},Operators=Object.values(Operator);function isOperator(value){return Operators.includes(value)}const Scope={OPEN:Punctuation_LEFT_BRACE,CLOSE:Punctuation_RIGHT_BRACE};function isScope(value){return value===Scope.OPEN||value===Scope.CLOSE}const TokenType={COMMENT:"comment",DIVIDER:"divider",GROUP:"group",IDENTIFIER:"identifier",KEYWORD:"keyword",LIST:"list",LITERAL:"literal",OPERATOR:"operator",REGEX:"regex",SCOPE:"scope",WHITESPACE:"whitespace"},Whitespace={SPACE:" ",TAB:"\t",NEWLINE:"\n",CARRIAGE_RETURN:"\r"},Whitespaces=Object.values(Whitespace);function isWhitespace(value){return Whitespaces.includes(value)}class Lexer{tokenize(code){const charList=new CharList(code),tokens=[];let last;for(;charList.notAtEnd();){const token=this.#getNextToken(charList,last);if(void 0===token)break;token.isType(TokenType.WHITESPACE)||token.isType(TokenType.COMMENT)?charList.step():(tokens.push(token),this.#isCodeToken(token)&&(last=token),charList.step())}return new TokenList(tokens)}#isCodeToken(token){return!1===[TokenType.WHITESPACE,TokenType.COMMENT].includes(token.type)}#getNextToken(charList,lastToken){const char=charList.current,start=charList.position;if(isWhitespace(char)){const end=charList.position;return new Token(TokenType.WHITESPACE,char,start,end)}if(function(value){return Comments.includes(value)}(char+charList.next)){const value=this.#readComment(charList),end=charList.position;return new Token(TokenType.COMMENT,value,start,end)}if(this.#startsRegex(char,lastToken)){const value=this.#readRegex(charList),end=charList.position;return new Token(TokenType.REGEX,value,start,end)}if(isLiteral(char)){const value=this.#readLiteral(charList),end=charList.position;return new Token(TokenType.LITERAL,value,start,end)}if(isOperator(char)){const value=this.#readOperation(charList),end=charList.position;return new Token(TokenType.OPERATOR,value,start,end)}if(isDivider(char)){const end=charList.position;return new Token(TokenType.DIVIDER,char,start,end)}if(isGroup(char)){const end=charList.position;return new Token(TokenType.GROUP,char,start,end)}if(isScope(char)){const end=charList.position;return new Token(TokenType.SCOPE,char,start,end)}if(isList(char)){const end=charList.position;return new Token(TokenType.LIST,char,start,end)}if(isEmpty(char))return;const value=this.#readIdentifier(charList),type=isKeyword(value)?TokenType.KEYWORD:TokenType.IDENTIFIER,end=charList.position;return new Token(type,value,start,end)}#readComment(charList){const isMulti=charList.current+charList.next===Comment.MULTI_START,terminator=isMulti?Comment.MULTI_END:Whitespace.NEWLINE;let value=isMulti?Comment.MULTI_START:Comment.SINGLE;for(charList.step(2);charList.notAtEnd();){const char=charList.current;if((isMulti?char+charList.next:char)===terminator){charList.step(terminator.length-1);break}value+=char,charList.step()}return isMulti?value+Comment.MULTI_END:value.trim()}#startsRegex(char,lastToken){return char===Operator.DIVIDE&&(void 0===lastToken||([TokenType.OPERATOR,TokenType.DIVIDER,TokenType.KEYWORD].includes(lastToken.type)||[Group.OPEN,List.OPEN].includes(lastToken.value)))}#endsRegex(char){return isWhitespace(char)||char==Punctuation_DOT||!1===this.#isIdentifier(char)}#readRegex(charList){let value=charList.current,closed=!1;for(charList.step();charList.notAtEnd();){const current=charList.current,previous=charList.previous;if(current===Operator.DIVIDE&&"\\"!==previous)closed=!0;else if(!0===closed&&this.#endsRegex(current)){charList.stepBack();break}value+=current,charList.step()}return value}#readLiteral(charList){const identifier=charList.current;let value=identifier,escaped=!1;for(charList.step();charList.notAtEnd();){const char=charList.current;if(!1===escaped){if(char===identifier){value+=char;break}"\\"===char&&(escaped=!0)}else escaped=!1;value+=char,charList.step()}return value}#isIdentifier(char){return!1===(isEmpty(char)||isWhitespace(char)||isOperator(char)||isLiteral(char)||isDivider(char)||isGroup(char)||isScope(char)||isList(char))}#readIdentifier(charList){let value="";for(;charList.notAtEnd();){const char=charList.current;if(!1===this.#isIdentifier(char)){charList.stepBack();break}value+=char,charList.step()}return value}#readOperation(charList){let value=charList.current;for(charList.step();charList.notAtEnd();){const char=charList.current;if(!1===isOperator(char)||!1===isOperator(value+char)){charList.stepBack();break}value+=char,charList.step()}return value}}class ExpectedKeyword extends Error{constructor(value,position){super(`Expected keyword '${value}' at position ${position}`)}}class ExpectedToken extends Error{constructor(value,position){super(`Expected token '${value}' at position ${position}`)}}class UnexpectedKeyword extends Error{constructor(keyword,position){super(`Unexpected keyword '${keyword}' at position ${position}`)}}class UnexpectedParseResult extends Error{constructor(expected){super(`The given code does not contain ${expected}`)}}class UnexpectedToken extends Error{constructor(value,position){super(`Unexpected token '${value}' at position ${position}`)}}const IMPORT_NAME=ReflectionImport.name,EXPORT_NAME=ReflectionExport.name,DECLARATION_NAME=ReflectionDeclaration.name,FUNCTION_NAME=ReflectionFunction.name,GETTER_NAME=ReflectionGetter.name,SETTER_NAME=ReflectionSetter.name,GENERATOR_NAME=ReflectionGenerator.name,CLASS_NAME=ReflectionClass.name;class ReflectionScope{#members;constructor(members){this.#members=members}get members(){return this.#members}get imports(){return this.#members.filter((member=>member.constructor.name===IMPORT_NAME))}get exports(){return this.#members.filter((member=>member.constructor.name===EXPORT_NAME))}get declarations(){return this.#members.filter((member=>member.constructor.name===DECLARATION_NAME))}get functions(){return this.#members.filter((member=>member.constructor.name===FUNCTION_NAME))}get getters(){return this.#members.filter((member=>member.constructor.name===GETTER_NAME))}get setters(){return this.#members.filter((member=>member.constructor.name===SETTER_NAME))}get generators(){return this.#members.filter((member=>member.constructor.name===GENERATOR_NAME))}get classes(){return this.#members.filter((member=>member.constructor.name===CLASS_NAME))}getMember(name){return this.#members.find((member=>member.name===name))}getDeclaration(name){return this.declarations.find((member=>member.name===name))}getFunction(name){return this.functions.find((member=>member.name===name))}getGetter(name){return this.getters.find((member=>member.name===name))}getSetter(name){return this.setters.find((member=>member.name===name))}getGenerator(name){return this.generators.find((member=>member.name===name))}getClass(name){return this.classes.find((member=>member.name===name))}hasMember(name){return void 0!==this.getMember(name)}hasDeclaration(name){return void 0!==this.getDeclaration(name)}hasFunction(name){return void 0!==this.getFunction(name)}hasGetter(name){return void 0!==this.getGetter(name)}hasSetter(name){return void 0!==this.getSetter(name)}hasGenerator(name){return void 0!==this.getGenerator(name)}hasClass(name){return void 0!==this.getClass(name)}toString(){return this.#members.map((member=>member.toString())).join("\n")}}class Parser{#lexer;constructor(lexer=new Lexer){this.#lexer=lexer}parse(code){const tokenList=this.#lexer.tokenize(code),scope=this.#parseScope(tokenList);return new ReflectionModule(scope)}parseFirst(code){const tokenList=this.#lexer.tokenize(code);return this.#parseNext(tokenList)}parseValue(code){const model=this.parseFirst(code);if(model instanceof ReflectionValue==!1)throw new UnexpectedParseResult("a value definition");return model}parseImport(code){const model=this.parseFirst(code);if(model instanceof ReflectionImport==!1)throw new UnexpectedParseResult("an import definition");return model}parseExport(code){const model=this.parseFirst(code);if(model instanceof ReflectionExport==!1)throw new UnexpectedParseResult("an export definition");return model}parseDeclaration(code){const model=this.parseFirst(code);if(model instanceof ReflectionDeclaration==!1)throw new UnexpectedParseResult("a declaration definition");return model}parseFunction(code){const tokenList=this.#lexer.tokenize(code),model=this.#parseMember(tokenList);if(model instanceof ReflectionFunction==!1)throw new UnexpectedParseResult("a function definition");return model}parseClass(code){const tokenList=this.#lexer.tokenize(code),model=this.#parseMember(tokenList);if(model instanceof ReflectionClass==!1)throw new UnexpectedParseResult("a class definition");return model}#parseScope(tokenList){const members=[];for(;tokenList.notAtEnd();){const member=this.#parseNext(tokenList);member instanceof ReflectionMember&&members.push(member)}return new ReflectionScope(members)}#parseNext(tokenList,isAsync=!1){const token=tokenList.current;if(token.isType(TokenType.LITERAL))return this.#parseExpression(tokenList);if(token.isType(TokenType.IDENTIFIER)){const next=tokenList.next;return next?.hasValue(Operator.ARROW)?this.#parseArrowFunction(tokenList,isAsync):this.#parseExpression(tokenList)}if(token.isType(TokenType.KEYWORD)){if(isNotReserved(token.value)){const next=tokenList.next,nextIsFunction=void 0!==next&&(next.hasValue(Keyword.FUNCTION)||next.hasValue(Group.OPEN));if(token.hasValue(Keyword.ASYNC)&&nextIsFunction)return tokenList.step(),this.#parseNext(tokenList,!0);if(void 0===next||this.#atEndOfStatement(next))return this.#parseExpression(tokenList)}return token.hasValue(Keyword.RETURN)?this.#parseExpression(tokenList):this.#parseMember(tokenList,isAsync)}if(token.isType(TokenType.REGEX))return this.#parseExpression(tokenList);if(token.hasValue(Group.OPEN)){const next=this.#peekAfterBlock(tokenList,Group.OPEN,Group.CLOSE);return next?.hasValue(Operator.ARROW)?this.#parseArrowFunction(tokenList,isAsync):this.#parseExpression(tokenList)}if(token.hasValue(Scope.OPEN))return this.#parseObject(tokenList);if(token.hasValue(List.OPEN))return this.#parseArray(tokenList);if(token.hasValue(Operator.NOT)||token.hasValue(Operator.SUBTRACT))return this.#parseExpression(tokenList);if(!isDivider(token.value))throw new UnexpectedToken(token.value,token.start);tokenList.step()}#parseMember(tokenList,isAsync=!1){const token=tokenList.current;switch(tokenList.step(),token.value){case Keyword.IMPORT:return this.#parseImport(tokenList);case Keyword.EXPORT:return this.#parseExport(tokenList);case Keyword.CLASS:return this.#parseClass(tokenList);case Keyword.FUNCTION:return this.#parseFunction(tokenList,isAsync);case Keyword.VAR:case Keyword.LET:case Keyword.CONST:return this.#parseDeclaration(tokenList,!1,!0);case Keyword.ASYNC:return this.#parseMember(tokenList,!0);default:throw new UnexpectedKeyword(token.value,token.start)}}#parseImport(tokenList){const members=[];let token=tokenList.current;if(token.isType(TokenType.LITERAL))return new ReflectionImport(members,token.value);if(token.hasValue(Group.OPEN)){token=tokenList.step();const from=token.value;return tokenList.step(2),new ReflectionImport(members,from)}if(!1===token.hasValue(Scope.OPEN)){const name=token.hasValue(Operator.MULTIPLY)?Operator.MULTIPLY:"default";let as=token.value;token=tokenList.step(),token.hasValue(Keyword.AS)&&(token=tokenList.step(),as=token.value,token=tokenList.step()),members.push(new ReflectionAlias(name,as))}if(token.hasValue(Divider.SEPARATOR)&&(token=tokenList.step()),token.hasValue(Scope.OPEN)){const aliases=this.#parseAliasList(tokenList);members.push(...aliases),token=tokenList.current}if(!1===token.hasValue(Keyword.FROM))throw new ExpectedKeyword(Keyword.FROM,token.start);token=tokenList.step();const from=token.value;return tokenList.step(),new ReflectionImport(members,from)}#parseExport(tokenList){switch(tokenList.current.value){case Keyword.DEFAULT:return tokenList.step(),this.#parseSingleExport(tokenList,!0);case Scope.OPEN:return this.#parseMultiExport(tokenList);default:return this.#parseSingleExport(tokenList,!1)}}#parseSingleExport(tokenList,isDefault){let token=tokenList.current,stepSize=0;var value;token.hasValue(Keyword.ASYNC)&&(token=tokenList.step(),stepSize++),((value=token.value)===Keyword.CLASS||value===Keyword.FUNCTION||value===Keyword.CONST||value===Keyword.LET||value===Keyword.VAR)&&(token=tokenList.step(),stepSize++);const name=this.#isIdentifier(token)?token.value:"",as=isDefault?"default":name;let from;token=tokenList.step(),token?.hasValue(Keyword.FROM)&&(token=tokenList.step(),from=token.value),stepSize>0&&(stepSize++,tokenList.stepBack(stepSize));const alias=new ReflectionAlias(name,as);return new ReflectionExport([alias],from)}#parseMultiExport(tokenList){const members=this.#parseAliasList(tokenList);let from,token=tokenList.current;return token?.hasValue(Keyword.FROM)&&(token=tokenList.step(),from=token.value),tokenList.step(),new ReflectionExport(members,from)}#parseAliasList(tokenList){const aliases=[];let token=tokenList.step();for(;tokenList.notAtEnd();){if(token.hasValue(Scope.CLOSE)){tokenList.step();break}if(token.hasValue(Divider.SEPARATOR)){token=tokenList.step();continue}const alias=this.#parseAlias(tokenList);aliases.push(alias),token=tokenList.step()}return aliases}#parseAlias(tokenList){let token=tokenList.current;const name=token.value;let as=name;return tokenList.next.hasValue(Keyword.AS)&&(token=tokenList.step(2),as=token.value),new ReflectionAlias(name,as)}#parseDeclaration(tokenList,isStatic,parseMultiple=!1){let value,token=tokenList.current,identifier="",isPrivate=!1;return token.hasValue(List.OPEN)?(identifier=this.#parseDestructuredArray(tokenList),token=tokenList.current):token.hasValue(Scope.OPEN)?(identifier=this.#parseDestructuredObject(tokenList),token=tokenList.current):(isPrivate=token.value.startsWith("#"),identifier=isPrivate?token.value.substring(1):token.value,token=tokenList.step()),token.hasValue(Operator.ASSIGN)&&(tokenList.step(),value=this.#parseNext(tokenList,!1),token=tokenList.current),void 0!==token&&(token.hasValue(Divider.TERMINATOR)?tokenList.step():!0===parseMultiple&&token.hasValue(Divider.SEPARATOR)&&(tokenList.step(),this.#parseDeclaration(tokenList,isStatic,!0))),value instanceof ReflectionGenerator?new ReflectionGenerator(identifier.toString(),value.parameters,value.body,isStatic,value.isAsync,isPrivate):value instanceof ReflectionFunction?new ReflectionFunction(identifier.toString(),value.parameters,value.body,isStatic,value.isAsync,isPrivate):value instanceof ReflectionClass?new ReflectionClass(identifier.toString(),value.parentName,value.scope):new ReflectionDeclaration(identifier,value,isStatic,isPrivate)}#parseFunction(tokenList,isAsync,isStatic=!1,isGetter=!1,isSetter=!1){let token=tokenList.current,name="",isGenerator=!1,isPrivate=!1;token.hasValue(Operator.MULTIPLY)&&(isGenerator=!0,token=tokenList.step()),this.#isIdentifier(token)&&(isPrivate=token.value.startsWith("#"),name=isPrivate?token.value.substring(1):token.value,token=tokenList.step());const parameters=this.#parseParameters(tokenList,Group.CLOSE);if(token=tokenList.current,!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const body=this.#parseBlock(tokenList,Scope.OPEN,Scope.CLOSE);return isGenerator?new ReflectionGenerator(name,parameters,body,isStatic,isAsync,isPrivate):isGetter?new ReflectionGetter(name,parameters,body,isStatic,isAsync,isPrivate):isSetter?new ReflectionSetter(name,parameters,body,isStatic,isAsync,isPrivate):new ReflectionFunction(name,parameters,body,isStatic,isAsync,isPrivate)}#parseArrowFunction(tokenList,isAsync){let parameters,token=tokenList.current;if(token.hasValue(Group.OPEN)?(parameters=this.#parseParameters(tokenList,Group.CLOSE),token=tokenList.current):(parameters=[new ReflectionField(token.value,void 0)],token=tokenList.step()),!1===token.hasValue(Operator.ARROW))throw new ExpectedToken(Operator.ARROW,token.start);token=tokenList.step();const body=token.hasValue(Scope.OPEN)?this.#parseBlock(tokenList,Scope.OPEN,Scope.CLOSE):this.#parseExpression(tokenList).definition;return new ReflectionFunction("",parameters,body,!1,isAsync,!1)}#parseParameters(tokenList,closeId){const parameters=[];for(tokenList.step();tokenList.notAtEnd();){const token=tokenList.current;if(token.hasValue(closeId)){tokenList.step();break}if(token.hasValue(Divider.SEPARATOR)){tokenList.step();continue}let parameter;parameter=token.hasValue(Scope.OPEN)?this.#parseDestructuredObject(tokenList):token.hasValue(List.OPEN)?this.#parseDestructuredArray(tokenList):this.#parseField(tokenList),parameters.push(parameter)}return parameters}#parseClass(tokenList){let parent,token=tokenList.current,name="";if(this.#isIdentifier(token)&&(name=token.value,token=tokenList.step()),token.hasValue(Keyword.EXTENDS)&&(token=tokenList.step(),parent=token.value,token=tokenList.step()),!1===token.hasValue(Scope.OPEN))throw new ExpectedToken(Scope.OPEN,token.start);const scope=this.#parseClassScope(tokenList);return new ReflectionClass(name,parent,scope)}#parseClassScope(tokenList){let token=tokenList.step();const members=[];for(;tokenList.notAtEnd();){if(token.hasValue(Scope.CLOSE)){tokenList.step();break}const member=this.#parseClassMember(tokenList);members.push(member),token=tokenList.current}return new ReflectionScope(members)}#parseClassMember(tokenList){let token=tokenList.current,isAsync=!1,isStatic=!1,isGetter=!1,isSetter=!1;for(;tokenList.notAtEnd();){if(token.hasValue(Keyword.STATIC))isStatic=!0;else if(token.hasValue(Keyword.ASYNC))isAsync=!0;else if(token.hasValue(Keyword.GET))isGetter=!0;else{if(!token.hasValue(Keyword.SET)){if(token.hasValue(Operator.MULTIPLY))return this.#parseFunction(tokenList,isAsync,isStatic,!1,!1);break}isSetter=!0}token=tokenList.step()}return tokenList.next.hasValue(Group.OPEN)?this.#parseFunction(tokenList,isAsync,isStatic,isGetter,isSetter):this.#parseDeclaration(tokenList,isStatic)}#parseArray(tokenList){const items=this.#parseBlock(tokenList,List.OPEN,List.CLOSE);return new ReflectionArray(items)}#parseDestructuredArray(tokenList){const fields=this.#parseParameters(tokenList,List.CLOSE);return new ReflectionDestructuredArray(fields)}#parseObject(tokenList){const fields=this.#parseBlock(tokenList,Scope.OPEN,Scope.CLOSE);return new ReflectionObject(fields)}#parseDestructuredObject(tokenList){const fields=this.#parseParameters(tokenList,Scope.CLOSE);return new ReflectionDestructuredObject(fields)}#parseField(tokenList){let token=tokenList.current;const name=token.value;let value;return token=tokenList.step(),token.hasValue(Operator.ASSIGN)&&(tokenList.step(),value=this.#parseNext(tokenList,!1)),new ReflectionField(name,value)}#parseExpression(tokenList){let token=tokenList.current,code="";for(;tokenList.notAtEnd();){if(token.hasValue(List.OPEN)){code+=this.#parseBlock(tokenList,List.OPEN,List.CLOSE)+" ",token=tokenList.current}else if(token.hasValue(Group.OPEN)){code+=this.#parseBlock(tokenList,Group.OPEN,Group.CLOSE)+" ",token=tokenList.current}else if(token.hasValue(Scope.OPEN)){code+=this.#parseBlock(tokenList,Scope.OPEN,Scope.CLOSE)+" ",token=tokenList.current}else code+=token.toString()+" ",token=tokenList.step();if(void 0===token||this.#atEndOfStatement(token))break}return new ReflectionExpression(code.trim())}#parseBlock(tokenList,openId,closeId){let token=tokenList.step(),code=openId+" ";for(;tokenList.notAtEnd();)if(token.hasValue(openId))code+=this.#parseBlock(tokenList,openId,closeId)+" ",token=tokenList.current;else{if(token.hasValue(closeId))return tokenList.step(),code+=closeId,code;code+=token.toString()+" ",token=tokenList.step()}return code}#peekAfterBlock(tokenList,openId,closeId){const start=tokenList.position;this.#parseBlock(tokenList,openId,closeId);const token=tokenList.current,end=tokenList.position;return tokenList.stepBack(end-start),token}#atEndOfStatement(token){return[Divider.TERMINATOR,Divider.SEPARATOR].includes(token.value)||[List.CLOSE,Group.CLOSE,Scope.CLOSE].includes(token.value)||isKeyword(token.value)}#isIdentifier(token){return token.isType(TokenType.IDENTIFIER)||token.isType(TokenType.KEYWORD)&&isNotReserved(token.value)}}class ClassMerger{merge(model,parent){const declarations=this.#mergeDeclarations(model.declarations,parent.declarations),functions=this.#mergeFunctions(model.functions,parent.functions),getters=this.#mergeFunctions(model.getters,parent.getters),setters=this.#mergeFunctions(model.setters,parent.setters),members=[...declarations.values(),...functions.values(),...getters.values(),...setters.values()];return new ReflectionClass(model.name,parent.name,new ReflectionScope(members))}#mergeDeclarations(model,parent){const declarations=new Map;return parent.forEach((declaration=>declarations.set(declaration.name,declaration))),model.forEach((declaration=>declarations.set(declaration.name,declaration))),[...declarations.values()]}#mergeFunctions(model,parent){const functions=new Map;return parent.forEach((funktion=>functions.set(funktion.name,funktion))),model.forEach((funktion=>functions.set(funktion.name,funktion))),[...functions.values()]}}class Reflector{#parser;#merger;constructor(parser=new Parser,merger=new ClassMerger){this.#parser=parser,this.#merger=merger}parse(code){return this.#parser.parse(code)}parseClass(code){return this.#parser.parseClass(code)}parseFunction(code){return this.#parser.parseFunction(code)}parseDeclaration(code){return this.#parser.parseDeclaration(code)}parseImport(code){return this.#parser.parseImport(code)}parseExport(code){return this.#parser.parseExport(code)}fromModule(module,inherit=!1){const entries=Object.entries(module),members=[];for(const[key,member]of entries){if("function"!=typeof member.toString)continue;const code=member.toString();if(code.startsWith("class"))members.push(this.fromClass(member,inherit));else if(code.startsWith("function"))members.push(this.fromFunction(member));else{const expression=new ReflectionExpression(code);members.push(new ReflectionDeclaration(key,expression))}}return new ReflectionModule(new ReflectionScope(members))}fromClass(clazz,inherit=!1){const model=this.isClass(clazz)?this.#reflectStatic(clazz):this.#reflectDynamic(clazz);if(!1===inherit)return model;const parentClazz=this.getParentClass(clazz);if(""===parentClazz.name)return model;const parentModel=this.fromClass(parentClazz,!0);return this.#merger.merge(model,parentModel)}fromObject(object,inherit=!0){const clazz=this.getClass(object);return this.fromClass(clazz,inherit)}fromFunction(funktion){const code=funktion.toString();return this.parseFunction(code)}createInstance(clazz,args=[]){return new clazz(...args)}getClass(object){return object.constructor}getParentClass(clazz){return Object.getPrototypeOf(clazz)}isClassObject(object){return this.isClass(object.constructor)}isFunctionObject(object){return this.isFunction(object.constructor)}isClass(clazz){return clazz.toString().startsWith("class")}isFunction(clazz){return clazz.toString().startsWith("function")||clazz.toString().startsWith("async function")}#reflectStatic(clazz){const code=clazz.toString();return this.parseClass(code)}#reflectDynamic(clazz){const object=this.createInstance(clazz),members=this.#getMembers(clazz,object),scope=new ReflectionScope(members);return new ReflectionClass(clazz.name,void 0,scope)}#getMembers(clazz,object){return[...this.#getDeclarations(object),...this.#getFunctions(clazz)]}#getDeclarations(object){const fieldNames=Object.getOwnPropertyNames(object),values=object,models=[];for(const fieldName of fieldNames){const content=values[fieldName],value=void 0!==content?new ReflectionValue(String(content)):void 0,model=new ReflectionDeclaration(fieldName,value);models.push(model)}return models}#getFunctions(clazz){const functionDescriptions=Object.getOwnPropertyDescriptors(clazz.prototype),models=[];for(const functionName in functionDescriptions){const description=functionDescriptions[functionName],funktion=description.value;if(funktion instanceof Function==!1)continue;const model=this.fromFunction(funktion);void 0!==description.get?models.push(new ReflectionGetter(model.name,model.parameters,model.body,model.isStatic,model.isAsync,model.isPrivate)):void 0!==description.set?models.push(new ReflectionSetter(model.name,model.parameters,model.body,model.isStatic,model.isAsync,model.isPrivate)):models.push(model)}return models}}const reflector$1=new Reflector;class ClassSerializer extends ValueSerializer{#classLoader;constructor(classLoader){super(),this.#classLoader=classLoader}canSerialize(value){return value instanceof Object&&reflector$1.isClassObject(value)}canDeserialize(value){const object=value;return object instanceof Object&&!0===object.serialized&&"string"==typeof object.name&&object.args instanceof Object&&object.args.constructor===Object&&object.fields instanceof Object&&object.fields.constructor===Object}async serialize(object){const clazz=reflector$1.getClass(object),model=reflector$1.fromClass(clazz,!0),parameterNames=this.#extractConstructorParameters(model);return{serialized:!0,name:clazz.name,source:clazz.source,args:await this.#serializeConstructor(model,parameterNames,object),fields:await this.#serializeFields(model,parameterNames,object)}}#extractConstructorParameters(model){const constructor=model.getFunction("constructor");return(constructor?.parameters??[]).map((parameter=>parameter.name))}async#serializeConstructor(model,includeNames,object){const args={};for(const name of includeNames){const objectValue=model.canRead(name)?await this.serializeOther(object[name]):void 0;args[name]=objectValue}return args}async#serializeFields(model,excludeNames,object){const fields={};for(const property of model.writable){const name=property.name;excludeNames.includes(name)||!1===model.canRead(name)||(fields[name]=await this.serializeOther(object[name]))}return fields}async deserialize(object){const clazz=await this.#getClass(object);if(void 0===clazz)throw new ClassNotFound(object.name);if(clazz instanceof Function==!1)throw new InvalidClass(object.name);const args=await this.#deserializeConstructor(clazz,object.args),instance=reflector$1.createInstance(clazz,args);for(const name in object.fields){const fieldValue=object.fields[name];instance[name]=await this.deserializeOther(fieldValue)}return instance}async#deserializeConstructor(clazz,args){const constructor=reflector$1.fromClass(clazz,!0).getFunction("constructor"),values=(constructor?.parameters??[]).map((parameter=>{const value=args[parameter.name];return this.deserializeOther(value)}));return Promise.all(values)}async#getClass(loadable){return void 0===loadable.source?globalThis[loadable.name]:this.#classLoader.loadClass(loadable)}}class InvalidDateString extends Error{constructor(dateString){super(`Invalid date string '${dateString}'`)}}class DateSerializer extends ValueSerializer{canSerialize(value){return value instanceof Date}canDeserialize(value){const date=value;return date instanceof Object&&!0===date.serialized&&"Date"===date.name&&"string"==typeof date.value}async serialize(date){return{serialized:!0,name:"Date",value:date.toISOString()}}async deserialize(object){const date=new Date(object.value);if("Invalid Date"===date.toString())throw new InvalidDateString(object.value);return date}}class ErrorSerializer extends ValueSerializer{canSerialize(value){if(value instanceof Object==!1)return!1;const error=value;return error.constructor===Error||error.constructor===EvalError||error.constructor===RangeError||error.constructor===ReferenceError||error.constructor===SyntaxError||error.constructor===TypeError||error.constructor===URIError||error.constructor===AggregateError}canDeserialize(value){const error=value;return error instanceof Object&&!0===error.serialized&&"Error"===error.name&&error.type in globalThis}async serialize(error){return{serialized:!0,name:"Error",type:error.constructor.name,stack:error.stack,message:error.message,cause:error.cause}}async deserialize(object){const error=new(0,globalThis[object.type]);return error.stack=object.stack,error.message=object.message,error.cause=object.cause,error}}class MapSerializer extends ValueSerializer{canSerialize(value){return value instanceof Map}canDeserialize(value){const map=value;return map instanceof Object&&!0===map.serialized&&"Map"===map.name&&map.entries instanceof Object&&map.entries.keys instanceof Array&&map.entries.values instanceof Array}async serialize(map){const keys=[],values=[];for(const[key,value]of map)keys.push(await this.serializeOther(key)),values.push(await this.serializeOther(value));return{serialized:!0,name:"Map",entries:{keys:keys,values:values}}}async deserialize(object){const keys=object.entries.keys,values=object.entries.values,result=new Map;for(let index=0;index<keys.length;index++){const key=await this.deserializeOther(keys[index]),value=await this.deserializeOther(values[index]);result.set(key,value)}return result}}class ObjectSerializer extends ValueSerializer{canSerialize(value){return value instanceof Object&&value.constructor===Object}canDeserialize(value){return value instanceof Object&&value.constructor===Object}async serialize(object){const result={};for(const key in object){const value=object[key];result[key]=await this.serializeOther(value)}return result}async deserialize(object){const result={};for(const key in object){const value=object[key];result[key]=await this.deserializeOther(value)}return result}}class PrimitiveSerializer extends ValueSerializer{canSerialize(value){return value instanceof Object==!1}canDeserialize(value){return value instanceof Object==!1}async serialize(primitive){return primitive}async deserialize(primitive){return primitive}}class InvalidRegExp extends Error{constructor(source,flags){super(`Invalid regular expression '${source}' with flags '${flags}'`)}}class RegExpSerializer extends ValueSerializer{canSerialize(value){return value instanceof RegExp}canDeserialize(value){const regExp=value;return regExp instanceof Object&&!0===regExp.serialized&&"RegExp"===regExp.name&&"string"==typeof regExp.source&&"string"==typeof regExp.flags}async serialize(regExp){return{serialized:!0,name:"RegExp",source:regExp.source,flags:regExp.flags}}async deserialize(object){try{return new RegExp(object.source,object.flags)}catch(error){throw new InvalidRegExp(object.source,object.flags)}}}class SetSerializer extends ValueSerializer{canSerialize(value){return value instanceof Set}canDeserialize(value){const set=value;return set instanceof Object&&!0===set.serialized&&"Set"===set.name&&set.values instanceof Array}async serialize(set){const values=[];for(const value of set.values())values.push(await this.serializeOther(value));return{serialized:!0,name:"Set",values:values}}async deserialize(object){const values=await Promise.all(object.values.map((async value=>this.deserializeOther(value))));return new Set([...values])}}const reflector=new Reflector;class ArrayBufferSerializer extends ValueSerializer{canSerialize(value){return value instanceof Int8Array||value instanceof Uint8Array||value instanceof Uint8ClampedArray||value instanceof Int16Array||value instanceof Uint16Array||value instanceof Int32Array||value instanceof Uint32Array||value instanceof Float32Array||value instanceof Float64Array||value instanceof BigInt64Array||value instanceof BigUint64Array}canDeserialize(value){const array=value;return array instanceof Object&&!0===array.serialized&&"TypedArray"===array.name&&array.type in globalThis&&array.bytes instanceof Array}async serialize(array){const type=array.constructor.name,view=new DataView(array.buffer),bytes=[];for(let index=0;index<view.byteLength;index++)bytes.push(view.getUint8(index));return{serialized:!0,name:"TypedArray",type:type,bytes:bytes}}async deserialize(object){const type=object.type,bytes=object.bytes,buffer=new ArrayBuffer(bytes.length),view=new DataView(buffer);for(let index=0;index<bytes.length;index++)view.setUint8(index,bytes[index]);const clazz=globalThis[type];return reflector.createInstance(clazz,[buffer])}}class InvalidUrlString extends Error{constructor(urlString){super(`Invalid url string '${urlString}'`)}}class UrlSerializer extends ValueSerializer{canSerialize(value){return value instanceof URL}canDeserialize(value){const url=value;return url instanceof Object&&!0===url.serialized&&"Url"===url.name&&"string"==typeof url.value}async serialize(url){return{serialized:!0,name:"Url",value:url.toString()}}async deserialize(object){try{return new URL(object.value)}catch(error){throw new InvalidUrlString(object.value)}}}const defaultClassLoader=new class{async loadClass(loadable){if("string"!=typeof loadable.source)throw new ClassNotFound(loadable.name);const module=await import(loadable.source),clazz=module[loadable.name]??module.default;if(void 0===clazz)throw new ClassNotFound(loadable.name);if(clazz instanceof Function==!1)throw new InvalidClass(loadable.name);return clazz}};class SerializerBuilder{static build(loader=defaultClassLoader){const serializer=new Serializer;return serializer.addSerializer(new PrimitiveSerializer),serializer.addSerializer(new ObjectSerializer),serializer.addSerializer(new ClassSerializer(loader)),serializer.addSerializer(new ErrorSerializer),serializer.addSerializer(new RegExpSerializer),serializer.addSerializer(new BigIntSerializer),serializer.addSerializer(new UrlSerializer),serializer.addSerializer(new DateSerializer),serializer.addSerializer(new SetSerializer),serializer.addSerializer(new MapSerializer),serializer.addSerializer(new ArraySerializer),serializer.addSerializer(new ArrayBufferSerializer),serializer}}class RemoteClassLoader{async loadClass(loadable){if("string"!=typeof loadable.source)throw new ClassNotFound(loadable.name);const module=await ModuleLoader.load(loadable.source),clazz=module[loadable.name]??module.default;if(void 0===clazz)throw new ClassNotFound(loadable.name);if(clazz instanceof Function==!1)throw new InvalidClass(loadable.name);return clazz}}const remoteClassLoader=new RemoteClassLoader,defaultSerializer=SerializerBuilder.build(remoteClassLoader);class Remote{#url;#serializer;constructor(url,serializer=defaultSerializer){this.#url=url,this.#serializer=serializer}async registerClient(segmentFiles){const url=`${this.#url}/modules`,options={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(segmentFiles)};return(await this.#callRemote(url,options)).text()}async loadFile(filename){const url=`${this.#url}/${filename}`,response=await this.#callRemote(url,{method:"GET"}),type=response.headers.get("Content-Type")||"application/octet-stream",content=await response.text();return new File(filename,type,content)}async isHealthy(){const url=`${this.#url}/health/status`,response=await this.#callRemote(url,{method:"GET"}),healthy=await response.text();return Boolean(healthy)}async getHealth(){const url=`${this.#url}/health`,response=await this.#callRemote(url,{method:"GET"}),health=await response.json();return new Map(Object.entries(health))}async addWorker(worker){const url=`${this.#url}/workers`,body={url:worker.url,procedureNames:worker.getProcedureNames(),trustKey:worker.trustKey},options={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)};await this.#callRemote(url,options)}async run(request){request.setHeader("content-type","application/json");const versionString=request.version.toString(),argsObject=Object.fromEntries(request.args),headersObject=Object.fromEntries(request.headers),url=`${this.#url}/rpc/${request.fqn}?version=${versionString}&serialize=true`,options={method:"POST",headers:headersObject,body:await this.#createRequestBody(argsObject)},response=await this.#callRemote(url,options),result=await this.#createResponseResult(response),headers=this.#createResponseHeaders(response);return new Response(result,headers)}async#callRemote(url,options){const response=await fetch(url,options);if(this.#isErrorResponse(response))throw await this.#createResponseResult(response);return response}#isErrorResponse(response){return response.status<200||response.status>299}async#createRequestBody(body){const data=await this.#serializer.serialize(body);return JSON.stringify(data)}async#createResponseResult(response){const result=await this.#getResponseResult(response);return this.#serializer.deserialize(result)}async#getResponseResult(response){const contentType=response.headers.get("X-Jitar-Content-Type");if(null!==contentType&&contentType.includes("null"))return null;if(null!==contentType&&contentType.includes("undefined"))return;if(null!==contentType&&contentType.includes("json"))return response.json();const content=await response.text();return null!==contentType&&contentType.includes("boolean")?"true"===content:null!==contentType&&contentType.includes("number")?Number(content):content}#createResponseHeaders(response){const headers=new Map;for(const[name,value]of response.headers)headers.set(name,value);return headers}}class DummyRepository extends Repository{async start(){}async stop(){}async registerClient(segmentFiles){throw new RepositoryNotAvailable}async readAsset(filename){throw new RepositoryNotAvailable}async readModule(filename,clientId){throw new RepositoryNotAvailable}async loadModule(filename){throw new RepositoryNotAvailable}}class RemoteGateway extends Gateway{#remote;#worker;constructor(url){super(new DummyRepository,url),this.#remote=new Remote(url)}get worker(){return this.#worker}set worker(worker){this.#worker=worker}async start(){await super.start(),void 0!==this.#worker&&await this.addWorker(this.#worker)}getProcedureNames(){throw new NotImplemented}hasProcedure(name){throw new NotImplemented}addWorker(worker){return this.#remote.addWorker(worker)}run(request){return this.#remote.run(request)}}class RemoteRepository extends Repository{#remote;#segmentNames=new Set;constructor(url){super(url),this.#remote=new Remote(url)}get segmentNames(){return[...this.#segmentNames.values()]}set segmentNames(segmentNames){this.#segmentNames=segmentNames}async start(){const clientId=await this.registerClient(this.segmentNames),baseUrl=this.#getModuleBaseUrl(clientId);ModuleLoader.setBaseUrl(baseUrl),await super.start()}registerClient(segmentFiles){return this.#remote.registerClient(segmentFiles)}readAsset(filename){return this.#remote.loadFile(filename)}readModule(filename,clientId){return this.#remote.loadFile(`modules/${clientId}/${filename}`)}loadModule(filename){return ModuleLoader.load(filename)}#getModuleBaseUrl(clientId){return`${this.url}/modules/${clientId}`}}class RuntimeNotBuilt extends ServerError{constructor(reason){super(`Building the runtime failed: ${reason}`)}}RuntimeNotBuilt.source="/jitar/client.js";const globals=globalThis;globals.__import=async function(name,scope,extractDefault=!0){const runtime=getRuntime();RUNS_IN_BROWSER&&"jitar"===name&&(name="/jitar/client.js");const module=await runtime.import(name,scope);return extractDefault&&void 0!==module.default?module.default:module},globals.__run=async function(fqn,versionNumber,args,sourceRequest){const runtime=getRuntime(),version=VersionParser.parse(versionNumber),argsMap=new Map(Object.entries(args)),headersMap=sourceRequest instanceof Request?sourceRequest.headers:new Map,targetRequest=new Request(fqn,version,argsMap,headersMap);return(await runtime.handle(targetRequest)).result},globals.ProcedureNotAccessible=ProcedureNotAccessible;export{InvalidVersionNumber as $,AccessLevels as A,BadRequest as B,ClientNotFound as C,DummyRepository as D,RemoteClassLoader as E,FileNotFound as F,Gateway as G,ExecutionScopes as H,InvalidTrustKey as I,Version as J,Response as K,LocalWorker as L,ModuleLoader as M,NoWorkerAvailable as N,NamedParameter as O,ProcedureNotFound as P,ArrayParameter as Q,Repository as R,SerializerBuilder as S,Teapot as T,Unauthorized as U,VersionParser as V,Worker as W,ObjectParameter as X,ServerError as Y,ImplementationNotFound as Z,InvalidParameterValue as _,InvalidSegmentFile as a,MissingParameterValue as a0,ModuleNotAccessible as a1,ModuleNotLoaded as a2,ProcedureNotAccessible as a3,RepositoryNotAvailable as a4,RuntimeNotAvailable as a5,SegmentNotFound as a6,UnknownParameter as a7,InvalidClientId as b,File as c,convertToRemoteFilename as d,convertToLocalFilename as e,createRepositoryFilename as f,ProcedureRuntime as g,Remote as h,isSegmentFilename as i,RemoteRepository as j,RemoteGateway as k,RuntimeNotBuilt as l,Reflector as m,ReflectionField as n,ReflectionDestructuredArray as o,ReflectionDestructuredObject as p,ReflectionDestructuredValue as q,createWorkerFilename as r,setRuntime as s,ReflectionFunction as t,Files as u,PaymentRequired as v,Forbidden as w,NotFound as x,NotImplemented as y,Request as z};
package/dist/lib.d.ts DELETED
@@ -1,397 +0,0 @@
1
- declare const AccessLevels: {
2
- readonly PRIVATE: "private";
3
- readonly PROTECTED: "protected";
4
- readonly PUBLIC: "public";
5
- };
6
- type Keys$1 = keyof typeof AccessLevels;
7
- type AccessLevel = typeof AccessLevels[Keys$1];
8
-
9
- declare const ExecutionScopes: {
10
- readonly APPLICATION: "application";
11
- readonly RUNTIME: "runtime";
12
- };
13
- type Keys = keyof typeof ExecutionScopes;
14
- type ExecutionScope = typeof ExecutionScopes[Keys];
15
-
16
- declare class BadRequest extends Error {
17
- constructor(message?: string);
18
- }
19
-
20
- declare class Forbidden extends Error {
21
- constructor(message?: string);
22
- }
23
-
24
- declare class NotFound extends Error {
25
- constructor(message?: string);
26
- }
27
-
28
- declare class NotImplemented extends Error {
29
- constructor(message?: string);
30
- }
31
-
32
- declare class PaymentRequired extends Error {
33
- constructor(message?: string);
34
- }
35
-
36
- declare class ServerError extends Error {
37
- constructor(message?: string);
38
- }
39
-
40
- declare class Teapot extends Error {
41
- constructor();
42
- }
43
-
44
- declare class Unauthorized extends Error {
45
- constructor(message?: string);
46
- }
47
-
48
- declare class ClientNotFound extends BadRequest {
49
- #private;
50
- constructor(clientId: string);
51
- get clientId(): string;
52
- }
53
-
54
- declare class FileNotFound extends NotFound {
55
- #private;
56
- constructor(filename: string);
57
- get filename(): string;
58
- }
59
-
60
- declare class ImplementationNotFound extends NotFound {
61
- #private;
62
- constructor(fqn: string, version: string);
63
- get fqn(): string;
64
- get version(): string;
65
- }
66
-
67
- declare class InvalidClientId extends BadRequest {
68
- #private;
69
- constructor(clientId: string);
70
- get clientId(): string;
71
- }
72
-
73
- declare class InvalidParameterValue extends BadRequest {
74
- #private;
75
- constructor(parameterName: string);
76
- get parameterName(): string;
77
- }
78
-
79
- declare class InvalidSegmentFile extends ServerError {
80
- #private;
81
- constructor(filename: string);
82
- get filename(): string;
83
- }
84
-
85
- declare class InvalidVersionNumber extends BadRequest {
86
- #private;
87
- constructor(number: string);
88
- get number(): string;
89
- }
90
-
91
- declare class MissingParameterValue extends BadRequest {
92
- #private;
93
- constructor(parameterName: string);
94
- get parameterName(): string;
95
- }
96
-
97
- declare class ModuleNotAccessible extends Forbidden {
98
- #private;
99
- constructor(url: string);
100
- get url(): string;
101
- }
102
-
103
- declare class ModuleNotLoaded extends ServerError {
104
- #private;
105
- constructor(url: string, reason?: string);
106
- get url(): string;
107
- get reason(): string | undefined;
108
- }
109
-
110
- declare class NoWorkerAvailable extends ServerError {
111
- #private;
112
- constructor(name: string);
113
- get name(): string;
114
- }
115
-
116
- declare class ProcedureNotAccessible extends Forbidden {
117
- #private;
118
- constructor(fqn: string, versionNumber: string);
119
- get fqn(): string;
120
- get versionNumber(): string;
121
- }
122
-
123
- declare class ProcedureNotFound extends NotFound {
124
- #private;
125
- constructor(fqn: string);
126
- get fqn(): string;
127
- }
128
-
129
- declare class RepositoryNotAvailable extends ServerError {
130
- constructor();
131
- }
132
-
133
- declare class RuntimeNotAvailable extends ServerError {
134
- constructor();
135
- }
136
-
137
- declare class SegmentNotFound extends ServerError {
138
- #private;
139
- constructor(source: string);
140
- get source(): string;
141
- }
142
-
143
- declare class UnknownParameter extends BadRequest {
144
- #private;
145
- constructor(parameterName: string);
146
- get parameterName(): string;
147
- }
148
-
149
- declare class File {
150
- #private;
151
- constructor(location: string, type: string, content: Buffer | string);
152
- get location(): string;
153
- get type(): string;
154
- get content(): string | Buffer;
155
- get size(): number;
156
- }
157
-
158
- interface HealthCheck {
159
- get name(): string;
160
- get timeout(): number | undefined;
161
- isHealthy(): Promise<boolean>;
162
- }
163
-
164
- declare class Version {
165
- #private;
166
- static get DEFAULT(): Version;
167
- constructor(major?: number, minor?: number, patch?: number);
168
- get major(): number;
169
- get minor(): number;
170
- get patch(): number;
171
- equals(version: Version): boolean;
172
- greater(version: Version): boolean;
173
- less(version: Version): boolean;
174
- toString(): string;
175
- }
176
-
177
- declare class Request {
178
- #private;
179
- constructor(fqn: string, version: Version, args: Map<string, unknown>, headers: Map<string, string>);
180
- get fqn(): string;
181
- get version(): Version;
182
- get args(): Map<string, unknown>;
183
- get headers(): Map<string, string>;
184
- clearArguments(): void;
185
- setArgument(name: string, value: unknown): void;
186
- getArgument(name: string): unknown;
187
- hasArgument(name: string): boolean;
188
- removeArgument(name: string): void;
189
- clearHeaders(): void;
190
- setHeader(name: string, value: string): void;
191
- getHeader(name: string): string | undefined;
192
- hasHeader(name: string): boolean;
193
- removeHeader(name: string): void;
194
- }
195
-
196
- declare class Response {
197
- #private;
198
- constructor(result?: unknown, headers?: Map<any, any>);
199
- get result(): unknown;
200
- set result(value: unknown);
201
- get headers(): Map<string, string>;
202
- clearHeaders(): void;
203
- setHeader(name: string, value: string): void;
204
- getHeader(name: string): string | undefined;
205
- hasHeader(name: string): boolean;
206
- removeHeader(name: string): void;
207
- }
208
-
209
- type NextHandler = () => Promise<Response>;
210
-
211
- interface Middleware {
212
- handle(request: Request, next: NextHandler): Promise<Response>;
213
- }
214
-
215
- declare class Parameter {
216
- #private;
217
- constructor(name: string, isOptional?: boolean);
218
- get name(): string;
219
- get isOptional(): boolean;
220
- }
221
-
222
- declare class DestructuredParameter extends Parameter {
223
- #private;
224
- constructor(variables: Parameter[], name?: string, isOptional?: boolean);
225
- get variables(): Parameter[];
226
- }
227
-
228
- declare class ArrayParameter extends DestructuredParameter {
229
- }
230
-
231
- declare class Implementation {
232
- #private;
233
- constructor(version: Version, access: AccessLevel, parameters: Parameter[], executable: Function);
234
- get version(): Version;
235
- get public(): boolean;
236
- get protected(): boolean;
237
- get parameters(): Parameter[];
238
- get executable(): Function;
239
- }
240
-
241
- declare class NamedParameter extends Parameter {
242
- }
243
-
244
- declare class ObjectParameter extends DestructuredParameter {
245
- }
246
-
247
- declare class Procedure {
248
- #private;
249
- constructor(fqn: string);
250
- get fqn(): string;
251
- get public(): boolean;
252
- get protected(): boolean;
253
- addImplementation(implementation: Implementation): Procedure;
254
- getImplementation(version: Version): Implementation | undefined;
255
- }
256
-
257
- declare class Segment {
258
- #private;
259
- constructor(id: string);
260
- get id(): string;
261
- addProcedure(procedure: Procedure): Segment;
262
- hasProcedure(fqn: string): boolean;
263
- getProcedure(fqn: string): Procedure | undefined;
264
- getExposedProcedures(): Procedure[];
265
- }
266
-
267
- interface Runner {
268
- run(request: Request): Promise<Response>;
269
- }
270
-
271
- type Module = Record<string, unknown>;
272
-
273
- declare abstract class Runtime {
274
- #private;
275
- constructor(url?: string);
276
- get url(): string | undefined;
277
- set healthCheckFiles(filenames: Set<string>);
278
- abstract import(url: string, scope: ExecutionScope): Promise<Module>;
279
- start(): Promise<void>;
280
- stop(): Promise<void>;
281
- addHealthCheck(healthCheck: HealthCheck): void;
282
- isHealthy(): Promise<boolean>;
283
- getHealth(): Promise<Map<string, boolean>>;
284
- }
285
-
286
- declare abstract class Repository extends Runtime {
287
- import(url: string, scope: ExecutionScope): Promise<Module>;
288
- abstract registerClient(segmentFiles: string[]): Promise<string>;
289
- abstract readAsset(filename: string): Promise<File>;
290
- abstract readModule(name: string, clientId: string): Promise<File>;
291
- abstract loadModule(name: string): Promise<Module>;
292
- }
293
-
294
- declare abstract class ProcedureRuntime extends Runtime implements Runner {
295
- #private;
296
- constructor(repository: Repository, url?: string);
297
- get repository(): Repository;
298
- set middlewareFiles(filenames: Set<string>);
299
- start(): Promise<void>;
300
- stop(): Promise<void>;
301
- abstract getProcedureNames(): string[];
302
- abstract hasProcedure(name: string): boolean;
303
- abstract run(request: Request): Promise<Response>;
304
- import(url: string, scope: ExecutionScope): Promise<Module>;
305
- addMiddleware(middleware: Middleware): void;
306
- getMiddleware(type: Function): Middleware | undefined;
307
- handle(request: Request): Promise<Response>;
308
- }
309
-
310
- declare abstract class Worker extends ProcedureRuntime {
311
- abstract get trustKey(): string | undefined;
312
- }
313
-
314
- declare abstract class Gateway extends ProcedureRuntime {
315
- abstract addWorker(worker: Worker): Promise<void>;
316
- }
317
-
318
- declare class ArgumentExtractor {
319
- #private;
320
- extract(parameters: Parameter[], args: Map<string, unknown>): unknown[];
321
- }
322
-
323
- declare class LocalWorker extends Worker {
324
- #private;
325
- constructor(repository: Repository, gateway?: Gateway, url?: string, trustKey?: string, argumentConstructor?: ArgumentExtractor);
326
- get trustKey(): string | undefined;
327
- set segmentNames(names: Set<string>);
328
- start(): Promise<void>;
329
- stop(): Promise<void>;
330
- getProcedureNames(): string[];
331
- addSegment(segment: Segment): void;
332
- hasProcedure(fqn: string): boolean;
333
- run(request: Request): Promise<Response>;
334
- }
335
-
336
- type Loadable = {
337
- name: string;
338
- source?: string;
339
- };
340
-
341
- interface ClassLoader {
342
- loadClass(loadable: Loadable): Promise<Function>;
343
- }
344
-
345
- declare abstract class ValueSerializer {
346
- #private;
347
- set parent(parent: Serializer);
348
- abstract canSerialize(value: unknown): boolean;
349
- abstract canDeserialize(value: unknown): boolean;
350
- abstract serialize(value: unknown): Promise<unknown>;
351
- abstract deserialize(value: unknown): Promise<unknown>;
352
- serializeOther(value: unknown): Promise<unknown>;
353
- deserializeOther(value: unknown): Promise<unknown>;
354
- }
355
-
356
- declare class Serializer {
357
- #private;
358
- addSerializer(serializer: ValueSerializer): void;
359
- serialize(value: unknown): Promise<unknown>;
360
- deserialize(value: unknown): Promise<unknown>;
361
- }
362
-
363
- type ModuleImporter = (name: string) => Promise<Module>;
364
-
365
- declare function startClient(remoteUrl: string, segmentNames?: string[], middlewares?: string[]): Promise<LocalWorker>;
366
- declare function getClient(): Promise<LocalWorker>;
367
-
368
- declare function importModule(name: string, scope: ExecutionScope, extractDefault?: boolean): Promise<unknown>;
369
- declare function runProcedure(fqn: string, versionNumber: string, args: object, sourceRequest?: Request): Promise<unknown>;
370
-
371
- declare global {
372
- const __import: typeof importModule;
373
- const __run: typeof runProcedure;
374
- }
375
-
376
- declare class CorsMiddleware implements Middleware {
377
- #private;
378
- constructor(origin?: string, headers?: string);
379
- get allowOrigin(): string;
380
- get allowMethods(): string;
381
- get allowHeaders(): string;
382
- handle(request: Request, next: NextHandler): Promise<Response>;
383
- }
384
-
385
- declare class JitarServer {
386
- #private;
387
- constructor();
388
- get classLoader(): ClassLoader;
389
- build(): Promise<void>;
390
- start(): Promise<void>;
391
- stop(): Promise<void>;
392
- addSerializer(serializer: ValueSerializer): void;
393
- }
394
-
395
- declare function buildServer(moduleImporter: ModuleImporter): Promise<JitarServer>;
396
-
397
- export { ArrayParameter, BadRequest, ClientNotFound, CorsMiddleware, FileNotFound, Forbidden, type HealthCheck, Implementation, ImplementationNotFound, InvalidClientId, InvalidParameterValue, InvalidSegmentFile, InvalidVersionNumber, type Middleware, MissingParameterValue, ModuleNotAccessible, ModuleNotLoaded, NamedParameter, type NextHandler, NoWorkerAvailable, NotFound, NotImplemented, ObjectParameter, PaymentRequired, Procedure, ProcedureNotAccessible, ProcedureNotFound, RepositoryNotAvailable, Request, Response, RuntimeNotAvailable, Segment, SegmentNotFound, ServerError, Teapot, Unauthorized, UnknownParameter, Version, buildServer, getClient, startClient };