@interopio/gateway-server 0.22.0 → 0.23.1
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/changelog.md +16 -0
- package/dist/gateway-ent.cjs +1 -1
- package/dist/gateway-ent.cjs.map +3 -3
- package/dist/gateway-ent.js +2 -2
- package/dist/gateway-ent.js.map +3 -3
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +4 -4
- package/dist/index.js +7 -7
- package/dist/index.js.map +4 -4
- package/package.json +8 -5
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
You are probably missing an await or return statement in your middleware function.`);return
|
|
1
|
+
var Ls=Object.defineProperty;var Fs=(r,e)=>{for(var t in e)Ls(r,t,{get:e[t],enumerable:!0})};var Os={};Fs(Os,{Factory:()=>ln,VERSION:()=>Ws});import Is from"node:http";import Zo from"node:https";import{AsyncLocalStorage as ea}from"node:async_hooks";import{networkInterfaces as Ds}from"node:os";var $s=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function hr(r){if(r>65535)throw new Error(`bad port ${r}`);return r}function*hn(r){if(typeof r=="string")for(let e of r.split(",")){let t=e.trim(),n=$s.exec(t);if(n){let s=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let o=hr(s);o<hr(i)+1;o++)yield o}else throw new Error(`'${e}' is not a valid port or range.`)}else yield hr(r)}var pn=(()=>{function r(t){return t.length>0?t[0]:void 0}let e=Object.values(Ds()).flatMap(t=>(t??[]).filter(n=>n.family==="IPv4")).reduce((t,n)=>(t[n.internal?"internal":"external"].push(n),t),{internal:[],external:[]});return(r(e.internal)??r(e.external))?.address})();function ee(r){if(r)return r.family==="IPv6"?`[${r.address}]:${r.port}`:`${r.address}:${r.port}`}import*as fn from"@interopio/gateway/logging/core";function S(r){return fn.getLogger(`gateway.server.${r}`)}function gn(r,e){return e instanceof RegExp?e.toString():e}import{IOGateway as Ns}from"@interopio/gateway";import{AsyncLocalStorage as Us}from"node:async_hooks";var V=S("ws"),qs=Ns.Encoding.json();function _s(r){let e;if(r.authenticated&&(e=r.name,e===void 0&&r.principal!==void 0)){let t=r.principal;typeof t=="object"&&t!==null&&("username"in t||"name"in t)&&(e=t.username??t.name),e===void 0&&(t==null?e="":e=String(t))}return e}function Bs(r,e,t,n){let s=ee(n),i=n?.address??"<unknown>",o={key:s,host:i,codec:qs,onAuthenticate:async()=>{let a=await t();if(a?.authenticated)return{type:"success",user:_s(a)};throw new Error(`no valid client authentication ${s}`)},onPing:()=>{e.ping(a=>{a?V.warn(`failed to ping ${s}`,a):V.info(`ping sent to ${s}`)})},onDisconnect:a=>{switch(a){case"inactive":{V.warn(`no heartbeat (ping) received from ${s}, closing socket`),e.close(4001,"ping expected");break}case"shutdown":{e.close(1001,"shutdown");break}}}};try{return r.client(a=>e.send(a),o)}catch(a){V.warn(`${s} failed to create client`,a)}}async function Gs(r){return V.info(`starting gateway on ${r.endpoint}`),await this.start(r),async({socket:e,handshake:t})=>{let{logPrefix:n,remoteAddress:s,principal:i}=t,o=(await i())?.name;V.info(`${n}connected on gw as ${o??"<anonymous>"}`);let a=await this.getGateway(o),c=Bs(a,e,i,s);if(!c){V.error(`${n}gw client init failed`),e.terminate();return}e.on("error",u=>{V.error(`${n}websocket error: ${u}`,u)});let d=r.storage!==void 0?Us.snapshot():void 0;e.on("message",(u,h)=>{Array.isArray(u)&&(u=Buffer.concat(u)),d!==void 0?d(()=>c.send(u)):c.send(u)}),e.on("close",u=>{V.info(`${n}disconnected from gw. code: ${u}`),c.close()})}}var mn=Gs;import{IOGateway as wn}from"@interopio/gateway";import{IOGateway as Oe}from"@interopio/gateway";function pr(r){if(r!==void 0)return r.map(e=>{let t={...e};for(let[n,s]of Object.entries(e))n!=="identity"&&n!=="restrictions"&&s!==void 0&&(t[n]=Oe.Filtering.regexify(s));if(e.identity!==void 0){t.identity={};for(let[n,s]of Object.entries(e.identity))t.identity[n]=Oe.Filtering.regexify(s)}return t})}function yn(r){if(!r)return;let e={...r};return r.publishers&&(e.publishers=r.publishers.map(t=>{let{metrics:n,identity:s,...i}=t,o={...i};if(o.identity={},s)for(let[a,c]of Object.entries(s))o.identity[a]=Oe.Filtering.regexify(c);if(o.metrics={},n){let a=(n.allow??n.whitelist??[]).map(d=>Oe.Filtering.regexify(d)),c=(n.block??n.blacklist??[]).map(d=>Oe.Filtering.regexify(d));a.length>0&&(o.metrics.allow=a),c.length>0&&(o.metrics.block=c)}return o})),e}function fr(r){if(!r)return;let e={...r};return r.filters&&(e.filters=yn(r.filters)),e}function Vs(r){if(r?.enabled!==!1)return r}function zs(r){if(r===void 0||r?.enabled===!1)return;let e={...r};return r.filters&&(e.filters=yn(r.filters)),r.file&&(e.file=fr(r.file)),r.rest&&(e.rest=fr(r.rest)),r.publishers&&(e.publishers=r.publishers.map(t=>{if(typeof t=="string")return[t];let n=fr(t);return n!==void 0?[n]:[]}).flat()),e}function bn(r){let e={...r};return r.contexts&&(e.contexts={...r.contexts,visibility:pr(r.contexts.visibility)}),r.methods&&(e.methods={...r.methods,visibility:pr(r.methods.visibility)}),r.peers&&(e.peers={...r.peers,visibility:pr(r.peers.visibility)}),r.metrics&&(e.metrics=zs(r.metrics)),r.mesh&&(e.mesh=Vs(r.mesh)),e}var k=S("gateway-manager");function Sn(){return globalThis.crypto.randomUUID().replaceAll("-","")}var st=class{#e;#t;#r=new Map;#n=new Map;#s;#i=!1;#o;constructor(e){this.#s={baseConfig:bn(e.baseConfig),scope:e.scope??"principal"},this.#e=e.baseConfig.node??Sn(),k.enabledFor("debug")&&k.debug(`creating default gateway with gateway id: ${this.#e}`),this.#t=wn.Factory({...this.#s.baseConfig,node:this.#e})}async start(e){return this.#i?this:(this.#o=e,k.debug("starting default gateway"),await this.#t.start(e),this.#i=!0,this)}async getGateway(e){if(this.#s.scope==="singleton"||!e)return this.#t;let t=this.#n.get(e),n=t?this.#r.get(t):void 0;return n?k.enabledFor("debug")&&k.debug(`reusing existing gateway for principal '${e}'`):(k.enabledFor("debug")&&k.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.#c(e)),n}async#c(e){let t=Sn(),n={...this.#s.baseConfig,node:t};k.enabledFor("debug")&&k.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let s=wn.Factory(n);return this.#n.set(e,t),this.#r.set(t,s),await s.start(this.#o),s}getGateways(){let e=new Map(this.#r);return e.set(this.#e,this.#t),e}info(e){if(e&&this.#e!==e){let t=this.#r.get(e);if(t)return t.info();throw new Error(`no gateway found with ID: ${e}`)}return e===this.#e?this.#t.info():{...this.#t.info(),managedGateways:this.#r.size,scope:this.#s.scope}}async stop(e){if(e&&this.#e!==e){let t=this.#r.get(e);if(t){k.info(`stopping gateway with ID: ${e}`),await t.stop(),this.#r.delete(e);for(let[n,s]of this.#n.entries())if(s===e){this.#n.delete(n);break}return t}else throw new Error(`no gateway found with ID: ${e}`)}if(e===this.#e)return k.debug("stopping default gateway (managed gateways will continue running)"),await this.#t.stop(),this.#i=!1,this.#t;k.info(`stopping all gateways (1 default + ${this.#r.size} managed)`);for(let[t,n]of this.#r.entries())k.enabledFor("debug")&&k.debug(`stopping gateway with ID: ${t}`),await n.stop();return this.#r.clear(),this.#n.clear(),k.debug("stopping default gateway"),await this.#t.stop(),this.#i=!1,this.#t}getPrincipalGatewayId(e){return this.#n.get(e)}getPrincipalGatewayIds(){return new Map(this.#n)}getDefaultGateway(){return this.#t}client(e,t){return this.#t.client(e,t)}async connect(e){return this.#t.connect(e)}getPrincipalCount(){return this.#r.size}};function En(...r){if(!Array.isArray(r))throw new Error("middleware must be array!");let e=r.flat();for(let t of e)if(typeof t!="function")throw new Error("middleware must be compose of functions!");return async function(t,n){let s=async(i,o)=>{let a=i===e.length?n:e[i];if(a===void 0)return;let c=!1,d=!1,h=await a(o,async g=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await s(i+1,g??o)}finally{d=!0}});if(c&&!d)throw new Error(`middleware resolved before downstream.
|
|
2
|
+
You are probably missing an await or return statement in your middleware function.`);return h};return s(0,t)}}import{isIP as js}from"node:net";import{Cookie as gr}from"tough-cookie";function Xs(r,e){let t=r.get("x-forwarded-host");if(Array.isArray(t)&&(t=t[0]),t){let n=r.one("x-forwarded-port");n&&(t=`${t}:${n}`)}return t??=r.one("host"),Array.isArray(t)&&(t=t[0]),t?t.split(",",1)[0].trim():e}function Js(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function Ys(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():Js(r)?"https":e}function Ks(r,e,t){let n=t?t.port:r.protocol==="https:"?443:80,s=e.one("x-forwarded-for");if(Array.isArray(s)&&(s=s[0]),s!==void 0)return s=s.split(",",1)[0].trim(),{address:s,port:Number(n),family:js(s)===6?"IPv6":"IPv4"}}var it=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},ot=class r extends it{static logIdCounter=0;#e;get id(){return this.#e===void 0&&(this.#e=`${this.initId()}-${++r.logIdCounter}`),this.#e}initId(){return"request"}get cookies(){return Qs(this.headers)}parseHost(e){return Xs(this.headers,e)}parseProtocol(e){return Ys(this.headers,e)}parseRemoteAddress(e){return Ks(this.URL,this.headers,e)}},at=class extends it{get cookies(){return Zs(this.headers)}setCookieValue(e){return new gr({key:e.name,value:e.value,maxAge:e.maxAge,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httpOnly,sameSite:e.sameSite}).toString()}};function Qs(r){return r.list("cookie").map(e=>e.split(";").map(t=>gr.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function Zs(r){return r.list("set-cookie").map(e=>{let t=gr.parse(e);if(t){let n={name:t.key,value:t.value,maxAge:Number(t.maxAge??-1)};return t.httpOnly&&(n.httpOnly=!0),t.domain&&(n.domain=t.domain),t.path&&(n.path=t.path),t.secure&&(n.secure=!0),t.httpOnly&&(n.httpOnly=!0),t.sameSite&&(n.sameSite=t.sameSite),Object.freeze(n)}}).filter(e=>e!==void 0)}import{MIMEType as ei}from"node:util";import{MIMEType as mr}from"node:util";var ce="*",Fe=new mr(`${ce}/${ce}`),yr="application/octet-stream",Ca=new mr(yr);function fe(r){return r.type===ce}function te(r){return r.subtype===ce||r.subtype.startsWith(`${ce}+`)}function br(r){return!fe(r)&&!te(r)}var Le=class extends Error{mimeType;constructor(e,t,n){super(t===void 0?`Invalid MIME type "${e}"`:`Invalid MIME type "${e}": ${t}`,n),this.mimeType=e}};function wr(r,e,t){let n=`${r}/${e}`,s;try{s=new mr(n)}catch(i){throw new Le(n,void 0,{cause:i})}return t&&s.params.set("charset",t),s}function vn(r){let e=r.subtype.lastIndexOf("+");return e!==-1&&e<r.subtype.length?r.subtype.substring(e+1):null}function re(r,e){if(!e)return!1;if(fe(r)||fe(e))return!0;if(r.type===e.type){if(r.subtype===e.subtype)return!0;if(te(r)||te(e)){let t=vn(r),n=vn(e);if(r.subtype===ce||e.subtype===ce)return!0;if(te(r)&&n!==null)return t===e.subtype||t===n;if(te(e)&&t!==null)return r.subtype===n||n===t}}return!1}var ti=`
|
|
3
3
|
application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy
|
|
4
4
|
application/json json
|
|
5
5
|
application/wasm wasm
|
|
@@ -9,14 +9,14 @@ text/csv csv
|
|
|
9
9
|
text/html html htm
|
|
10
10
|
text/javascript js mjs
|
|
11
11
|
text/plain txt text conf def list log in
|
|
12
|
-
`,
|
|
13
|
-
`)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.split(/\s+/);if(s.length<2)continue;let[i,...o]=s,a=A.parseMediaType(i);for(let c of o){let d="."+c.toLowerCase(),u=e.get(d);u?u.push(a):e.set(d,[a])}}return e})();function En(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function Sn(r){return En(r)?r.substring(1,r.length-1):r}function Ks(r,e){if(r instanceof A&&e instanceof A){let s=r.quality,i=e.quality;if(s>i)return!0;if(s<i)return!1}let t=pe(r),n=pe(e);if(t&&!n)return!1;if(!t&&n)return!0;{let s=te(r),i=te(e);if(s&&!i)return!1;if(!s&&i)return!0;if(r.type===e.type&&r.subtype===e.subtype){let o=Array.from(r.params.keys()).length,a=Array.from(e.params.keys()).length;return o>a}else return!1}}function Qs(r,e){return Ks(e,r)}function Zs(r,e){let t=r.length;for(let n=0;n<t;n++)for(let s=1;s<t-n;s++){let i=r[s-1],o=r[s];e(i,o)&&(r[s]=i,r[s-1]=o)}}function vn(r){if(r===void 0)throw new Error("mimeTypes must not be undefined");if(r.length>100)throw new Oe("too many elements");Zs(r,Qs)}function ei(r){let e=[];{let t=0,n=0;for(let s=0;s<r.length;s++)switch(r.charCodeAt(s)){case 32:t===n&&(t=n=s+1);break;case 44:e.push(r.slice(t,n)),t=n=s+1;break;default:n=n+1;break}e.push(r.slice(t,n))}return e}function Pn(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...ei(t));return e}var Fe=class{constructor(){}toList(e){let t=this.get(e);return Pn(t)}},x=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let t=super.get(e.toLowerCase());return Pn(t)}set(e,t){return typeof t=="number"&&(t=String(t)),typeof t=="string"&&(t=[t]),t?super.set(e.toLowerCase(),t):(super.delete(e.toLowerCase()),this)}add(e,t){let n=super.get(e.toLowerCase());return typeof t=="string"&&(t=[t]),n&&(t=n.concat(t)),this.set(e,t),this}},Cn=new x;function fe(r){let e=r.one("content-type");return e?A.parseMediaType(e):void 0}var yr=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},y=class r{static CONTINUE=new r(100,"Continue");static SWITCHING_PROTOCOLS=new r(101,"Switching Protocols");static OK=new r(200,"OK");static CREATED=new r(201,"Created");static ACCEPTED=new r(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new r(203,"Non-Authoritative Information");static NO_CONTENT=new r(204,"No Content");static RESET_CONTENT=new r(205,"Reset Content");static PARTIAL_CONTENT=new r(206,"Partial Content");static MULTI_STATUS=new r(207,"Multi-Status");static IM_USED=new r(226,"IM Used");static MULTIPLE_CHOICES=new r(300,"Multiple Choices");static MOVED_PERMANENTLY=new r(301,"Moved Permanently");static BAD_REQUEST=new r(400,"Bad Request");static UNAUTHORIZED=new r(401,"Unauthorized");static FORBIDDEN=new r(403,"Forbidden");static NOT_FOUND=new r(404,"Not Found");static METHOD_NOT_ALLOWED=new r(405,"Method Not Allowed");static NOT_ACCEPTABLE=new r(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new r(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new r(408,"Request Timeout");static CONFLICT=new r(409,"Conflict");static GONE=new r(410,"Gone");static LENGTH_REQUIRED=new r(411,"Length Required");static PRECONDITION_FAILED=new r(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new r(413,"Payload Too Large");static URI_TOO_LONG=new r(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new r(415,"Unsupported Media Type");static EXPECTATION_FAILED=new r(417,"Expectation Failed");static IM_A_TEAPOT=new r(418,"I'm a teapot");static TOO_EARLY=new r(425,"Too Early");static UPGRADE_REQUIRED=new r(426,"Upgrade Required");static PRECONDITION_REQUIRED=new r(428,"Precondition Required");static TOO_MANY_REQUESTS=new r(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new r(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new r(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new r(500,"Internal Server Error");static NOT_IMPLEMENTED=new r(501,"Not Implemented");static BAD_GATEWAY=new r(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new r(503,"Service Unavailable");static GATEWAY_TIMEOUT=new r(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new r(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new r(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new r(507,"Insufficient Storage");static LOOP_DETECTED=new r(508,"Loop Detected");static NOT_EXTENDED=new r(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new r(511,"Network Authentication Required");static#e=[];static{Object.keys(r).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let t=r[e];t instanceof r&&(Object.defineProperty(t,"name",{enumerable:!0,value:e,writable:!1}),r.#e.push(t))})}static resolve(e){for(let t of r.#e)if(t.value===e)return t}#t;#r;constructor(e,t){this.#t=e,this.#r=t}get value(){return this.#t}get phrase(){return this.#r}toString(){return`${this.#t} ${this.name}`}};function at(r){if(typeof r=="number"){if(r<100||r>999)throw new Error(`status code ${r} should be in range 100-999`);let e=y.resolve(r);return e!==void 0?e:new yr(r)}return r}import Pr from"node:http";function Ue(r,e,t){let n=r.elements;if(t=t??n.length,e===0&&t===n.length)return r;if(e===t)return $e.EMPTY_PATH;if(!(e>=0&&e<n.length))throw new Error("start index out of bounds: "+e);if(!(e>=0&&t<=n.length))throw new Error("end index out of bounds: "+t);if(!(e<t))throw new Error("start index must be less than end index: "+e+" >= "+t);let s=n.slice(e,t),i=s.map(o=>o.value).join("");return new $e(i,s)}function z(r){return r.value.length===1&&r.valueToMatch===void 0&&r.parameters===void 0}function F(r){return!z(r)}var br={separator:47,decodeAndParseParameters:!0};function j(r,e){return $e.createFromUrlPath(r,e??br)}var $e=class r{static EMPTY_PATH=new r("",[]);static#e=new Map([[47,{value:"/",encoded:"%2F"}],[46,{value:".",encoded:"%2E"}]]);#t;#r;constructor(e,t){this.#t=e,this.#r=Object.freeze(t)}get value(){return this.#t}get elements(){return this.#r}static createFromUrlPath(e,t){if(e==="")return r.EMPTY_PATH;let n=t.separator,s=r.#e.get(n);if(s===void 0)throw new Error("Unsupported separator: "+n);let i=[],o;for(e.charCodeAt(0)===n?(o=1,i.push(s)):o=0;o<e.length;){let a=-1;for(let d=o;d<e.length;d++)if(e.charCodeAt(d)===n){a=d;break}let c=a!==-1?e.substring(o,a):e.substring(o);if(c.length>0&&i.push(t.decodeAndParseParameters?r.#n(c):De.from(c,s)),a===-1)break;i.push(s),o=a+1}return new r(e,i)}static#n(e){let t=e.indexOf(";");if(t===-1){let n=decodeURIComponent(e);return De.from(e,n)}else{let n=decodeURIComponent(e.substring(0,t)),s=e.substring(t),i=r.#s(s);return De.from(e,n,i)}}static#s(e){let t=new Map,n=1;for(;n<e.length;){let s=-1;for(let o=n;o<e.length;o++)if(e.charAt(o)===";"){s=o;break}let i=s!==-1?e.substring(n,s):e.substring(n);if(r.#i(i,t),s===-1)break;n=s+1}if(t.size>0)for(let s of t.values())Object.freeze(s);return t}static#i(e,t){if(e){let n=e.indexOf("=");if(n!==-1){let s=decodeURIComponent(e.substring(0,n));if(s.trim()){let i=e.substring(n+1);for(let o of i.split(",")){let a=t.get(s);a!==void 0?a.push(decodeURIComponent(o)):t.set(s,[decodeURIComponent(o)])}}}else{let s=decodeURIComponent(e);if(s.trim()){let i=t.get(s);i!==void 0?i.push(""):t.set(s,[""])}}}}},De=class r{static#e=new Map;static from(e,t,n){if(typeof t=="string"){let s=t;return new r(e,s,n)}else{let s=t,i=e.includes(s.encoded)?e.replaceAll(s.encoded,s.value):e;return r.from(e,i,n)}}#t;#r;#n;constructor(e,t,n=r.#e){this.#t=e,this.#r=t,this.#n=n}get value(){return this.#t}get valueToMatch(){return this.#r}get parameters(){return this.#n}};function xn(r,e){return typeof r=="string"?wr.parse(r,e):xn(r.href,e)}var wr=class r{static#e(e,t){if(!(t&&t.trim())||t.charAt(0)!=="/")return j("");r.#t(e.value,t);let n=t.length,s=0;for(let i=0;i<e.elements.length;i++){let o=e.elements[i];if(s+=o.value.length,n===s)return Ue(e,0,i+1)}throw new Error(`Failed to initialize context path: '${t}' for request path: '${e.value}'`)}static#t(e,t){let n=t.length;if(t.charAt(0)!=="/"||t.charAt(n-1)==="/")throw new Error(`Invalid context path: '${t}'. Context path must start with '/' and must not end with '/'`);if(!e.startsWith(t))throw new Error(`Invalid context path: '${t}'. Context path must be a prefix of request path: '${e}'`);if(e.length>n&&e.charAt(n)!=="/")throw new Error(`Invalid context path: '${t}'. Context path must match to full path segments for request path: '${e}'`)}static#r(e,t){let n=t.elements.length;return Ue(e,n)}static parse(e,t){let n=j(e),s=r.#e(n,t),i=r.#r(n,s);return new r(j(e),s,i)}#n;#s;#i;constructor(e,t,n){this.#n=e,this.#s=t,this.#i=n}get value(){return this.#n.value}get elements(){return this.#n.elements}get contextPath(){return this.#s}get pathWithinApplication(){return this.#i}modifyContextPath(e){let t=r.#e(this,e),n=r.#r(this,t);return new r(this,t,n)}toString(){return this.#n.toString()}},Ne=class extends st{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=xn(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var ct=class extends Pr.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},ge=class extends Pr.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},dt=class extends it{#e=[];#t;#r="new";#n=[];setStatusCode(e){return this.#r==="committed"?!1:(this.#t=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:at(e))}get statusCode(){return this.#t}addCookie(e){if(this.#r==="committed")throw new Error(`Cannot add cookie ${JSON.stringify(e)} because HTTP response has already been committed`);return this.#e.push(e),this}beforeCommit(e){this.#n.push(e)}get commited(){let e=this.#r;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let t=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(t))).catch(n=>{throw n})}catch(n){throw n}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let t=this.#r,n=Promise.resolve();if(t==="new")this.#r="committing",this.#n.length>0&&(n=this.#n.reduce((s,i)=>s.then(()=>i()),Promise.resolve()).catch(s=>{this.#r==="committing"&&(this.#r="commit-action-failed")}));else if(t==="commit-action-failed")this.#r="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#r="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},me=class extends Ne{#e;#t;#r;constructor(e){super(new Er(e)),this.#r=e}getNativeRequest(){return this.#r}get upgrade(){return this.#r.upgrade}get http2(){return this.#r.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#r.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#r.method}get host(){let e;return this.#r.httpVersionMajor>=2&&(e=this.#r.headers[":authority"]),e??=this.#r.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#r.httpVersionMajor>2&&(e=this.#r.headers[":scheme"]),e??=this.#r.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#r.socket}get remoteAddress(){let e=this.#r.socket.remoteFamily,t=this.#r.socket.remoteAddress,n=this.#r.socket.remotePort,s=!e||!t||!n?void 0:{family:e,address:t,port:n};return super.parseRemoteAddress(s)??s}initSslInfo(){if(this.#r.socketEncrypted)return new Sr(this.#r.socket)}get cookies(){return this.#t??=super.cookies,this.#t}get body(){return Pr.IncomingMessage.toWeb(this.#r)}async blob(){let e=[];if(this.body!==void 0)for await(let t of this.body)e.push(t);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let t=await(await this.blob()).text();return new URLSearchParams(t)}async json(){let e=await this.blob();if(e.size===0)return;let t=await e.text();return JSON.parse(t)}initId(){let e=this.#r.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#r.socket.remotePort}`}},Sr=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},Er=class extends Fe{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.headers[e]!==void 0}get(e){return this.#e.headers[e]}list(e){return super.toList(e)}one(e){let t=this.#e.headers[e];return Array.isArray(t)?t[0]:t}keys(){return Object.keys(this.#e.headers).values()}},vr=class extends Fe{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.hasHeader(e)}keys(){return this.#e.getHeaderNames().values()}get(e){return this.#e.getHeader(e)}one(e){let t=this.#e.getHeader(e);return Array.isArray(t)?t[0]:t}set(e,t){return this.#e.headersSent||(Array.isArray(t)?t=t.map(n=>typeof n=="number"?String(n):n):typeof t=="number"&&(t=String(t)),t?this.#e.setHeader(e,t):this.#e.removeHeader(e)),this}add(e,t){return this.#e.headersSent||this.#e.appendHeader(e,t),this}list(e){return super.toList(e)}},ut=class extends dt{#e;constructor(e){super(new vr(e)),this.#e=e}getNativeResponse(){return this.#e}get statusCode(){return super.statusCode??{value:this.#e.statusCode}}applyStatusCode(){let e=super.statusCode;e!==void 0&&(this.#e.statusCode=e.value)}addCookie(e){return this.headers.add("Set-Cookie",super.setCookieValue(e)),this}async bodyInternal(e){if(this.#e.headersSent)return!1;if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported in response");{let t=await e;return await new Promise((n,s)=>{try{t===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof t=="string"?this.headers.set("Content-Length",Buffer.byteLength(t)):t instanceof Blob?this.headers.set("Content-Length",t.size):this.headers.set("Content-Length",t.byteLength)),this.#e.end(t,()=>{n(!0)}))}catch(i){s(i instanceof Error?i:new Error(`end failed: ${i}`))}})}}},lt=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get id(){return this.#e.id}get method(){return this.#e.method}get path(){return this.#e.path}get requestPath(){return this.#e.requestPath}get protocol(){return this.#e.protocol}get host(){return this.#e.host}get URL(){return this.#e.URL}get headers(){return this.#e.headers}get cookies(){return this.#e.cookies}get remoteAddress(){return this.#e.remoteAddress}get upgrade(){return this.#e.upgrade}get sslInfo(){return this.#e.sslInfo}get body(){return this.#e.body}async blob(){return await this.#e.blob()}async text(){return await this.#e.text()}async formData(){return await this.#e.formData()}async json(){return await this.#e.json()}toString(){return`${r.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof Ne)return e.getNativeRequest();if(e instanceof r)return r.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},ye=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}setStatusCode(e){return this.delegate.setStatusCode(e)}setRawStatusCode(e){return this.delegate.setRawStatusCode(e)}get statusCode(){return this.delegate.statusCode}get cookies(){return this.delegate.cookies}addCookie(e){return this.delegate.addCookie(e),this}async end(){return await this.delegate.end()}async body(e){return await this.#e.body(e)}get headers(){return this.#e.headers}toString(){return`${r.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof dt)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},ht=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get request(){return this.#e.request}get response(){return this.#e.response}attribute(e){return this.#e.attribute(e)}get attributes(){return this.#e.attributes}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${r.name} [delegate: ${this.delegate}]`}},pt=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[An]=e.id,this.request=e,this.response=t}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes.get(e)}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(An);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},An="io.interop.web.server.exchange.log_id";import{getHeapStatistics as ti,writeHeapSnapshot as ri}from"node:v8";import{access as ni,mkdir as si,rename as Rn,unlink as ii}from"node:fs/promises";var P=w("monitoring"),oi={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function ai(){return ti()}async function Tn(r){let e=r.dumpPrefix??"Heap",t=`${r.dumpLocation}/${e}.heapsnapshot`;P.enabledFor("debug")&&P.debug(`starting heap dump in ${t}`),await Cr(r.dumpLocation).catch(async s=>{P.enabledFor("debug")&&P.debug(`dump location ${r.dumpLocation} does not exists. Will try to create it`);try{await si(r.dumpLocation,{recursive:!0}),P.info(`dump location dir ${r.dumpLocation} successfully created`)}catch{P.error(`failed to create dump location ${r.dumpLocation}`)}});let n=ri(t);P.info("heap dumped");try{P.debug("rolling snapshot backups");let s=`${r.dumpLocation}/${e}.${r.maxBackups}.heapsnapshot`;await Cr(s).then(async()=>{P.enabledFor("debug")&&P.debug(`deleting ${s}`);try{await ii(s)}catch(o){P.warn(`failed to delete ${s}`,o)}}).catch(()=>{});for(let o=r.maxBackups-1;o>0;o--){let a=`${r.dumpLocation}/${e}.${o}.heapsnapshot`,c=`${r.dumpLocation}/${e}.${o+1}.heapsnapshot`;await Cr(a).then(async()=>{try{await Rn(a,c)}catch(d){P.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${r.dumpLocation}/${e}.1.heapsnapshot`;try{await Rn(n,i)}catch(o){P.warn(`failed to rename ${n} to ${i}`,o)}P.debug("snapshots rolled")}catch(s){throw P.error("error rolling backups",s),s}}async function Cr(r){P.enabledFor("trace")&&P.debug(`checking file ${r}`),await ni(r)}async function ci(r,e,t){P.enabledFor("debug")&&P.debug(`processing heap stats ${JSON.stringify(r)}`);let n=Math.min(t.memoryLimit,.95*r.heap_size_limit),s=r.used_heap_size;P.info(`heap stats ${JSON.stringify(r)}`),s>=n?(P.warn(`used heap ${s} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await Tn(t)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function Hn(r){let e={...oi,...r},t=!1,n={memoryLimitExceeded:!1},s=async()=>{let a=ai();await ci(a,n,e)},i=setInterval(s,e.reportInterval);return{...e,channel:async a=>{if(!t)switch(a??="run",a){case"run":{await s();break}case"dump":{await Tn(e);break}case"stop":{t=!0,clearInterval(i),P.info("exit memory diagnostic");break}}return t}}}async function di({channel:r},e){await r(e)||P.warn(`cannot execute command "${e}" already closed`)}async function Mn(r){return await di(r,"stop")}var li=(r,e)=>(e??=r,async({response:t},n)=>{e!==!1&&!t.headers.has("server")&&t.headers.set("Server",e),await n()}),kn=(r,e)=>li(r,e);import{IOGateway as ft}from"@interopio/gateway";var xr=w("gateway.ws.client-verify");function hi(r){switch(r.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function pi(r,e){let t=r.block??r.blacklist,n=r.allow??r.whitelist;if(t.length>0&&ft.Filtering.valuesMatch(t,e))return xr.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&ft.Filtering.valuesMatch(n,e))return xr.enabledFor("debug")&&xr.debug(`origin ${e} matches allow filter`),!0}function fi(r){switch(r.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Wn(r,e){if(!e)return!0;if(r){let t=pi(e,r);return t||fi(e)}else return hi(e)}function In(r){if(r){let e=(r.block??r.blacklist??[]).map(ft.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(ft.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var On=r=>async e=>{for(let t of r)if((await t(e)).match)return D();return W},be=r=>{let e=async t=>{for(let n of r)if(!(await n(t)).match)return W;return D()};return e.toString=()=>`and(${r.map(t=>t.toString()).join(", ")})`,e},Ln=r=>async e=>(await r(e)).match?W:D(),we=async r=>D();we.toString=()=>"any-exchange";var Fn=Object.freeze({}),W=Object.freeze({match:!1,variables:Fn}),D=(r=Fn)=>({match:!0,variables:r}),$=(r,e)=>{let t=e?.method,n=async s=>{let i=s.request,o=i.path;if(t!==void 0&&i.method!==t)return W;if(typeof r=="string")return o===r?D():W;{let a=r.exec(o);return a===null?W:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n},qe=r=>{let e=t=>{if(r.ignoredMediaTypes!==void 0){for(let n of r.ignoredMediaTypes)if(t===n||n==="*/*")return!0}return!1};return async t=>{let n=t.request,s;try{s=n.headers.list("accept")}catch{return W}for(let i of s)if(!e(i)){for(let o of r.mediaTypes)if(i.startsWith(o))return D()}return W}},ce=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?D():W;ce.toString=()=>"websocket upgrade";import{IOGateway as Dn}from"@interopio/gateway";async function Ar(r,e,t){let n=(i,o)=>{if(o?.cors){let a=o.cors===!0?{allowOrigins:o.origins?.allow?.map(Dn.Filtering.regexify),allowMethods:i.method===void 0?["*"]:[i.method],allowCredentials:o.authorize?.access!=="permitted"?!0:void 0}:o.cors,c=i.path;t.cors.push([c,a])}},s=new class{handle(...i){i.forEach(({request:o,options:a,handler:c})=>{let d=$(Dn.Filtering.regexify(o.path),{method:o.method});a?.authorize&&t.authorize.push([d,a.authorize]),n(o,a);let u=async(f,m)=>{let{match:v,variables:l}=await d(f);v?await c(f,l):await m()};t.middleware.push(u)})}socket(...i){for(let{path:o,factory:a,options:c}of i){let d=o??"/";t.sockets.set(d,{default:o===void 0||o==="/",ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:In(c?.origins)})}}};await r(s,e)}import{IOGateway as Tr}from"@interopio/gateway";function mi(r){let e=r.headers.one("origin");if(e===void 0)return!0;let t=r.URL,n=t.protocol,s=t.host,i=URL.parse(e),o=i?.host,a=i?.protocol;return n===a&&s===o}function $n(r){return r.headers.has("origin")&&!mi(r)}function X(r){return r.method==="OPTIONS"&&r.headers.has("origin")&&r.headers.has("access-control-request-method")}var Un=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],yi=(r,e)=>{let{request:t,response:n}=r,s=n.headers;if(!s.has("Vary"))s.set("Vary",Un.join(", "));else{let o=s.list("Vary");for(let a of Un)o.find(c=>c===a)||o.push(a);s.set("Vary",o.join(", "))}try{if(!$n(t))return!0}catch{return U.enabledFor("debug")&&U.debug("reject: origin is malformed"),_e(n),!1}if(s.has("access-control-allow-origin"))return U.enabledFor("trace")&&U.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let i=X(t);return e?wi(r,e,i):i?(_e(n),!1):!0},mt=["*"],Rr=["GET","HEAD","POST"],Nn={allowOrigins:mt,allowMethods:Rr,allowHeaders:mt,maxAge:1800};function yt(r){if(r){let e=r.allowHeaders;e&&e!==C&&(r={...r,allowHeaders:e.map(n=>n.toLowerCase())});let t=r.allowOrigins;return t&&(t==="*"?(_n(r),Bn(r)):r={...r,allowOrigins:t.map(n=>typeof n=="string"&&n!==C&&(n=Tr.Filtering.regexify(n),typeof n=="string")?Gn(n).toLowerCase():n)}),r}}function gt(r,e){if(e===void 0)return r!==void 0?r===C?[C]:r:[];if(r===void 0)return e===C?[C]:e;if(r==mt||r===Rr)return e===C?[C]:e;if(e==mt||e===Rr)return r===C?[C]:r;if(r===C||r.includes(C)||e===C||e.includes(C))return[C];let t=new Set;return r.forEach(n=>t.add(n)),e.forEach(n=>t.add(n)),Array.from(t)}var Be=(r,e)=>e===void 0?r:{allowOrigins:gt(r.allowOrigins,e?.allowOrigins),allowMethods:gt(r.allowMethods,e?.allowMethods),allowHeaders:gt(r.allowHeaders,e?.allowHeaders),exposeHeaders:gt(r.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??r.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??r.allowPrivateNetwork,maxAge:e?.maxAge??r.maxAge},bi=r=>{let e=r.corsConfigSource,t=r.corsProcessor??yi;if(e===void 0)throw new Error("corsConfigSource is required");if(t===void 0)throw new Error("corsProcessor is required");return{filter:async(n,s)=>{let i=await e(n);!t(n,i)||X(n.request)||await s.filter(n)}}},qn=bi,U=w("cors");function _e(r){r.setStatusCode(y.FORBIDDEN)}function wi(r,e,t){let{request:n,response:s}=r,i=s.headers,o=n.headers.one("origin"),a=Ei(e,o);if(a===void 0)return U.enabledFor("debug")&&U.debug(`reject: '${o}' origin is not allowed`),_e(s),!1;let c=Ci(n,t),d=vi(e,c);if(d===void 0)return U.enabledFor("debug")&&U.debug(`reject: HTTP '${c}' is not allowed`),_e(s),!1;let u=xi(n,t),f=Pi(e,u);if(t&&f===void 0)return U.enabledFor("debug")&&U.debug(`reject: headers '${u}' are not allowed`),_e(s),!1;i.set("Access-Control-Allow-Origin",a),t&&i.set("Access-Control-Allow-Methods",d.join(",")),t&&f!==void 0&&f.length>0&&i.set("Access-Control-Allow-Headers",f.join(", "));let m=e.exposeHeaders;return m&&m.length>0&&i.set("Access-Control-Expose-Headers",m.join(", ")),e.allowCredentials&&i.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&i.set("Access-Control-Allow-Private-Network","true"),t&&e.maxAge!==void 0&&i.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var C="*",Si=["GET","HEAD"];function _n(r){if(r.allowCredentials===!0&&r.allowOrigins===C)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function Bn(r){if(r.allowPrivateNetwork===!0&&r.allowOrigins===C)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Ei(r,e){if(e){let t=r.allowOrigins;if(t){if(t===C)return _n(r),Bn(r),C;let n=Gn(e.toLowerCase());for(let s of t)if(s===C||Tr.Filtering.valueMatches(s,n))return e}}}function vi(r,e){if(e){let t=r.allowMethods??Si;if(t===C)return[e];if(Tr.Filtering.valuesMatch(t,e))return t}}function Pi(r,e){if(e===void 0)return;if(e.length==0)return[];let t=r.allowHeaders;if(t===void 0)return;let n=t===C||t.includes(C),s=[];for(let i of e){let o=i?.trim();if(o){if(n)s.push(o);else for(let a of t)if(o.toLowerCase()===a){s.push(o);break}}}if(s.length>0)return s}function Gn(r){return r.endsWith("/")?r.slice(0,-1):r}function Ci(r,e){return e?r.headers.one("access-control-request-method"):r.method}function xi(r,e){let t=r.headers;return e?t.list("access-control-request-headers"):Array.from(t.keys())}var Vn=r=>async e=>{for(let[t,n]of r.mappings)if((await t(e)).match)return U.debug(`resolved cors config on '${e.request.path}' using ${t}: ${JSON.stringify(n)}`),n};import{IOGateway as Ai}from"@interopio/gateway";function zn(r){let{sockets:e,cors:t}=r,n=r.corsConfig===!1?void 0:Be(Nn,r.corsConfig),s=[];for(let[o,a]of e){let c=n;for(let[u,f]of t)Ai.Filtering.valueMatches(u,o)&&(f===void 0?c=void 0:c=c===void 0?f:Be(c,f));let d=r.corsConfig===!1?void 0:{allowOrigins:a.originFilters?.allow,allowMethods:["GET","CONNECT","OPTIONS"],allowHeaders:["Upgrade","Connection","Origin","Sec-Websocket-Key","Sec-Websocket-Version","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],exposeHeaders:["Sec-Websocket-Accept","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0};c=c===void 0?d:Be(c,d),s.push([be([ce,$(o)]),yt(c)])}let i=[];for(let[o,a]of t){let[,c]=i.find(([u])=>String(u)===String(o))??[o,n];c=c===void 0?a:Be(c,a);let d=!1;for(let u of i)if(String(u[0])===String(o)){u[1]=c,d=!0;break}d||i.push([o,c])}for(let[o,a]of i)s.push([$(o),yt(a)]);return s.push([$(/\/api\/.*/),yt(n)]),Vn({mappings:s})}function jn(r){return r!==void 0&&typeof r.type=="string"&&typeof r.authenticated=="boolean"}var k=class extends Error{_authentication;get authentication(){return this._authentication}set authentication(e){if(e===void 0)throw new TypeError("Authentication cannot be undefined");this._authentication=e}},bt=class extends k{},Se=class extends k{},Ee=class extends k{constructor(e){super(e)}},Ge=class extends Ee{constructor(e){super(e)}},Ve=class extends Ee{constructor(e){super(e)}},ze=class extends Ee{constructor(e){super(e)}},je=class extends Ee{constructor(e){super(e)}};var de=class extends Error{},J=class{constructor(e){this.granted=e}granted},ne=class{#e;constructor(e){this.#e=e}async verify(e,t){if(!(await this.#e(e,t))?.granted)throw new de("Access denied")}async authorize(e,t){return await this.#e(e,t)}},ve=class extends k{};var N=r=>async e=>{let t=!0,{response:n}=e;for(let s of r.keys())n.headers.has(s)&&(t=!1);if(t)for(let[s,i]of r)n.headers.set(s,i)},Ri=()=>N(new x().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Ti=()=>N(new x().add("x-content-type-options","nosniff")),Hi=(r,e,t)=>{let n=`max-age=${r}`;e&&(n+=" ; includeSubDomains"),t&&(n+=" ; preload");let s=N(new x().add("strict-transport-security",n)),i=o=>o.request.URL.protocol==="https:";return async o=>{i(o)&&await s(o)}},Mi=r=>N(new x().add("x-frame-options",r)),ki=r=>N(new x().add("x-xss-protection",r)),Wi=r=>{let e=r===void 0?void 0:N(new x().add("permissions-policy",r));return async t=>{e!==void 0&&await e(t)}},Ii=(r,e)=>{let t=e?"content-security-policy-report-only":"content-security-policy",n=r===void 0?void 0:N(new x().add(t,r));return async s=>{n!==void 0&&await n(s)}},Oi=(r="no-referrer")=>N(new x().add("referer-policy",r)),Li=r=>{let e=r===void 0?void 0:N(new x().add("cross-origin-opener-policy",r));return async t=>{e!==void 0&&await e(t)}},Fi=r=>{let e=r===void 0?void 0:N(new x().add("cross-origin-embedder-policy",r));return async t=>{e!==void 0&&await e(t)}},Di=r=>{let e=r===void 0?void 0:N(new x().add("cross-origin-resource-policy",r));return async t=>{e!==void 0&&await e(t)}},$i=(...r)=>async e=>{for(let t of r)await t(e)};function Hr(r){let e=[];r?.cache?.disabled||e.push(Ri()),r?.contentType?.disabled||e.push(Ti()),r?.hsts?.disabled||e.push(Hi(r?.hsts?.maxAge??365*24*60*60,r?.hsts?.includeSubDomains??!0,r?.hsts?.preload??!1)),r?.frameOptions?.disabled||e.push(Mi(r?.frameOptions?.mode??"DENY")),r?.xss?.disabled||e.push(ki(r?.xss?.headerValue??"0")),r?.permissionsPolicy?.disabled||e.push(Wi(r?.permissionsPolicy?.policyDirectives)),r?.contentSecurityPolicy?.disabled||e.push(Ii(r?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",r?.contentSecurityPolicy?.reportOnly)),r?.refererPolicy?.disabled||e.push(Oi(r?.refererPolicy?.policy??"no-referrer")),r?.crossOriginOpenerPolicy?.disabled||e.push(Li(r?.crossOriginOpenerPolicy?.policy)),r?.crossOriginEmbedderPolicy?.disabled||e.push(Fi(r?.crossOriginEmbedderPolicy?.policy)),r?.crossOriginResourcePolicy?.disabled||e.push(Di(r?.crossOriginResourcePolicy?.policy)),r?.writers&&e.push(...r.writers);let t=$i(...e);return{filter:async(n,s)=>(await t(n),s.filter(n))}}var Pe=r=>{let e=r.entryPoint,t=r?.rethrowAuthenticationServiceError??!0;return async({exchange:n},s)=>{if(!t||!(s instanceof ve))return e(n,s);throw s}};var Ui="Realm",Ni=r=>`Basic realm="${r}"`,Ce=r=>{let e=Ni(r?.realm??Ui);return async(t,n)=>{let{response:s}=t;s.setStatusCode(y.UNAUTHORIZED),s.headers.set("WWW-Authenticate",e)}};var Xn="Basic ",wt=r=>{let e=r?.credentialsEncoding??"utf-8";return async t=>{let{request:n}=t,s=n.headers.one("authorization");if(!s||!/basic/i.test(s.substring(0)))return;let i=s.length<=Xn.length?"":s.substring(Xn.length),a=Buffer.from(i,"base64").toString(e).split(":",2);if(a.length!==2)return;let c=a[0],d=a[1];return{type:"UsernamePassword",authenticated:!1,principal:c,credentials:d,name:c,eraseCredentials:()=>{d=null}}}};import{AsyncLocalStorage as qi}from"node:async_hooks";var se=class r{static hasSecurityContext(e){return e.getStore()?.securityContext!==void 0}static async getSecurityContext(e){return await e.getStore()?.securityContext}static clearSecurityContext(e){delete e.getStore()?.securityContext}static withSecurityContext(e){return(t=new qi)=>(t.getStore().securityContext=e,t)}static withAuthentication(e){return r.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(r.hasSecurityContext(e))return r.getSecurityContext(e)}};async function _i(r,e,t,n,s,i){let a=await(await n(r))?.(t);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await Bi(a,{exchange:r,chain:e},s,i)}catch(c){throw c instanceof k,c}}async function Bi(r,e,t,n){se.withAuthentication(r)(n),await t(e,r)}function ie(r){let e={matcher:we,successHandler:async({exchange:n,chain:s})=>{await s.filter(n)},converter:wt({}),failureHandler:Pe({entryPoint:Ce({})}),...r},t=e.managerResolver;if(t===void 0&&e.manager!==void 0){let n=e.manager;t=async s=>n}if(t===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return{filter:async(n,s)=>{let o=(await e.matcher(n)).match?await e.converter(n):void 0;if(o===void 0){await s.filter(n);return}try{await _i(n,s,o,t,e.successHandler,e.storage)}catch(a){if(a instanceof k){await e.failureHandler({exchange:n,chain:s},a);return}throw a}}}}var Jn=r=>async(e,t)=>{e.response.setStatusCode(r.httpStatus)};var xe=w("auth.entry-point"),St=r=>{let e=r.defaultEntryPoint??(async({response:t},n)=>{t.setStatusCode(y.UNAUTHORIZED),await t.end()});return async(t,n)=>{for(let[s,i]of r.entryPoints)if(xe.enabledFor("debug")&&xe.debug(`trying to match using: ${s}`),(await s(t)).match)return xe.enabledFor("debug")&&xe.debug(`match found. using default entry point ${i}`),i(t,n);return xe.enabledFor("debug")&&xe.debug(`no match found. using default entry point ${e}`),e(t,n)}};var Yn=r=>async({exchange:e,chain:t},n)=>{for(let s of r)await s({exchange:e,chain:t},n)};function Mr(r){let e=async m=>m.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?D():W,t=St({entryPoints:[[e,Jn({httpStatus:y.UNAUTHORIZED})]],defaultEntryPoint:Ce({})}),n=r.entryPoint??t,s=r.manager,i=qe({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),o=Ln(qe({mediaTypes:["text/html"]})),a=be([o,i]),c=On([e,a]);r.defaultEntryPoints.push([c,n]);let d=r.failureHandler??Pe({entryPoint:n}),u=Yn(r.successHandlers??r.defaultSuccessHandlers),f=wt({});return ie({storage:r.storage,manager:s,failureHandler:d,successHandler:u,converter:f})}var Kn={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},Qn="https://tools.ietf.org/html/rfc6750#section-3.1";function Et(r){return{errorCode:Kn.invalid_token,httpStatus:y.UNAUTHORIZED,description:r,uri:Qn}}function kr(r){return{errorCode:Kn.invalid_request,httpStatus:y.BAD_REQUEST,description:r,uri:Qn}}var Gi="access_token",Vi=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,_=class extends k{error;constructor(e,t,n){super(t??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},Zn=r=>r.type==="BearerToken",zi=r=>async e=>{let{request:t}=e;return Promise.all([Xi(t.headers,r?.headerName).then(n=>n!==void 0?[n]:void 0),Ji(t,r?.uriQueryParameter),Yi(e,r?.formEncodedBodyParameter)]).then(n=>n.filter(s=>s!==void 0).flat(1)).then(ji).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function ji(r){if(r.length===0)return;if(r.length>1){let t=kr("Found multiple access tokens in the request");throw new _(t)}let e=r[0];if(!e||e.length===0){let t=kr("The requested access token parameter is an empty string");throw new _(t)}return e}async function Xi(r,e="authorization"){let t=r.one(e);if(!t||!/bearer/i.test(t.substring(0)))return;let n=Vi.exec(t);if(n===null){let s=Et("Bearer token is malformed");throw new _(s)}return n.groups?.token}async function es(r){let e=r.getAll(Gi);if(e.length!==0)return e}async function Ji(r,e=!1){if(!(!e||r.method!=="GET"))return es(r.URL.searchParams)}async function Yi(r,e=!1){let{request:t}=r;if(!e||t.headers.one("content-type")!=="application/x-www-form-urlencoded"||t.method!=="POST")return;let n=await r.request.formData();if(n)return es(n)}var vt=zi;function Ki(r){let e="Bearer";if(r.size!==0){e+=" ";let t=0;for(let[n,s]of r)e+=`${n}="${s}"`,t!==r.size-1&&(e+=", "),t++}return e}var ts=r=>r.httpStatus!==void 0;function Qi(r){if(r instanceof _){let{error:e}=r;if(ts(e))return e.httpStatus}return y.UNAUTHORIZED}function Zi(r,e){let t=new Map;if(e&&t.set("realm",e),r instanceof _){let{error:n}=r;t.set("error",n.errorCode),n.description&&t.set("error_description",n.description),n.uri&&t.set("error_uri",n.uri),ts(n)&&n.scope&&t.set("scope",n.scope)}return t}var eo=r=>async(e,t)=>{let n=Qi(t),s=Zi(t,r?.realmName),i=Ki(s),{response:o}=e;o.headers.set("WWW-Authenticate",i),o.setStatusCode(n),await o.end()},Pt=eo;var to=r=>{let e=r?.principalClaimName??"sub";return t=>({type:"JwtToken",authenticated:!0,name:t.getClaimAsString(e)})},ro=r=>async e=>r(e),Ae=class extends Error{},Xe=class extends Ae{};function no(r){if(r instanceof Xe)return new _(Et(r.message),r.message,{cause:r});throw new ve(r.message,{cause:r})}function Wr(r){let e=r.decoder,t=r.authConverter??ro(to({}));return async n=>{if(Zn(n)){let s=n.token;try{let i=await e(s);return await t(i)}catch(i){throw i instanceof Ae?no(i):i}}}}function Ir(r){let e=r.entryPoint??Pt({}),t=r?.converter??vt({}),n=r.failureHandler??Pe({entryPoint:e});if(r.managerResolver!==void 0)return ie({storage:r.storage,converter:t,failureHandler:n,managerResolver:r.managerResolver});if(r.jwt!==void 0){let s=r.jwt.manager??Wr(r.jwt);return ie({storage:r.storage,converter:t,failureHandler:n,managerResolver:async i=>s})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}import{jwtVerifier as uo,JwtVerifyError as lo}from"@interopio/gateway/jose/jwt";async function rs(r,e,t){let n=new bt("Full authentication is required to access this resource."),s=new k("Access Denied",{cause:n});e&&(s.authentication=e),await t(r,s)}function so(r){return async(e,t)=>{e.response.setStatusCode(r),e.response.headers.set("Content-Type","text/plain; charset=utf-8");let n=Buffer.from("Access Denied","utf-8");e.response.headers.set("Content-Length",n.length),await e.response.body(n)}}var ns=r=>{let e=so(y.FORBIDDEN),t=r.authenticationEntryPoint??Ce();return{filter:async(n,s)=>{try{await s.filter(n)}catch(i){if(i instanceof de){let o=await n.principal();jn(o)?(o.authenticated||await e(n,i),await rs(n,o,t)):await rs(n,void 0,t);return}throw i}}}};var io=w("security.auth");function Or(r){let e=async(t,n)=>{let s;for(let[i,o]of r.mappings)if((await i(n))?.match){io.debug(`checking authorization on '${n.request.path}' using [${i}, ${o}]`);let a=await o.authorize(t,{exchange:n});if(a!==void 0){s=a;break}}return s??=new J(!1),s};return new ne(e)}var Ct=w("security.auth");function Lr(r){let{manager:e,storage:t}=r;return{filter:async(n,s)=>{let i=se.getContext(t).then(o=>o?.authentication);try{await e.verify(i,n),Ct.enabledFor("debug")&&Ct.debug("authorization successful")}catch(o){throw o instanceof de&&Ct.enabledFor("debug")&&Ct.debug(`authorization failed: ${o.message}`),o}await s.filter(n)}}}var Fr=class extends ht{#e;constructor(e,t){super(e),this.#e=t}async principal(){return(await this.#e())?.authentication}},ss=r=>{let e=r.storage;return{filter:async(t,n)=>{await n.filter(new Fr(t,async()=>await se.getContext(e)))}}};var is=r=>{let{principalExtractor:e}=r;return async t=>{let n=t.request.sslInfo;if(n===void 0||n.peerCertificate===void 0)return;let s=n.peerCertificate,i=e(s);return{type:"PreAuthenticated",authenticated:!1,principal:i,name:i??"",credentials:s}}};var xt=r=>{let e=r?.principalAltName==="email",t=/CN=(.*?)(?:,|$)/mi;return n=>{if(e){let o=n.subjectAltName?.split(", ").find(a=>a.startsWith("email:"));if(o)return o.replace("email:","")}let s=t.exec(n.subject);if(s===null)throw new Se(`Cannot extract principal from subject DN: ${n.subject}`);return s[1]}};var ue=class{async encode(e){if(e!=null)return await this.encodeDefinedPassword(e.toString())}async matches(e,t){return!e||!t?!1:await this.matchesDefined(e.toString(),t)}upgradeEncoding(e){return e?this.upgradeEncodingDefined(e):!1}upgradeEncodingDefined(e){return!1}},Re=class r extends ue{static DEFAULT_ID_PREFIX="{";static DEFAULT_ID_SUFFIX="}";#e;#t;#r;#n;#s;#i=new class extends ue{#d;constructor(e){super(),this.#d=e}async encodeDefinedPassword(e){throw new Error("encode is not supported")}async matchesDefined(e,t){let n=this.#d.#o(t);if(!n)throw new Error(`No password encoder mapped for id ${n}`);if(t){let s=t.indexOf(this.#d.#e),i=t.indexOf(this.#d.#t,s+this.#d.#e.length);if(s===-1&&i===-1)throw new Error("No prefix found in encoded password")}throw new Error("malformed password encoder prefix")}}(this);constructor(e,t,n=r.DEFAULT_ID_PREFIX,s=r.DEFAULT_ID_SUFFIX){if(e==null)throw new Error("idForEncode cannot be null or undefined");if(n==null)throw new Error("idPrefix cannot be null or undefined");if(!s)throw new Error("idSuffix cannot be empty");if(n.indexOf(s)!==-1)throw new Error(`idPrefix "${n}" cannot contain idSuffix "${s}"`);if(!t.has(e))throw new Error(`No PasswordEncoder mapped for id "${e}"`);for(let i of t.keys())if(i!==null){if(n&&i.includes(n))throw new Error(`id "${i}" cannot include ${n}`);if(s&&i.includes(s))throw new Error(`id "${i}" cannot include ${s}`)}super(),this.#r=e,this.#n=t.get(e),this.#s=new Map(t),this.#e=n,this.#t=s}set defaultPasswordEncoderForMatches(e){if(e==null)throw new Error("defaultPasswordEncoderForMatches cannot be null or undefined");this.#i=e}async encodeDefinedPassword(e){let t=await this.#n.encode(e);return`${this.#e}${this.#r}${this.#t}${t}`}async matchesDefined(e,t){let n=this.#o(t),s=n?this.#s.get(n):void 0;if(s===void 0)return await this.#i.matches(e,t);{let i=this.#c(t);return await s.matches(e,i)}}#o(e){if(e===void 0)return;let t=e.indexOf(this.#e);if(t!==0)return;let n=e.indexOf(this.#t,t+this.#e.length);if(n!==-1)return e.substring(t+this.#e.length,n)}upgradeEncodingDefined(e){let t=this.#o(e);if(this.#r!==t)return!0;{let n=this.#c(e);return this.#n.upgradeEncoding?.(n)??!1}}#c(e){let t=e.indexOf(this.#t);return e.substring(t+this.#t.length)}},At=class r extends ue{static#e=new r;static get instance(){return r.#e}constructor(){super()}async encodeDefinedPassword(e){return e.toString()}async matchesDefined(e,t){return e.toString()===t}};import{argon2 as O,keygen as oo}from"@interopio/gateway-server/tools";function ao(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Rt=class extends ue{#e;#t;#r;#n;#s;constructor(e=O.DEFAULT_SALT_LENGTH,t=O.DEFAULT_HASH_LENGTH,n=O.DEFAULT_PARALLELISM,s=O.DEFAULT_MEMORY,i=O.DEFAULT_PASSES){super(),this.#e=e,this.#t=t,this.#r=n,this.#n=s,this.#s=i}async matchesDefined(e,t){try{let n=O.decode(t),s=await O.createHash(n.algorithm,e,n.hash.length,n.parameters);return ao(n.hash,s)}catch{return!1}}async encodeDefinedPassword(e){let t=oo.createSalt(this.#e),n={memory:this.#n,passes:this.#s,parallelism:this.#r,nonce:t},s=await O.createHash("argon2id",e,this.#t,n);return O.encode({algorithm:"argon2id",version:O.ARGON2_VERSION,parameters:n,hash:s})}upgradeEncodingDefined(e){let t=O.decode(e);return t.version<O.ARGON2_VERSION||t.parameters.memory<this.#n||t.parameters.passes<this.#s}};var Dr=4096;function os(){let r="argon2id",e=new Map([[r,new Rt],["noop",At.instance]]);return new Re(r,e,Re.DEFAULT_ID_PREFIX,Re.DEFAULT_ID_SUFFIX)}var as={async updatePassword(r,e){return r}},Tt=class extends k{username;constructor(e,t,n){super(e,n),this.username=t}},Ht=class r{#e;#t;#r=[];#n;#s;#i;#o;#c=e=>e;constructor(){}static ofUsername(e){return new r().username(e)}static ofUserDetails(e){let t=r.ofUsername(e.username).accountExpired(e.accountExpired??!1).accountLocked(e.accountLocked??!1).authorities(e.authorities).credentialsExpired(e.credentialsExpired??!1).disabled(e.disabled??!1);return e.password!==void 0&&t.password(e.password),t}username(e){if(!e)throw new TypeError("username cannot be empty");return this.#e=e,this}password(e){return this.#t=e,this}passwordEncoder(e){if(!e)throw new TypeError("password encoder cannot be null or undefined");return this.#c=e,this}roles(...e){return this.authorities(e.map(t=>{if(t.startsWith("role:"))throw new Error(`${t} must not start with 'role:' (it is automatically added)`);return{authority:`role:${t}`}}))}authorities(e){return this.#r=[...e],this}accountExpired(e){return this.#n=e,this}accountLocked(e){return this.#s=e,this}credentialsExpired(e){return this.#i=e,this}disabled(e){return this.#o=e,this}build(){if(!this.#e)throw new TypeError("username is required");let e=this.#t!==void 0?this.#c(this.#t):void 0;return{username:this.#e,password:e,authorities:this.#r,accountExpired:this.#n,accountLocked:this.#s,credentialsExpired:this.#i,disabled:this.#o,eraseCredentials(){e=null},toString(){return`User(username=${this.username}, password=[PROTECTED], authorities=${JSON.stringify(this.authorities)}, accountExpired=${this.accountExpired}, accountLocked=${this.accountLocked}, credentialsExpired=${this.credentialsExpired}, disabled=${this.disabled})`}}}};var oe=w("security.users");function cs(r,e){let t=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw oe.debug("user account is locked"),new Ge("User account is locked");if(a.disabled)throw oe.debug("user account is disabled"),new Ve("User is disabled");if(a.accountExpired)throw oe.debug("user account is expired"),new ze("User account has expired")}),n=e?.postAuthenticationChecks??(a=>{if(a.credentialsExpired)throw oe.debug("user credentials have expired"),new je("User credentials have expired")}),s=e?.passwordEncoder??os(),i=e?.userDetailsPasswordService??as,o=async(a,c)=>{let d=a.password;if(d!==void 0&&s.upgradeEncoding?.(d)){let f=await s.encode(c);return await i.updatePassword(a,f)}return a};return async a=>{let c=a.name,d=a.credentials!==void 0&&a.credentials!==null?a.credentials.toString():void 0,u=await r.findByUsername(c);if(!u)throw new Error(`User not found: ${c}`);if(t(u),!await s.matches(d,u.password))throw new Se("Invalid Credentials");let f=await o(u,d);n(f);let m=f.password;return{type:"UsernamePassword",principal:f,credentials:m,authorities:f.authorities,authenticated:!0,name:f.username,eraseCredentials(){m=null}}}}function co(){return r=>{if(r.accountLocked)throw oe.debug("failed to authenticate since user account is locked"),new Ge("User account is locked");if(r.disabled)throw oe.debug("failed to authenticate user account is disabled"),new Ve("User is disabled");if(r.accountExpired)throw oe.debug("failed to authenticate since user account is expired"),new ze("User account has expired");if(r.credentialsExpired)throw oe.debug("failed to authenticate since user credentials have expired"),new je("User credentials have expired")}}function ds(r){let e=r.userDetailsService,t=r.userDetailsChecker??co(),n=s=>s.type==="PreAuthenticated"&&s.name!==void 0;return async s=>{let i=n(s)&&await e.findByUsername(s.name);if(!i)throw new Tt("user not found",s.name);t(i);let o=s.credentials;return{type:"PreAuthenticated",principal:i,credentials:o,authorities:i.authorities,authenticated:!0,details:i,name:i.username,eraseCredentials(){o=null}}}}function $r(r){let e=r.manager??ds({userDetailsService:r.getService("UserDetailsService")}),t=r.extractor??xt(),n=r.converter??is({principalExtractor:t});return ie({storage:r.storage,manager:e,converter:n})}var Mt=class{#e;constructor(e){if(e==null)throw new Error("delegate must not be null or undefined");this.#e=e}get delegate(){return this.#e}async handle(e){return await this.#e.handle(e)}toString(){return`WebHandlerDecorator[delegate=${this.#e}]`}},kt=class extends Mt{#e;constructor(e,...t){super(e),this.#e=[...t],Object.freeze(this.#e)}get errorHandlers(){return this.#e}handle(e){let t;try{t=super.handle(e)}catch(n){t=Promise.reject(n)}for(let n of this.#e)t=t.catch(async s=>{let i=s instanceof Error?s:new Error(String(s));await n.handle(e,i)});return t}},Je=class r{#e;#t;#r;#n;static of(e,...t){let n=[...t],s=new r(t,e),i=r.initChain(t,e);return s.#r=i.#r,s.#n=i.#n,s}static initChain(e,t){let n=new r(e,t,void 0,void 0);for(let s of[...e].reverse())n=new r(e,t,s,n);return n}constructor(e,t,n,s){this.#e=e,this.#t=t,this.#r=n,this.#n=s}get filters(){return this.#e}get handler(){return this.#t}async filter(e){this.#r!==void 0&&this.#n!==void 0?await this.#s(this.#r,this.#n,e):await this.#t.handle(e)}#s(e,t,n){return e.filter(n,t)}},Wt=class extends Mt{#e;constructor(e,...t){super(e),this.#e=Je.of(e,...t)}get filters(){return this.#e.filters}handle(e){return this.#e.filter(e)}};var It=class{#e;#t=new Nr;#r=new Ur;#n=new _r;constructor(...e){this.#e=[...e]}async filter(e,t){let n=await this.#t.firewalledExchange(e);try{await this.#s(n,t)}catch(s){if(s instanceof qr)await this.#n.handle(e,s);else throw s}}async#s(e,t){for(let n of this.#e)if(await n.matches(e)){let s=await n.webFilters();await this.#r.decorate(t,s).filter(e);return}await this.#r.decorate(t).filter(e)}set firewall(e){if(!e)throw new Error("firewall must be provided");this.#t=e}set decorator(e){if(!e)throw new Error("decorator must be provided");this.#r=e}set exchangeRejectedHandler(e){if(!e)throw new Error("handler must be provided");this.#n=e}},Ur=class{decorate(e,t){return t=t||[],Je.of({handle:n=>e.filter(n)},...t)}},Ot=class{#e;#t;constructor(e,...t){this.#e=e,this.#t=t}async matches(e){return(await this.#e(e))?.match===!0}async webFilters(){return this.#t}},Nr=class{async firewalledExchange(e){return e}},qr=class extends Error{constructor(e){super(e),this.name="ServerExchangeRejectedError"}},_r=class{#e;constructor(e=y.BAD_REQUEST){this.#e=e}async handle(e,t){e.response.setStatusCode(this.#e)}};var B={first:Number.MAX_SAFE_INTEGER,http_headers:100,https_redirect:200,cors:300,http_basic:600,authentication:800,security_context_server_web_exchange:1500,error_translation:1800,authorization:1900,last:Number.MAX_SAFE_INTEGER},G=Symbol.for("filterOrder"),us=(r,e)=>{let t=(a,c)=>{if(e===void 0)return c;if(a==="UserDetailsService"&&e.userDetailsService!==void 0)return e.userDetailsService;if(a==="AuthenticationManager"&&e.authenticationManager!==void 0)return e.authenticationManager;if(c!==void 0)return c;throw new Error(`No service registered with name: ${a}`)},n=()=>{if(e.authenticationManager!==void 0)return e.authenticationManager;if(e.userDetailsService!==void 0)return cs(e.userDetailsService,{userDetailsPasswordService:e.userDetailsPasswordService})},s=[];class i{#e;#t=[];#r;set authenticationManager(c){this.#r=c}get authenticationEntryPoint(){return this.#e!==void 0||this.#t.length===0?this.#e:this.#t.length===1?this.#t[0][1]:St({entryPoints:this.#t,defaultEntryPoint:this.#t[this.#t.length-1][1]})}build(){if(r.headers!==void 0&&r.headers.disabled!==!0){let d=Hr(r.headers);d[G]=B.http_headers,s.push(d)}if(r.x509!==void 0&&r.x509.disabled!==!0){let d=$r({storage:e.storage,getService:t,extractor:xt({principalAltName:r.x509.principalAltName})});d[G]=B.authentication,s.push(d)}if(r.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=qn({corsConfigSource:e.corsConfigSource});d[G]=B.cors,s.push(d)}if(r.basic!==void 0&&r.basic?.disabled!==!0){let d=[async({exchange:f,chain:m},v)=>await m.filter(f)],u=Mr({storage:e.storage,manager:this.#r,defaultEntryPoints:this.#t,defaultSuccessHandlers:d});u[G]=B.http_basic,s.push(u)}if(r.jwt!==void 0&&r.jwt.disabled!==!0){let d=uo({issuerBaseUri:r.jwt.issuerUri,issuer:r.jwt.issuer,audience:r.jwt.audience}),u=async h=>{try{let{payload:p}=await d(h);return{tokenValue:h,subject:p.sub,getClaimAsString(g){return p[g]}}}catch(p){throw p instanceof lo?new Xe(p.message,{cause:p}):new Ae("error occurred while attempting to decoding jwt",{cause:p})}},f=vt({uriQueryParameter:!0}),m=async h=>{try{return await f(h)===void 0?W:D()}catch{return W}},v=Pt({});this.#t.push([m,v]);let l=Ir({storage:e.storage,entryPoint:v,converter:f,jwt:{decoder:u}});l[G]=B.authentication,s.push(l)}let c=ss({storage:e.storage});if(s.push(c),c[G]=B.security_context_server_web_exchange,r.authorize!==void 0){let d=ns({authenticationEntryPoint:this.authenticationEntryPoint});d[G]=B.error_translation,s.push(d);let f=(v=>{let l=[],h=!1;for(let[p,g]of v??[]){let b;if(p==="any-exchange")h=!0,b=we;else{if(h)throw new Error("Cannot register other matchers after 'any-exchange' matcher");b=p}let S;if(g.access==="permitted")S=new ne(async()=>new J(!0)),S.toString=()=>"AuthorizationManager[permitted]";else if(g.access==="denied")S=new ne(async()=>new J(!1)),S.toString=()=>"AuthorizationManager[denied]";else if(g.access==="authenticated")S=new ne(async T=>{let L=await T;return L!==void 0?new J(L.authenticated):new J(!1)}),S.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(g)}`);l.push([b,S])}return Or({mappings:l})})(r.authorize),m=Lr({manager:f,storage:e.storage});m[G]=B.authorization,s.push(m)}s.sort((d,u)=>{let f=d[G]??B.last,m=u[G]??B.last;return f-m})}}let o=new i;return o.authenticationManager=n(),o.build(),new Ot(we,...s)};var Lt=class{#e=new Map;constructor(...e){for(let t of e)this.#e.set(this.#t(t.username),t)}async findByUsername(e){let t=this.#t(e),n=this.#e.get(t);return n!==void 0?{...n}:void 0}async updatePassword(e,t){let n={...e,password:t};if(n){let s=this.#t(e.username);this.#e.set(s,n)}return n}#t(e){return e.toLowerCase()}};import{randomUUID as ho}from"node:crypto";var Ft=w("auth");function po(r){let e=[],t=r.authConfig?.type,n={access:t!=="none"?"authenticated":"permitted"};Ft.enabledFor("info")&&Ft.info(`using auth type: ${t??"none"}, default access: ${n.access}`);for(let[s,i]of r.sockets){let o=i.authorize??n,a=$(s,{method:"GET"});a=be([ce,a]),e.push([a,o])}return e.push([$("/",{method:"GET"}),{access:"permitted"}]),e.push([$("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([$("/health",{method:"GET"}),{access:"permitted"}]),r.authorize.length>0&&e.push(...r.authorize),e.push(["any-exchange",n]),{authorize:e,cors:{disabled:r.corsConfig===!1},x509:{disabled:t!=="x509",...r.authConfig?.x509},basic:{disabled:t!=="basic",...r.authConfig?.basic},jwt:{disabled:t!=="oauth2",...r.authConfig?.oauth2?.jwt}}}function fo(r){if(r.authConfig?.type==="none")return;function e(o,a){if(r.authConfig?.type==="x509")return null;let c=o.password;if(c===void 0){let d=ho().replaceAll("-","");Ft.enabledFor("info")&&Ft.info(`
|
|
12
|
+
`,M=class r extends ei{static ALL=new r("*/*");static APPLICATION_OCTET_STREAM=new r(yr);static APPLICATION_JSON=new r("application/json");static APPLICATION_NDJSON=new r("application/x-ndjson");static MULTIPART_FORM_DATA=new r("multipart/form-data");static TEXT_PLAIN=new r("text/plain");static TEXT_HTML=new r("text/html");static#e="q";constructor(e){super(e),this.#t(this.type),this.#t(this.subtype);for(let[t,n]of this.params)this.checkParameters(t,n)}checkParameters(e,t){if(this.#t(e),Cn(t)||this.#t(t),e===r.#e){let n=Pn(t),s=parseFloat(n);if(isNaN(s)||s<0||s>1)throw new ct(`Invalid quality value: ${t}`)}}#t(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n>126||n===40||n===41||n===60||n===62||n===64||n===44||n===59||n===58||n===92||n===34||n===53||n===91||n===93||n===63||n===61||n===123||n===125||n===32||n===9)throw new ct(`Invalid token: ${e}`)}}get quality(){let e=this.params.get(r.#e);return e!==null?parseFloat(Pn(e)):1}static parseMediaType(e){return new r(e)}static parseMediaTypesList(e){return e?.trim()?e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>r.parseMediaType(t)):[]}static parseMediaTypes(...e){return e?e.length===1?r.parseMediaTypesList(e[0]):e.flatMap(t=>r.parseMediaTypesList(t)):[]}static asMediaType(e){return e instanceof r?e:new r(e.toString())}static asMediaTypes(...e){return e.map(t=>r.asMediaType(t))}},ct=class extends Error{constructor(e){super(e)}},Ta=(function(){let e=new Map;for(let t of ti.trim().split(`
|
|
13
|
+
`)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.split(/\s+/);if(s.length<2)continue;let[i,...o]=s,a=M.parseMediaType(i);for(let c of o){let d="."+c.toLowerCase(),u=e.get(d);u?u.push(a):e.set(d,[a])}}return e})();function Cn(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function Pn(r){return Cn(r)?r.substring(1,r.length-1):r}function ri(r,e){if(r instanceof M&&e instanceof M){let s=r.quality,i=e.quality;if(s>i)return!0;if(s<i)return!1}let t=fe(r),n=fe(e);if(t&&!n)return!1;if(!t&&n)return!0;{let s=te(r),i=te(e);if(s&&!i)return!1;if(!s&&i)return!0;if(r.type===e.type&&r.subtype===e.subtype){let o=Array.from(r.params.keys()).length,a=Array.from(e.params.keys()).length;return o>a}else return!1}}function ni(r,e){return ri(e,r)}function si(r,e){let t=r.length;for(let n=0;n<t;n++)for(let s=1;s<t-n;s++){let i=r[s-1],o=r[s];e(i,o)&&(r[s]=i,r[s-1]=o)}}function xn(r){if(r===void 0)throw new Error("mimeTypes must not be undefined");if(r.length>100)throw new Le("too many elements");si(r,ni)}function ii(r){let e=[];{let t=0,n=0;for(let s=0;s<r.length;s++)switch(r.charCodeAt(s)){case 32:t===n&&(t=n=s+1);break;case 44:e.push(r.slice(t,n)),t=n=s+1;break;default:n=n+1;break}e.push(r.slice(t,n))}return e}function An(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...ii(t));return e}var De=class{constructor(){}toList(e){let t=this.get(e);return An(t)}},R=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let t=super.get(e.toLowerCase());return An(t)}set(e,t){return typeof t=="number"&&(t=String(t)),typeof t=="string"&&(t=[t]),t?super.set(e.toLowerCase(),t):(super.delete(e.toLowerCase()),this)}add(e,t){let n=super.get(e.toLowerCase());return typeof t=="string"&&(t=[t]),n&&(t=n.concat(t)),this.set(e,t),this}},Rn=new R;function ge(r){let e=r.one("content-type");return e?M.parseMediaType(e):void 0}var Sr=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},b=class r{static CONTINUE=new r(100,"Continue");static SWITCHING_PROTOCOLS=new r(101,"Switching Protocols");static OK=new r(200,"OK");static CREATED=new r(201,"Created");static ACCEPTED=new r(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new r(203,"Non-Authoritative Information");static NO_CONTENT=new r(204,"No Content");static RESET_CONTENT=new r(205,"Reset Content");static PARTIAL_CONTENT=new r(206,"Partial Content");static MULTI_STATUS=new r(207,"Multi-Status");static IM_USED=new r(226,"IM Used");static MULTIPLE_CHOICES=new r(300,"Multiple Choices");static MOVED_PERMANENTLY=new r(301,"Moved Permanently");static BAD_REQUEST=new r(400,"Bad Request");static UNAUTHORIZED=new r(401,"Unauthorized");static FORBIDDEN=new r(403,"Forbidden");static NOT_FOUND=new r(404,"Not Found");static METHOD_NOT_ALLOWED=new r(405,"Method Not Allowed");static NOT_ACCEPTABLE=new r(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new r(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new r(408,"Request Timeout");static CONFLICT=new r(409,"Conflict");static GONE=new r(410,"Gone");static LENGTH_REQUIRED=new r(411,"Length Required");static PRECONDITION_FAILED=new r(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new r(413,"Payload Too Large");static URI_TOO_LONG=new r(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new r(415,"Unsupported Media Type");static EXPECTATION_FAILED=new r(417,"Expectation Failed");static IM_A_TEAPOT=new r(418,"I'm a teapot");static TOO_EARLY=new r(425,"Too Early");static UPGRADE_REQUIRED=new r(426,"Upgrade Required");static PRECONDITION_REQUIRED=new r(428,"Precondition Required");static TOO_MANY_REQUESTS=new r(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new r(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new r(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new r(500,"Internal Server Error");static NOT_IMPLEMENTED=new r(501,"Not Implemented");static BAD_GATEWAY=new r(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new r(503,"Service Unavailable");static GATEWAY_TIMEOUT=new r(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new r(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new r(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new r(507,"Insufficient Storage");static LOOP_DETECTED=new r(508,"Loop Detected");static NOT_EXTENDED=new r(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new r(511,"Network Authentication Required");static#e=[];static{Object.keys(r).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let t=r[e];t instanceof r&&(Object.defineProperty(t,"name",{enumerable:!0,value:e,writable:!1}),r.#e.push(t))})}static resolve(e){for(let t of r.#e)if(t.value===e)return t}#t;#r;constructor(e,t){this.#t=e,this.#r=t}get value(){return this.#t}get phrase(){return this.#r}toString(){return`${this.#t} ${this.name}`}};function dt(r){if(typeof r=="number"){if(r<100||r>999)throw new Error(`status code ${r} should be in range 100-999`);let e=b.resolve(r);return e!==void 0?e:new Sr(r)}return r}import Ar from"node:http";function Ue(r,e,t){let n=r.elements;if(t=t??n.length,e===0&&t===n.length)return r;if(e===t)return Ne.EMPTY_PATH;if(!(e>=0&&e<n.length))throw new Error("start index out of bounds: "+e);if(!(e>=0&&t<=n.length))throw new Error("end index out of bounds: "+t);if(!(e<t))throw new Error("start index must be less than end index: "+e+" >= "+t);let s=n.slice(e,t),i=s.map(o=>o.value).join("");return new Ne(i,s)}function z(r){return r.value.length===1&&r.valueToMatch===void 0&&r.parameters===void 0}function F(r){return!z(r)}var Er={separator:47,decodeAndParseParameters:!0};function j(r,e){return Ne.createFromUrlPath(r,e??Er)}var Ne=class r{static EMPTY_PATH=new r("",[]);static#e=new Map([[47,{value:"/",encoded:"%2F"}],[46,{value:".",encoded:"%2E"}]]);#t;#r;constructor(e,t){this.#t=e,this.#r=Object.freeze(t)}get value(){return this.#t}get elements(){return this.#r}static createFromUrlPath(e,t){if(e==="")return r.EMPTY_PATH;let n=t.separator,s=r.#e.get(n);if(s===void 0)throw new Error("Unsupported separator: "+n);let i=[],o;for(e.charCodeAt(0)===n?(o=1,i.push(s)):o=0;o<e.length;){let a=-1;for(let d=o;d<e.length;d++)if(e.charCodeAt(d)===n){a=d;break}let c=a!==-1?e.substring(o,a):e.substring(o);if(c.length>0&&i.push(t.decodeAndParseParameters?r.#n(c):$e.from(c,s)),a===-1)break;i.push(s),o=a+1}return new r(e,i)}static#n(e){let t=e.indexOf(";");if(t===-1){let n=decodeURIComponent(e);return $e.from(e,n)}else{let n=decodeURIComponent(e.substring(0,t)),s=e.substring(t),i=r.#s(s);return $e.from(e,n,i)}}static#s(e){let t=new Map,n=1;for(;n<e.length;){let s=-1;for(let o=n;o<e.length;o++)if(e.charAt(o)===";"){s=o;break}let i=s!==-1?e.substring(n,s):e.substring(n);if(r.#i(i,t),s===-1)break;n=s+1}if(t.size>0)for(let s of t.values())Object.freeze(s);return t}static#i(e,t){if(e){let n=e.indexOf("=");if(n!==-1){let s=decodeURIComponent(e.substring(0,n));if(s.trim()){let i=e.substring(n+1);for(let o of i.split(",")){let a=t.get(s);a!==void 0?a.push(decodeURIComponent(o)):t.set(s,[decodeURIComponent(o)])}}}else{let s=decodeURIComponent(e);if(s.trim()){let i=t.get(s);i!==void 0?i.push(""):t.set(s,[""])}}}}},$e=class r{static#e=new Map;static from(e,t,n){if(typeof t=="string"){let s=t;return new r(e,s,n)}else{let s=t,i=e.includes(s.encoded)?e.replaceAll(s.encoded,s.value):e;return r.from(e,i,n)}}#t;#r;#n;constructor(e,t,n=r.#e){this.#t=e,this.#r=t,this.#n=n}get value(){return this.#t}get valueToMatch(){return this.#r}get parameters(){return this.#n}};function Tn(r,e){return typeof r=="string"?vr.parse(r,e):Tn(r.href,e)}var vr=class r{static#e(e,t){if(!(t&&t.trim())||t.charAt(0)!=="/")return j("");r.#t(e.value,t);let n=t.length,s=0;for(let i=0;i<e.elements.length;i++){let o=e.elements[i];if(s+=o.value.length,n===s)return Ue(e,0,i+1)}throw new Error(`Failed to initialize context path: '${t}' for request path: '${e.value}'`)}static#t(e,t){let n=t.length;if(t.charAt(0)!=="/"||t.charAt(n-1)==="/")throw new Error(`Invalid context path: '${t}'. Context path must start with '/' and must not end with '/'`);if(!e.startsWith(t))throw new Error(`Invalid context path: '${t}'. Context path must be a prefix of request path: '${e}'`);if(e.length>n&&e.charAt(n)!=="/")throw new Error(`Invalid context path: '${t}'. Context path must match to full path segments for request path: '${e}'`)}static#r(e,t){let n=t.elements.length;return Ue(e,n)}static parse(e,t){let n=j(e),s=r.#e(n,t),i=r.#r(n,s);return new r(j(e),s,i)}#n;#s;#i;constructor(e,t,n){this.#n=e,this.#s=t,this.#i=n}get value(){return this.#n.value}get elements(){return this.#n.elements}get contextPath(){return this.#s}get pathWithinApplication(){return this.#i}modifyContextPath(e){let t=r.#e(this,e),n=r.#r(this,t);return new r(this,t,n)}toString(){return this.#n.toString()}},qe=class extends ot{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=Tn(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var ut=class extends Ar.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},me=class extends Ar.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},lt=class extends at{#e=[];#t;#r="new";#n=[];setStatusCode(e){return this.#r==="committed"?!1:(this.#t=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:dt(e))}get statusCode(){return this.#t}addCookie(e){if(this.#r==="committed")throw new Error(`Cannot add cookie ${JSON.stringify(e)} because HTTP response has already been committed`);return this.#e.push(e),this}beforeCommit(e){this.#n.push(e)}get commited(){let e=this.#r;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let t=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(t))).catch(n=>{throw n})}catch(n){throw n}}async end(){return this.commited?Promise.resolve(!1):this.doCommit(async()=>await this.bodyInternal(Promise.resolve()))}doCommit(e){let t=this.#r,n=Promise.resolve();if(t==="new")this.#r="committing",this.#n.length>0&&(n=this.#n.reduce((s,i)=>s.then(()=>i()),Promise.resolve()).catch(s=>{this.#r==="committing"&&(this.#r="commit-action-failed")}));else if(t==="commit-action-failed")this.#r="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#r="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},ye=class extends qe{#e;#t;#r;constructor(e){super(new Cr(e)),this.#r=e}getNativeRequest(){return this.#r}get upgrade(){return this.#r.upgrade}get http2(){return this.#r.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#r.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#r.method}get host(){let e;return this.#r.httpVersionMajor>=2&&(e=this.#r.headers[":authority"]),e??=this.#r.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#r.httpVersionMajor>2&&(e=this.#r.headers[":scheme"]),e??=this.#r.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#r.socket}get remoteAddress(){let e=this.#r.socket.remoteFamily,t=this.#r.socket.remoteAddress,n=this.#r.socket.remotePort,s=!e||!t||!n?void 0:{family:e,address:t,port:n};return super.parseRemoteAddress(s)??s}initSslInfo(){if(this.#r.socketEncrypted)return new Pr(this.#r.socket)}get cookies(){return this.#t??=super.cookies,this.#t}get body(){return Ar.IncomingMessage.toWeb(this.#r)}async blob(){let e=[];if(this.body!==void 0)for await(let t of this.body)e.push(t);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let t=await(await this.blob()).text();return new URLSearchParams(t)}async json(){let e=await this.blob();if(e.size===0)return;let t=await e.text();return JSON.parse(t)}initId(){let e=this.#r.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#r.socket.remotePort}`}},Pr=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},Cr=class extends De{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.headers[e]!==void 0}get(e){return this.#e.headers[e]}list(e){return super.toList(e)}one(e){let t=this.#e.headers[e];return Array.isArray(t)?t[0]:t}keys(){return Object.keys(this.#e.headers).values()}},xr=class extends De{#e;constructor(e){super(),this.#e=e}has(e){return this.#e.hasHeader(e)}keys(){return this.#e.getHeaderNames().values()}get(e){return this.#e.getHeader(e)}one(e){let t=this.#e.getHeader(e);return Array.isArray(t)?t[0]:t}set(e,t){return this.#e.headersSent||(Array.isArray(t)?t=t.map(n=>typeof n=="number"?String(n):n):typeof t=="number"&&(t=String(t)),t?this.#e.setHeader(e,t):this.#e.removeHeader(e)),this}add(e,t){return this.#e.headersSent||this.#e.appendHeader(e,t),this}list(e){return super.toList(e)}},ht=class extends lt{#e;constructor(e){super(new xr(e)),this.#e=e}getNativeResponse(){return this.#e}get statusCode(){return super.statusCode??{value:this.#e.statusCode}}applyStatusCode(){let e=super.statusCode;e!==void 0&&(this.#e.statusCode=e.value)}addCookie(e){return this.headers.add("Set-Cookie",super.setCookieValue(e)),this}async bodyInternal(e){if(this.#e.headersSent)return!1;if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported in response");{let t=await e;return await new Promise((n,s)=>{try{t===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof t=="string"?this.headers.set("Content-Length",Buffer.byteLength(t)):t instanceof Blob?this.headers.set("Content-Length",t.size):this.headers.set("Content-Length",t.byteLength)),this.#e.end(t,()=>{n(!0)}))}catch(i){s(i instanceof Error?i:new Error(`end failed: ${i}`))}})}}},pt=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get id(){return this.#e.id}get method(){return this.#e.method}get path(){return this.#e.path}get requestPath(){return this.#e.requestPath}get protocol(){return this.#e.protocol}get host(){return this.#e.host}get URL(){return this.#e.URL}get headers(){return this.#e.headers}get cookies(){return this.#e.cookies}get remoteAddress(){return this.#e.remoteAddress}get upgrade(){return this.#e.upgrade}get sslInfo(){return this.#e.sslInfo}get body(){return this.#e.body}async blob(){return await this.#e.blob()}async text(){return await this.#e.text()}async formData(){return await this.#e.formData()}async json(){return await this.#e.json()}toString(){return`${r.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof qe)return e.getNativeRequest();if(e instanceof r)return r.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},be=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}setStatusCode(e){return this.delegate.setStatusCode(e)}setRawStatusCode(e){return this.delegate.setRawStatusCode(e)}get statusCode(){return this.delegate.statusCode}get cookies(){return this.delegate.cookies}addCookie(e){return this.delegate.addCookie(e),this}async end(){return await this.delegate.end()}async body(e){return await this.#e.body(e)}get headers(){return this.#e.headers}toString(){return`${r.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof lt)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},ft=class r{#e;constructor(e){this.#e=e}get delegate(){return this.#e}get request(){return this.#e.request}get response(){return this.#e.response}attribute(e){return this.#e.attribute(e)}get attributes(){return this.#e.attributes}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${r.name} [delegate: ${this.delegate}]`}},gt=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[Mn]=e.id,this.request=e,this.response=t}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes.get(e)}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(Mn);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},Mn="io.interop.web.server.exchange.log_id";import{getHeapStatistics as oi,writeHeapSnapshot as ai}from"node:v8";import{access as ci,mkdir as di,rename as Hn,unlink as ui}from"node:fs/promises";var x=S("monitoring"),li={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function hi(){return oi()}async function kn(r){let e=r.dumpPrefix??"Heap",t=`${r.dumpLocation}/${e}.heapsnapshot`;x.enabledFor("debug")&&x.debug(`starting heap dump in ${t}`),await Rr(r.dumpLocation).catch(async s=>{x.enabledFor("debug")&&x.debug(`dump location ${r.dumpLocation} does not exists. Will try to create it`);try{await di(r.dumpLocation,{recursive:!0}),x.info(`dump location dir ${r.dumpLocation} successfully created`)}catch{x.error(`failed to create dump location ${r.dumpLocation}`)}});let n=ai(t);x.info("heap dumped");try{x.debug("rolling snapshot backups");let s=`${r.dumpLocation}/${e}.${r.maxBackups}.heapsnapshot`;await Rr(s).then(async()=>{x.enabledFor("debug")&&x.debug(`deleting ${s}`);try{await ui(s)}catch(o){x.warn(`failed to delete ${s}`,o)}}).catch(()=>{});for(let o=r.maxBackups-1;o>0;o--){let a=`${r.dumpLocation}/${e}.${o}.heapsnapshot`,c=`${r.dumpLocation}/${e}.${o+1}.heapsnapshot`;await Rr(a).then(async()=>{try{await Hn(a,c)}catch(d){x.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${r.dumpLocation}/${e}.1.heapsnapshot`;try{await Hn(n,i)}catch(o){x.warn(`failed to rename ${n} to ${i}`,o)}x.debug("snapshots rolled")}catch(s){throw x.error("error rolling backups",s),s}}async function Rr(r){x.enabledFor("trace")&&x.debug(`checking file ${r}`),await ci(r)}async function pi(r,e,t){x.enabledFor("debug")&&x.debug(`processing heap stats ${JSON.stringify(r)}`);let n=Math.min(t.memoryLimit,.95*r.heap_size_limit),s=r.used_heap_size;x.info(`heap stats ${JSON.stringify(r)}`),s>=n?(x.warn(`used heap ${s} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await kn(t)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function In(r){let e={...li,...r},t=!1,n={memoryLimitExceeded:!1},s=async()=>{let a=hi();await pi(a,n,e)},i=setInterval(s,e.reportInterval);return{...e,channel:async a=>{if(!t)switch(a??="run",a){case"run":{await s();break}case"dump":{await kn(e);break}case"stop":{t=!0,clearInterval(i),x.info("exit memory diagnostic");break}}return t}}}async function fi({channel:r},e){await r(e)||x.warn(`cannot execute command "${e}" already closed`)}async function Wn(r){return await fi(r,"stop")}var mi=(r,e)=>(e??=r,async({response:t},n)=>{e!==!1&&!t.headers.has("server")&&t.headers.set("Server",e),await n()}),On=(r,e)=>mi(r,e);import{IOGateway as mt}from"@interopio/gateway";var Tr=S("gateway.ws.client-verify");function yi(r){switch(r.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function bi(r,e){let t=r.block??r.blacklist,n=r.allow??r.whitelist;if(t.length>0&&mt.Filtering.valuesMatch(t,e))return Tr.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&mt.Filtering.valuesMatch(n,e))return Tr.enabledFor("debug")&&Tr.debug(`origin ${e} matches allow filter`),!0}function wi(r){switch(r.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Ln(r,e){if(!e)return!0;if(r){let t=bi(e,r);return t||wi(e)}else return yi(e)}function Fn(r){if(r){let e=(r.block??r.blacklist??[]).map(mt.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(mt.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var Dn=r=>async e=>{for(let t of r)if((await t(e)).match)return D();return W},we=r=>{let e=async t=>{for(let n of r)if(!(await n(t)).match)return W;return D()};return e.toString=()=>`and(${r.map(t=>t.toString()).join(", ")})`,e},$n=r=>async e=>(await r(e)).match?W:D(),Se=async r=>D();Se.toString=()=>"any-exchange";var Nn=Object.freeze({}),W=Object.freeze({match:!1,variables:Nn}),D=(r=Nn)=>({match:!0,variables:r}),$=(r,e)=>{let t=e?.method,n=async s=>{let i=s.request,o=i.path;if(t!==void 0&&i.method!==t)return W;if(typeof r=="string")return o===r?D():W;{let a=r.exec(o);return a===null?W:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n},_e=r=>{let e=t=>{if(r.ignoredMediaTypes!==void 0){for(let n of r.ignoredMediaTypes)if(t===n||n==="*/*")return!0}return!1};return async t=>{let n=t.request,s;try{s=n.headers.list("accept")}catch{return W}for(let i of s)if(!e(i)){for(let o of r.mediaTypes)if(i.startsWith(o))return D()}return W}},de=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?D():W;de.toString=()=>"websocket upgrade";import{IOGateway as Un}from"@interopio/gateway";async function Mr(r,e,t){let n=(i,o)=>{if(o?.cors){let a=o.cors===!0?{allowOrigins:o.origins?.allow?.map(Un.Filtering.regexify),allowMethods:i.method===void 0?["*"]:[i.method],allowCredentials:o.authorize?.access!=="permitted"?!0:void 0}:o.cors,c=i.path;t.cors.push([c,a])}},s=new class{handle(...i){i.forEach(({request:o,options:a,handler:c})=>{let d=$(Un.Filtering.regexify(o.path),{method:o.method});a?.authorize&&t.authorize.push([d,a.authorize]),n(o,a);let u=async(h,g)=>{let{match:E,variables:l}=await d(h);E?await c(h,l):await g()};t.middleware.push(u)})}socket(...i){for(let{path:o,factory:a,options:c}of i){let d=o??"/";t.sockets.set(d,{default:o===void 0||o==="/",ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:Fn(c?.origins)})}}};await r(s,e)}import{IOGateway as kr}from"@interopio/gateway";function Ei(r){let e=r.headers.one("origin");if(e===void 0)return!0;let t=r.URL,n=t.protocol,s=t.host,i=URL.parse(e),o=i?.host,a=i?.protocol;return n===a&&s===o}function qn(r){return r.headers.has("origin")&&!Ei(r)}function X(r){return r.method==="OPTIONS"&&r.headers.has("origin")&&r.headers.has("access-control-request-method")}var _n=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],vi=(r,e)=>{let{request:t,response:n}=r,s=n.headers;if(!s.has("Vary"))s.set("Vary",_n.join(", "));else{let o=s.list("Vary");for(let a of _n)o.find(c=>c===a)||o.push(a);s.set("Vary",o.join(", "))}try{if(!qn(t))return!0}catch{return N.enabledFor("debug")&&N.debug("reject: origin is malformed"),Be(n),!1}if(s.has("access-control-allow-origin"))return N.enabledFor("trace")&&N.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let i=X(t);return e?Ci(r,e,i):i?(Be(n),!1):!0},bt=["*"],Hr=["GET","HEAD","POST"],Bn={allowOrigins:bt,allowMethods:Hr,allowHeaders:bt,maxAge:1800};function wt(r){if(r){let e=r.allowHeaders;e&&e!==A&&(r={...r,allowHeaders:e.map(n=>n.toLowerCase())});let t=r.allowOrigins;return t&&(t==="*"?(Vn(r),zn(r)):r={...r,allowOrigins:t.map(n=>typeof n=="string"&&n!==A&&(n=kr.Filtering.regexify(n),typeof n=="string")?jn(n).toLowerCase():n)}),r}}function yt(r,e){if(e===void 0)return r!==void 0?r===A?[A]:r:[];if(r===void 0)return e===A?[A]:e;if(r==bt||r===Hr)return e===A?[A]:e;if(e==bt||e===Hr)return r===A?[A]:r;if(r===A||r.includes(A)||e===A||e.includes(A))return[A];let t=new Set;return r.forEach(n=>t.add(n)),e.forEach(n=>t.add(n)),Array.from(t)}var Ge=(r,e)=>e===void 0?r:{allowOrigins:yt(r.allowOrigins,e?.allowOrigins),allowMethods:yt(r.allowMethods,e?.allowMethods),allowHeaders:yt(r.allowHeaders,e?.allowHeaders),exposeHeaders:yt(r.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??r.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??r.allowPrivateNetwork,maxAge:e?.maxAge??r.maxAge},Pi=r=>{let e=r.corsConfigSource,t=r.corsProcessor??vi;if(e===void 0)throw new Error("corsConfigSource is required");if(t===void 0)throw new Error("corsProcessor is required");return{filter:async(n,s)=>{let i=await e(n);!t(n,i)||X(n.request)||await s.filter(n)}}},Gn=Pi,N=S("cors");function Be(r){r.setStatusCode(b.FORBIDDEN)}function Ci(r,e,t){let{request:n,response:s}=r,i=s.headers,o=n.headers.one("origin"),a=Ai(e,o);if(a===void 0)return N.enabledFor("debug")&&N.debug(`reject: '${o}' origin is not allowed`),Be(s),!1;let c=Mi(n,t),d=Ri(e,c);if(d===void 0)return N.enabledFor("debug")&&N.debug(`reject: HTTP '${c}' is not allowed`),Be(s),!1;let u=Hi(n,t),h=Ti(e,u);if(t&&h===void 0)return N.enabledFor("debug")&&N.debug(`reject: headers '${u}' are not allowed`),Be(s),!1;i.set("Access-Control-Allow-Origin",a),t&&i.set("Access-Control-Allow-Methods",d.join(",")),t&&h!==void 0&&h.length>0&&i.set("Access-Control-Allow-Headers",h.join(", "));let g=e.exposeHeaders;return g&&g.length>0&&i.set("Access-Control-Expose-Headers",g.join(", ")),e.allowCredentials&&i.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&i.set("Access-Control-Allow-Private-Network","true"),t&&e.maxAge!==void 0&&i.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var A="*",xi=["GET","HEAD"];function Vn(r){if(r.allowCredentials===!0&&r.allowOrigins===A)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function zn(r){if(r.allowPrivateNetwork===!0&&r.allowOrigins===A)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Ai(r,e){if(e){let t=r.allowOrigins;if(t){if(t===A)return Vn(r),zn(r),A;let n=jn(e.toLowerCase());for(let s of t)if(s===A||kr.Filtering.valueMatches(s,n))return e}}}function Ri(r,e){if(e){let t=r.allowMethods??xi;if(t===A)return[e];if(kr.Filtering.valuesMatch(t,e))return t}}function Ti(r,e){if(e===void 0)return;if(e.length==0)return[];let t=r.allowHeaders;if(t===void 0)return;let n=t===A||t.includes(A),s=[];for(let i of e){let o=i?.trim();if(o){if(n)s.push(o);else for(let a of t)if(o.toLowerCase()===a){s.push(o);break}}}if(s.length>0)return s}function jn(r){return r.endsWith("/")?r.slice(0,-1):r}function Mi(r,e){return e?r.headers.one("access-control-request-method"):r.method}function Hi(r,e){let t=r.headers;return e?t.list("access-control-request-headers"):Array.from(t.keys())}var Xn=r=>async e=>{for(let[t,n]of r.mappings)if((await t(e)).match)return N.debug(`resolved cors config on '${e.request.path}' using ${t}: ${JSON.stringify(n)}`),n};import{IOGateway as ki}from"@interopio/gateway";function Jn(r){let{sockets:e,cors:t}=r,n=r.corsConfig===!1?void 0:Ge(Bn,r.corsConfig),s=[];for(let[o,a]of e){let c=n;for(let[u,h]of t)ki.Filtering.valueMatches(u,o)&&(h===void 0?c=void 0:c=c===void 0?h:Ge(c,h));let d=r.corsConfig===!1?void 0:{allowOrigins:a.originFilters?.allow,allowMethods:["GET","CONNECT","OPTIONS"],allowHeaders:["Upgrade","Connection","Origin","Sec-Websocket-Key","Sec-Websocket-Version","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],exposeHeaders:["Sec-Websocket-Accept","Sec-Websocket-Protocol","Sec-Websocket-Extensions"],allowCredentials:a.authorize?.access!=="permitted"?!0:void 0};c=c===void 0?d:Ge(c,d),s.push([we([de,$(o)]),wt(c)])}let i=[];for(let[o,a]of t){let[,c]=i.find(([u])=>String(u)===String(o))??[o,n];c=c===void 0?a:Ge(c,a);let d=!1;for(let u of i)if(String(u[0])===String(o)){u[1]=c,d=!0;break}d||i.push([o,c])}for(let[o,a]of i)s.push([$(o),wt(a)]);return s.push([$(/\/api\/.*/),wt(n)]),Xn({mappings:s})}function Yn(r){return r!==void 0&&typeof r.type=="string"&&typeof r.authenticated=="boolean"}var I=class extends Error{_authentication;get authentication(){return this._authentication}set authentication(e){if(e===void 0)throw new TypeError("Authentication cannot be undefined");this._authentication=e}},St=class extends I{},Ee=class extends I{},ve=class extends I{constructor(e){super(e)}},Ve=class extends ve{constructor(e){super(e)}},ze=class extends ve{constructor(e){super(e)}},je=class extends ve{constructor(e){super(e)}},Xe=class extends ve{constructor(e){super(e)}};var ue=class extends Error{},J=class{constructor(e){this.granted=e}granted},ne=class{#e;constructor(e){this.#e=e}async verify(e,t){if(!(await this.#e(e,t))?.granted)throw new ue("Access denied")}async authorize(e,t){return await this.#e(e,t)}},Pe=class extends I{};var U=r=>async e=>{let t=!0,{response:n}=e;for(let s of r.keys())n.headers.has(s)&&(t=!1);if(t)for(let[s,i]of r)n.headers.set(s,i)},Ii=()=>U(new R().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Wi=()=>U(new R().add("x-content-type-options","nosniff")),Oi=(r,e,t)=>{let n=`max-age=${r}`;e&&(n+=" ; includeSubDomains"),t&&(n+=" ; preload");let s=U(new R().add("strict-transport-security",n)),i=o=>o.request.URL.protocol==="https:";return async o=>{i(o)&&await s(o)}},Li=r=>U(new R().add("x-frame-options",r)),Fi=r=>U(new R().add("x-xss-protection",r)),Di=r=>{let e=r===void 0?void 0:U(new R().add("permissions-policy",r));return async t=>{e!==void 0&&await e(t)}},$i=(r,e)=>{let t=e?"content-security-policy-report-only":"content-security-policy",n=r===void 0?void 0:U(new R().add(t,r));return async s=>{n!==void 0&&await n(s)}},Ni=(r="no-referrer")=>U(new R().add("referer-policy",r)),Ui=r=>{let e=r===void 0?void 0:U(new R().add("cross-origin-opener-policy",r));return async t=>{e!==void 0&&await e(t)}},qi=r=>{let e=r===void 0?void 0:U(new R().add("cross-origin-embedder-policy",r));return async t=>{e!==void 0&&await e(t)}},_i=r=>{let e=r===void 0?void 0:U(new R().add("cross-origin-resource-policy",r));return async t=>{e!==void 0&&await e(t)}},Bi=(...r)=>async e=>{for(let t of r)await t(e)};function Ir(r){let e=[];r?.cache?.disabled||e.push(Ii()),r?.contentType?.disabled||e.push(Wi()),r?.hsts?.disabled||e.push(Oi(r?.hsts?.maxAge??365*24*60*60,r?.hsts?.includeSubDomains??!0,r?.hsts?.preload??!1)),r?.frameOptions?.disabled||e.push(Li(r?.frameOptions?.mode??"DENY")),r?.xss?.disabled||e.push(Fi(r?.xss?.headerValue??"0")),r?.permissionsPolicy?.disabled||e.push(Di(r?.permissionsPolicy?.policyDirectives)),r?.contentSecurityPolicy?.disabled||e.push($i(r?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",r?.contentSecurityPolicy?.reportOnly)),r?.refererPolicy?.disabled||e.push(Ni(r?.refererPolicy?.policy??"no-referrer")),r?.crossOriginOpenerPolicy?.disabled||e.push(Ui(r?.crossOriginOpenerPolicy?.policy)),r?.crossOriginEmbedderPolicy?.disabled||e.push(qi(r?.crossOriginEmbedderPolicy?.policy)),r?.crossOriginResourcePolicy?.disabled||e.push(_i(r?.crossOriginResourcePolicy?.policy)),r?.writers&&e.push(...r.writers);let t=Bi(...e);return{filter:async(n,s)=>(await t(n),s.filter(n))}}var Ce=r=>{let e=r.entryPoint,t=r?.rethrowAuthenticationServiceError??!0;return async({exchange:n},s)=>{if(!t||!(s instanceof Pe))return e(n,s);throw s}};var Gi="Realm",Vi=r=>`Basic realm="${r}"`,xe=r=>{let e=Vi(r?.realm??Gi);return async(t,n)=>{let{response:s}=t;s.setStatusCode(b.UNAUTHORIZED),s.headers.set("WWW-Authenticate",e)}};var Kn="Basic ",Et=r=>{let e=r?.credentialsEncoding??"utf-8";return async t=>{let{request:n}=t,s=n.headers.one("authorization");if(!s||!/basic/i.test(s.substring(0)))return;let i=s.length<=Kn.length?"":s.substring(Kn.length),a=Buffer.from(i,"base64").toString(e).split(":",2);if(a.length!==2)return;let c=a[0],d=a[1];return{type:"UsernamePassword",authenticated:!1,principal:c,credentials:d,name:c,eraseCredentials:()=>{d=null}}}};import{AsyncLocalStorage as zi}from"node:async_hooks";var se=class r{static hasSecurityContext(e){return e.getStore()?.securityContext!==void 0}static async getSecurityContext(e){return await e.getStore()?.securityContext}static clearSecurityContext(e){delete e.getStore()?.securityContext}static withSecurityContext(e){return(t=new zi)=>(t.getStore().securityContext=e,t)}static withAuthentication(e){return r.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(r.hasSecurityContext(e))return r.getSecurityContext(e)}};async function ji(r,e,t,n,s,i){let a=await(await n(r))?.(t);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await Xi(a,{exchange:r,chain:e},s,i)}catch(c){throw c instanceof I,c}}async function Xi(r,e,t,n){se.withAuthentication(r)(n),await t(e,r)}function ie(r){let e={matcher:Se,successHandler:async({exchange:n,chain:s})=>{await s.filter(n)},converter:Et({}),failureHandler:Ce({entryPoint:xe({})}),...r},t=e.managerResolver;if(t===void 0&&e.manager!==void 0){let n=e.manager;t=async s=>n}if(t===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return{filter:async(n,s)=>{let o=(await e.matcher(n)).match?await e.converter(n):void 0;if(o===void 0){await s.filter(n);return}try{await ji(n,s,o,t,e.successHandler,e.storage)}catch(a){if(a instanceof I){await e.failureHandler({exchange:n,chain:s},a);return}throw a}}}}var Qn=r=>async(e,t)=>{e.response.setStatusCode(r.httpStatus)};var Ae=S("auth.entry-point"),vt=r=>{let e=r.defaultEntryPoint??(async({response:t},n)=>{t.setStatusCode(b.UNAUTHORIZED),await t.end()});return async(t,n)=>{for(let[s,i]of r.entryPoints)if(Ae.enabledFor("debug")&&Ae.debug(`trying to match using: ${s}`),(await s(t)).match)return Ae.enabledFor("debug")&&Ae.debug(`match found. using default entry point ${i}`),i(t,n);return Ae.enabledFor("debug")&&Ae.debug(`no match found. using default entry point ${e}`),e(t,n)}};var Zn=r=>async({exchange:e,chain:t},n)=>{for(let s of r)await s({exchange:e,chain:t},n)};function Wr(r){let e=async g=>g.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?D():W,t=vt({entryPoints:[[e,Qn({httpStatus:b.UNAUTHORIZED})]],defaultEntryPoint:xe({})}),n=r.entryPoint??t,s=r.manager,i=_e({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),o=$n(_e({mediaTypes:["text/html"]})),a=we([o,i]),c=Dn([e,a]);r.defaultEntryPoints.push([c,n]);let d=r.failureHandler??Ce({entryPoint:n}),u=Zn(r.successHandlers??r.defaultSuccessHandlers),h=Et({});return ie({storage:r.storage,manager:s,failureHandler:d,successHandler:u,converter:h})}var es={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},ts="https://tools.ietf.org/html/rfc6750#section-3.1";function Pt(r){return{errorCode:es.invalid_token,httpStatus:b.UNAUTHORIZED,description:r,uri:ts}}function Or(r){return{errorCode:es.invalid_request,httpStatus:b.BAD_REQUEST,description:r,uri:ts}}var Ji="access_token",Yi=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,_=class extends I{error;constructor(e,t,n){super(t??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},rs=r=>r.type==="BearerToken",Ki=r=>async e=>{let{request:t}=e;return Promise.all([Zi(t.headers,r?.headerName).then(n=>n!==void 0?[n]:void 0),eo(t,r?.uriQueryParameter),to(e,r?.formEncodedBodyParameter)]).then(n=>n.filter(s=>s!==void 0).flat(1)).then(Qi).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function Qi(r){if(r.length===0)return;if(r.length>1){let t=Or("Found multiple access tokens in the request");throw new _(t)}let e=r[0];if(!e||e.length===0){let t=Or("The requested access token parameter is an empty string");throw new _(t)}return e}async function Zi(r,e="authorization"){let t=r.one(e);if(!t||!/bearer/i.test(t.substring(0)))return;let n=Yi.exec(t);if(n===null){let s=Pt("Bearer token is malformed");throw new _(s)}return n.groups?.token}async function ns(r){let e=r.getAll(Ji);if(e.length!==0)return e}async function eo(r,e=!1){if(!(!e||r.method!=="GET"))return ns(r.URL.searchParams)}async function to(r,e=!1){let{request:t}=r;if(!e||t.headers.one("content-type")!=="application/x-www-form-urlencoded"||t.method!=="POST")return;let n=await r.request.formData();if(n)return ns(n)}var Ct=Ki;function ro(r){let e="Bearer";if(r.size!==0){e+=" ";let t=0;for(let[n,s]of r)e+=`${n}="${s}"`,t!==r.size-1&&(e+=", "),t++}return e}var ss=r=>r.httpStatus!==void 0;function no(r){if(r instanceof _){let{error:e}=r;if(ss(e))return e.httpStatus}return b.UNAUTHORIZED}function so(r,e){let t=new Map;if(e&&t.set("realm",e),r instanceof _){let{error:n}=r;t.set("error",n.errorCode),n.description&&t.set("error_description",n.description),n.uri&&t.set("error_uri",n.uri),ss(n)&&n.scope&&t.set("scope",n.scope)}return t}var io=r=>async(e,t)=>{let n=no(t),s=so(t,r?.realmName),i=ro(s),{response:o}=e;o.headers.set("WWW-Authenticate",i),o.setStatusCode(n),await o.end()},xt=io;var oo=r=>{let e=r?.principalClaimName??"sub";return t=>({type:"JwtToken",authenticated:!0,name:t.getClaimAsString(e)})},ao=r=>async e=>r(e),Re=class extends Error{},Je=class extends Re{};function co(r){if(r instanceof Je)return new _(Pt(r.message),r.message,{cause:r});throw new Pe(r.message,{cause:r})}function Lr(r){let e=r.decoder,t=r.authConverter??ao(oo({}));return async n=>{if(rs(n)){let s=n.token;try{let i=await e(s);return await t(i)}catch(i){throw i instanceof Re?co(i):i}}}}function Fr(r){let e=r.entryPoint??xt({}),t=r?.converter??Ct({}),n=r.failureHandler??Ce({entryPoint:e});if(r.managerResolver!==void 0)return ie({storage:r.storage,converter:t,failureHandler:n,managerResolver:r.managerResolver});if(r.jwt!==void 0){let s=r.jwt.manager??Lr(r.jwt);return ie({storage:r.storage,converter:t,failureHandler:n,managerResolver:async i=>s})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}import{jwtVerifier as go,JwtVerifyError as mo}from"@interopio/gateway/jose/jwt";async function is(r,e,t){let n=new St("Full authentication is required to access this resource."),s=new I("Access Denied",{cause:n});e&&(s.authentication=e),await t(r,s)}function uo(r){return async(e,t)=>{e.response.setStatusCode(r),e.response.headers.set("Content-Type","text/plain; charset=utf-8");let n=Buffer.from("Access Denied","utf-8");e.response.headers.set("Content-Length",n.length),await e.response.body(n)}}var os=r=>{let e=uo(b.FORBIDDEN),t=r.authenticationEntryPoint??xe();return{filter:async(n,s)=>{try{await s.filter(n)}catch(i){if(i instanceof ue){let o=await n.principal();Yn(o)?(o.authenticated||await e(n,i),await is(n,o,t)):await is(n,void 0,t);return}throw i}}}};var lo=S("security.auth");function Dr(r){let e=async(t,n)=>{let s;for(let[i,o]of r.mappings)if((await i(n))?.match){lo.debug(`checking authorization on '${n.request.path}' using [${i}, ${o}]`);let a=await o.authorize(t,{exchange:n});if(a!==void 0){s=a;break}}return s??=new J(!1),s};return new ne(e)}var At=S("security.auth");function $r(r){let{manager:e,storage:t}=r;return{filter:async(n,s)=>{let i=se.getContext(t).then(o=>o?.authentication);try{await e.verify(i,n),At.enabledFor("debug")&&At.debug("authorization successful")}catch(o){throw o instanceof ue&&At.enabledFor("debug")&&At.debug(`authorization failed: ${o.message}`),o}await s.filter(n)}}}var Nr=class extends ft{#e;constructor(e,t){super(e),this.#e=t}async principal(){return(await this.#e())?.authentication}},as=r=>{let e=r.storage;return{filter:async(t,n)=>{await n.filter(new Nr(t,async()=>await se.getContext(e)))}}};var cs=r=>{let{principalExtractor:e}=r;return async t=>{let n=t.request.sslInfo;if(n===void 0||n.peerCertificate===void 0)return;let s=n.peerCertificate,i=e(s);return{type:"PreAuthenticated",authenticated:!1,principal:i,name:i??"",credentials:s}}};var Rt=r=>{let e=r?.principalAltName==="email",t=/CN=(.*?)(?:,|$)/mi;return n=>{if(e){let o=n.subjectAltName?.split(", ").find(a=>a.startsWith("email:"));if(o)return o.replace("email:","")}let s=t.exec(n.subject);if(s===null)throw new Ee(`Cannot extract principal from subject DN: ${n.subject}`);return s[1]}};var le=class{async encode(e){if(e!=null)return await this.encodeDefinedPassword(e.toString())}async matches(e,t){return!e||!t?!1:await this.matchesDefined(e.toString(),t)}upgradeEncoding(e){return e?this.upgradeEncodingDefined(e):!1}upgradeEncodingDefined(e){return!1}},Te=class r extends le{static DEFAULT_ID_PREFIX="{";static DEFAULT_ID_SUFFIX="}";#e;#t;#r;#n;#s;#i=new class extends le{#d;constructor(e){super(),this.#d=e}async encodeDefinedPassword(e){throw new Error("encode is not supported")}async matchesDefined(e,t){let n=this.#d.#o(t);if(!n)throw new Error(`No password encoder mapped for id ${n}`);if(t){let s=t.indexOf(this.#d.#e),i=t.indexOf(this.#d.#t,s+this.#d.#e.length);if(s===-1&&i===-1)throw new Error("No prefix found in encoded password")}throw new Error("malformed password encoder prefix")}}(this);constructor(e,t,n=r.DEFAULT_ID_PREFIX,s=r.DEFAULT_ID_SUFFIX){if(e==null)throw new Error("idForEncode cannot be null or undefined");if(n==null)throw new Error("idPrefix cannot be null or undefined");if(!s)throw new Error("idSuffix cannot be empty");if(n.indexOf(s)!==-1)throw new Error(`idPrefix "${n}" cannot contain idSuffix "${s}"`);if(!t.has(e))throw new Error(`No PasswordEncoder mapped for id "${e}"`);for(let i of t.keys())if(i!==null){if(n&&i.includes(n))throw new Error(`id "${i}" cannot include ${n}`);if(s&&i.includes(s))throw new Error(`id "${i}" cannot include ${s}`)}super(),this.#r=e,this.#n=t.get(e),this.#s=new Map(t),this.#e=n,this.#t=s}set defaultPasswordEncoderForMatches(e){if(e==null)throw new Error("defaultPasswordEncoderForMatches cannot be null or undefined");this.#i=e}async encodeDefinedPassword(e){let t=await this.#n.encode(e);return`${this.#e}${this.#r}${this.#t}${t}`}async matchesDefined(e,t){let n=this.#o(t),s=n?this.#s.get(n):void 0;if(s===void 0)return await this.#i.matches(e,t);{let i=this.#c(t);return await s.matches(e,i)}}#o(e){if(e===void 0)return;let t=e.indexOf(this.#e);if(t!==0)return;let n=e.indexOf(this.#t,t+this.#e.length);if(n!==-1)return e.substring(t+this.#e.length,n)}upgradeEncodingDefined(e){let t=this.#o(e);if(this.#r!==t)return!0;{let n=this.#c(e);return this.#n.upgradeEncoding?.(n)??!1}}#c(e){let t=e.indexOf(this.#t);return e.substring(t+this.#t.length)}},Tt=class r extends le{static#e=new r;static get instance(){return r.#e}constructor(){super()}async encodeDefinedPassword(e){return e.toString()}async matchesDefined(e,t){return e.toString()===t}};import{argon2 as L,keygen as ho}from"@interopio/gateway-server/tools";function po(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Mt=class extends le{#e;#t;#r;#n;#s;constructor(e=L.DEFAULT_SALT_LENGTH,t=L.DEFAULT_HASH_LENGTH,n=L.DEFAULT_PARALLELISM,s=L.DEFAULT_MEMORY,i=L.DEFAULT_PASSES){super(),this.#e=e,this.#t=t,this.#r=n,this.#n=s,this.#s=i}async matchesDefined(e,t){try{let n=L.decode(t),s=await L.createHash(n.algorithm,e,n.hash.length,n.parameters);return po(n.hash,s)}catch{return!1}}async encodeDefinedPassword(e){let t=ho.createSalt(this.#e),n={memory:this.#n,passes:this.#s,parallelism:this.#r,nonce:t},s=await L.createHash("argon2id",e,this.#t,n);return L.encode({algorithm:"argon2id",version:L.ARGON2_VERSION,parameters:n,hash:s})}upgradeEncodingDefined(e){let t=L.decode(e);return t.version<L.ARGON2_VERSION||t.parameters.memory<this.#n||t.parameters.passes<this.#s}};var Ur=4096;function ds(){let r="argon2id",e=new Map([[r,new Mt],["noop",Tt.instance]]);return new Te(r,e,Te.DEFAULT_ID_PREFIX,Te.DEFAULT_ID_SUFFIX)}var us={async updatePassword(r,e){return r}},Ht=class extends I{username;constructor(e,t,n){super(e,n),this.username=t}},kt=class r{#e;#t;#r=[];#n;#s;#i;#o;#c=e=>e;constructor(){}static ofUsername(e){return new r().username(e)}static ofUserDetails(e){let t=r.ofUsername(e.username).accountExpired(e.accountExpired??!1).accountLocked(e.accountLocked??!1).authorities(e.authorities).credentialsExpired(e.credentialsExpired??!1).disabled(e.disabled??!1);return e.password!==void 0&&t.password(e.password),t}username(e){if(!e)throw new TypeError("username cannot be empty");return this.#e=e,this}password(e){return this.#t=e,this}passwordEncoder(e){if(!e)throw new TypeError("password encoder cannot be null or undefined");return this.#c=e,this}roles(...e){return this.authorities(e.map(t=>{if(t.startsWith("role:"))throw new Error(`${t} must not start with 'role:' (it is automatically added)`);return{authority:`role:${t}`}}))}authorities(e){return this.#r=[...e],this}accountExpired(e){return this.#n=e,this}accountLocked(e){return this.#s=e,this}credentialsExpired(e){return this.#i=e,this}disabled(e){return this.#o=e,this}build(){if(!this.#e)throw new TypeError("username is required");let e=this.#t!==void 0?this.#c(this.#t):void 0;return{username:this.#e,password:e,authorities:this.#r,accountExpired:this.#n,accountLocked:this.#s,credentialsExpired:this.#i,disabled:this.#o,eraseCredentials(){e=null},toString(){return`User(username=${this.username}, password=[PROTECTED], authorities=${JSON.stringify(this.authorities)}, accountExpired=${this.accountExpired}, accountLocked=${this.accountLocked}, credentialsExpired=${this.credentialsExpired}, disabled=${this.disabled})`}}}};var oe=S("security.users");function ls(r,e){let t=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw oe.debug("user account is locked"),new Ve("User account is locked");if(a.disabled)throw oe.debug("user account is disabled"),new ze("User is disabled");if(a.accountExpired)throw oe.debug("user account is expired"),new je("User account has expired")}),n=e?.postAuthenticationChecks??(a=>{if(a.credentialsExpired)throw oe.debug("user credentials have expired"),new Xe("User credentials have expired")}),s=e?.passwordEncoder??ds(),i=e?.userDetailsPasswordService??us,o=async(a,c)=>{let d=a.password;if(d!==void 0&&s.upgradeEncoding?.(d)){let h=await s.encode(c);return await i.updatePassword(a,h)}return a};return async a=>{let c=a.name,d=a.credentials!==void 0&&a.credentials!==null?a.credentials.toString():void 0,u=await r.findByUsername(c);if(!u)throw new Error(`User not found: ${c}`);if(t(u),!await s.matches(d,u.password))throw new Ee("Invalid Credentials");let h=await o(u,d);n(h);let g=h.password;return{type:"UsernamePassword",principal:h,credentials:g,authorities:h.authorities,authenticated:!0,name:h.username,eraseCredentials(){g=null}}}}function fo(){return r=>{if(r.accountLocked)throw oe.debug("failed to authenticate since user account is locked"),new Ve("User account is locked");if(r.disabled)throw oe.debug("failed to authenticate user account is disabled"),new ze("User is disabled");if(r.accountExpired)throw oe.debug("failed to authenticate since user account is expired"),new je("User account has expired");if(r.credentialsExpired)throw oe.debug("failed to authenticate since user credentials have expired"),new Xe("User credentials have expired")}}function hs(r){let e=r.userDetailsService,t=r.userDetailsChecker??fo(),n=s=>s.type==="PreAuthenticated"&&s.name!==void 0;return async s=>{let i=n(s)&&await e.findByUsername(s.name);if(!i)throw new Ht("user not found",s.name);t(i);let o=s.credentials;return{type:"PreAuthenticated",principal:i,credentials:o,authorities:i.authorities,authenticated:!0,details:i,name:i.username,eraseCredentials(){o=null}}}}function qr(r){let e=r.manager??hs({userDetailsService:r.getService("UserDetailsService")}),t=r.extractor??Rt(),n=r.converter??cs({principalExtractor:t});return ie({storage:r.storage,manager:e,converter:n})}var It=class{#e;constructor(e){if(e==null)throw new Error("delegate must not be null or undefined");this.#e=e}get delegate(){return this.#e}async handle(e){return await this.#e.handle(e)}toString(){return`WebHandlerDecorator[delegate=${this.#e}]`}},Wt=class extends It{#e;constructor(e,...t){super(e),this.#e=[...t],Object.freeze(this.#e)}get errorHandlers(){return this.#e}handle(e){let t;try{t=super.handle(e)}catch(n){t=Promise.reject(n)}for(let n of this.#e)t=t.catch(async s=>{let i=s instanceof Error?s:new Error(String(s));await n.handle(e,i)});return t}},Ye=class r{#e;#t;#r;#n;static of(e,...t){let n=[...t],s=new r(t,e),i=r.initChain(t,e);return s.#r=i.#r,s.#n=i.#n,s}static initChain(e,t){let n=new r(e,t,void 0,void 0);for(let s of[...e].reverse())n=new r(e,t,s,n);return n}constructor(e,t,n,s){this.#e=e,this.#t=t,this.#r=n,this.#n=s}get filters(){return this.#e}get handler(){return this.#t}async filter(e){this.#r!==void 0&&this.#n!==void 0?await this.#s(this.#r,this.#n,e):await this.#t.handle(e)}#s(e,t,n){return e.filter(n,t)}},Ot=class extends It{#e;constructor(e,...t){super(e),this.#e=Ye.of(e,...t)}get filters(){return this.#e.filters}handle(e){return this.#e.filter(e)}};var Lt=class{#e;#t=new Br;#r=new _r;#n=new Vr;constructor(...e){this.#e=[...e]}async filter(e,t){let n=await this.#t.firewalledExchange(e);try{await this.#s(n,t)}catch(s){if(s instanceof Gr)await this.#n.handle(e,s);else throw s}}async#s(e,t){for(let n of this.#e)if(await n.matches(e)){let s=await n.webFilters();await this.#r.decorate(t,s).filter(e);return}await this.#r.decorate(t).filter(e)}set firewall(e){if(!e)throw new Error("firewall must be provided");this.#t=e}set decorator(e){if(!e)throw new Error("decorator must be provided");this.#r=e}set exchangeRejectedHandler(e){if(!e)throw new Error("handler must be provided");this.#n=e}},_r=class{decorate(e,t){return t=t||[],Ye.of({handle:n=>e.filter(n)},...t)}},Ft=class{#e;#t;constructor(e,...t){this.#e=e,this.#t=t}async matches(e){return(await this.#e(e))?.match===!0}async webFilters(){return this.#t}},Br=class{async firewalledExchange(e){return e}},Gr=class extends Error{constructor(e){super(e),this.name="ServerExchangeRejectedError"}},Vr=class{#e;constructor(e=b.BAD_REQUEST){this.#e=e}async handle(e,t){e.response.setStatusCode(this.#e)}};var B={first:Number.MAX_SAFE_INTEGER,http_headers:100,https_redirect:200,cors:300,http_basic:600,authentication:800,security_context_server_web_exchange:1500,error_translation:1800,authorization:1900,last:Number.MAX_SAFE_INTEGER},G=Symbol.for("filterOrder"),ps=(r,e)=>{let t=(a,c)=>{if(e===void 0)return c;if(a==="UserDetailsService"&&e.userDetailsService!==void 0)return e.userDetailsService;if(a==="AuthenticationManager"&&e.authenticationManager!==void 0)return e.authenticationManager;if(c!==void 0)return c;throw new Error(`No service registered with name: ${a}`)},n=()=>{if(e.authenticationManager!==void 0)return e.authenticationManager;if(e.userDetailsService!==void 0)return ls(e.userDetailsService,{userDetailsPasswordService:e.userDetailsPasswordService})},s=[];class i{#e;#t=[];#r;set authenticationManager(c){this.#r=c}get authenticationEntryPoint(){return this.#e!==void 0||this.#t.length===0?this.#e:this.#t.length===1?this.#t[0][1]:vt({entryPoints:this.#t,defaultEntryPoint:this.#t[this.#t.length-1][1]})}build(){if(r.headers!==void 0&&r.headers.disabled!==!0){let d=Ir(r.headers);d[G]=B.http_headers,s.push(d)}if(r.x509!==void 0&&r.x509.disabled!==!0){let d=qr({storage:e.storage,getService:t,extractor:Rt({principalAltName:r.x509.principalAltName})});d[G]=B.authentication,s.push(d)}if(r.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=Gn({corsConfigSource:e.corsConfigSource});d[G]=B.cors,s.push(d)}if(r.basic!==void 0&&r.basic?.disabled!==!0){let d=[async({exchange:h,chain:g},E)=>await g.filter(h)],u=Wr({storage:e.storage,manager:this.#r,defaultEntryPoints:this.#t,defaultSuccessHandlers:d});u[G]=B.http_basic,s.push(u)}if(r.jwt!==void 0&&r.jwt.disabled!==!0){let d=go({issuerBaseUri:r.jwt.issuerUri,issuer:r.jwt.issuer,audience:r.jwt.audience}),u=async p=>{try{let{payload:f}=await d(p);return{tokenValue:p,subject:f.sub,getClaimAsString(w){return f[w]}}}catch(f){throw f instanceof mo?new Je(f.message,{cause:f}):new Re("error occurred while attempting to decoding jwt",{cause:f})}},h=Ct({uriQueryParameter:!0}),g=async p=>{try{return await h(p)===void 0?W:D()}catch{return W}},E=xt({});this.#t.push([g,E]);let l=Fr({storage:e.storage,entryPoint:E,converter:h,jwt:{decoder:u}});l[G]=B.authentication,s.push(l)}let c=as({storage:e.storage});if(s.push(c),c[G]=B.security_context_server_web_exchange,r.authorize!==void 0){let d=os({authenticationEntryPoint:this.authenticationEntryPoint});d[G]=B.error_translation,s.push(d);let h=(E=>{let l=[],p=!1;for(let[f,w]of E??[]){let m;if(f==="any-exchange")p=!0,m=Se;else{if(p)throw new Error("Cannot register other matchers after 'any-exchange' matcher");m=f}let y;if(w.access==="permitted")y=new ne(async()=>new J(!0)),y.toString=()=>"AuthorizationManager[permitted]";else if(w.access==="denied")y=new ne(async()=>new J(!1)),y.toString=()=>"AuthorizationManager[denied]";else if(w.access==="authenticated")y=new ne(async v=>{let P=await v;return P!==void 0?new J(P.authenticated):new J(!1)}),y.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(w)}`);l.push([m,y])}return Dr({mappings:l})})(r.authorize),g=$r({manager:h,storage:e.storage});g[G]=B.authorization,s.push(g)}s.sort((d,u)=>{let h=d[G]??B.last,g=u[G]??B.last;return h-g})}}let o=new i;return o.authenticationManager=n(),o.build(),new Ft(Se,...s)};var Dt=class{#e=new Map;constructor(...e){for(let t of e)this.#e.set(this.#t(t.username),t)}async findByUsername(e){let t=this.#t(e),n=this.#e.get(t);return n!==void 0?{...n}:void 0}async updatePassword(e,t){let n={...e,password:t};if(n){let s=this.#t(e.username);this.#e.set(s,n)}return n}#t(e){return e.toLowerCase()}};import{randomUUID as yo}from"node:crypto";var $t=S("auth");function bo(r){let e=[],t=r.authConfig?.type,n={access:t!=="none"?"authenticated":"permitted"};$t.enabledFor("info")&&$t.info(`using auth type: ${t??"none"}, default access: ${n.access}`);for(let[s,i]of r.sockets){let o=i.authorize??n,a=$(s,{method:"GET"});a=we([de,a]),e.push([a,o])}return e.push([$("/",{method:"GET"}),{access:"permitted"}]),e.push([$("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([$("/health",{method:"GET"}),{access:"permitted"}]),r.authorize.length>0&&e.push(...r.authorize),e.push(["any-exchange",n]),{authorize:e,cors:{disabled:r.corsConfig===!1},x509:{disabled:t!=="x509",...r.authConfig?.x509},basic:{disabled:t!=="basic",...r.authConfig?.basic},jwt:{disabled:t!=="oauth2",...r.authConfig?.oauth2?.jwt}}}function wo(r){if(r.authConfig?.type==="none")return;function e(o,a){if(r.authConfig?.type==="x509")return null;let c=o.password;if(c===void 0){let d=yo().replaceAll("-","");$t.enabledFor("info")&&$t.info(`
|
|
14
14
|
|
|
15
15
|
using generated password: ${d}
|
|
16
16
|
|
|
17
17
|
This generated password is for development only. Your authentication configuration should be updated before running in production.
|
|
18
|
-
`),c=d}if(c.length>Dr)throw new Error(`Password length exceeds maximum length of ${Dr} characters`);return a!=null||/^\{.+}.*$/.test(c)?c:`{noop}${c}`}let t={name:"dev-user",roles:[],...r.authConfig?.user},n=e(t),s=t.roles,i=Ht.ofUsername(t.name).password(n).roles(...s).build();return new Lt(i)}async function ls(r){let e=zn(r),t=po(r),n=fo(r),{storage:s}=r;return us(t,{storage:s,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}var Dt=class extends ye{};import{WebSocketServer as mo}from"ws";function hs(r,e){let t=r?.exchange,n=t?.request??new me(r),s=t?.principal,i=s?s.bind(t):async function(){},o=n.URL,a=new x;for(let m of n.headers.keys())a.set(m,n.headers.list(m));let c=n.cookies,d=t?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:o,headers:a,cookies:c,principal:i,protocol:e,remoteAddress:u,logPrefix:d}}function ps(r){return[async(t,n)=>{let i=t.request.path??"/",o=r.sockets,a=o.get(i)??Array.from(o.values()).find(c=>{if(i==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=t,u=await ce(t);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(t);return}else throw new Error(`No upgrade strategy defined for route on ${i}`);else{if(a.default){await n();return}d.setStatusCode(y.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let f=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(f)}}else await n()}]}import{WebSocket as go}from"ws";var $t=class extends go{constructor(e,t,n){super(null,void 0,n)}connected},Ut=class r{static#e=Buffer.alloc(0);static#t=[0,Buffer.alloc(8)];#r;#n;#s;#i=!1;#o;constructor(e,t,n){this.#o=e,this.#n=typeof n=="number"?n:n?.interval,this.#r=typeof n=="number"||n?.data==="timestamp"?()=>r.#a(Date.now()):()=>r.#e,this.#n&&(this.#s=setInterval(()=>{let[s,i]=t();for(let o of i)this.#c(o,s)||this.#d(o,s)},this.#n))}#c(e,t){return e.connected===!1?(this.#o.enabledFor("debug")&&this.#o.debug(`terminating unresponsive ws client on [${t}]`),e.terminate(),!0):!1}#d(e,t){e.connected=!1;let n=this.#r();this.#o.enabledFor("trace")&&this.#o.debug(`pinging ws client on [${t}]`),e.ping(n,this.#i,s=>{s&&this.#o.enabledFor("warn")&&this.#o.warn(`failed to ping ws client on [${t}]`,s)})}static#a(e=Date.now()){if(e-r.#t[0]>0){let t=Buffer.allocUnsafe(8);t.writeBigInt64BE(BigInt(e),0),r.#t=[e,t]}return r.#t[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#s)}handlePing(e,t,n){t.connected=!0,t.pong(n,!1,s=>{s&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}failed to pong ws client ${ee(e.remoteAddress)}`,s)})}handlePong(e,t,n){if(t.connected=!0,this.#o.enabledFor("warn")){let s=r.#u(n);if(s>0){let i=Date.now()-s;this.#o.enabledFor("debug")&&this.#o.debug(`${e.logPrefix}ws client ${ee(e.remoteAddress)} ping-pong latency: ${i}ms`),this.#n&&i>this.#n/2&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}ws client ${ee(e.remoteAddress)} high ping-pong latency: ${i}ms`)}}}};var q=w("ws");function yo(r,e,t,n){return s=>{let{logPrefix:i,request:o}=s,a=lt.getNativeRequest(o);a.exchange=s;let{socket:c,upgradeHead:d}=a,u=o.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&t.clients?.size>=e.maxConnections){q.warn(`${i}dropping ws connection request on ${u}${r}. max connections exceeded.`),c.destroy();return}let f=o.headers.one("origin");if(!Wn(f,e.originFilters)){q.enabledFor("info")&&q.info(`${i}dropping ws connection request on ${u}${r}. origin ${f??"<missing>"}`),c.destroy();return}q.enabledFor("debug")&&q.debug(`${i}accepted new ws connection request on ${u}${r}`),t.handleUpgrade(a,c,d,(m,v)=>{t.emit("connection",m,v)})}}function bo(r,e){let t=new Set;r.forEach((s,i)=>{if(i===0&&s.startsWith("HTTP/1.1 101 ")){e.setStatusCode(y.SWITCHING_PROTOCOLS);return}let[o,a]=s.split(": ");e.headers.has(o)?r[i]=`${o}: ${e.headers.one(o)}`:e.headers.set(o,a),t.add(o.toLowerCase())});let n=ye.getNativeResponse(e);for(let s of n.getRawHeaderNames()){let i=s.toLowerCase();if(!t.has(i)){let o=e.headers.get(i);o!==void 0&&r.push(`${s}: ${o}`)}}n.markHeadersSent()}async function fs(r,e,t,n,s){try{q.info(`creating ws server for [${r}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,hn):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new mo({noServer:!0,WebSocket:$t,autoPong:!1}),o=new Ut(q.child("pings"),()=>[r,i.clients],e.ping),a=await e.factory({endpoint:t,storage:n});i.on("error",c=>{q.error(`error starting the ws server for [${r}]`,c)}).on("listening",()=>{q.info(`ws server for [${r}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;bo(c,u)}}).on("connection",(c,d)=>{let u=hs(d,c.protocol);c.on("pong",f=>{o.handlePong(u,c,f)}),c.on("ping",f=>{o.handlePing(u,c,f)}),a({socket:c,handshake:u})}),i.on("close",()=>{o.close()}),e.upgradeStrategy=yo(r,e,i,s),e.close=async()=>{await a.close?.call(a),q.info(`stopping ws server for [${r}]. clients: ${i.clients?.size??0}`),i.clients?.forEach(c=>{c.terminate()}),i.close()}}catch(i){q.warn(`failed to init route ${r}`,i)}}import{existsSync as I,readFileSync as Y,writeFileSync as Nt,mkdirSync as qt}from"node:fs";import{dirname as _t}from"node:path";import{KEYUTIL as wo,X509 as So}from"jsrsasign";import{mkcert as Br}from"@interopio/gateway-server/tools";var Te=w("ssl");function gs(r,e){let t={};if(r.requestCert!==void 0&&(t.requestCert=r.requestCert),r.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=r.rejectUnauthorized),r.key&&r.cert&&I(r.key)&&I(r.cert)){Te.info(`using SSL/TLS certificate ${r.cert} with private key in ${r.key}${r.passphrase?" (password-protected)":""}`);let l={key:Y(r.key),cert:Y(r.cert),...t};return r.passphrase&&(l.passphrase=r.passphrase),r.requestCert&&r.ca&&I(r.ca)&&(l.ca=Y(r.ca)),l}if(!r.key&&!r.cert){let l="./gateway-server.key",h="./gateway-server.crt";if(I(l)&&I(h)){Te.info(`using SSL/TLS certificate ${h} with private key in ${l}${r.passphrase?" (password-protected)":""}`);let p={key:Y(l),cert:Y(h),...t};return r.passphrase&&(p.passphrase=r.passphrase),r.requestCert&&r.ca&&I(r.ca)&&(p.ca=Y(r.ca)),p}}if(!e)throw new Error("SSL/TLS enabled but no server certificate provided. Either provide ssl.key and ssl.cert, or configure auth.x509.key for auto-generation.");let n=e.key??"gateway-ca.key",s=r.ca??`${n.replace(/\.key$/,".crt")}`,i=e.passphrase??r.passphrase;if(!I(n)){if(I(s))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${s})`);let l=Br.generateRootCA({name:Br.DEFAULT_CA_NAME,passphrase:i}),h=_t(n);h&&h!=="."&&!I(h)&&qt(h,{recursive:!0});let p=_t(s);p&&p!=="."&&p!==h&&!I(p)&&qt(p,{recursive:!0}),Nt(n,l.key,{mode:256}),Nt(s,l.cert,{mode:420}),Te.info(`created new local Root CA in ${s}, ${n}${i?" (password-protected)":""}`)}let o=Y(n,"utf8"),a=wo.getKey(o,i),c=Y(s,"utf8"),d=new So;d.readCertPEM(c);let u=d.getSubjectString(),f=e.host;Te.debug(`generating server certificate signed by: ${u} for host: ${f}`);let m=Br.generateCert(a,u,[f],!1);if(r.key||r.cert){let l=r.key||"./gateway-server.key",h=r.cert||"./gateway-server.crt",p=_t(l);p&&p!=="."&&!I(p)&&qt(p,{recursive:!0});let g=_t(h);g&&g!=="."&&g!==p&&!I(g)&&qt(g,{recursive:!0}),Nt(l,m.key,{mode:384}),Nt(h,m.cert,{mode:420}),Te.info(`generated server certificate saved to ${h} with private key in ${l}${i?" (password-protected)":""}`)}else Te.info(`using in-memory server certificate for host: ${f}`);let v={key:m.key,cert:m.cert,...t};return r.requestCert&&r.ca&&I(s)&&(v.ca=Y(s)),v}function Gr(r){return r?.get("io.gateway.logging.suppress")===!0}var Bt="io.gateway.logging.prefix";function Vr(r){return r?.has(Bt)?r.get(Bt)??"":""}var He=class{#e;logger=w("codec.encoder");constructor(...e){this.#e=[...e]}setLogger(e){this.logger=e}encodableMimeTypes(){return this.#e}canEncode(e,t){if(t===void 0)return!0;for(let n of this.#e)if(re(t,n))return!0;return!1}},Gt=class extends He{constructor(){super(Le)}canEncode(e,t){return super.canEncode(e,t)}async encode(e,t,n){let s=await e;return this.logger.enabledFor("debug")&&!Gr(n)&&this.#e(s),s}#e(e,t){let n=Vr(t);this.logger.debug(`${n}Encoding value of type ${typeof e} with size ${e.byteLength??e.size??e.length}`)}},Vt=class r extends He{constructor(...e){super(...e)}canEncode(e,t){return super.canEncode(e,t)&&e==="string"}async encode(e,t,n){if(e=await e,!Gr(n)&&this.logger.enabledFor("debug")){let s=Vr(n),i=this.logger.enabledFor("trace");this.logger.debug(`${s}Writing ${i?`${e}`:`${e.substring(0,100)}...`}`)}return e}static textPlainOnly(){return new r(mr("text","plain","utf-8"))}static allMimeTypes(){return new r(mr("text","plain","utf-8"),Le)}};var le=class{log=w("http.codec");#e=!1;set enableLoggingRequestDetails(e){this.#e=e}get enableLoggingRequestDetails(){return this.#e}};var Ye=class r extends le{static MEDIA_TYPES=Object.freeze([A.MULTIPART_FORM_DATA]);#e;constructor(e){super(),this.#e=e}get partReader(){return this.#e}getReadableMediaTypes(){return r.MEDIA_TYPES}canRead(e,t){return this.#t(t)&&e.name===FormData.name}#t(e){if(e===void 0)return!0;for(let t of r.MEDIA_TYPES)if(re(t,e))return!0;return!1}async readPromise(e,t,n){let s=this.#e.read(e,t,n),i=new FormData;for await(let[o,a]of s)i.append(o,a);return i}read(e,t,n){throw new Error("not implemented yet")}},Ke=class extends le{getReadableMediaTypes(){return[A.MULTIPART_FORM_DATA]}canRead(e,t){return e==="string"||e.name===File.name&&(t===void 0||re(A.MULTIPART_FORM_DATA,t))}readPromise(e,t,n){throw new Error("not implemented yet")}read(e,t,n){throw new Error("not implemented yet")}};var Qe=class r{#e;#t;#r;constructor(e){r.initLogger(e),this.#e=e,this.#t=A.asMediaTypes(...e.encodableMimeTypes()),this.#r=this.#t.find(t=>gr(t))}get encoder(){return this.#e}getWriteableMediaTypes(){return this.#t}canWrite(e,t){return this.#e.canEncode(e,t)}async write(e,t,n,s,i){let o=this.#n(n,s),a=this.#e.encode(e,o,i);await n.body(a)}static initLogger(e){e instanceof He}#n(e,t){let n=fe(e.headers);if(n)return n;let s=this.#r;n=vo(t,s)?s:t,n&&(n=Eo(n,s),e.headers.set("Content-Type",n.toString()))}};function Eo(r,e){if(!r.params.has("charset")&&e!==void 0){let t=e.params.get("charset");if(t){let n=A.parseMediaType(r.toString());return n.params.set("charset",t),n}}return r}function vo(r,e){return(r===void 0||!gr(r)||r.essence===A.APPLICATION_OCTET_STREAM.essence)&&e!==void 0}var zr=class{#e;#t;#r;#n=!0;#s=Array();#i=Array();constructor(){this.initReaders(),this.initWriters()}multipartReader(e){this.#e=e,this.initReaders()}registerDefaults(e){this.#n!==e&&(this.#n=e,this.initReaders(),this.initWriters())}initReaders(){if(this.#i.length=0,!!this.#n)if(this.#e!==void 0)this.addCodec(this.#i,this.#e);else{let e=new Ke;this.addCodec(this.#i,e),this.addCodec(this.#i,new Ye(e))}}initWriters(){this.#s.length=0,this.#n&&(this.#s.push(...this.#o()),this.extendWriters(this.#s))}extendWriters(e){}#o(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new Qe(new Gt)),e}maxInMemorySize(e){this.#t!==e&&(this.#t=e,this.initReaders())}enableLoggingRequestDetails(e){this.#r!==e&&(this.#r=e,this.initReaders(),this.initWriters())}get catchAllReaders(){return this.#n?Array():[]}get typedWriters(){return this.#s}get typedReaders(){return this.#i}get catchAllWriters(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new Qe(Vt.allMimeTypes())),e}addCodec(e,t){this.#c(t),e.push(t)}#c(e){if(e instanceof Qe&&(e=e.encoder),e===void 0)return;let t=this.#t,n=this.#r;n!==void 0&&(e instanceof Ye&&(e.enableLoggingRequestDetails=n),e instanceof Ke&&(e.enableLoggingRequestDetails=n))}},jr=class{baseDefaultCodecs;constructor(e){this.baseDefaultCodecs=e}get defaultCodecs(){return this.baseDefaultCodecs}registerDefaults(e){this.baseDefaultCodecs.registerDefaults(e)}get readers(){let e=new Array;return e.push(...this.baseDefaultCodecs.typedReaders),e.push(...this.baseDefaultCodecs.catchAllReaders),e}get writers(){let e=new Array;return e.push(...this.baseDefaultCodecs.typedWriters),e.push(...this.baseDefaultCodecs.catchAllWriters),e}},Xr=class extends zr{},Jr=class extends jr{constructor(){super(new Xr)}};function Po(){return new Jr}var Me={serverConfigurer:{create:Po}};import{createServer as Co}from"node:net";function xo({logger:r,options:e,handler:t,onClose:n}){let s=e.path;r.enabledFor("info")&&r.info(`[${s}] opening command server pipe, waiting for the data...`);try{let i=Co(o=>{r.enabledFor("debug")&&r.debug(`[${s}] command pipe server got client, waiting for the data...`),o.on("close",()=>{r.enabledFor("debug")&&r.debug(`[${s}] client closed`)}),o.on("error",a=>{r.error(`[${s}] error on pipe stream`,a)}),o.on("data",async(...a)=>{try{let c=a.toString(),d=JSON.parse(c);r.enabledFor("info")&&r.info(`[${s}] received command ${d.command}`),t(d).then(u=>{let f=JSON.stringify({result:u});r.enabledFor("info")&&r.info(`[${s}] command ${d.command} processed successfully. sending : ${f}`),o.write(f,m=>{m&&r.enabledFor("debug")&&r.debug(`[${s}] error while sending response for command ${d.command}`,m)})}).catch(u=>{let f=JSON.stringify({error:u.message});r.error(`[${s}] processing command ${d.command} failed, sending ${f}`,u),o.write(f,m=>{m&&r.enabledFor("debug")&&r.debug(`[${s}] error while sending error response for command ${d.command}`,m)})}).finally(()=>{d.command==="shutdown"&&(r.enabledFor("info")&&r.info(`[${s}] stopping management pipe server`),i.close(n))})}catch(c){r.error(`[${s}] unable to parse the data`,c)}})});i.on("listening",()=>{r.enabledFor("info")&&r.info(`[${s}] connected to the pipe, waiting for the data...`)}),i.on("error",o=>{throw r.error(`[${s}] error while opening the pipe - ${s}`,o),o}),i.listen(e)}catch(i){let o=`error while opening the pipe - ${s}`;r.error(o,i);let a=new Error(o);throw a.cause=i,a}}function ms({options:r,logger:e,shutdown:t,info:n}){xo({options:r,logger:e,onClose:()=>{e.enabledFor("info")&&e.info(`[${r.path}] command server closed, exiting gateway-server process`),process.exit(0)},handler:async s=>{if(s.command==="shutdown")return t?(await t?.(),"gateway-server stopped"):"gateway-server stopping is disabled";if(s.command==="get-info"||s.command==="info")return await n()}})}import As from"@interopio/gateway-server/package.json"with{type:"json"};import{resolve as Ao}from"node:path";import{access as Ro,readFile as To}from"node:fs/promises";import{constants as Ho}from"node:fs";async function Mo(r){if(r)for(let e of r){let t=Ao(e,"index.html");try{return await Ro(t,Ho.R_OK),t}catch{}}}async function Yr(r){let e=await Mo(r),t=qe({mediaTypes:["text/html"]});return async(n,s)=>{let{request:i,response:o}=n;if(i.method==="GET"&&i.path==="/")if(o.setStatusCode(y.OK),e!==void 0&&(await t(n)).match)o.headers.set("Content-Type","text/html; charset=utf-8"),await o.body(To(e));else{o.headers.set("Content-Type","text/plain; charset=utf-8");let a=Buffer.from("io.Gateway Server","utf-8");await o.body(a)}else await s()}}import{AsyncLocalStorage as ko}from"node:async_hooks";function Kr(r){if(r==null)return!1;let{code:e,message:t}=r;return e==="ECONNRESET"||e==="EPIPE"||e==="ERR_STREAM_PREMATURE_CLOSE"||t?.toLowerCase().includes("client aborted")||t?.toLowerCase().includes("socket hang up")||t?.toLowerCase().includes("aborted")}function ys(r,e){return Kr(r)?(e.enabledFor("trace")?e.debug("looks like the client has gone away:",r):e.enabledFor("debug")&&e.debug(`looks like the client has gone away: ${r.message} (For full stack trace enable trace logging level.)`),!0):!1}var Qr=class{#e;#t=void 0;#r=!1;#n;#s;constructor(e,t){this.#e=e,this.#n=t}get codecConfigurer(){return this.#t===void 0&&(this.codecConfigurer=Me.serverConfigurer.create()),this.#t}set codecConfigurer(e){if(e==null)throw new Error("codecConfigurer must not be null or undefined");this.#t=e,this.#r=!1;for(let t of this.#t.readers)if(t instanceof le&&t.enableLoggingRequestDetails){this.#r=!0;break}}createExchange(e,t){return new pt(e,t,this.codecConfigurer)}set storage(e){this.#s=e}formatHeaders(e){let t="{";for(let n of e.keys())if(this.#r){let s=e.get(n);t+=`"${n}": "${s}", `}else{t+="masked, ";break}return t.endsWith(", ")&&(t=t.slice(0,-2)),t+="}",t}formatRequest(e){let t=e.URL.search;return`HTTP ${e.method} "${e.path}${t}`}logRequest(e){if(this.#e.enabledFor("debug")){let t=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${t?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let t=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${t?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,t){let{request:n,response:s,logPrefix:i}=e;if(s.setStatusCode(y.INTERNAL_SERVER_ERROR)){this.#e.error(`${i}500 Server Error for ${this.formatRequest(n)}`,t);return}else{if(ys(t,this.#e))return;throw this.#e.error(`${i}Error [${t.message} for ${this.formatRequest(n)}, but already ended (${s.statusCode})`,t),t}}async web(e){return await this.#n.handle(e)}async http(e,t){let n=this.createExchange(e,t),s=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(i=>{this.handleUnresolvedError(n,i)}).then(async()=>{await n.response.end()}));await new Promise((i,o)=>{this.#s!==void 0?this.#s.run({exchange:n},()=>{s().then(()=>i()).catch(a=>o(a))}):s().then(()=>i()).catch(a=>o(a))})}},zt=class r{#e;#t=[];#r=[];#n=[];#s;#i=new ko;#o;constructor(e){this.#e=e}static webHandler(e){return new r(e)}filter(...e){return e&&this.#t.push(...e),this}middleware(e){return e(this.#n),this}exceptionHandler(...e){return e&&this.#r.push(...e),this}exceptionHandlers(e){return e(this.#r),this}storage(e){return this.#i=e,this}codecConfigurer(e){return this.#o=e,this}hasCodecConfigurer(){return this.#o!==void 0}httpHandlerDecorator(e){if(this.#s===void 0)this.#s=e;else{let t=this.#s;this.#s=n=>(n=e(n),n=t(n),n)}return this}hasHttpHandlerDecorator(){return this.#s!==void 0}build(){let e=w("http"),t=new Wt(this.#e,...this.#t);t=new kt(t,...this.#r);let n=new Qr(e,t);this.#i!==void 0&&(n.storage=this.#i),this.#o!==void 0&&(n.codecConfigurer=this.#o);let s=async(i,o)=>n.http(i,o);return this.#s?this.#s(s):s}};var jt={create:(r,e)=>new en(r,e)},Zr=class{#e;constructor(e){this.#e=e}accept(){return A.parseMediaTypes(...this.#e.list("accept"))}contentLength(){let e=this.#e.one("content-length");return e!==void 0?Number.parseInt(e):void 0}contentType(){return fe(this.#e)}header(e){return this.#e.list(e)}firstHeader(e){let t=this.#e.list(e);return t.length>0?t[0]:void 0}asHttpHeaders(){return this.#e}},en=class{exchange;messageReaders;#e;constructor(e,t){this.exchange=e,this.messageReaders=[...t],this.#e=new Zr(e.request.headers)}get attributes(){return this.exchange.attributes}get headers(){return this.#e}get method(){return this.request.method}get URL(){return this.request.URL}get requestPath(){return this.request.requestPath}queryParam(e){return this.request.URL.searchParams.get(e)}get principal(){return this.exchange.principal()}get request(){return this.exchange.request}};var E=class{static WILDCARD_WEIGHT=100;static CAPTURE_VARIABLE_WEIGHT=1;static NO_PARAMETERS=new Map;pos;separator;next;prev;constructor(e,t){this.pos=e,this.separator=t}get captureCount(){return 0}get wildcardCount(){return 0}get score(){return 0}get literal(){return!1}noMorePattern(){return this.next===void 0}};var he=class extends E{constructor(e,t){super(e,t)}matches(e,t){return e<t.pathLength&&t.isSeparator(e)?this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e+1,!0):e+1===t.pathLength:(e++,this.next!==void 0&&this.next.matches(e,t)):!1}get normalizedLength(){return 1}get chars(){return new Uint16Array([this.separator])}get literal(){return!0}toString(){return`Separator(${String.fromCharCode(this.separator)})`}};var ke=class extends E{constructor(e,t){super(e,t)}matches(e,t){let n;if(e<t.pathLength){let s=t.pathElements[e];if(!F(s))return!1;n=s.valueToMatch,e++}return this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:n===void 0||n.length===0?!1:this.next!==void 0&&this.next.matches(e,t)}get normalizedLength(){return 1}get chars(){return new Uint16Array([42])}get wildcardCount(){return 1}get score(){return E.WILDCARD_WEIGHT}toString(){return"Wildcard(*)"}};var K=class extends E{#e;constructor(e,t,n){super(e,n),this.#e=String.fromCharCode(...t.slice(2,t.length-1))}matches(e,t){if(e===0&&this.next!==void 0){let n=e;for(;n<t.pathLength;){if(this.next.matches(n,t))return this.#t(t,e,n),!0;n++}return!1}else if(e<t.pathLength&&!t.isSeparator(e))return!1;return t.determinedRemainingPath&&(t.remainingPathIndex=t.pathLength),this.#t(t,e,t.pathLength),!0}#t(e,t,n){if(e.extractingVariables){let s=E.NO_PARAMETERS;for(let i=t;i<n;i++){let o=e.pathElements[i];if(F(o)){let{parameters:a}=o;if(a.size>0){s===E.NO_PARAMETERS&&(s=new Map);for(let[c,d]of a)if(s.has(c)){let u=s.get(c);s.set(c,u.concat(d))}else s.set(c,d)}}}e.set(this.#e,this.#r(t,n,e.pathElements),s)}}#r(e,t,n){let s=[];for(let i=e;i<t;i++){let o=n[i];F(o)?s.push(o.valueToMatch):s.push(o.value)}return s.join("")}get normalizedLength(){return 1}get chars(){let e=`${String.fromCharCode(this.separator)}{*${this.#e}}`,t=new Uint16Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}get wildcardCount(){return 0}get captureCount(){return 1}toString(){return`CaptureSegments(${String.fromCharCode(this.separator)}{*${this.#e}})`}};var Q=class extends E{constructor(e,t){super(e,t)}matches(e,t){if(e===0&&this.next!==void 0){let n=e;for(;n<t.pathLength;){if(this.next.matches(n,t))return!0;n++}return!1}else if(e<t.pathLength&&!t.isSeparator(e))return!1;return t.determinedRemainingPath&&(t.remainingPathIndex=t.pathLength),!0}get normalizedLength(){return 1}get chars(){let e=`${String.fromCharCode(this.separator)}**`,t=new Uint16Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}get wildcardCount(){return 1}toString(){return`WildcardSegments(${String.fromCharCode(this.separator)}**)`}};var Xt=class{#e;pathElements;pathLength;#t;#r;extractingVariables=!1;#n=!1;remainingPathIndex=0;constructor(e,t){this.#e=e,this.pathElements=e.elements,this.pathLength=this.pathElements.length,this.extractingVariables=t}get determinedRemainingPath(){return this.#n}setMatchAllowExtraPath(){this.#n=!0}set(e,t,n){this.#t===void 0&&(this.#t=new Map),this.#t.set(e,t),n.size>0&&(this.#r===void 0&&(this.#r=new Map),this.#r.set(e,n))}get pathMatchResult(){return this.#t===void 0?Ze.EMPTY:new Ze(this.#t,this.#r)}isSeparator(e){return z(this.pathElements[e])}pathElementValue(e){let t=e<this.pathLength?this.pathElements[e]:null;return t!==null&&F(t)?t.valueToMatch:""}},Ze=class r{static EMPTY=new r(new Map,new Map);uriVariables;matrixVariables;constructor(e,t){this.uriVariables=e,this.matrixVariables=t??new Map}toString(){return`PathMatchInfo(uriVariables=${this.uriVariables}, matrixVariables=${this.matrixVariables})`}},Jt=class r{static#e=j("");static SPECIFICITY_COMPARATOR=(e,t)=>e==null?t==null?0:1:t==null?-1:e.catchAll&&!t.catchAll?1:!e.catchAll&&t.catchAll?-1:0;#t;#r;#n;#s;#i;#o=0;#c=0;#d=!1;#a=0;#u=!1;constructor(e,t,n){this.#t=e,this.#r=t,this.#n=t.pathOptions,this.#s=t.caseSensitive,this.#i=n;let s=n;for(;s!==void 0;)this.#o+=s.captureCount,this.#c+=s.normalizedLength,this.#a+=s.score,(s instanceof K||s instanceof Q)&&(this.#u=!0),s instanceof he&&s.next instanceof ke&&s.next.next===void 0&&(this.#d=!0),s=s.next}get patternString(){return this.#t}get hasPatternSyntax(){return this.#a>0||this.#u||this.#t.indexOf("?")!==-1}#h(e){return e!==void 0&&e.elements.length>0}#p(e){return e.value.length===1&&e.value.charCodeAt(0)===this.separator}matches(e){if(this.#i===void 0)return!this.#h(e);if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return!1;let t=new Xt(e,!1);return this.#i.matches(0,t)}matchAndExtract(e){if(this.#i===void 0)return this.#h(e)&&!this.#p(e)?void 0:Ze.EMPTY;if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return;let t=new Xt(e,!0);return this.#i.matches(0,t)?t.pathMatchResult:void 0}extractPathWithinPattern(e){let t=e.elements,n=t.length,s=0,i=this.#i;for(;i!==void 0&&i.literal;)i=i.next,s++;if(i===void 0)return j("");for(;s<n&&z(t[s]);)s++;let o=n;for(;o>0&&z(t[o-1]);)o--;let a=!1;for(let d=s;d<o-1;d++)if(z(t[d])&&z(t[d+1])){a=!0;break}let c;if(a){let d=[],u=s;for(;u<o;){let f=t[u++];if(d.push(f.value),z(f))for(;u<o&&z(t[u]);)u++}c=j(d.join(""),this.#n)}else s>=o?c=j("",this.#n):c=Ue(e,s,o);return c}get score(){return this.#a}get catchAll(){return this.#u}get normalizedLength(){return this.#c}get separator(){return this.#n.separator}get capturedVariableCount(){return this.#o}toChainString(){let e=[],t=this.#i;for(;t!==void 0;)e.push(t.toString()),t=t.next;return e.join(" ")}computePatternString(){let e=[],t=this.#i;for(;t!==void 0;)e.push(String.fromCharCode(...t.chars)),t=t.next;return e.join("")}get head(){return this.#i}};import{format as Wo}from"node:util";var Io={MISSING_CLOSE_CAPTURE:"Expected close capture character after variable name '}'",MISSING_OPEN_CAPTURE:"Missing preceding open capture character before variable name'{'",ILLEGAL_NESTED_CAPTURE:"Not allowed to nest variable captures",CANNOT_HAVE_ADJACENT_CAPTURES:"Adjacent captures are not allowed",ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR:"Char '%s' not allowed at start of captured variable name",ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR:"Char '%s' is not allowed in a captured variable name",CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS:"Multiple '{*...}' or '**' pattern elements are not allowed",INVALID_LOCATION_FOR_MULTISEGMENT_PATH_ELEMENT:"'{*...}' or '**' pattern elements should be placed at the start or end of the pattern",MISSING_REGEX_CONSTRAINT:"Missing regex constraint on capture",ILLEGAL_DOUBLE_CAPTURE:"Not allowed to capture ''{0}'' twice in the same pattern",REGEX_PATTERN_SYNTAX_EXCEPTION:"Exception occurred in regex pattern compilation",CAPTURE_ALL_IS_STANDALONE_CONSTRUCT:"'{*...}' cannot be mixed with other path elements in the same path segment"},H=class r extends Error{position;messageType;inserts;#e;static formatMessage(e,t){return Wo(Io[e],...t)}static createWithCause(e,t,n,s,...i){let o=r.formatMessage(s,i);return new r(t,n,s,i,o,{cause:e})}static create(e,t,n,...s){let i=r.formatMessage(n,s);return new r(e,t,n,s,i)}constructor(e,t,n,s,i,o){super(i,o),this.position=e,this.#e=t,this.messageType=n,this.inserts=s}toDetailedString(){let e=[];e.push(String.fromCharCode(...this.#e)),e.push(`
|
|
18
|
+
`),c=d}if(c.length>Ur)throw new Error(`Password length exceeds maximum length of ${Ur} characters`);return a!=null||/^\{.+}.*$/.test(c)?c:`{noop}${c}`}let t={name:"dev-user",roles:[],...r.authConfig?.user},n=e(t),s=t.roles,i=kt.ofUsername(t.name).password(n).roles(...s).build();return new Dt(i)}async function fs(r){let e=Jn(r),t=bo(r),n=wo(r),{storage:s}=r;return ps(t,{storage:s,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}var Nt=class extends be{};import{WebSocketServer as Eo}from"ws";function gs(r,e){let t=r?.exchange,n=t?.request??new ye(r),s=t?.principal,i=s?s.bind(t):async function(){},o=n.URL,a=new R;for(let g of n.headers.keys())a.set(g,n.headers.list(g));let c=n.cookies,d=t?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:o,headers:a,cookies:c,principal:i,protocol:e,remoteAddress:u,logPrefix:d}}function ms(r){return[async(t,n)=>{let i=t.request.path??"/",o=r.sockets,a=o.get(i)??Array.from(o.values()).find(c=>{if(i==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=t,u=await de(t);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(t);return}else throw new Error(`No upgrade strategy defined for route on ${i}`);else{if(a.default){await n();return}d.setStatusCode(b.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let h=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(h)}}else await n()}]}import{WebSocket as So}from"ws";var Ut=class extends So{constructor(e,t,n){super(null,void 0,n)}connected},qt=class r{static#e=Buffer.alloc(0);static#t=[0,Buffer.alloc(8)];#r;#n;#s;#i=!1;#o;constructor(e,t,n){this.#o=e,this.#n=typeof n=="number"?n:n?.interval,this.#r=typeof n=="number"||n?.data==="timestamp"?()=>r.#a(Date.now()):()=>r.#e,this.#n&&(this.#s=setInterval(()=>{let[s,i]=t();for(let o of i)this.#c(o,s)||this.#d(o,s)},this.#n))}#c(e,t){return e.connected===!1?(this.#o.enabledFor("debug")&&this.#o.debug(`terminating unresponsive ws client on [${t}]`),e.terminate(),!0):!1}#d(e,t){e.connected=!1;let n=this.#r();this.#o.enabledFor("trace")&&this.#o.debug(`pinging ws client on [${t}]`),e.ping(n,this.#i,s=>{s&&this.#o.enabledFor("warn")&&this.#o.warn(`failed to ping ws client on [${t}]`,s)})}static#a(e=Date.now()){if(e-r.#t[0]>0){let t=Buffer.allocUnsafe(8);t.writeBigInt64BE(BigInt(e),0),r.#t=[e,t]}return r.#t[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#s)}handlePing(e,t,n){t.connected=!0,t.pong(n,!1,s=>{s&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}failed to pong ws client ${ee(e.remoteAddress)}`,s)})}handlePong(e,t,n){if(t.connected=!0,this.#o.enabledFor("warn")){let s=r.#u(n);if(s>0){let i=Date.now()-s;this.#o.enabledFor("debug")&&this.#o.debug(`${e.logPrefix}ws client ${ee(e.remoteAddress)} ping-pong latency: ${i}ms`),this.#n&&i>this.#n/2&&this.#o.enabledFor("warn")&&this.#o.warn(`${e.logPrefix}ws client ${ee(e.remoteAddress)} high ping-pong latency: ${i}ms`)}}}};var q=S("ws");function vo(r,e,t,n){return s=>{let{logPrefix:i,request:o}=s,a=pt.getNativeRequest(o);a.exchange=s;let{socket:c,upgradeHead:d}=a,u=o.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&t.clients?.size>=e.maxConnections){q.warn(`${i}dropping ws connection request on ${u}${r}. max connections exceeded.`),c.destroy();return}let h=o.headers.one("origin");if(!Ln(h,e.originFilters)){q.enabledFor("info")&&q.info(`${i}dropping ws connection request on ${u}${r}. origin ${h??"<missing>"}`),c.destroy();return}q.enabledFor("debug")&&q.debug(`${i}accepted new ws connection request on ${u}${r}`),t.handleUpgrade(a,c,d,(g,E)=>{t.emit("connection",g,E)})}}function Po(r,e){let t=new Set;r.forEach((s,i)=>{if(i===0&&s.startsWith("HTTP/1.1 101 ")){e.setStatusCode(b.SWITCHING_PROTOCOLS);return}let[o,a]=s.split(": ");e.headers.has(o)?r[i]=`${o}: ${e.headers.one(o)}`:e.headers.set(o,a),t.add(o.toLowerCase())});let n=be.getNativeResponse(e);for(let s of n.getRawHeaderNames()){let i=s.toLowerCase();if(!t.has(i)){let o=e.headers.get(i);o!==void 0&&r.push(`${s}: ${o}`)}}n.markHeadersSent()}async function ys(r,e,t,n,s){try{q.info(`creating ws server for [${r}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,gn):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new Eo({noServer:!0,WebSocket:Ut,autoPong:!1}),o=new qt(q.child("pings"),()=>[r,i.clients],e.ping),a=await e.factory({endpoint:t,storage:n});i.on("error",c=>{q.error(`error starting the ws server for [${r}]`,c)}).on("listening",()=>{q.info(`ws server for [${r}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;Po(c,u)}}).on("connection",(c,d)=>{let u=gs(d,c.protocol);c.on("pong",h=>{o.handlePong(u,c,h)}),c.on("ping",h=>{o.handlePing(u,c,h)}),a({socket:c,handshake:u})}),i.on("close",()=>{o.close()}),e.upgradeStrategy=vo(r,e,i,s),e.close=async()=>{await a.close?.call(a),q.info(`stopping ws server for [${r}]. clients: ${i.clients?.size??0}`),i.clients?.forEach(c=>{c.terminate()}),i.close()}}catch(i){q.warn(`failed to init route ${r}`,i)}}import{existsSync as O,readFileSync as Y,writeFileSync as _t,mkdirSync as Bt}from"node:fs";import{dirname as Gt}from"node:path";import{KEYUTIL as Co,X509 as xo}from"jsrsasign";import{mkcert as zr}from"@interopio/gateway-server/tools";var Me=S("ssl");function bs(r,e){let t={};if(r.requestCert!==void 0&&(t.requestCert=r.requestCert),r.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=r.rejectUnauthorized),r.key&&r.cert&&O(r.key)&&O(r.cert)){Me.info(`using SSL/TLS certificate ${r.cert} with private key in ${r.key}${r.passphrase?" (password-protected)":""}`);let l={key:Y(r.key),cert:Y(r.cert),...t};return r.passphrase&&(l.passphrase=r.passphrase),r.requestCert&&r.ca&&O(r.ca)&&(l.ca=Y(r.ca)),l}if(!r.key&&!r.cert){let l="./gateway-server.key",p="./gateway-server.crt";if(O(l)&&O(p)){Me.info(`using SSL/TLS certificate ${p} with private key in ${l}${r.passphrase?" (password-protected)":""}`);let f={key:Y(l),cert:Y(p),...t};return r.passphrase&&(f.passphrase=r.passphrase),r.requestCert&&r.ca&&O(r.ca)&&(f.ca=Y(r.ca)),f}}if(!e)throw new Error("SSL/TLS enabled but no server certificate provided. Either provide ssl.key and ssl.cert, or configure auth.x509.key for auto-generation.");let n=e.key??"gateway-ca.key",s=r.ca??`${n.replace(/\.key$/,".crt")}`,i=e.passphrase??r.passphrase;if(!O(n)){if(O(s))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${s})`);let l=zr.generateRootCA({name:zr.DEFAULT_CA_NAME,passphrase:i}),p=Gt(n);p&&p!=="."&&!O(p)&&Bt(p,{recursive:!0});let f=Gt(s);f&&f!=="."&&f!==p&&!O(f)&&Bt(f,{recursive:!0}),_t(n,l.key,{mode:256}),_t(s,l.cert,{mode:420}),Me.info(`created new local Root CA in ${s}, ${n}${i?" (password-protected)":""}`)}let o=Y(n,"utf8"),a=Co.getKey(o,i),c=Y(s,"utf8"),d=new xo;d.readCertPEM(c);let u=d.getSubjectString(),h=e.host;Me.debug(`generating server certificate signed by: ${u} for host: ${h}`);let g=zr.generateCert(a,u,[h],!1);if(r.key||r.cert){let l=r.key||"./gateway-server.key",p=r.cert||"./gateway-server.crt",f=Gt(l);f&&f!=="."&&!O(f)&&Bt(f,{recursive:!0});let w=Gt(p);w&&w!=="."&&w!==f&&!O(w)&&Bt(w,{recursive:!0}),_t(l,g.key,{mode:384}),_t(p,g.cert,{mode:420}),Me.info(`generated server certificate saved to ${p} with private key in ${l}${i?" (password-protected)":""}`)}else Me.info(`using in-memory server certificate for host: ${h}`);let E={key:g.key,cert:g.cert,...t};return r.requestCert&&r.ca&&O(s)&&(E.ca=Y(s)),E}function jr(r){return r?.get("io.gateway.logging.suppress")===!0}var Vt="io.gateway.logging.prefix";function Xr(r){return r?.has(Vt)?r.get(Vt)??"":""}var He=class{#e;logger=S("codec.encoder");constructor(...e){this.#e=[...e]}setLogger(e){this.logger=e}encodableMimeTypes(){return this.#e}canEncode(e,t){if(t===void 0)return!0;for(let n of this.#e)if(re(t,n))return!0;return!1}},zt=class extends He{constructor(){super(Fe)}canEncode(e,t){return super.canEncode(e,t)}async encode(e,t,n){let s=await e;return this.logger.enabledFor("debug")&&!jr(n)&&this.#e(s),s}#e(e,t){let n=Xr(t);this.logger.debug(`${n}Encoding value of type ${typeof e} with size ${e.byteLength??e.size??e.length}`)}},jt=class r extends He{constructor(...e){super(...e)}canEncode(e,t){return super.canEncode(e,t)&&e==="string"}async encode(e,t,n){if(e=await e,!jr(n)&&this.logger.enabledFor("debug")){let s=Xr(n),i=this.logger.enabledFor("trace");this.logger.debug(`${s}Writing ${i?`${e}`:`${e.substring(0,100)}...`}`)}return e}static textPlainOnly(){return new r(wr("text","plain","utf-8"))}static allMimeTypes(){return new r(wr("text","plain","utf-8"),Fe)}};var he=class{log=S("http.codec");#e=!1;set enableLoggingRequestDetails(e){this.#e=e}get enableLoggingRequestDetails(){return this.#e}};var Ke=class r extends he{static MEDIA_TYPES=Object.freeze([M.MULTIPART_FORM_DATA]);#e;constructor(e){super(),this.#e=e}get partReader(){return this.#e}getReadableMediaTypes(){return r.MEDIA_TYPES}canRead(e,t){return this.#t(t)&&e.name===FormData.name}#t(e){if(e===void 0)return!0;for(let t of r.MEDIA_TYPES)if(re(t,e))return!0;return!1}async readPromise(e,t,n){let s=this.#e.read(e,t,n),i=new FormData;for await(let[o,a]of s)i.append(o,a);return i}read(e,t,n){throw new Error("not implemented yet")}},Qe=class extends he{getReadableMediaTypes(){return[M.MULTIPART_FORM_DATA]}canRead(e,t){return e==="string"||e.name===File.name&&(t===void 0||re(M.MULTIPART_FORM_DATA,t))}readPromise(e,t,n){throw new Error("not implemented yet")}read(e,t,n){throw new Error("not implemented yet")}};var Ze=class r{#e;#t;#r;constructor(e){r.initLogger(e),this.#e=e,this.#t=M.asMediaTypes(...e.encodableMimeTypes()),this.#r=this.#t.find(t=>br(t))}get encoder(){return this.#e}getWriteableMediaTypes(){return this.#t}canWrite(e,t){return this.#e.canEncode(e,t)}async write(e,t,n,s,i){let o=this.#n(n,s),a=this.#e.encode(e,o,i);await n.body(a)}static initLogger(e){e instanceof He}#n(e,t){let n=ge(e.headers);if(n)return n;let s=this.#r;n=Ro(t,s)?s:t,n&&(n=Ao(n,s),e.headers.set("Content-Type",n.toString()))}};function Ao(r,e){if(!r.params.has("charset")&&e!==void 0){let t=e.params.get("charset");if(t){let n=M.parseMediaType(r.toString());return n.params.set("charset",t),n}}return r}function Ro(r,e){return(r===void 0||!br(r)||r.essence===M.APPLICATION_OCTET_STREAM.essence)&&e!==void 0}var Jr=class{#e;#t;#r;#n=!0;#s=Array();#i=Array();constructor(){this.initReaders(),this.initWriters()}multipartReader(e){this.#e=e,this.initReaders()}registerDefaults(e){this.#n!==e&&(this.#n=e,this.initReaders(),this.initWriters())}initReaders(){if(this.#i.length=0,!!this.#n)if(this.#e!==void 0)this.addCodec(this.#i,this.#e);else{let e=new Qe;this.addCodec(this.#i,e),this.addCodec(this.#i,new Ke(e))}}initWriters(){this.#s.length=0,this.#n&&(this.#s.push(...this.#o()),this.extendWriters(this.#s))}extendWriters(e){}#o(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new Ze(new zt)),e}maxInMemorySize(e){this.#t!==e&&(this.#t=e,this.initReaders())}enableLoggingRequestDetails(e){this.#r!==e&&(this.#r=e,this.initReaders(),this.initWriters())}get catchAllReaders(){return this.#n?Array():[]}get typedWriters(){return this.#s}get typedReaders(){return this.#i}get catchAllWriters(){if(!this.#n)return[];let e=Array();return this.addCodec(e,new Ze(jt.allMimeTypes())),e}addCodec(e,t){this.#c(t),e.push(t)}#c(e){if(e instanceof Ze&&(e=e.encoder),e===void 0)return;let t=this.#t,n=this.#r;n!==void 0&&(e instanceof Ke&&(e.enableLoggingRequestDetails=n),e instanceof Qe&&(e.enableLoggingRequestDetails=n))}},Yr=class{baseDefaultCodecs;constructor(e){this.baseDefaultCodecs=e}get defaultCodecs(){return this.baseDefaultCodecs}registerDefaults(e){this.baseDefaultCodecs.registerDefaults(e)}get readers(){let e=new Array;return e.push(...this.baseDefaultCodecs.typedReaders),e.push(...this.baseDefaultCodecs.catchAllReaders),e}get writers(){let e=new Array;return e.push(...this.baseDefaultCodecs.typedWriters),e.push(...this.baseDefaultCodecs.catchAllWriters),e}},Kr=class extends Jr{},Qr=class extends Yr{constructor(){super(new Kr)}};function To(){return new Qr}var ke={serverConfigurer:{create:To}};import{createServer as Ho}from"node:net";import{unlink as ko}from"node:fs/promises";import Mo from"net";function ws(r,e,t={}){let{timeout:n=5e3}=t,s=r?.path?{path:r.path}:{port:r?.port??0},i=r?.path??`port ${r?.port}`;return new Promise((o,a)=>{let c=Mo.connect(s,()=>{c.write(JSON.stringify(e))}),d=setTimeout(()=>{c.destroy(),a(new Error(`Connection timed out after ${n}`))},n);c.on("data",u=>{clearTimeout(d);try{let h=JSON.parse(u.toString());h.error?a(new Error(h.error)):o(h.result)}catch{o(u.toString())}c.end()}),c.on("error",u=>{clearTimeout(d),u.code==="ENOENT"||u.code==="ECONNREFUSED"?a(new Error(`Cannot connect to gateway at ${i}. Make sure the gateway server is running and the path is correct.`,{cause:u})):a(u)})})}async function Io(r){try{return{stale:!1,pid:(await ws({path:r},{command:"info"},{timeout:2e3}))?.pid??0}}catch{return{stale:!0}}}async function Wo(r,e){if(process.platform!=="win32"&&e)try{await ko(e)}catch(t){let n=t.code;n!=="ENOENT"&&r.warn(`[${e}] error while removing the pipe - ${e} (${n})`,t)}}function Oo({logger:r,options:e,handler:t,onClose:n}){let s=e.path;return r.enabledFor("info")&&r.info(`[${s}] opening command server pipe, waiting for the data...`),new Promise((i,o)=>{try{let a=Ho(c=>{r.enabledFor("debug")&&r.debug(`[${s}] command pipe server got client, waiting for the data...`),c.on("close",()=>{r.enabledFor("debug")&&r.debug(`[${s}] client closed`)}),c.on("error",d=>{r.error(`[${s}] error on pipe stream`,d)}),c.on("data",async d=>{try{let u=d.toString("utf8"),h=JSON.parse(u);r.enabledFor("debug")&&r.debug(`[${s}] received command ${h.command}`),t(h).then(g=>{let E=JSON.stringify({result:g});r.enabledFor("debug")&&r.debug(`[${s}] command ${h.command} processed successfully. sending : ${E}`),c.write(E,l=>{l&&r.enabledFor("debug")&&r.debug(`[${s}] error while sending response for command ${h.command}`,l)})}).catch(g=>{let E=JSON.stringify({error:g.message});r.error(`[${s}] processing command ${h.command} failed, sending ${E}`,g),c.write(E,l=>{l&&r.enabledFor("debug")&&r.debug(`[${s}] error while sending error response for command ${h.command}`,l)})}).finally(()=>{})}catch(u){r.error(`[${s}] unable to parse the data`,u)}})});a.on("listening",()=>{r.enabledFor("info")&&r.info(`[${s}] ready for commands...`),i(a)}),a.on("error",c=>{if(c.code==="EADDRINUSE"&&s){r.info(`[${s}] already in use, checking if socket is stale...`),Io(s).then(d=>{if(d.stale)r.info(`[${s}] socket is stale, cleaning up and retrying...`),Wo(r,s).then(()=>{a.listen(e)}).catch(u=>{o(u)});else{let u=`[${s}] another gateway-server instance is already running on this path (pid: ${d.pid})`;r.error(u),o(new Error(u))}}).catch(d=>{o(d)});return}r.error(`[${s}] error while opening the pipe - ${s}`,c),o(c)}),a.on("close",()=>n?.()),a.listen(e)}catch(a){let c=`error while opening the pipe - ${s}`;r.error(c,a);let d=new Error(c);d.cause=a,o(d)}})}async function Ss({options:r,logger:e,shutdown:t,info:n}){return await Oo({options:r,logger:e,onClose:()=>{e.enabledFor("info")&&e.info(`[${r.path}] command server closed`)},handler:async s=>{if(s.command==="shutdown")return t?(t().catch(i=>{e.enabledFor("error")&&e.error(`[${r.path}] error during shutdown`,i)}),"shutdown initiated"):"shutdown disabled";if(s.command==="get-info"||s.command==="info")return await n()}})}import ks from"@interopio/gateway-server/package.json"with{type:"json"};import{resolve as Lo}from"node:path";import{access as Fo,readFile as Do}from"node:fs/promises";import{constants as $o}from"node:fs";async function No(r){if(r)for(let e of r){let t=Lo(e,"index.html");try{return await Fo(t,$o.R_OK),t}catch{}}}async function Zr(r){let e=await No(r),t=_e({mediaTypes:["text/html"]});return async(n,s)=>{let{request:i,response:o}=n;if(i.method==="GET"&&i.path==="/")if(o.setStatusCode(b.OK),e!==void 0&&(await t(n)).match)o.headers.set("Content-Type","text/html; charset=utf-8"),await o.body(Do(e));else{o.headers.set("Content-Type","text/plain; charset=utf-8");let a=Buffer.from("io.Gateway Server","utf-8");await o.body(a)}else await s()}}import{AsyncLocalStorage as Uo}from"node:async_hooks";function en(r){if(r==null)return!1;let{code:e,message:t}=r;return e==="ECONNRESET"||e==="EPIPE"||e==="ERR_STREAM_PREMATURE_CLOSE"||t?.toLowerCase().includes("client aborted")||t?.toLowerCase().includes("socket hang up")||t?.toLowerCase().includes("aborted")}function Es(r,e){return en(r)?(e.enabledFor("trace")?e.debug("looks like the client has gone away:",r):e.enabledFor("debug")&&e.debug(`looks like the client has gone away: ${r.message} (For full stack trace enable trace logging level.)`),!0):!1}var tn=class{#e;#t=void 0;#r=!1;#n;#s;constructor(e,t){this.#e=e,this.#n=t}get codecConfigurer(){return this.#t===void 0&&(this.codecConfigurer=ke.serverConfigurer.create()),this.#t}set codecConfigurer(e){if(e==null)throw new Error("codecConfigurer must not be null or undefined");this.#t=e,this.#r=!1;for(let t of this.#t.readers)if(t instanceof he&&t.enableLoggingRequestDetails){this.#r=!0;break}}createExchange(e,t){return new gt(e,t,this.codecConfigurer)}set storage(e){this.#s=e}formatHeaders(e){let t="{";for(let n of e.keys())if(this.#r){let s=e.get(n);t+=`"${n}": "${s}", `}else{t+="masked, ";break}return t.endsWith(", ")&&(t=t.slice(0,-2)),t+="}",t}formatRequest(e){let t=e.URL.search;return`HTTP ${e.method} "${e.path}${t}`}logRequest(e){if(this.#e.enabledFor("debug")){let t=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${t?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let t=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${t?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,t){let{request:n,response:s,logPrefix:i}=e;if(s.setStatusCode(b.INTERNAL_SERVER_ERROR)){this.#e.error(`${i}500 Server Error for ${this.formatRequest(n)}`,t);return}else{if(Es(t,this.#e))return;throw this.#e.error(`${i}Error [${t.message} for ${this.formatRequest(n)}, but already ended (${s.statusCode})`,t),t}}async web(e){return await this.#n.handle(e)}async http(e,t){let n=this.createExchange(e,t),s=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(i=>{this.handleUnresolvedError(n,i)}).then(async()=>{await n.response.end()}));await new Promise((i,o)=>{this.#s!==void 0?this.#s.run({exchange:n},()=>{s().then(()=>i()).catch(a=>o(a))}):s().then(()=>i()).catch(a=>o(a))})}},Xt=class r{#e;#t=[];#r=[];#n=[];#s;#i=new Uo;#o;constructor(e){this.#e=e}static webHandler(e){return new r(e)}filter(...e){return e&&this.#t.push(...e),this}middleware(e){return e(this.#n),this}exceptionHandler(...e){return e&&this.#r.push(...e),this}exceptionHandlers(e){return e(this.#r),this}storage(e){return this.#i=e,this}codecConfigurer(e){return this.#o=e,this}hasCodecConfigurer(){return this.#o!==void 0}httpHandlerDecorator(e){if(this.#s===void 0)this.#s=e;else{let t=this.#s;this.#s=n=>(n=e(n),n=t(n),n)}return this}hasHttpHandlerDecorator(){return this.#s!==void 0}build(){let e=S("http"),t=new Ot(this.#e,...this.#t);t=new Wt(t,...this.#r);let n=new tn(e,t);this.#i!==void 0&&(n.storage=this.#i),this.#o!==void 0&&(n.codecConfigurer=this.#o);let s=async(i,o)=>n.http(i,o);return this.#s?this.#s(s):s}};var Jt={create:(r,e)=>new nn(r,e)},rn=class{#e;constructor(e){this.#e=e}accept(){return M.parseMediaTypes(...this.#e.list("accept"))}contentLength(){let e=this.#e.one("content-length");return e!==void 0?Number.parseInt(e):void 0}contentType(){return ge(this.#e)}header(e){return this.#e.list(e)}firstHeader(e){let t=this.#e.list(e);return t.length>0?t[0]:void 0}asHttpHeaders(){return this.#e}},nn=class{exchange;messageReaders;#e;constructor(e,t){this.exchange=e,this.messageReaders=[...t],this.#e=new rn(e.request.headers)}get attributes(){return this.exchange.attributes}get headers(){return this.#e}get method(){return this.request.method}get URL(){return this.request.URL}get requestPath(){return this.request.requestPath}queryParam(e){return this.request.URL.searchParams.get(e)}get principal(){return this.exchange.principal()}get request(){return this.exchange.request}};var C=class{static WILDCARD_WEIGHT=100;static CAPTURE_VARIABLE_WEIGHT=1;static NO_PARAMETERS=new Map;pos;separator;next;prev;constructor(e,t){this.pos=e,this.separator=t}get captureCount(){return 0}get wildcardCount(){return 0}get score(){return 0}get literal(){return!1}noMorePattern(){return this.next===void 0}};var pe=class extends C{constructor(e,t){super(e,t)}matches(e,t){return e<t.pathLength&&t.isSeparator(e)?this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e+1,!0):e+1===t.pathLength:(e++,this.next!==void 0&&this.next.matches(e,t)):!1}get normalizedLength(){return 1}get chars(){return new Uint16Array([this.separator])}get literal(){return!0}toString(){return`Separator(${String.fromCharCode(this.separator)})`}};var Ie=class extends C{constructor(e,t){super(e,t)}matches(e,t){let n;if(e<t.pathLength){let s=t.pathElements[e];if(!F(s))return!1;n=s.valueToMatch,e++}return this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:n===void 0||n.length===0?!1:this.next!==void 0&&this.next.matches(e,t)}get normalizedLength(){return 1}get chars(){return new Uint16Array([42])}get wildcardCount(){return 1}get score(){return C.WILDCARD_WEIGHT}toString(){return"Wildcard(*)"}};var K=class extends C{#e;constructor(e,t,n){super(e,n),this.#e=String.fromCharCode(...t.slice(2,t.length-1))}matches(e,t){if(e===0&&this.next!==void 0){let n=e;for(;n<t.pathLength;){if(this.next.matches(n,t))return this.#t(t,e,n),!0;n++}return!1}else if(e<t.pathLength&&!t.isSeparator(e))return!1;return t.determinedRemainingPath&&(t.remainingPathIndex=t.pathLength),this.#t(t,e,t.pathLength),!0}#t(e,t,n){if(e.extractingVariables){let s=C.NO_PARAMETERS;for(let i=t;i<n;i++){let o=e.pathElements[i];if(F(o)){let{parameters:a}=o;if(a.size>0){s===C.NO_PARAMETERS&&(s=new Map);for(let[c,d]of a)if(s.has(c)){let u=s.get(c);s.set(c,u.concat(d))}else s.set(c,d)}}}e.set(this.#e,this.#r(t,n,e.pathElements),s)}}#r(e,t,n){let s=[];for(let i=e;i<t;i++){let o=n[i];F(o)?s.push(o.valueToMatch):s.push(o.value)}return s.join("")}get normalizedLength(){return 1}get chars(){let e=`${String.fromCharCode(this.separator)}{*${this.#e}}`,t=new Uint16Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}get wildcardCount(){return 0}get captureCount(){return 1}toString(){return`CaptureSegments(${String.fromCharCode(this.separator)}{*${this.#e}})`}};var Q=class extends C{constructor(e,t){super(e,t)}matches(e,t){if(e===0&&this.next!==void 0){let n=e;for(;n<t.pathLength;){if(this.next.matches(n,t))return!0;n++}return!1}else if(e<t.pathLength&&!t.isSeparator(e))return!1;return t.determinedRemainingPath&&(t.remainingPathIndex=t.pathLength),!0}get normalizedLength(){return 1}get chars(){let e=`${String.fromCharCode(this.separator)}**`,t=new Uint16Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}get wildcardCount(){return 1}toString(){return`WildcardSegments(${String.fromCharCode(this.separator)}**)`}};var Yt=class{#e;pathElements;pathLength;#t;#r;extractingVariables=!1;#n=!1;remainingPathIndex=0;constructor(e,t){this.#e=e,this.pathElements=e.elements,this.pathLength=this.pathElements.length,this.extractingVariables=t}get determinedRemainingPath(){return this.#n}setMatchAllowExtraPath(){this.#n=!0}set(e,t,n){this.#t===void 0&&(this.#t=new Map),this.#t.set(e,t),n.size>0&&(this.#r===void 0&&(this.#r=new Map),this.#r.set(e,n))}get pathMatchResult(){return this.#t===void 0?et.EMPTY:new et(this.#t,this.#r)}isSeparator(e){return z(this.pathElements[e])}pathElementValue(e){let t=e<this.pathLength?this.pathElements[e]:null;return t!==null&&F(t)?t.valueToMatch:""}},et=class r{static EMPTY=new r(new Map,new Map);uriVariables;matrixVariables;constructor(e,t){this.uriVariables=e,this.matrixVariables=t??new Map}toString(){return`PathMatchInfo(uriVariables=${this.uriVariables}, matrixVariables=${this.matrixVariables})`}},Kt=class r{static#e=j("");static SPECIFICITY_COMPARATOR=(e,t)=>e==null?t==null?0:1:t==null?-1:e.catchAll&&!t.catchAll?1:!e.catchAll&&t.catchAll?-1:0;#t;#r;#n;#s;#i;#o=0;#c=0;#d=!1;#a=0;#u=!1;constructor(e,t,n){this.#t=e,this.#r=t,this.#n=t.pathOptions,this.#s=t.caseSensitive,this.#i=n;let s=n;for(;s!==void 0;)this.#o+=s.captureCount,this.#c+=s.normalizedLength,this.#a+=s.score,(s instanceof K||s instanceof Q)&&(this.#u=!0),s instanceof pe&&s.next instanceof Ie&&s.next.next===void 0&&(this.#d=!0),s=s.next}get patternString(){return this.#t}get hasPatternSyntax(){return this.#a>0||this.#u||this.#t.indexOf("?")!==-1}#h(e){return e!==void 0&&e.elements.length>0}#p(e){return e.value.length===1&&e.value.charCodeAt(0)===this.separator}matches(e){if(this.#i===void 0)return!this.#h(e);if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return!1;let t=new Yt(e,!1);return this.#i.matches(0,t)}matchAndExtract(e){if(this.#i===void 0)return this.#h(e)&&!this.#p(e)?void 0:et.EMPTY;if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return;let t=new Yt(e,!0);return this.#i.matches(0,t)?t.pathMatchResult:void 0}extractPathWithinPattern(e){let t=e.elements,n=t.length,s=0,i=this.#i;for(;i!==void 0&&i.literal;)i=i.next,s++;if(i===void 0)return j("");for(;s<n&&z(t[s]);)s++;let o=n;for(;o>0&&z(t[o-1]);)o--;let a=!1;for(let d=s;d<o-1;d++)if(z(t[d])&&z(t[d+1])){a=!0;break}let c;if(a){let d=[],u=s;for(;u<o;){let h=t[u++];if(d.push(h.value),z(h))for(;u<o&&z(t[u]);)u++}c=j(d.join(""),this.#n)}else s>=o?c=j("",this.#n):c=Ue(e,s,o);return c}get score(){return this.#a}get catchAll(){return this.#u}get normalizedLength(){return this.#c}get separator(){return this.#n.separator}get capturedVariableCount(){return this.#o}toChainString(){let e=[],t=this.#i;for(;t!==void 0;)e.push(t.toString()),t=t.next;return e.join(" ")}computePatternString(){let e=[],t=this.#i;for(;t!==void 0;)e.push(String.fromCharCode(...t.chars)),t=t.next;return e.join("")}get head(){return this.#i}};import{format as qo}from"node:util";var _o={MISSING_CLOSE_CAPTURE:"Expected close capture character after variable name '}'",MISSING_OPEN_CAPTURE:"Missing preceding open capture character before variable name'{'",ILLEGAL_NESTED_CAPTURE:"Not allowed to nest variable captures",CANNOT_HAVE_ADJACENT_CAPTURES:"Adjacent captures are not allowed",ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR:"Char '%s' not allowed at start of captured variable name",ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR:"Char '%s' is not allowed in a captured variable name",CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS:"Multiple '{*...}' or '**' pattern elements are not allowed",INVALID_LOCATION_FOR_MULTISEGMENT_PATH_ELEMENT:"'{*...}' or '**' pattern elements should be placed at the start or end of the pattern",MISSING_REGEX_CONSTRAINT:"Missing regex constraint on capture",ILLEGAL_DOUBLE_CAPTURE:"Not allowed to capture ''{0}'' twice in the same pattern",REGEX_PATTERN_SYNTAX_EXCEPTION:"Exception occurred in regex pattern compilation",CAPTURE_ALL_IS_STANDALONE_CONSTRUCT:"'{*...}' cannot be mixed with other path elements in the same path segment"},H=class r extends Error{position;messageType;inserts;#e;static formatMessage(e,t){return qo(_o[e],...t)}static createWithCause(e,t,n,s,...i){let o=r.formatMessage(s,i);return new r(t,n,s,i,o,{cause:e})}static create(e,t,n,...s){let i=r.formatMessage(n,s);return new r(e,t,n,s,i)}constructor(e,t,n,s,i,o){super(i,o),this.position=e,this.#e=t,this.messageType=n,this.inserts=s}toDetailedString(){let e=[];e.push(String.fromCharCode(...this.#e)),e.push(`
|
|
19
19
|
`);for(let t=0;t<Math.max(0,this.position);t++)e.push(" ");return e.push(`^
|
|
20
|
-
`),e.push(this.message),e.join("")}};var
|
|
21
|
-
${this.#r} does not match the number of variables it defines, which can occur if capturing groups are used in the regex itself. Use non-capturing groups (?:...) instead.`);for(let o=1;o<s.length;o++){let a=this.#s[o-1],c=s[o];t.set(a,c,o==this.#s.length?t.pathElements[e].parameters:E.NO_PARAMETERS)}}return i}get variableNames(){return this.#s}get normalizedLength(){let e=0;for(let t of this.#s)e+=t.length;return this.#e.length-e-this.#s.length}get chars(){return this.#e}get captureCount(){return this.#s.length}get wildcardCount(){return this.#n}get score(){return this.captureCount*E.CAPTURE_VARIABLE_WEIGHT+this.wildcardCount*E.WILDCARD_WEIGHT}toString(){return`Regex(${String.fromCharCode(...this.#e)})`}};var Qt=class extends E{#e;#t;#r;constructor(e,t,n,s){super(e,s),this.#t=t.length,this.#r=n,this.#e=String.fromCharCode(...t)}matches(e,t){if(e>=t.pathLength)return!1;let n=t.pathElements[e];if(!F(n))return!1;let s=n.valueToMatch;if(s.length!==this.#t)return!1;if(this.#r){if(this.#e!==s)return!1}else if(this.#e.toLowerCase()!==s.toLowerCase())return!1;return e++,this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:this.next.matches(e,t)}get normalizedLength(){return this.#t}get chars(){let e=new Uint16Array(this.#t);for(let t=0;t<this.#t;t++)e[t]=this.#e.charCodeAt(t);return e}get literal(){return!0}toString(){return`Literal(${this.#e})`}};function Oo(r){return r===36||r===95||r>=65&&r<=90||r>=97&&r<=122}function Lo(r){return r===36||r===95||r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57}var Zt=class{#e;#t=new Uint16Array(0);#r=0;#n=0;#s=0;#i=!1;#o=!1;#c=!1;#d=0;#a=0;#u=0;#h=!1;#p;#f;#l;constructor(e){this.#e=e}parse(e){if(e==null)throw new TypeError("pathPattern must be defined");this.#t=new Uint16Array(e.length);for(let t=0;t<e.length;t++)this.#t[t]=e.charCodeAt(t);for(this.#r=this.#t.length,this.#f=void 0,this.#l=void 0,this.#p=void 0,this.#a=-1,this.#n=0,this.#w();this.#n<this.#r;){let t=this.#t[this.#n],n=this.#e.pathOptions.separator;if(t===n)this.#a!==-1&&this.#m(this.#y()),this.#m(new he(this.#n,n));else{if(this.#a===-1&&(this.#a=this.#n),t===63)this.#s++;else if(t===123){if(this.#c)throw H.create(this.#n,this.#t,"ILLEGAL_NESTED_CAPTURE");this.#c=!0,this.#u=this.#n}else if(t===125){if(!this.#c)throw H.create(this.#n,this.#t,"MISSING_OPEN_CAPTURE");this.#c=!1,this.#d++}else t===58?this.#c&&!this.#o&&(this.#E(),this.#c=!1,this.#d++):this.#v(n)?(this.#b(this.#n,this.#n+1),this.#m(new Q(this.#n,n)),this.#h=!0,this.#n++):t===42&&(this.#c&&this.#u==this.#n-1&&(this.#o=!0),this.#i=!0);if(this.#c){if(this.#u+1+(this.#o?1:0)===this.#n&&!Oo(t))throw H.create(this.#n,this.#t,"ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR",String.fromCharCode(t));if(this.#n>this.#u+1+(this.#o?1:0)&&!Lo(t)&&t!==45)throw H.create(this.#n,this.#t,"ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR",String.fromCharCode(t))}}this.#n++}return this.#a!==-1&&this.#m(this.#y()),new Jt(e,this.#e,this.#f)}#g(){let e=new Uint16Array(this.#n-this.#a),t=0;for(let n=this.#a;n<this.#n;n++)e[t++]=this.#t[n];return e}#y(){if(this.#c)throw H.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");let e,t=this.#e.pathOptions.separator;if(this.#d>0)if(this.#d===1&&this.#a===this.#u&&this.#t[this.#n-1]===125)if(this.#o)this.#b(this.#a,this.#n-1),this.#h=!0,e=new K(this.#a,this.#g(),t);else{try{e=new Yt(this.#a,this.#g(),this.#e.caseSensitive,t)}catch(n){throw n instanceof SyntaxError?H.createWithCause(n,this.#P(this.#t,this.#a)+(n.index??0),this.#t,"REGEX_PATTERN_SYNTAX_EXCEPTION"):n}this.#S(this.#a,e.variableName)}else{if(this.#o)throw H.create(this.#a,this.#t,"CAPTURE_ALL_IS_STANDALONE_CONSTRUCT");let n=new et(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t);for(let s of n.variableNames)this.#S(this.#a,s);e=n}else this.#i?this.#n-1===this.#a?e=new ke(this.#a,t):e=new et(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t):this.#s!==0?e=new Kt(this.#a,this.#g(),this.#s,this.#e.caseSensitive,t):e=new Qt(this.#a,this.#g(),this.#e.caseSensitive,t);return e}#E(){this.#n++;let e=this.#n,t=0,n=!1;for(;this.#n<this.#r;){let s=this.#t[this.#n];if(s===92&&!n){this.#n++,n=!0;continue}if(s===123&&!n)t++;else if(s===125&&!n){if(t===0){if(e==this.#n)throw H.create(this.#n,this.#t,"MISSING_REGEX_CONSTRAINT");return}t--}if(s==this.#e.pathOptions.separator&&!n)throw H.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");this.#n++,n=!1}throw H.create(this.#n-1,this.#t,"MISSING_CLOSE_CAPTURE")}#v(e){return!(this.#n+1>=this.#r||this.#t[this.#n]!==42||this.#t[this.#n+1]!==42||this.#n-1>=0&&this.#t[this.#n-1]!==e||this.#n+2<this.#r&&this.#t[this.#n+2]!==e)}#b(e,t){if(this.#h)throw H.create(this.#n,this.#t,"CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS");if(e>1&&t!==this.#r-1)throw H.create(this.#n,this.#t,"INVALID_LOCATION_FOR_MULTISEGMENT_PATH_ELEMENT")}#m(e){if(e instanceof K||e instanceof Q)if(this.#l===void 0)this.#f=e,this.#l=e;else if(this.#l instanceof he){let t=this.#l.prev;t===void 0?(this.#f=e,e.prev=void 0):(t.next=e,e.prev=t),this.#l=e}else throw new Error(`expected SeparatorPathElement before ${e} but was ${this.#l}`);else this.#f===void 0?(this.#f=e,this.#l=e):this.#l!==void 0&&(this.#l.next=e,e.prev=this.#l,this.#l=e);this.#w()}#P(e,t){let n=t;for(;n<e.length;){if(e[n]===58)return n+1;n++}return-1}#w(){this.#a=-1,this.#s=0,this.#c=!1,this.#d=0,this.#i=!1,this.#o=!1,this.#u=-1}#S(e,t){if(this.#p===void 0&&(this.#p=[]),this.#p?.find(n=>n===t)!==void 0)throw H.create(e,this.#t,"ILLEGAL_DOUBLE_CAPTURE",t);this.#p.push(t)}};var er=class r{#e=!0;#t=br;get caseSensitive(){return this.#e}set caseSensitive(e){this.#e=e}get pathOptions(){return this.#t}set pathOptions(e){this.#t=e}initFullPathPattern(e){return e&&!e.startsWith("/")?"/"+e:e}parse(e){return new Zt(this).parse(e)}static DEFAULT=new class extends r{get caseSensitive(){return super.caseSensitive}set caseSensitive(e){this.#r()}get pathOptions(){return super.pathOptions}set pathOptions(e){this.#r()}#r(){throw new Error("PathPatternParser.DEFAULT is immutable")}}};var bs=w("web.async.fn.router"),tn="io.interop.web.async.fn.router.request",rn="io.interop.web.async.fn.router.variables",ws="io.interop.web.async.fn.router.pattern";function Ss(r){let e={route:r,and:t=>Fo(e,t)};return e}function Fo(r,e){return Ss(async t=>{let n=r.route(t);return n!==void 0?n:e.route(t)})}function Es(r,e){return Ss(async t=>{if(r.test(t)){if(bs.enabledFor("trace")){let n=t.exchange.logPrefix;bs.debug(`${n}Matched ${r}`)}return e}else return})}var vs=(function(){let r=w("request.predicates");function e(l){if(X(l.exchange.request)){let h=l.headers.firstHeader("Access-Control-Request-Method");if(h!==void 0)return h.toUpperCase()}return l.method}function t(l){let h={test:l,and:p=>n(h,p),negate:()=>i(h),or:p=>s(h,p),toString:()=>l.toString()};return h}function n(l,h){return t(p=>l.test(p)&&h.test(p))}function s(l,h){let p=t(g=>l.test(g)||h.test(g));return p.toString=()=>`(${l} || ${h})`,p}function i(l){let h=t(p=>!l.test(p));return h.toString=()=>`!${l}`,h}function o(l){let h=p=>{let g=e(p),b=l===g;return u("Method",l,g,b),b};return h.toString=()=>`${l}`,t(h)}function a(...l){if(!l)throw new Error("At least one HTTP method must be provided");if(l.length===1)return o(l[0]);let h=new Set(...l),p=g=>{let b=e(g),S=h.has(b);return u("Method",`[${[...h].join(", ")}]`,b,S),S};return p.toString=()=>`[${l.join(", ")}]`,t(p)}function c(l){let h=er.DEFAULT;return l=h.initFullPathPattern(l),d(h)(l)}function d(l){return h=>{let p=l.parse(h),g=b=>{let S=b.requestPath.pathWithinApplication,T=p.matchAndExtract(S);return u("Pattern",p.patternString,S.value,T!==void 0),T!==void 0};return g.toString=()=>p.patternString,t(g)}}function u(l,h,p,g){r.enabledFor("trace")&&r.debug(`${l} "${h}" ${g?"matches":"does not match"} against value "${p}"`)}function f(l){let h=p=>X(p.exchange.request)?!0:l(p.headers);return h.toString=()=>l.toString(),t(h)}function m(...l){if(!l)throw new Error("mediaTypes must not be empty");function h(p){let g=p.accept();return g.length===0?g=[A.ALL]:vn(g),g}if(l.length===1){let p=l[0],g=b=>{let S=h(b),T=!1;for(let L of S)if(re(L,p)){T=!0;break}return u("Accept",p,S,T),T};return g.toString=()=>`Accept: ${p}`,f(g)}else{let p=g=>{let b=h(g),S=!1;e:for(let T of b)for(let L of l)if(re(T,L)){S=!0;break e}return u("Accept",l,b,S),S};return p.toString=()=>`Accept: ${l.join(", ")}`,f(p)}}function v(l,h){let p=typeof h=="string"?h:void 0,g=typeof h=="string"?S=>S===p:h,b=S=>{let T=S.queryParam(l);return T!=null&&g(T)};return b.toString=()=>`?${l} ${h}`,t(b)}return{all:()=>t(l=>!0),method:o,methods:a,path:c,pathPredicates:d,headers:f,accept:m,GET:l=>o("GET").and(c(l)),HEAD:l=>o("HEAD").and(c(l)),POST:l=>o("POST").and(c(l)),PUT:l=>o("PUT").and(c(l)),PATCH:l=>o("PATCH").and(c(l)),DELETE:l=>o("DELETE").and(c(l)),OPTIONS:l=>o("OPTIONS").and(c(l)),queryParam:v}})();async function Do(r){return tr(r.statusCode).headers(e=>{for(let t of r.headers.keys())e.add(t,r.headers.list(t))}).bodyValue(r.body)}function tr(r){return r=typeof r=="number"?at(r):r,new nn(r)}function $o(){return tr(y.OK)}function Uo(r){return tr(y.CREATED).location(r)}var Ps={from:Do,status:tr,ok:$o,created:Uo};function No(r,e,t,n){let s=fe(r.headers);for(let i of e.messageWriters)if(i.canWrite(n,s))return i.write(t,n,r,s);return Promise.reject(new Error(`No HttpMessageWriter found for body type ${n} and media type ${s}`))}function qo(r){return async(e,t)=>No(e,t,Promise.resolve(r),typeof r)}var nn=class{#e;#t=new x;#r=new Map;#n=new Map;constructor(e){this.#e=e}header(e,...t){for(let n of t)this.#t.add(e,n);return this}cookie(e){let t=this.#r.get(e.name)??[];return t.push(e),this.#r.set(e.name,t),this}headers(e){return e(this.#t),this}contentType(e){return this.#t.set("Content-Type",e.toString()),this}contentLength(e){return this.#t.set("Content-Length",e.toString()),this}location(e){return this.#t.set("Location",e?.href),this}bodyValue(e){return this.#s(e,qo(e))}#s(e,t){return Promise.resolve(new on(this.#e,this.#t,new Map(this.#r),e,t,new Map(this.#n)))}build(e){return e?Promise.resolve(new sn(this.#e,this.#t,this.#r,e)):this.build(async(t,n)=>{await t.response.end()})}},We=class{#e;#t;#r;hints;constructor(e,t,n,s){this.#e=e,this.#t=t,this.#r=n,this.hints=s}get statusCode(){return this.#e}get headers(){return this.#t}get cookies(){let e=[];for(let t of this.#r.values())e.push(...t);return e}async writeTo(e,t){return this.#n(e.response),this.writeInternal(e,t)}#n(e){e.setStatusCode(this.#e);for(let t of this.#t.keys())e.headers.add(t,this.#t.list(t));for(let t of this.#r.values())for(let n of t)e.addCookie(n)}};var sn=class extends We{#e;constructor(e,t,n,s){super(e,t,n),this.#e=s}async writeInternal(e,t){await this.#e(e,t)}},on=class extends We{#e;#t;constructor(e,t,n,s,i,o){super(e,t,n,o),this.#e=s,this.#t=i}get entity(){return this.#e}get inserter(){return this.#t}async writeInternal(e,{messageWriters:t}){this.hints?.set(Bt,e.logPrefix),await this.inserter(e.response,{messageWriters:t,serverRequest:e.request,hints:this.hints})}};import{MIMEType as _o}from"node:util";var rr=class r extends Error{#e;#t=new x;body;constructor(e,t){super(),this.#e=e,this.body=t??r.problemDetailFor(e)}get statusCode(){return this.#e}set detail(e){this.body.detail=e}get headers(){return this.#t}static problemDetailFor(e,t){let n={status:e.value};return t!==void 0&&(n.detail=t),n}};var Z=class r extends rr{#e;constructor(e,t){super(e,r.problemDetailFor(e,t)),this.#e=t}get reason(){return this.#e}get headers(){return Cn}};var tt=class r{static ERROR_ATTRIBUTE="io.interop.web.server.exchange.error";getErrorAttributes(e,t){return this.#e(e,t.includes.includes("trace"))}getError(e){let t=e.attributes.get(r.ERROR_ATTRIBUTE);if(t===void 0)throw new Error("No error found in request attributes");return t}storeErrorInformation(e,t){t.attributes.set(r.ERROR_ATTRIBUTE,e)}#e(e,t){let n={};n.timestamp=new Date;let s=this.getError(e),i=this.#t(s);return n.status=i.value,n.reason=i.phrase,n.requestId=e.exchange.request.id,this.#r(n,s,t),n}#t(e){if(e instanceof Z){let t=y.resolve(e.statusCode.value);if(t)return t}return y.INTERNAL_SERVER_ERROR}#r(e,t,n){t instanceof Z&&(e.message=t.reason)}},an=class{#e;#t;#r;constructor(e,t,n){if(!t)throw new Error("messageWriters must not be null.");this.#e=n,this.#t=e,this.#r=t}getErrorAttributes(e,t){return this.#e.getErrorAttributes(e,t)}async handle(e,t){if(e.response.commited||this.#n(t))return Promise.reject(t);this.#e.storeErrorInformation(t,e);let n=jt.create(e,this.#t),s=await this.getRoutingFunction(this.#e)?.route(n);if(s){let i=await s(n);this.logError(n,i,t),await this.#s(e,i)}else throw t}logError(e,t,n){}#n(e){return Kr(e)}async#s(e,t){e.response.headers.set("Content-Type",t.headers.get("Content-Type"));let n={messageWriters:this.#r};return t.writeTo(e,n)}},nr=class r extends an{static#e=new tt;static#t={includes:["status"]};constructor(e,t,n,s={}){super(e,t,n)}getRoutingFunction(e){return Es(vs.all(),t=>this.#n(t))}#r(e,t){return super.getErrorAttributes(e,this.getErrorAttributeOptions(e,t))}getErrorAttributeOptions(e,t){return{includes:["error","message","status","path"]}}async#n(e){let t=this.#r(e,Le),n=this.#s(e,t);return Ps.status(n).contentType(new _o("application/json")).bodyValue(JSON.stringify(t))}#s(e,t){return this.getHttpStatus(t.status!==void 0?t:r.#e.getErrorAttributes(e,r.#t))}getHttpStatus(e){let t=e.status;if(typeof t=="number")return t;throw new Error(`Invalid status code: ${t}`)}};var Cs="io.interop.web.async.handler.handler",xs="io.interop.web.async.handler.pattern";var sr=class{#e;#t;#r;constructor(e,t,n){this.#e=e,this.#t=t,this.#r=n}async handle(e){if(!this.#e)return this.#o();if(X(e.request))return this.handlePreFlight(e);let t;try{for(let n of this.#e)if(t=await n.getHandler(e),t!==void 0)break;t===void 0&&await this.#o()}catch(n){return this.#n(e,Promise.reject(n))}return this.#i(e,t)}async#n(e,t){this.#t;let n=await t;try{await this.#s(e,n,`Handler ${n.handler}`)}catch(s){let i=n.exceptionHandler;if(i){let o=s instanceof Error?s:new Error(String(s)),a=await i(e,o);await this.#s(e,a,`Exception handler ${a.handler}, error="${o.message}"`)}}}#s(e,t,n){if(this.#r){for(let s of this.#r)if(s.supports(t))return n+=" [DispatcherHandler]",s.handle(e,t)}return Promise.reject(new Error(`No HandlerResultHandler for ${t.returnValue}`))}#i(e,t){if(e.response.statusCode?.value===y.FORBIDDEN.value)return Promise.resolve();if(this.#t){for(let n of this.#t)if(n.supports(t)){let s=n.handle(e,t);return this.#n(e,s)}}return Promise.reject(new Error(`No HandlerAdapter for handler ${t}`))}#o(){return Promise.reject(new Z(y.NOT_FOUND))}async handlePreFlight(e){let t;for(let n of this.#e??[])if(t=await n.getHandler(e),t!==void 0)break;if(t===void 0){e.response.setStatusCode(y.FORBIDDEN);return}}},ir=class{logger=w("web.async.handler");#e;set corsConfigSource(e){if(e===void 0)throw new Error("CorsConfigSource must not be undefined");this.#e=e}async getHandler(e){let t=await this.getHandlerInternal(e);if(t!==void 0){this.logger.enabledFor("debug")&&this.logger.debug(`${e.logPrefix}Mapped to ${t}`);let n=e.request;if(this.hasCorsConfigSource(t)||X(n)){let s=this.#e!==void 0?await this.#e(e):void 0,i=this.getCorsConfig(t,e)}return t}}hasCorsConfigSource(e){return this.#e!==void 0}getCorsConfig(e,t){}};var or=class{supports(e){return typeof e=="function"}async handle(e,t){let n=t,s=e.attribute(tn);if(!s)throw new Error("ServerRequest is not found in exchange attributes.");return n(s).then(i=>({handler:t,returnValue:i}))}},ar=class{#e=Array();constructor(e){if(!e||e.length===0)throw new Error("messageWriters must not be empty.");this.#e=e}supports(e){return e.returnValue instanceof We}get messageWriters(){return this.#e}async handle(e,t){let n=t.returnValue;if(n===void 0)throw new Error("No ServerResponse");return n.writeTo(e,{messageWriters:this.messageWriters})}},cr=class extends ir{#e;#t=void 0;constructor(e){super(),this.#e=e}set messageReaders(e){this.#t=e}init(...e){if((this.#t===void 0||this.#t.length===0)&&(this.#t=Me.serverConfigurer.create().readers),this.#e)throw new Error("RouterFunctionMapping is already initialized with a RouterFunction");this.#e=e.reduce((t,n)=>t.and(n))}async getHandlerInternal(e){if(this.#e===void 0)return;let t=jt.create(e,this.#t),n=await this.#e.route(t);return n!==void 0&&this.#r(e.attributes,t,n),n}#r(e,t,n){e.set(tn,t),e.set(Cs,n);let s=e.get(ws);s&&e.set(xs,s);let i=e.get(rn);i!==void 0&&e.set(rn,i)}};var R=w("app");async function zo(r,e){let t=r.build();return async(n,s)=>{n.socket.addListener("error",e);let i;s instanceof ge?i=s:(n.upgradeHead=s,i=new ge(n),i.assignSocket(n.socket));try{let o=new me(n),a=new ut(i),c=o.method==="HEAD"?new Dt(a):a,d=t(o,c);try{await d,R.enabledFor("trace")&&R.debug(`${o.id} handling completed.`)}catch(u){if(u instanceof Error&&u.code==="ERR_INVALID_URL")throw u;R.enabledFor("trace")&&R.debug(`${o.id} failed to complete: ${u instanceof Error?u.message:u}`)}}catch(o){if(o instanceof Error&&o.code==="ERR_INVALID_URL")return R.enabledFor("debug")&&R.debug(`failed to get request URI: ${o.message}`),i.statusCode=400,i.end(Rs.STATUS_CODES[400]),Promise.resolve();throw o}}}function jo(r){return new Promise((e,t)=>{let n=r(s=>{s?t(s):e(n)})})}function Xo(r){if(r)return Hn({memoryLimit:r.memory_limit,dumpLocation:r.dump_location,dumpPrefix:r.dump_prefix,reportInterval:r.report_interval,maxBackups:r.max_backups})}var Ts=`${As.name} - v${As.version}`;async function Jo(r){let e=r.storage,t=await ls(r),n=ps(r),s=Me.serverConfigurer.create();s.defaultCodecs.enableLoggingRequestDetails(!0);let i=new cr,o=new sr([i],[new or],[new ar(s.writers)]),a={handle:bn(kn(Ts,r.serverHeader),...n,...r.middleware,async({request:c,response:d},u)=>{if(c.method==="GET"&&c.path==="/health"){d.setStatusCode(y.OK);let f=Buffer.from("UP","utf-8");d.headers.set("Content-Type","text/plain; charset=utf-8"),await d.body(f)}else await u()},await Yr(r.resourcesConfig?.locations),async({response:c},d)=>{throw new Z(y.NOT_FOUND)})};return new zt(a).filter(new It(t)).codecConfigurer(s).exceptionHandler(new nr(s.readers,s.writers,new tt)).storage(e)}var cn=async r=>{let e=r.ssl,t=r.host,n=r.auth?.x509?.key?{host:t??"localhost",key:r.auth.x509.key,passphrase:r.auth.x509.passphrase}:void 0,s=e?(h,p)=>Go.createServer({...h,...gs(e,n)},p):(h,p)=>Rs.createServer(h,p),i=Xo(r.memory),o={middleware:[],corsConfig:r.cors,cors:[],authConfig:r.auth,authorize:[],storage:new Vo,sockets:new Map,resourcesConfig:r.resources},a=new rt({baseConfig:{...r.gateway},scope:r.gateway?.scope??"principal"});if(r.gateway){let h=r.gateway.route?r.gateway.route==="/"?void 0:r.gateway.route:void 0;await Ar(async p=>{p.socket({path:h,factory:pn.bind(a),options:r.gateway})},r,o)}r.app&&await Ar(r.app,r,o);let c=dn(r.port??0),d=h=>R.error(`socket error: ${h}`,h),u=await Jo(o),f=await zo(u,d),v=await new Promise((h,p)=>{let g=s({IncomingMessage:ct,ServerResponse:ge,...r.http},f);g.on("error",b=>{if(b.code==="EADDRINUSE"){R.debug(`port ${b.port} already in use on address ${b.address}`);let{value:S}=c.next();S?(R.info(`retry starting server on port ${S} and host ${t??"<unspecified>"}`),g.close(),g.listen(S,t)):(R.warn(`all configured port(s) ${r.port} are in use. closing...`),g.close(),p(b))}else R.error(`server error: ${b.message}`,b),p(b)}),g.on("listening",async()=>{let b=g.address();for(let[S,T]of o.sockets){let L=`${e?"wss":"ws"}://${un}:${b.port}${S}`;await fs(S,T,L,o.storage,d)}R.info(`http server listening on ${e?"https":"http"}://${ee(b)}`),h(g)}),g.on("upgrade",(b,S,T)=>{try{f(b,T)}catch(L){R.error(`upgrade error: ${L}`,L)}}).on("close",async()=>{R.info("http server closed.")});try{let{value:b}=c.next();g.listen(b,t)}catch(b){R.error("error starting web socket server",b),p(b instanceof Error?b:new Error(`listen failed: ${b}`))}}),l=new class{gateway=a;get address(){let h=v.address();return typeof h=="object"?h:null}async close(){for(let[h,p]of o.sockets)try{p.close!==void 0&&await p.close()}catch(g){R.warn(`error closing route ${h}`,g)}await jo(h=>{v.closeAllConnections(),v.close(h)}),i&&await Mn(i),await a.stop()}};return r.management?.server.path&&ms({options:r.management.server,info:async()=>({pid:process.pid,type:"gateway-server",...l.gateway.info()}),logger:R.child("management"),shutdown:r.management.commands?.shutdown.enabled?async()=>{R.enabledFor("info")&&R.info("stopping gateway-server..."),await l.close()}:void 0}),l};var Cp=cn;export{Hs as GatewayServer,Cp as default};
|
|
20
|
+
`),e.push(this.message),e.join("")}};var Qt=class extends C{variableName;#e;constructor(e,t,n,s){super(e,s);let i=-1;for(let o=0;o<t.length;o++)if(t[o]===58){i=o;break}if(i===-1)this.variableName=String.fromCharCode(...t.slice(1,t.length-1)),this.#e=void 0;else{this.variableName=String.fromCharCode(...t.slice(1,i));let o=String.fromCharCode(...t.slice(i+1,t.length-1)),a=n?"s":"si";this.#e=new RegExp(o,a)}}matches(e,t){if(e>=t.pathLength)return!1;let n=t.pathElementValue(e);if(n.length===0)return!1;if(this.#e!==void 0){let i=this.#e.exec(n);if(i===null||i.index!==0||i[0].length!==n.length)return!1;if(i.length>1)throw new TypeError(`No capture groups allowed in the constraint regex: ${this.#e}`)}let s=!1;return e++,this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,s=!0):s=e===t.pathLength:this.next!==void 0&&(s=this.next.matches(e,t)),s&&t.extractingVariables&&t.set(this.variableName,n,t.pathElements[e-1].parameters),s}get normalizedLength(){return 1}get chars(){let e=[];e.push("{"),e.push(this.variableName),this.#e!==void 0&&(e.push(":"),e.push(this.#e.source)),e.push("}");let t=e.join(""),n=new Uint16Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}get wildcardCount(){return 0}get captureCount(){return 1}get score(){return C.CAPTURE_VARIABLE_WEIGHT}toString(){return`CaptureVariable({${this.variableName}${this.#e?":"+this.#e.source:""}})`}};var Zt=class extends C{#e;#t;#r;#n;constructor(e,t,n,s,i){if(super(e,i),this.#t=t.length,this.#r=n,this.#n=s,s)this.#e=t;else{this.#e=new Uint16Array(t.length);for(let o=0;o<t.length;o++)this.#e[o]=String.fromCharCode(t[o]).toLowerCase().charCodeAt(0)}}matches(e,t){if(e>=t.pathLength)return!1;let n=t.pathElements[e];if(!F(n))return!1;let s=n.valueToMatch;if(s.length!==this.#t)return!1;if(this.#n)for(let i=0;i<this.#t;i++){let o=this.#e[i];if(o!==63&&o!==s.charCodeAt(i))return!1}else for(let i=0;i<this.#t;i++){let o=this.#e[i];if(o!==63&&o!==String.fromCharCode(s.charCodeAt(i)).toLowerCase().charCodeAt(0))return!1}return e++,this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:this.next!==void 0&&this.next.matches(e,t)}get wildcardCount(){return this.#r}get normalizedLength(){return this.#t}get chars(){return this.#e}toString(){return`SingleCharWildcarded(${String.fromCharCode(...this.#e)})`}};var tt=class extends C{#e;#t;#r;#n;#s;constructor(e,t,n,s,i){super(e,i),this.#e=t,this.#t=n,[this.#r,this.#n,this.#s]=this.#i(t,s)}#i(e,t){let n=String.fromCharCode(...e),s=[],i=0,o=[],a=0;for(;a<n.length;){let u=n.charAt(a);if(u==="{"){let h=n.indexOf("}",a);if(h===-1)throw new SyntaxError(`Missing closing brace in pattern: ${n}`);let g=n.substring(a+1,h),E=g.indexOf(":"),l,p;E!==-1?(l=g.substring(0,E),p=g.substring(E+1)):(l=g,p="[^/]*"),l.startsWith("*")&&(l=l.substring(1),p=".*"),s.push(l),o.push("(",p,")"),a=h+1}else u==="*"?(i++,o.push("[^/]*"),a++):u==="?"?(o.push("."),a++):".+()[]^$|\\".includes(u)?(o.push("\\",u),a++):(o.push(u),a++)}let c=o.join(""),d=this.#t?"s":"si";return[new RegExp(`^${c}$`,d),i,s]}matches(e,t){let n=t.pathElementValue(e),s=this.#r.exec(n),i=s!==null&&s.index===0&&s[0].length===n.length;if(i&&(this.noMorePattern()?t.determinedRemainingPath&&(this.#s.length===0||n.length!==0)?(t.remainingPathIndex=e+1,i=!0):i=e+1>=t.pathLength&&(this.#s.length===0||n.length!==0):i=this.next!==void 0&&this.next.matches(e+1,t)),i&&t.extractingVariables){if(this.#s.length+1!==s?.length)throw new Error(`The number of capturing groups in the pattern segment
|
|
21
|
+
${this.#r} does not match the number of variables it defines, which can occur if capturing groups are used in the regex itself. Use non-capturing groups (?:...) instead.`);for(let o=1;o<s.length;o++){let a=this.#s[o-1],c=s[o];t.set(a,c,o==this.#s.length?t.pathElements[e].parameters:C.NO_PARAMETERS)}}return i}get variableNames(){return this.#s}get normalizedLength(){let e=0;for(let t of this.#s)e+=t.length;return this.#e.length-e-this.#s.length}get chars(){return this.#e}get captureCount(){return this.#s.length}get wildcardCount(){return this.#n}get score(){return this.captureCount*C.CAPTURE_VARIABLE_WEIGHT+this.wildcardCount*C.WILDCARD_WEIGHT}toString(){return`Regex(${String.fromCharCode(...this.#e)})`}};var er=class extends C{#e;#t;#r;constructor(e,t,n,s){super(e,s),this.#t=t.length,this.#r=n,this.#e=String.fromCharCode(...t)}matches(e,t){if(e>=t.pathLength)return!1;let n=t.pathElements[e];if(!F(n))return!1;let s=n.valueToMatch;if(s.length!==this.#t)return!1;if(this.#r){if(this.#e!==s)return!1}else if(this.#e.toLowerCase()!==s.toLowerCase())return!1;return e++,this.noMorePattern()?t.determinedRemainingPath?(t.remainingPathIndex=e,!0):e===t.pathLength:this.next.matches(e,t)}get normalizedLength(){return this.#t}get chars(){let e=new Uint16Array(this.#t);for(let t=0;t<this.#t;t++)e[t]=this.#e.charCodeAt(t);return e}get literal(){return!0}toString(){return`Literal(${this.#e})`}};function Bo(r){return r===36||r===95||r>=65&&r<=90||r>=97&&r<=122}function Go(r){return r===36||r===95||r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57}var tr=class{#e;#t=new Uint16Array(0);#r=0;#n=0;#s=0;#i=!1;#o=!1;#c=!1;#d=0;#a=0;#u=0;#h=!1;#p;#f;#l;constructor(e){this.#e=e}parse(e){if(e==null)throw new TypeError("pathPattern must be defined");this.#t=new Uint16Array(e.length);for(let t=0;t<e.length;t++)this.#t[t]=e.charCodeAt(t);for(this.#r=this.#t.length,this.#f=void 0,this.#l=void 0,this.#p=void 0,this.#a=-1,this.#n=0,this.#w();this.#n<this.#r;){let t=this.#t[this.#n],n=this.#e.pathOptions.separator;if(t===n)this.#a!==-1&&this.#m(this.#y()),this.#m(new pe(this.#n,n));else{if(this.#a===-1&&(this.#a=this.#n),t===63)this.#s++;else if(t===123){if(this.#c)throw H.create(this.#n,this.#t,"ILLEGAL_NESTED_CAPTURE");this.#c=!0,this.#u=this.#n}else if(t===125){if(!this.#c)throw H.create(this.#n,this.#t,"MISSING_OPEN_CAPTURE");this.#c=!1,this.#d++}else t===58?this.#c&&!this.#o&&(this.#E(),this.#c=!1,this.#d++):this.#v(n)?(this.#b(this.#n,this.#n+1),this.#m(new Q(this.#n,n)),this.#h=!0,this.#n++):t===42&&(this.#c&&this.#u==this.#n-1&&(this.#o=!0),this.#i=!0);if(this.#c){if(this.#u+1+(this.#o?1:0)===this.#n&&!Bo(t))throw H.create(this.#n,this.#t,"ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR",String.fromCharCode(t));if(this.#n>this.#u+1+(this.#o?1:0)&&!Go(t)&&t!==45)throw H.create(this.#n,this.#t,"ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR",String.fromCharCode(t))}}this.#n++}return this.#a!==-1&&this.#m(this.#y()),new Kt(e,this.#e,this.#f)}#g(){let e=new Uint16Array(this.#n-this.#a),t=0;for(let n=this.#a;n<this.#n;n++)e[t++]=this.#t[n];return e}#y(){if(this.#c)throw H.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");let e,t=this.#e.pathOptions.separator;if(this.#d>0)if(this.#d===1&&this.#a===this.#u&&this.#t[this.#n-1]===125)if(this.#o)this.#b(this.#a,this.#n-1),this.#h=!0,e=new K(this.#a,this.#g(),t);else{try{e=new Qt(this.#a,this.#g(),this.#e.caseSensitive,t)}catch(n){throw n instanceof SyntaxError?H.createWithCause(n,this.#P(this.#t,this.#a)+(n.index??0),this.#t,"REGEX_PATTERN_SYNTAX_EXCEPTION"):n}this.#S(this.#a,e.variableName)}else{if(this.#o)throw H.create(this.#a,this.#t,"CAPTURE_ALL_IS_STANDALONE_CONSTRUCT");let n=new tt(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t);for(let s of n.variableNames)this.#S(this.#a,s);e=n}else this.#i?this.#n-1===this.#a?e=new Ie(this.#a,t):e=new tt(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t):this.#s!==0?e=new Zt(this.#a,this.#g(),this.#s,this.#e.caseSensitive,t):e=new er(this.#a,this.#g(),this.#e.caseSensitive,t);return e}#E(){this.#n++;let e=this.#n,t=0,n=!1;for(;this.#n<this.#r;){let s=this.#t[this.#n];if(s===92&&!n){this.#n++,n=!0;continue}if(s===123&&!n)t++;else if(s===125&&!n){if(t===0){if(e==this.#n)throw H.create(this.#n,this.#t,"MISSING_REGEX_CONSTRAINT");return}t--}if(s==this.#e.pathOptions.separator&&!n)throw H.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");this.#n++,n=!1}throw H.create(this.#n-1,this.#t,"MISSING_CLOSE_CAPTURE")}#v(e){return!(this.#n+1>=this.#r||this.#t[this.#n]!==42||this.#t[this.#n+1]!==42||this.#n-1>=0&&this.#t[this.#n-1]!==e||this.#n+2<this.#r&&this.#t[this.#n+2]!==e)}#b(e,t){if(this.#h)throw H.create(this.#n,this.#t,"CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS");if(e>1&&t!==this.#r-1)throw H.create(this.#n,this.#t,"INVALID_LOCATION_FOR_MULTISEGMENT_PATH_ELEMENT")}#m(e){if(e instanceof K||e instanceof Q)if(this.#l===void 0)this.#f=e,this.#l=e;else if(this.#l instanceof pe){let t=this.#l.prev;t===void 0?(this.#f=e,e.prev=void 0):(t.next=e,e.prev=t),this.#l=e}else throw new Error(`expected SeparatorPathElement before ${e} but was ${this.#l}`);else this.#f===void 0?(this.#f=e,this.#l=e):this.#l!==void 0&&(this.#l.next=e,e.prev=this.#l,this.#l=e);this.#w()}#P(e,t){let n=t;for(;n<e.length;){if(e[n]===58)return n+1;n++}return-1}#w(){this.#a=-1,this.#s=0,this.#c=!1,this.#d=0,this.#i=!1,this.#o=!1,this.#u=-1}#S(e,t){if(this.#p===void 0&&(this.#p=[]),this.#p?.find(n=>n===t)!==void 0)throw H.create(e,this.#t,"ILLEGAL_DOUBLE_CAPTURE",t);this.#p.push(t)}};var rr=class r{#e=!0;#t=Er;get caseSensitive(){return this.#e}set caseSensitive(e){this.#e=e}get pathOptions(){return this.#t}set pathOptions(e){this.#t=e}initFullPathPattern(e){return e&&!e.startsWith("/")?"/"+e:e}parse(e){return new tr(this).parse(e)}static DEFAULT=new class extends r{get caseSensitive(){return super.caseSensitive}set caseSensitive(e){this.#r()}get pathOptions(){return super.pathOptions}set pathOptions(e){this.#r()}#r(){throw new Error("PathPatternParser.DEFAULT is immutable")}}};var vs=S("web.async.fn.router"),sn="io.interop.web.async.fn.router.request",on="io.interop.web.async.fn.router.variables",Ps="io.interop.web.async.fn.router.pattern";function Cs(r){let e={route:r,and:t=>Vo(e,t)};return e}function Vo(r,e){return Cs(async t=>{let n=r.route(t);return n!==void 0?n:e.route(t)})}function xs(r,e){return Cs(async t=>{if(r.test(t)){if(vs.enabledFor("trace")){let n=t.exchange.logPrefix;vs.debug(`${n}Matched ${r}`)}return e}else return})}var As=(function(){let r=S("request.predicates");function e(l){if(X(l.exchange.request)){let p=l.headers.firstHeader("Access-Control-Request-Method");if(p!==void 0)return p.toUpperCase()}return l.method}function t(l){let p={test:l,and:f=>n(p,f),negate:()=>i(p),or:f=>s(p,f),toString:()=>l.toString()};return p}function n(l,p){return t(f=>l.test(f)&&p.test(f))}function s(l,p){let f=t(w=>l.test(w)||p.test(w));return f.toString=()=>`(${l} || ${p})`,f}function i(l){let p=t(f=>!l.test(f));return p.toString=()=>`!${l}`,p}function o(l){let p=f=>{let w=e(f),m=l===w;return u("Method",l,w,m),m};return p.toString=()=>`${l}`,t(p)}function a(...l){if(!l)throw new Error("At least one HTTP method must be provided");if(l.length===1)return o(l[0]);let p=new Set(...l),f=w=>{let m=e(w),y=p.has(m);return u("Method",`[${[...p].join(", ")}]`,m,y),y};return f.toString=()=>`[${l.join(", ")}]`,t(f)}function c(l){let p=rr.DEFAULT;return l=p.initFullPathPattern(l),d(p)(l)}function d(l){return p=>{let f=l.parse(p),w=m=>{let y=m.requestPath.pathWithinApplication,v=f.matchAndExtract(y);return u("Pattern",f.patternString,y.value,v!==void 0),v!==void 0};return w.toString=()=>f.patternString,t(w)}}function u(l,p,f,w){r.enabledFor("trace")&&r.debug(`${l} "${p}" ${w?"matches":"does not match"} against value "${f}"`)}function h(l){let p=f=>X(f.exchange.request)?!0:l(f.headers);return p.toString=()=>l.toString(),t(p)}function g(...l){if(!l)throw new Error("mediaTypes must not be empty");function p(f){let w=f.accept();return w.length===0?w=[M.ALL]:xn(w),w}if(l.length===1){let f=l[0],w=m=>{let y=p(m),v=!1;for(let P of y)if(re(P,f)){v=!0;break}return u("Accept",f,y,v),v};return w.toString=()=>`Accept: ${f}`,h(w)}else{let f=w=>{let m=p(w),y=!1;e:for(let v of m)for(let P of l)if(re(v,P)){y=!0;break e}return u("Accept",l,m,y),y};return f.toString=()=>`Accept: ${l.join(", ")}`,h(f)}}function E(l,p){let f=typeof p=="string"?p:void 0,w=typeof p=="string"?y=>y===f:p,m=y=>{let v=y.queryParam(l);return v!=null&&w(v)};return m.toString=()=>`?${l} ${p}`,t(m)}return{all:()=>t(l=>!0),method:o,methods:a,path:c,pathPredicates:d,headers:h,accept:g,GET:l=>o("GET").and(c(l)),HEAD:l=>o("HEAD").and(c(l)),POST:l=>o("POST").and(c(l)),PUT:l=>o("PUT").and(c(l)),PATCH:l=>o("PATCH").and(c(l)),DELETE:l=>o("DELETE").and(c(l)),OPTIONS:l=>o("OPTIONS").and(c(l)),queryParam:E}})();async function zo(r){return nr(r.statusCode).headers(e=>{for(let t of r.headers.keys())e.add(t,r.headers.list(t))}).bodyValue(r.body)}function nr(r){return r=typeof r=="number"?dt(r):r,new an(r)}function jo(){return nr(b.OK)}function Xo(r){return nr(b.CREATED).location(r)}var Rs={from:zo,status:nr,ok:jo,created:Xo};function Jo(r,e,t,n){let s=ge(r.headers);for(let i of e.messageWriters)if(i.canWrite(n,s))return i.write(t,n,r,s);return Promise.reject(new Error(`No HttpMessageWriter found for body type ${n} and media type ${s}`))}function Yo(r){return async(e,t)=>Jo(e,t,Promise.resolve(r),typeof r)}var an=class{#e;#t=new R;#r=new Map;#n=new Map;constructor(e){this.#e=e}header(e,...t){for(let n of t)this.#t.add(e,n);return this}cookie(e){let t=this.#r.get(e.name)??[];return t.push(e),this.#r.set(e.name,t),this}headers(e){return e(this.#t),this}contentType(e){return this.#t.set("Content-Type",e.toString()),this}contentLength(e){return this.#t.set("Content-Length",e.toString()),this}location(e){return this.#t.set("Location",e?.href),this}bodyValue(e){return this.#s(e,Yo(e))}#s(e,t){return Promise.resolve(new dn(this.#e,this.#t,new Map(this.#r),e,t,new Map(this.#n)))}build(e){return e?Promise.resolve(new cn(this.#e,this.#t,this.#r,e)):this.build(async(t,n)=>{await t.response.end()})}},We=class{#e;#t;#r;hints;constructor(e,t,n,s){this.#e=e,this.#t=t,this.#r=n,this.hints=s}get statusCode(){return this.#e}get headers(){return this.#t}get cookies(){let e=[];for(let t of this.#r.values())e.push(...t);return e}async writeTo(e,t){return this.#n(e.response),this.writeInternal(e,t)}#n(e){e.setStatusCode(this.#e);for(let t of this.#t.keys())e.headers.add(t,this.#t.list(t));for(let t of this.#r.values())for(let n of t)e.addCookie(n)}};var cn=class extends We{#e;constructor(e,t,n,s){super(e,t,n),this.#e=s}async writeInternal(e,t){await this.#e(e,t)}},dn=class extends We{#e;#t;constructor(e,t,n,s,i,o){super(e,t,n,o),this.#e=s,this.#t=i}get entity(){return this.#e}get inserter(){return this.#t}async writeInternal(e,{messageWriters:t}){this.hints?.set(Vt,e.logPrefix),await this.inserter(e.response,{messageWriters:t,serverRequest:e.request,hints:this.hints})}};import{MIMEType as Ko}from"node:util";var sr=class r extends Error{#e;#t=new R;body;constructor(e,t){super(),this.#e=e,this.body=t??r.problemDetailFor(e)}get statusCode(){return this.#e}set detail(e){this.body.detail=e}get headers(){return this.#t}static problemDetailFor(e,t){let n={status:e.value};return t!==void 0&&(n.detail=t),n}};var Z=class r extends sr{#e;constructor(e,t){super(e,r.problemDetailFor(e,t)),this.#e=t}get reason(){return this.#e}get headers(){return Rn}};var rt=class r{static ERROR_ATTRIBUTE="io.interop.web.server.exchange.error";getErrorAttributes(e,t){return this.#e(e,t.includes.includes("trace"))}getError(e){let t=e.attributes.get(r.ERROR_ATTRIBUTE);if(t===void 0)throw new Error("No error found in request attributes");return t}storeErrorInformation(e,t){t.attributes.set(r.ERROR_ATTRIBUTE,e)}#e(e,t){let n={};n.timestamp=new Date;let s=this.getError(e),i=this.#t(s);return n.status=i.value,n.reason=i.phrase,n.requestId=e.exchange.request.id,this.#r(n,s,t),n}#t(e){if(e instanceof Z){let t=b.resolve(e.statusCode.value);if(t)return t}return b.INTERNAL_SERVER_ERROR}#r(e,t,n){t instanceof Z&&(e.message=t.reason)}},un=class{#e;#t;#r;constructor(e,t,n){if(!t)throw new Error("messageWriters must not be null.");this.#e=n,this.#t=e,this.#r=t}getErrorAttributes(e,t){return this.#e.getErrorAttributes(e,t)}async handle(e,t){if(e.response.commited||this.#n(t))return Promise.reject(t);this.#e.storeErrorInformation(t,e);let n=Jt.create(e,this.#t),s=await this.getRoutingFunction(this.#e)?.route(n);if(s){let i=await s(n);this.logError(n,i,t),await this.#s(e,i)}else throw t}logError(e,t,n){}#n(e){return en(e)}async#s(e,t){e.response.headers.set("Content-Type",t.headers.get("Content-Type"));let n={messageWriters:this.#r};return t.writeTo(e,n)}},ir=class r extends un{static#e=new rt;static#t={includes:["status"]};constructor(e,t,n,s={}){super(e,t,n)}getRoutingFunction(e){return xs(As.all(),t=>this.#n(t))}#r(e,t){return super.getErrorAttributes(e,this.getErrorAttributeOptions(e,t))}getErrorAttributeOptions(e,t){return{includes:["error","message","status","path"]}}async#n(e){let t=this.#r(e,Fe),n=this.#s(e,t);return Rs.status(n).contentType(new Ko("application/json")).bodyValue(JSON.stringify(t))}#s(e,t){return this.getHttpStatus(t.status!==void 0?t:r.#e.getErrorAttributes(e,r.#t))}getHttpStatus(e){let t=e.status;if(typeof t=="number")return t;throw new Error(`Invalid status code: ${t}`)}};var Ts="io.interop.web.async.handler.handler",Ms="io.interop.web.async.handler.pattern";var or=class{#e;#t;#r;constructor(e,t,n){this.#e=e,this.#t=t,this.#r=n}async handle(e){if(!this.#e)return this.#o();if(X(e.request))return this.handlePreFlight(e);let t;try{for(let n of this.#e)if(t=await n.getHandler(e),t!==void 0)break;t===void 0&&await this.#o()}catch(n){return this.#n(e,Promise.reject(n))}return this.#i(e,t)}async#n(e,t){this.#t;let n=await t;try{await this.#s(e,n,`Handler ${n.handler}`)}catch(s){let i=n.exceptionHandler;if(i){let o=s instanceof Error?s:new Error(String(s)),a=await i(e,o);await this.#s(e,a,`Exception handler ${a.handler}, error="${o.message}"`)}}}#s(e,t,n){if(this.#r){for(let s of this.#r)if(s.supports(t))return n+=" [DispatcherHandler]",s.handle(e,t)}return Promise.reject(new Error(`No HandlerResultHandler for ${t.returnValue}`))}#i(e,t){if(e.response.statusCode?.value===b.FORBIDDEN.value)return Promise.resolve();if(this.#t){for(let n of this.#t)if(n.supports(t)){let s=n.handle(e,t);return this.#n(e,s)}}return Promise.reject(new Error(`No HandlerAdapter for handler ${t}`))}#o(){return Promise.reject(new Z(b.NOT_FOUND))}async handlePreFlight(e){let t;for(let n of this.#e??[])if(t=await n.getHandler(e),t!==void 0)break;if(t===void 0){e.response.setStatusCode(b.FORBIDDEN);return}}},ar=class{logger=S("web.async.handler");#e;set corsConfigSource(e){if(e===void 0)throw new Error("CorsConfigSource must not be undefined");this.#e=e}async getHandler(e){let t=await this.getHandlerInternal(e);if(t!==void 0){this.logger.enabledFor("debug")&&this.logger.debug(`${e.logPrefix}Mapped to ${t}`);let n=e.request;if(this.hasCorsConfigSource(t)||X(n)){let s=this.#e!==void 0?await this.#e(e):void 0,i=this.getCorsConfig(t,e)}return t}}hasCorsConfigSource(e){return this.#e!==void 0}getCorsConfig(e,t){}};var cr=class{supports(e){return typeof e=="function"}async handle(e,t){let n=t,s=e.attribute(sn);if(!s)throw new Error("ServerRequest is not found in exchange attributes.");return n(s).then(i=>({handler:t,returnValue:i}))}},dr=class{#e=Array();constructor(e){if(!e||e.length===0)throw new Error("messageWriters must not be empty.");this.#e=e}supports(e){return e.returnValue instanceof We}get messageWriters(){return this.#e}async handle(e,t){let n=t.returnValue;if(n===void 0)throw new Error("No ServerResponse");return n.writeTo(e,{messageWriters:this.messageWriters})}},ur=class extends ar{#e;#t=void 0;constructor(e){super(),this.#e=e}set messageReaders(e){this.#t=e}init(...e){if((this.#t===void 0||this.#t.length===0)&&(this.#t=ke.serverConfigurer.create().readers),this.#e)throw new Error("RouterFunctionMapping is already initialized with a RouterFunction");this.#e=e.reduce((t,n)=>t.and(n))}async getHandlerInternal(e){if(this.#e===void 0)return;let t=Jt.create(e,this.#t),n=await this.#e.route(t);return n!==void 0&&this.#r(e.attributes,t,n),n}#r(e,t,n){e.set(sn,t),e.set(Ts,n);let s=e.get(Ps);s&&e.set(Ms,s);let i=e.get(on);i!==void 0&&e.set(on,i)}};var T=S("app");async function ta(r,e){let t=r.build();return async(n,s)=>{n.socket.addListener("error",e);let i;s instanceof me?i=s:(n.upgradeHead=s,i=new me(n),i.assignSocket(n.socket));try{let o=new ye(n),a=new ht(i),c=o.method==="HEAD"?new Nt(a):a,d=t(o,c);try{await d,T.enabledFor("trace")&&T.debug(`${o.id} handling completed.`)}catch(u){if(u instanceof Error&&u.code==="ERR_INVALID_URL")throw u;T.enabledFor("trace")&&T.debug(`${o.id} failed to complete: ${u instanceof Error?u.message:u}`)}}catch(o){if(o instanceof Error&&o.code==="ERR_INVALID_URL")return T.enabledFor("debug")&&T.debug(`failed to get request URI: ${o.message}`),i.statusCode=400,i.end(Is.STATUS_CODES[400]),Promise.resolve();throw o}}}function Hs(r){return new Promise((e,t)=>{let n=r(s=>{s?t(s):e(n)})})}function ra(r){if(r)return In({memoryLimit:r.memory_limit,dumpLocation:r.dump_location,dumpPrefix:r.dump_prefix,reportInterval:r.report_interval,maxBackups:r.max_backups})}var Ws=`${ks.name} - v${ks.version}`;async function na(r){let e=r.storage,t=await fs(r),n=ms(r),s=ke.serverConfigurer.create();s.defaultCodecs.enableLoggingRequestDetails(!0);let i=new ur,o=new or([i],[new cr],[new dr(s.writers)]),a={handle:En(On(Ws,r.serverHeader),...n,...r.middleware,async({request:c,response:d},u)=>{if(c.method==="GET"&&c.path==="/health"){d.setStatusCode(b.OK);let h=Buffer.from("UP","utf-8");d.headers.set("Content-Type","text/plain; charset=utf-8"),await d.body(h)}else await u()},await Zr(r.resourcesConfig?.locations),async({response:c},d)=>{throw new Z(b.NOT_FOUND)})};return new Xt(a).filter(new Lt(t)).codecConfigurer(s).exceptionHandler(new ir(s.readers,s.writers,new rt)).storage(e)}var ln=async r=>{let e=r.ssl,t=r.host,n=r.auth?.x509?.key?{host:t??"localhost",key:r.auth.x509.key,passphrase:r.auth.x509.passphrase}:void 0,s=e?(m,y)=>Zo.createServer({...m,...bs(e,n)},y):(m,y)=>Is.createServer(m,y),i=ra(r.memory),o={middleware:[],corsConfig:r.cors,cors:[],authConfig:r.auth,authorize:[],storage:new ea,sockets:new Map,resourcesConfig:r.resources},a=new st({baseConfig:{...r.gateway},scope:r.gateway?.scope??"principal"});if(r.gateway){let m=r.gateway.route?r.gateway.route==="/"?void 0:r.gateway.route:void 0;await Mr(async y=>{y.socket({path:m,factory:mn.bind(a),options:r.gateway})},r,o)}r.app&&await Mr(r.app,r,o);let c=hn(r.port??0),d=m=>T.error(`socket error: ${m}`,m),u=await na(o),h=await ta(u,d),E=await new Promise((m,y)=>{let v=s({IncomingMessage:ut,ServerResponse:me,...r.http},h);v.on("error",P=>{if(P.code==="EADDRINUSE"){T.debug(`port ${P.port} already in use on address ${P.address}`);let{value:ae}=c.next();ae?(T.info(`retry starting server on port ${ae} and host ${t??"<unspecified>"}`),v.close(),v.listen(ae,t)):(T.warn(`all configured port(s) ${r.port} are in use. closing...`),v.close(),y(P))}else T.error(`server error: ${P.message}`,P),y(P)}),v.on("listening",async()=>{let P=v.address();for(let[ae,lr]of o.sockets){let nt=`${e?"wss":"ws"}://${pn}:${P.port}${ae}`;await ys(ae,lr,nt,o.storage,d)}T.info(`http server listening on ${e?"https":"http"}://${ee(P)}`),m(v)}),v.on("upgrade",(P,ae,lr)=>{try{h(P,lr)}catch(nt){T.error(`upgrade error: ${nt}`,nt)}}).on("close",async()=>{T.info("http server closed.")});try{let{value:P}=c.next();v.listen(P,t)}catch(P){T.error("error starting web socket server",P),y(P instanceof Error?P:new Error(`listen failed: ${P}`))}}),l=new Array,p=async()=>{for(let[m,y]of o.sockets)try{y.close!==void 0&&await y.close()}catch(v){T.warn(`error closing route ${m}`,v)}},f=async()=>{await Hs(m=>{E.closeAllConnections(),E.close(m)})};l.push(p),l.push(f),l.push(async()=>{i&&await Wn(i)}),l.push(async()=>{await a.stop()});let w=new class{gateway=a;get address(){let m=E.address();return typeof m=="object"?m:null}async close(){let m=new Array;for(let y of l)try{await y()}catch(v){m.push(v),T.warn("error during server shutdown",v)}if(m.length===1)throw m[0];if(m.length>1)throw new AggregateError(m,"multiple errors during server shutdown")}};if(r.management?.server.path){let m=await Ss({options:r.management.server,info:async()=>({pid:process.pid,type:"gateway-server",...a.info()}),logger:T.child("management"),shutdown:r.management.commands?.shutdown.enabled?async()=>{T.enabledFor("info")&&T.info("stopping gateway-server..."),await w.close()}:void 0});l.push(async()=>{await Hs(y=>{m.close(y)})})}return w};var Fp=ln;export{Os as GatewayServer,Fp as default};
|
|
22
22
|
//# sourceMappingURL=index.js.map
|