@interopio/gateway-server 0.23.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 +8 -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 +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
You are probably missing an await or return statement in your middleware function.`);return
|
|
1
|
+
"use strict";var oi=Object.create;var at=Object.defineProperty;var ai=Object.getOwnPropertyDescriptor;var ci=Object.getOwnPropertyNames;var di=Object.getPrototypeOf,ui=Object.prototype.hasOwnProperty;var En=(r,e)=>{for(var t in e)at(r,t,{get:e[t],enumerable:!0})},vn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ci(e))!ui.call(r,s)&&s!==t&&at(r,s,{get:()=>e[s],enumerable:!(n=ai(e,s))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?oi(di(r)):{},vn(e||!r||!r.__esModule?at(t,"default",{value:r,enumerable:!0}):t,r)),li=r=>vn(at({},"__esModule",{value:!0}),r);var ra={};En(ra,{GatewayServer:()=>Sn,default:()=>ta});module.exports=li(ra);var Sn={};En(Sn,{Factory:()=>wn,VERSION:()=>ii});var bn=fe(require("node:http"),1),ni=fe(require("node:https"),1),si=require("node:async_hooks");var Pn=require("node:os"),hi=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function Er(r){if(r>65535)throw new Error(`bad port ${r}`);return r}function*Cn(r){if(typeof r=="string")for(let e of r.split(",")){let t=e.trim(),n=hi.exec(t);if(n){let s=parseInt(n[1]),i=parseInt(n[4]??n[1]);for(let o=Er(s);o<Er(i)+1;o++)yield o}else throw new Error(`'${e}' is not a valid port or range.`)}else yield Er(r)}var xn=(()=>{function r(t){return t.length>0?t[0]:void 0}let e=Object.values((0,Pn.networkInterfaces)()).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}`}var An=fe(require("@interopio/gateway/logging/core"),1);function S(r){return An.getLogger(`gateway.server.${r}`)}function Rn(r,e){return e instanceof RegExp?e.toString():e}var Tn=require("@interopio/gateway"),Mn=require("node:async_hooks"),V=S("ws"),pi=Tn.IOGateway.Encoding.json();function fi(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 gi(r,e,t,n){let s=ee(n),i=n?.address??"<unknown>",o={key:s,host:i,codec:pi,onAuthenticate:async()=>{let a=await t();if(a?.authenticated)return{type:"success",user:fi(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 mi(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=gi(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?Mn.AsyncLocalStorage.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 Hn=mi;var Cr=require("@interopio/gateway");var ge=require("@interopio/gateway");function vr(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]=ge.IOGateway.Filtering.regexify(s));if(e.identity!==void 0){t.identity={};for(let[n,s]of Object.entries(e.identity))t.identity[n]=ge.IOGateway.Filtering.regexify(s)}return t})}function kn(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]=ge.IOGateway.Filtering.regexify(c);if(o.metrics={},n){let a=(n.allow??n.whitelist??[]).map(d=>ge.IOGateway.Filtering.regexify(d)),c=(n.block??n.blacklist??[]).map(d=>ge.IOGateway.Filtering.regexify(d));a.length>0&&(o.metrics.allow=a),c.length>0&&(o.metrics.block=c)}return o})),e}function Pr(r){if(!r)return;let e={...r};return r.filters&&(e.filters=kn(r.filters)),e}function yi(r){if(r?.enabled!==!1)return r}function bi(r){if(r===void 0||r?.enabled===!1)return;let e={...r};return r.filters&&(e.filters=kn(r.filters)),r.file&&(e.file=Pr(r.file)),r.rest&&(e.rest=Pr(r.rest)),r.publishers&&(e.publishers=r.publishers.map(t=>{if(typeof t=="string")return[t];let n=Pr(t);return n!==void 0?[n]:[]}).flat()),e}function In(r){let e={...r};return r.contexts&&(e.contexts={...r.contexts,visibility:vr(r.contexts.visibility)}),r.methods&&(e.methods={...r.methods,visibility:vr(r.methods.visibility)}),r.peers&&(e.peers={...r.peers,visibility:vr(r.peers.visibility)}),r.metrics&&(e.metrics=bi(r.metrics)),r.mesh&&(e.mesh=yi(r.mesh)),e}var I=S("gateway-manager");function Wn(){return globalThis.crypto.randomUUID().replaceAll("-","")}var ct=class{#e;#t;#r=new Map;#n=new Map;#s;#i=!1;#o;constructor(e){this.#s={baseConfig:In(e.baseConfig),scope:e.scope??"principal"},this.#e=e.baseConfig.node??Wn(),I.enabledFor("debug")&&I.debug(`creating default gateway with gateway id: ${this.#e}`),this.#t=Cr.IOGateway.Factory({...this.#s.baseConfig,node:this.#e})}async start(e){return this.#i?this:(this.#o=e,I.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?I.enabledFor("debug")&&I.debug(`reusing existing gateway for principal '${e}'`):(I.enabledFor("debug")&&I.debug(`no existing gateway for principal '${e}', creating new one`),n=await this.#c(e)),n}async#c(e){let t=Wn(),n={...this.#s.baseConfig,node:t};I.enabledFor("debug")&&I.debug(`creating gateway for principal '${e}' with gateway id: ${n.node}`);let s=Cr.IOGateway.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){I.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 I.debug("stopping default gateway (managed gateways will continue running)"),await this.#t.stop(),this.#i=!1,this.#t;I.info(`stopping all gateways (1 default + ${this.#r.size} managed)`);for(let[t,n]of this.#r.entries())I.enabledFor("debug")&&I.debug(`stopping gateway with ID: ${t}`),await n.stop();return this.#r.clear(),this.#n.clear(),I.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 On(...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)}}var Ln=require("node:net"),ht=require("tough-cookie");function wi(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 Si(r){let e=r.one("x-forwarded-ssl");return typeof e=="string"&&e.toLowerCase()==="on"}function Ei(r,e){let t=r.get("x-forwarded-proto");return Array.isArray(t)&&(t=t[0]),t!==void 0?t.split(",",1)[0].trim():Si(r)?"https":e}function vi(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:(0,Ln.isIP)(s)===6?"IPv6":"IPv4"}}var dt=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},ut=class r extends dt{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 Pi(this.headers)}parseHost(e){return wi(this.headers,e)}parseProtocol(e){return Ei(this.headers,e)}parseRemoteAddress(e){return vi(this.URL,this.headers,e)}},lt=class extends dt{get cookies(){return Ci(this.headers)}setCookieValue(e){return new ht.Cookie({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 Pi(r){return r.list("cookie").map(e=>e.split(";").map(t=>ht.Cookie.parse(t))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function Ci(r){return r.list("set-cookie").map(e=>{let t=ht.Cookie.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)}var $n=require("node:util");var pt=require("node:util"),ce="*",De=new pt.MIMEType(`${ce}/${ce}`),xr="application/octet-stream",ga=new pt.MIMEType(xr);function me(r){return r.type===ce}function te(r){return r.subtype===ce||r.subtype.startsWith(`${ce}+`)}function Ar(r){return!me(r)&&!te(r)}var Fe=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 Rr(r,e,t){let n=`${r}/${e}`,s;try{s=new pt.MIMEType(n)}catch(i){throw new Fe(n,void 0,{cause:i})}return t&&s.params.set("charset",t),s}function Fn(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(me(r)||me(e))return!0;if(r.type===e.type){if(r.subtype===e.subtype)return!0;if(te(r)||te(e)){let t=Fn(r),n=Fn(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 xi=`
|
|
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=R.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 Fn(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function On(r){return Fn(r)?r.substring(1,r.length-1):r}function wi(r,e){if(r instanceof R&&e instanceof R){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 Si(r,e){return wi(e,r)}function Ei(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 Dn(r){if(r===void 0)throw new Error("mimeTypes must not be undefined");if(r.length>100)throw new Le("too many elements");Ei(r,Si)}function vi(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 $n(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...vi(t));return e}var De=class{constructor(){}toList(e){let t=this.get(e);return $n(t)}},A=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 $n(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}},Un=new A;function ge(r){let e=r.one("content-type");return e?R.parseMediaType(e):void 0}var xr=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 pt(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 xr(r)}return r}var St=Oe(require("node:http"),1);function Ne(r,e,t){let n=r.elements;if(t=t??n.length,e===0&&t===n.length)return r;if(e===t)return Ue.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 Ue(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 Ar={separator:47,decodeAndParseParameters:!0};function j(r,e){return Ue.createFromUrlPath(r,e??Ar)}var Ue=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 Nn(r,e){return typeof r=="string"?Rr.parse(r,e):Nn(r.href,e)}var Rr=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 Ne(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 Ne(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 ct{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=Nn(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var ft=class extends St.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},me=class extends St.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},gt=class extends dt{#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:pt(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 Hr(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 Tr(this.#r.socket)}get cookies(){return this.#t??=super.cookies,this.#t}get body(){return St.default.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}`}},Tr=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},Hr=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()}},Mr=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)}},mt=class extends gt{#e;constructor(e){super(new Mr(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}`))}})}}},yt=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 gt)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},bt=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}]`}},wt=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[qn]=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(qn);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},qn="io.interop.web.server.exchange.log_id";var Et=require("node:v8"),X=require("node:fs/promises"),C=w("monitoring"),Pi={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function Ci(){return(0,Et.getHeapStatistics)()}async function _n(r){let e=r.dumpPrefix??"Heap",t=`${r.dumpLocation}/${e}.heapsnapshot`;C.enabledFor("debug")&&C.debug(`starting heap dump in ${t}`),await kr(r.dumpLocation).catch(async s=>{C.enabledFor("debug")&&C.debug(`dump location ${r.dumpLocation} does not exists. Will try to create it`);try{await(0,X.mkdir)(r.dumpLocation,{recursive:!0}),C.info(`dump location dir ${r.dumpLocation} successfully created`)}catch{C.error(`failed to create dump location ${r.dumpLocation}`)}});let n=(0,Et.writeHeapSnapshot)(t);C.info("heap dumped");try{C.debug("rolling snapshot backups");let s=`${r.dumpLocation}/${e}.${r.maxBackups}.heapsnapshot`;await kr(s).then(async()=>{C.enabledFor("debug")&&C.debug(`deleting ${s}`);try{await(0,X.unlink)(s)}catch(o){C.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 kr(a).then(async()=>{try{await(0,X.rename)(a,c)}catch(d){C.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${r.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,X.rename)(n,i)}catch(o){C.warn(`failed to rename ${n} to ${i}`,o)}C.debug("snapshots rolled")}catch(s){throw C.error("error rolling backups",s),s}}async function kr(r){C.enabledFor("trace")&&C.debug(`checking file ${r}`),await(0,X.access)(r)}async function xi(r,e,t){C.enabledFor("debug")&&C.debug(`processing heap stats ${JSON.stringify(r)}`);let n=Math.min(t.memoryLimit,.95*r.heap_size_limit),s=r.used_heap_size;C.info(`heap stats ${JSON.stringify(r)}`),s>=n?(C.warn(`used heap ${s} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await _n(t)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function Bn(r){let e={...Pi,...r},t=!1,n={memoryLimitExceeded:!1},s=async()=>{let a=Ci();await xi(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 _n(e);break}case"stop":{t=!0,clearInterval(i),C.info("exit memory diagnostic");break}}return t}}}async function Ai({channel:r},e){await r(e)||C.warn(`cannot execute command "${e}" already closed`)}async function Gn(r){return await Ai(r,"stop")}var Ti=(r,e)=>(e??=r,async({response:t},n)=>{e!==!1&&!t.headers.has("server")&&t.headers.set("Server",e),await n()}),Vn=(r,e)=>Ti(r,e);var _e=require("@interopio/gateway");var Wr=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 Mi(r,e){let t=r.block??r.blacklist,n=r.allow??r.whitelist;if(t.length>0&&_e.IOGateway.Filtering.valuesMatch(t,e))return Wr.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&_e.IOGateway.Filtering.valuesMatch(n,e))return Wr.enabledFor("debug")&&Wr.debug(`origin ${e} matches allow filter`),!0}function ki(r){switch(r.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function zn(r,e){if(!e)return!0;if(r){let t=Mi(e,r);return t||ki(e)}else return Hi(e)}function jn(r){if(r){let e=(r.block??r.blacklist??[]).map(_e.IOGateway.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(_e.IOGateway.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var Xn=r=>async e=>{for(let t of r)if((await t(e)).match)return D();return O},we=r=>{let e=async t=>{for(let n of r)if(!(await n(t)).match)return O;return D()};return e.toString=()=>`and(${r.map(t=>t.toString()).join(", ")})`,e},Jn=r=>async e=>(await r(e)).match?O:D(),Se=async r=>D();Se.toString=()=>"any-exchange";var Yn=Object.freeze({}),O=Object.freeze({match:!1,variables:Yn}),D=(r=Yn)=>({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 O;if(typeof r=="string")return o===r?D():O;{let a=r.exec(o);return a===null?O:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n},Be=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 O}for(let i of s)if(!e(i)){for(let o of r.mediaTypes)if(i.startsWith(o))return D()}return O}},ce=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?D():O;ce.toString=()=>"websocket upgrade";var Ir=require("@interopio/gateway");async function Or(r,e,t){let n=(i,o)=>{if(o?.cors){let a=o.cors===!0?{allowOrigins:o.origins?.allow?.map(Ir.IOGateway.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=$(Ir.IOGateway.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:P,variables:l}=await d(f);P?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:jn(c?.origins)})}}};await r(s,e)}var Ct=require("@interopio/gateway");function Ii(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 Kn(r){return r.headers.has("origin")&&!Ii(r)}function J(r){return r.method==="OPTIONS"&&r.headers.has("origin")&&r.headers.has("access-control-request-method")}var Qn=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],Oi=(r,e)=>{let{request:t,response:n}=r,s=n.headers;if(!s.has("Vary"))s.set("Vary",Qn.join(", "));else{let o=s.list("Vary");for(let a of Qn)o.find(c=>c===a)||o.push(a);s.set("Vary",o.join(", "))}try{if(!Kn(t))return!0}catch{return U.enabledFor("debug")&&U.debug("reject: origin is malformed"),Ge(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=J(t);return e?Fi(r,e,i):i?(Ge(n),!1):!0},Pt=["*"],Lr=["GET","HEAD","POST"],Zn={allowOrigins:Pt,allowMethods:Lr,allowHeaders:Pt,maxAge:1800};function xt(r){if(r){let e=r.allowHeaders;e&&e!==x&&(r={...r,allowHeaders:e.map(n=>n.toLowerCase())});let t=r.allowOrigins;return t&&(t==="*"?(ts(r),rs(r)):r={...r,allowOrigins:t.map(n=>typeof n=="string"&&n!==x&&(n=Ct.IOGateway.Filtering.regexify(n),typeof n=="string")?ns(n).toLowerCase():n)}),r}}function vt(r,e){if(e===void 0)return r!==void 0?r===x?[x]:r:[];if(r===void 0)return e===x?[x]:e;if(r==Pt||r===Lr)return e===x?[x]:e;if(e==Pt||e===Lr)return r===x?[x]:r;if(r===x||r.includes(x)||e===x||e.includes(x))return[x];let t=new Set;return r.forEach(n=>t.add(n)),e.forEach(n=>t.add(n)),Array.from(t)}var Ve=(r,e)=>e===void 0?r:{allowOrigins:vt(r.allowOrigins,e?.allowOrigins),allowMethods:vt(r.allowMethods,e?.allowMethods),allowHeaders:vt(r.allowHeaders,e?.allowHeaders),exposeHeaders:vt(r.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??r.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??r.allowPrivateNetwork,maxAge:e?.maxAge??r.maxAge},Li=r=>{let e=r.corsConfigSource,t=r.corsProcessor??Oi;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)||J(n.request)||await s.filter(n)}}},es=Li,U=w("cors");function Ge(r){r.setStatusCode(y.FORBIDDEN)}function Fi(r,e,t){let{request:n,response:s}=r,i=s.headers,o=n.headers.one("origin"),a=$i(e,o);if(a===void 0)return U.enabledFor("debug")&&U.debug(`reject: '${o}' origin is not allowed`),Ge(s),!1;let c=qi(n,t),d=Ui(e,c);if(d===void 0)return U.enabledFor("debug")&&U.debug(`reject: HTTP '${c}' is not allowed`),Ge(s),!1;let u=_i(n,t),f=Ni(e,u);if(t&&f===void 0)return U.enabledFor("debug")&&U.debug(`reject: headers '${u}' are not allowed`),Ge(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 x="*",Di=["GET","HEAD"];function ts(r){if(r.allowCredentials===!0&&r.allowOrigins===x)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function rs(r){if(r.allowPrivateNetwork===!0&&r.allowOrigins===x)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function $i(r,e){if(e){let t=r.allowOrigins;if(t){if(t===x)return ts(r),rs(r),x;let n=ns(e.toLowerCase());for(let s of t)if(s===x||Ct.IOGateway.Filtering.valueMatches(s,n))return e}}}function Ui(r,e){if(e){let t=r.allowMethods??Di;if(t===x)return[e];if(Ct.IOGateway.Filtering.valuesMatch(t,e))return t}}function Ni(r,e){if(e===void 0)return;if(e.length==0)return[];let t=r.allowHeaders;if(t===void 0)return;let n=t===x||t.includes(x),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 ns(r){return r.endsWith("/")?r.slice(0,-1):r}function qi(r,e){return e?r.headers.one("access-control-request-method"):r.method}function _i(r,e){let t=r.headers;return e?t.list("access-control-request-headers"):Array.from(t.keys())}var ss=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};var is=require("@interopio/gateway");function os(r){let{sockets:e,cors:t}=r,n=r.corsConfig===!1?void 0:Ve(Zn,r.corsConfig),s=[];for(let[o,a]of e){let c=n;for(let[u,f]of t)is.IOGateway.Filtering.valueMatches(u,o)&&(f===void 0?c=void 0:c=c===void 0?f:Ve(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:Ve(c,d),s.push([we([ce,$(o)]),xt(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:Ve(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),xt(a)]);return s.push([$(/\/api\/.*/),xt(n)]),ss({mappings:s})}function as(r){return r!==void 0&&typeof r.type=="string"&&typeof r.authenticated=="boolean"}var W=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}},At=class extends W{},Ee=class extends W{},ve=class extends W{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)}},Je=class extends ve{constructor(e){super(e)}};var de=class extends Error{},Y=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)}},Pe=class extends W{};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)},Bi=()=>N(new A().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Gi=()=>N(new A().add("x-content-type-options","nosniff")),Vi=(r,e,t)=>{let n=`max-age=${r}`;e&&(n+=" ; includeSubDomains"),t&&(n+=" ; preload");let s=N(new A().add("strict-transport-security",n)),i=o=>o.request.URL.protocol==="https:";return async o=>{i(o)&&await s(o)}},zi=r=>N(new A().add("x-frame-options",r)),ji=r=>N(new A().add("x-xss-protection",r)),Xi=r=>{let e=r===void 0?void 0:N(new A().add("permissions-policy",r));return async t=>{e!==void 0&&await e(t)}},Ji=(r,e)=>{let t=e?"content-security-policy-report-only":"content-security-policy",n=r===void 0?void 0:N(new A().add(t,r));return async s=>{n!==void 0&&await n(s)}},Yi=(r="no-referrer")=>N(new A().add("referer-policy",r)),Ki=r=>{let e=r===void 0?void 0:N(new A().add("cross-origin-opener-policy",r));return async t=>{e!==void 0&&await e(t)}},Qi=r=>{let e=r===void 0?void 0:N(new A().add("cross-origin-embedder-policy",r));return async t=>{e!==void 0&&await e(t)}},Zi=r=>{let e=r===void 0?void 0:N(new A().add("cross-origin-resource-policy",r));return async t=>{e!==void 0&&await e(t)}},eo=(...r)=>async e=>{for(let t of r)await t(e)};function Fr(r){let e=[];r?.cache?.disabled||e.push(Bi()),r?.contentType?.disabled||e.push(Gi()),r?.hsts?.disabled||e.push(Vi(r?.hsts?.maxAge??365*24*60*60,r?.hsts?.includeSubDomains??!0,r?.hsts?.preload??!1)),r?.frameOptions?.disabled||e.push(zi(r?.frameOptions?.mode??"DENY")),r?.xss?.disabled||e.push(ji(r?.xss?.headerValue??"0")),r?.permissionsPolicy?.disabled||e.push(Xi(r?.permissionsPolicy?.policyDirectives)),r?.contentSecurityPolicy?.disabled||e.push(Ji(r?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",r?.contentSecurityPolicy?.reportOnly)),r?.refererPolicy?.disabled||e.push(Yi(r?.refererPolicy?.policy??"no-referrer")),r?.crossOriginOpenerPolicy?.disabled||e.push(Ki(r?.crossOriginOpenerPolicy?.policy)),r?.crossOriginEmbedderPolicy?.disabled||e.push(Qi(r?.crossOriginEmbedderPolicy?.policy)),r?.crossOriginResourcePolicy?.disabled||e.push(Zi(r?.crossOriginResourcePolicy?.policy)),r?.writers&&e.push(...r.writers);let t=eo(...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 to="Realm",ro=r=>`Basic realm="${r}"`,xe=r=>{let e=ro(r?.realm??to);return async(t,n)=>{let{response:s}=t;s.setStatusCode(y.UNAUTHORIZED),s.headers.set("WWW-Authenticate",e)}};var cs="Basic ",Rt=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<=cs.length?"":s.substring(cs.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}}}};var ds=require("node:async_hooks"),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 ds.AsyncLocalStorage)=>(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 no(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 so(a,{exchange:r,chain:e},s,i)}catch(c){throw c instanceof W,c}}async function so(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:Rt({}),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 no(n,s,o,t,e.successHandler,e.storage)}catch(a){if(a instanceof W){await e.failureHandler({exchange:n,chain:s},a);return}throw a}}}}var us=r=>async(e,t)=>{e.response.setStatusCode(r.httpStatus)};var Ae=w("auth.entry-point"),Tt=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(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 ls=r=>async({exchange:e,chain:t},n)=>{for(let s of r)await s({exchange:e,chain:t},n)};function Dr(r){let e=async m=>m.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?D():O,t=Tt({entryPoints:[[e,us({httpStatus:y.UNAUTHORIZED})]],defaultEntryPoint:xe({})}),n=r.entryPoint??t,s=r.manager,i=Be({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),o=Jn(Be({mediaTypes:["text/html"]})),a=we([o,i]),c=Xn([e,a]);r.defaultEntryPoints.push([c,n]);let d=r.failureHandler??Ce({entryPoint:n}),u=ls(r.successHandlers??r.defaultSuccessHandlers),f=Rt({});return ie({storage:r.storage,manager:s,failureHandler:d,successHandler:u,converter:f})}var hs={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},ps="https://tools.ietf.org/html/rfc6750#section-3.1";function Ht(r){return{errorCode:hs.invalid_token,httpStatus:y.UNAUTHORIZED,description:r,uri:ps}}function $r(r){return{errorCode:hs.invalid_request,httpStatus:y.BAD_REQUEST,description:r,uri:ps}}var io="access_token",oo=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,_=class extends W{error;constructor(e,t,n){super(t??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},fs=r=>r.type==="BearerToken",ao=r=>async e=>{let{request:t}=e;return Promise.all([uo(t.headers,r?.headerName).then(n=>n!==void 0?[n]:void 0),lo(t,r?.uriQueryParameter),ho(e,r?.formEncodedBodyParameter)]).then(n=>n.filter(s=>s!==void 0).flat(1)).then(co).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function co(r){if(r.length===0)return;if(r.length>1){let t=$r("Found multiple access tokens in the request");throw new _(t)}let e=r[0];if(!e||e.length===0){let t=$r("The requested access token parameter is an empty string");throw new _(t)}return e}async function uo(r,e="authorization"){let t=r.one(e);if(!t||!/bearer/i.test(t.substring(0)))return;let n=oo.exec(t);if(n===null){let s=Ht("Bearer token is malformed");throw new _(s)}return n.groups?.token}async function gs(r){let e=r.getAll(io);if(e.length!==0)return e}async function lo(r,e=!1){if(!(!e||r.method!=="GET"))return gs(r.URL.searchParams)}async function ho(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 gs(n)}var Mt=ao;function po(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 ms=r=>r.httpStatus!==void 0;function fo(r){if(r instanceof _){let{error:e}=r;if(ms(e))return e.httpStatus}return y.UNAUTHORIZED}function go(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),ms(n)&&n.scope&&t.set("scope",n.scope)}return t}var mo=r=>async(e,t)=>{let n=fo(t),s=go(t,r?.realmName),i=po(s),{response:o}=e;o.headers.set("WWW-Authenticate",i),o.setStatusCode(n),await o.end()},kt=mo;var yo=r=>{let e=r?.principalClaimName??"sub";return t=>({type:"JwtToken",authenticated:!0,name:t.getClaimAsString(e)})},bo=r=>async e=>r(e),Re=class extends Error{},Ye=class extends Re{};function wo(r){if(r instanceof Ye)return new _(Ht(r.message),r.message,{cause:r});throw new Pe(r.message,{cause:r})}function Ur(r){let e=r.decoder,t=r.authConverter??bo(yo({}));return async n=>{if(fs(n)){let s=n.token;try{let i=await e(s);return await t(i)}catch(i){throw i instanceof Re?wo(i):i}}}}function Nr(r){let e=r.entryPoint??kt({}),t=r?.converter??Mt({}),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??Ur(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")}var Bt=require("@interopio/gateway/jose/jwt");async function ys(r,e,t){let n=new At("Full authentication is required to access this resource."),s=new W("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 bs=r=>{let e=So(y.FORBIDDEN),t=r.authenticationEntryPoint??xe();return{filter:async(n,s)=>{try{await s.filter(n)}catch(i){if(i instanceof de){let o=await n.principal();as(o)?(o.authenticated||await e(n,i),await ys(n,o,t)):await ys(n,void 0,t);return}throw i}}}};var Eo=w("security.auth");function qr(r){let e=async(t,n)=>{let s;for(let[i,o]of r.mappings)if((await i(n))?.match){Eo.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 Y(!1),s};return new ne(e)}var Wt=w("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),Wt.enabledFor("debug")&&Wt.debug("authorization successful")}catch(o){throw o instanceof de&&Wt.enabledFor("debug")&&Wt.debug(`authorization failed: ${o.message}`),o}await s.filter(n)}}}var Br=class extends bt{#e;constructor(e,t){super(e),this.#e=t}async principal(){return(await this.#e())?.authentication}},ws=r=>{let e=r.storage;return{filter:async(t,n)=>{await n.filter(new Br(t,async()=>await se.getContext(e)))}}};var Ss=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 It=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 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}},Te=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)}},Ot=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}};var I=require("@interopio/gateway-server/tools");function vo(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 Lt=class extends ue{#e;#t;#r;#n;#s;constructor(e=I.argon2.DEFAULT_SALT_LENGTH,t=I.argon2.DEFAULT_HASH_LENGTH,n=I.argon2.DEFAULT_PARALLELISM,s=I.argon2.DEFAULT_MEMORY,i=I.argon2.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=I.argon2.decode(t),s=await I.argon2.createHash(n.algorithm,e,n.hash.length,n.parameters);return vo(n.hash,s)}catch{return!1}}async encodeDefinedPassword(e){let t=I.keygen.createSalt(this.#e),n={memory:this.#n,passes:this.#s,parallelism:this.#r,nonce:t},s=await I.argon2.createHash("argon2id",e,this.#t,n);return I.argon2.encode({algorithm:"argon2id",version:I.argon2.ARGON2_VERSION,parameters:n,hash:s})}upgradeEncodingDefined(e){let t=I.argon2.decode(e);return t.version<I.argon2.ARGON2_VERSION||t.parameters.memory<this.#n||t.parameters.passes<this.#s}};var Gr=4096;function Es(){let r="argon2id",e=new Map([[r,new Lt],["noop",Ot.instance]]);return new Te(r,e,Te.DEFAULT_ID_PREFIX,Te.DEFAULT_ID_SUFFIX)}var vs={async updatePassword(r,e){return r}},Ft=class extends W{username;constructor(e,t,n){super(e,n),this.username=t}},Dt=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 Ps(r,e){let t=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw oe.debug("user account is locked"),new ze("User account is locked");if(a.disabled)throw oe.debug("user account is disabled"),new je("User is disabled");if(a.accountExpired)throw oe.debug("user account is expired"),new Xe("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??Es(),i=e?.userDetailsPasswordService??vs,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 Ee("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 Po(){return r=>{if(r.accountLocked)throw oe.debug("failed to authenticate since user account is locked"),new ze("User account is locked");if(r.disabled)throw oe.debug("failed to authenticate user account is disabled"),new je("User is disabled");if(r.accountExpired)throw oe.debug("failed to authenticate since user account is expired"),new Xe("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 Cs(r){let e=r.userDetailsService,t=r.userDetailsChecker??Po(),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 Ft("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 Vr(r){let e=r.manager??Cs({userDetailsService:r.getService("UserDetailsService")}),t=r.extractor??It(),n=r.converter??Ss({principalExtractor:t});return ie({storage:r.storage,manager:e,converter:n})}var $t=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}]`}},Ut=class extends $t{#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}},Ke=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)}},Nt=class extends $t{#e;constructor(e,...t){super(e),this.#e=Ke.of(e,...t)}get filters(){return this.#e.filters}handle(e){return this.#e.filter(e)}};var qt=class{#e;#t=new jr;#r=new zr;#n=new Jr;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 Xr)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}},zr=class{decorate(e,t){return t=t||[],Ke.of({handle:n=>e.filter(n)},...t)}},_t=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}},jr=class{async firewalledExchange(e){return e}},Xr=class extends Error{constructor(e){super(e),this.name="ServerExchangeRejectedError"}},Jr=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"),xs=(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 Ps(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]:Tt({entryPoints:this.#t,defaultEntryPoint:this.#t[this.#t.length-1][1]})}build(){if(r.headers!==void 0&&r.headers.disabled!==!0){let d=Fr(r.headers);d[G]=B.http_headers,s.push(d)}if(r.x509!==void 0&&r.x509.disabled!==!0){let d=Vr({storage:e.storage,getService:t,extractor:It({principalAltName:r.x509.principalAltName})});d[G]=B.authentication,s.push(d)}if(r.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=es({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},P)=>await m.filter(f)],u=Dr({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=(0,Bt.jwtVerifier)({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 Bt.JwtVerifyError?new Ye(p.message,{cause:p}):new Re("error occurred while attempting to decoding jwt",{cause:p})}},f=Mt({uriQueryParameter:!0}),m=async h=>{try{return await f(h)===void 0?O:D()}catch{return O}},P=kt({});this.#t.push([m,P]);let l=Nr({storage:e.storage,entryPoint:P,converter:f,jwt:{decoder:u}});l[G]=B.authentication,s.push(l)}let c=ws({storage:e.storage});if(s.push(c),c[G]=B.security_context_server_web_exchange,r.authorize!==void 0){let d=bs({authenticationEntryPoint:this.authenticationEntryPoint});d[G]=B.error_translation,s.push(d);let f=(P=>{let l=[],h=!1;for(let[p,g]of P??[]){let b;if(p==="any-exchange")h=!0,b=Se;else{if(h)throw new Error("Cannot register other matchers after 'any-exchange' matcher");b=p}let E;if(g.access==="permitted")E=new ne(async()=>new Y(!0)),E.toString=()=>"AuthorizationManager[permitted]";else if(g.access==="denied")E=new ne(async()=>new Y(!1)),E.toString=()=>"AuthorizationManager[denied]";else if(g.access==="authenticated")E=new ne(async H=>{let L=await H;return L!==void 0?new Y(L.authenticated):new Y(!1)}),E.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(g)}`);l.push([b,E])}return qr({mappings:l})})(r.authorize),m=_r({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 _t(Se,...s)};var Gt=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()}};var As=require("node:crypto");var Vt=w("auth");function Co(r){let e=[],t=r.authConfig?.type,n={access:t!=="none"?"authenticated":"permitted"};Vt.enabledFor("info")&&Vt.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([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 xo(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=(0,As.randomUUID)().replaceAll("-","");Vt.enabledFor("info")&&Vt.info(`
|
|
12
|
+
`,H=class r extends $n.MIMEType{static ALL=new r("*/*");static APPLICATION_OCTET_STREAM=new r(xr);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),Nn(t)||this.#t(t),e===r.#e){let n=Dn(t),s=parseFloat(n);if(isNaN(s)||s<0||s>1)throw new ft(`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 ft(`Invalid token: ${e}`)}}get quality(){let e=this.params.get(r.#e);return e!==null?parseFloat(Dn(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))}},ft=class extends Error{constructor(e){super(e)}},ba=(function(){let e=new Map;for(let t of xi.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=H.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 Nn(r){return r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))}function Dn(r){return Nn(r)?r.substring(1,r.length-1):r}function Ai(r,e){if(r instanceof H&&e instanceof H){let s=r.quality,i=e.quality;if(s>i)return!0;if(s<i)return!1}let t=me(r),n=me(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 Ri(r,e){return Ai(e,r)}function Ti(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 Un(r){if(r===void 0)throw new Error("mimeTypes must not be undefined");if(r.length>100)throw new Fe("too many elements");Ti(r,Ri)}function Mi(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 qn(r){typeof r=="string"&&(r=[r]),typeof r=="number"&&(r=[String(r)]);let e=[];if(r)for(let t of r)t&&e.push(...Mi(t));return e}var $e=class{constructor(){}toList(e){let t=this.get(e);return qn(t)}},T=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 qn(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}},_n=new T;function ye(r){let e=r.one("content-type");return e?H.parseMediaType(e):void 0}var Tr=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 gt(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 Tr(r)}return r}var vt=fe(require("node:http"),1);function qe(r,e,t){let n=r.elements;if(t=t??n.length,e===0&&t===n.length)return r;if(e===t)return Ue.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 Ue(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 Mr={separator:47,decodeAndParseParameters:!0};function j(r,e){return Ue.createFromUrlPath(r,e??Mr)}var Ue=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):Ne.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 Ne.from(e,n)}else{let n=decodeURIComponent(e.substring(0,t)),s=e.substring(t),i=r.#s(s);return Ne.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,[""])}}}}},Ne=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 Bn(r,e){return typeof r=="string"?Hr.parse(r,e):Bn(r.href,e)}var Hr=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 qe(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 qe(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()}},_e=class extends ut{#e;#t;#r;get requestPath(){return this.#t===void 0&&(this.#t=Bn(this.URL.pathname,this.#r)),this.#t}get sslInfo(){return this.#e===void 0&&(this.#e=this.initSslInfo()),this.#e}};var mt=class extends vt.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},be=class extends vt.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},yt=class extends lt{#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:gt(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(){}},we=class extends _e{#e;#t;#r;constructor(e){super(new Ir(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 kr(this.#r.socket)}get cookies(){return this.#t??=super.cookies,this.#t}get body(){return vt.default.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}`}},kr=class{peerCertificate;constructor(e){this.peerCertificate=e.getPeerX509Certificate()}},Ir=class extends $e{#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()}},Wr=class extends $e{#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)}},bt=class extends yt{#e;constructor(e){super(new Wr(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}`))}})}}},wt=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 _e)return e.getNativeRequest();if(e instanceof r)return r.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},Se=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 yt)return e.getNativeResponse();if(e instanceof r)return r.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},St=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}]`}},Et=class{request;response;#e=new Map;#t;#r="";constructor(e,t,n){this.#e[Gn]=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(Gn);return this.#t!==e&&(this.#t=e,this.#r=e!==void 0?`[${e}] `:""),this.#r}},Gn="io.interop.web.server.exchange.log_id";var Pt=require("node:v8"),X=require("node:fs/promises"),A=S("monitoring"),Hi={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function ki(){return(0,Pt.getHeapStatistics)()}async function Vn(r){let e=r.dumpPrefix??"Heap",t=`${r.dumpLocation}/${e}.heapsnapshot`;A.enabledFor("debug")&&A.debug(`starting heap dump in ${t}`),await Or(r.dumpLocation).catch(async s=>{A.enabledFor("debug")&&A.debug(`dump location ${r.dumpLocation} does not exists. Will try to create it`);try{await(0,X.mkdir)(r.dumpLocation,{recursive:!0}),A.info(`dump location dir ${r.dumpLocation} successfully created`)}catch{A.error(`failed to create dump location ${r.dumpLocation}`)}});let n=(0,Pt.writeHeapSnapshot)(t);A.info("heap dumped");try{A.debug("rolling snapshot backups");let s=`${r.dumpLocation}/${e}.${r.maxBackups}.heapsnapshot`;await Or(s).then(async()=>{A.enabledFor("debug")&&A.debug(`deleting ${s}`);try{await(0,X.unlink)(s)}catch(o){A.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 Or(a).then(async()=>{try{await(0,X.rename)(a,c)}catch(d){A.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let i=`${r.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,X.rename)(n,i)}catch(o){A.warn(`failed to rename ${n} to ${i}`,o)}A.debug("snapshots rolled")}catch(s){throw A.error("error rolling backups",s),s}}async function Or(r){A.enabledFor("trace")&&A.debug(`checking file ${r}`),await(0,X.access)(r)}async function Ii(r,e,t){A.enabledFor("debug")&&A.debug(`processing heap stats ${JSON.stringify(r)}`);let n=Math.min(t.memoryLimit,.95*r.heap_size_limit),s=r.used_heap_size;A.info(`heap stats ${JSON.stringify(r)}`),s>=n?(A.warn(`used heap ${s} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await Vn(t)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function zn(r){let e={...Hi,...r},t=!1,n={memoryLimitExceeded:!1},s=async()=>{let a=ki();await Ii(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 Vn(e);break}case"stop":{t=!0,clearInterval(i),A.info("exit memory diagnostic");break}}return t}}}async function Wi({channel:r},e){await r(e)||A.warn(`cannot execute command "${e}" already closed`)}async function jn(r){return await Wi(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()}),Xn=(r,e)=>Li(r,e);var Be=require("@interopio/gateway");var Lr=S("gateway.ws.client-verify");function Fi(r){switch(r.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Di(r,e){let t=r.block??r.blacklist,n=r.allow??r.whitelist;if(t.length>0&&Be.IOGateway.Filtering.valuesMatch(t,e))return Lr.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&Be.IOGateway.Filtering.valuesMatch(n,e))return Lr.enabledFor("debug")&&Lr.debug(`origin ${e} matches allow filter`),!0}function $i(r){switch(r.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Jn(r,e){if(!e)return!0;if(r){let t=Di(e,r);return t||$i(e)}else return Fi(e)}function Yn(r){if(r){let e=(r.block??r.blacklist??[]).map(Be.IOGateway.Filtering.regexify),t=(r.allow??r.whitelist??[]).map(Be.IOGateway.Filtering.regexify);return{non_matched:r.non_matched??"allow",missing:r.missing??"allow",allow:t,block:e}}}var Kn=r=>async e=>{for(let t of r)if((await t(e)).match)return D();return L},Ee=r=>{let e=async t=>{for(let n of r)if(!(await n(t)).match)return L;return D()};return e.toString=()=>`and(${r.map(t=>t.toString()).join(", ")})`,e},Qn=r=>async e=>(await r(e)).match?L:D(),ve=async r=>D();ve.toString=()=>"any-exchange";var Zn=Object.freeze({}),L=Object.freeze({match:!1,variables:Zn}),D=(r=Zn)=>({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 L;if(typeof r=="string")return o===r?D():L;{let a=r.exec(o);return a===null?L:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${r.toString()}, method=${t??"<any>"})`,n},Ge=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 L}for(let i of s)if(!e(i)){for(let o of r.mediaTypes)if(i.startsWith(o))return D()}return L}},de=async({request:r})=>r.upgrade&&r.headers.one("upgrade")?.toLowerCase()==="websocket"?D():L;de.toString=()=>"websocket upgrade";var Fr=require("@interopio/gateway");async function Dr(r,e,t){let n=(i,o)=>{if(o?.cors){let a=o.cors===!0?{allowOrigins:o.origins?.allow?.map(Fr.IOGateway.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=$(Fr.IOGateway.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:v,variables:l}=await d(h);v?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:Yn(c?.origins)})}}};await r(s,e)}var At=require("@interopio/gateway");function Ui(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 es(r){return r.headers.has("origin")&&!Ui(r)}function J(r){return r.method==="OPTIONS"&&r.headers.has("origin")&&r.headers.has("access-control-request-method")}var ts=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],qi=(r,e)=>{let{request:t,response:n}=r,s=n.headers;if(!s.has("Vary"))s.set("Vary",ts.join(", "));else{let o=s.list("Vary");for(let a of ts)o.find(c=>c===a)||o.push(a);s.set("Vary",o.join(", "))}try{if(!es(t))return!0}catch{return N.enabledFor("debug")&&N.debug("reject: origin is malformed"),Ve(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=J(t);return e?Bi(r,e,i):i?(Ve(n),!1):!0},xt=["*"],$r=["GET","HEAD","POST"],rs={allowOrigins:xt,allowMethods:$r,allowHeaders:xt,maxAge:1800};function Rt(r){if(r){let e=r.allowHeaders;e&&e!==R&&(r={...r,allowHeaders:e.map(n=>n.toLowerCase())});let t=r.allowOrigins;return t&&(t==="*"?(ss(r),is(r)):r={...r,allowOrigins:t.map(n=>typeof n=="string"&&n!==R&&(n=At.IOGateway.Filtering.regexify(n),typeof n=="string")?os(n).toLowerCase():n)}),r}}function Ct(r,e){if(e===void 0)return r!==void 0?r===R?[R]:r:[];if(r===void 0)return e===R?[R]:e;if(r==xt||r===$r)return e===R?[R]:e;if(e==xt||e===$r)return r===R?[R]:r;if(r===R||r.includes(R)||e===R||e.includes(R))return[R];let t=new Set;return r.forEach(n=>t.add(n)),e.forEach(n=>t.add(n)),Array.from(t)}var ze=(r,e)=>e===void 0?r:{allowOrigins:Ct(r.allowOrigins,e?.allowOrigins),allowMethods:Ct(r.allowMethods,e?.allowMethods),allowHeaders:Ct(r.allowHeaders,e?.allowHeaders),exposeHeaders:Ct(r.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??r.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??r.allowPrivateNetwork,maxAge:e?.maxAge??r.maxAge},_i=r=>{let e=r.corsConfigSource,t=r.corsProcessor??qi;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)||J(n.request)||await s.filter(n)}}},ns=_i,N=S("cors");function Ve(r){r.setStatusCode(b.FORBIDDEN)}function Bi(r,e,t){let{request:n,response:s}=r,i=s.headers,o=n.headers.one("origin"),a=Vi(e,o);if(a===void 0)return N.enabledFor("debug")&&N.debug(`reject: '${o}' origin is not allowed`),Ve(s),!1;let c=Xi(n,t),d=zi(e,c);if(d===void 0)return N.enabledFor("debug")&&N.debug(`reject: HTTP '${c}' is not allowed`),Ve(s),!1;let u=Ji(n,t),h=ji(e,u);if(t&&h===void 0)return N.enabledFor("debug")&&N.debug(`reject: headers '${u}' are not allowed`),Ve(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 R="*",Gi=["GET","HEAD"];function ss(r){if(r.allowCredentials===!0&&r.allowOrigins===R)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function is(r){if(r.allowPrivateNetwork===!0&&r.allowOrigins===R)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function Vi(r,e){if(e){let t=r.allowOrigins;if(t){if(t===R)return ss(r),is(r),R;let n=os(e.toLowerCase());for(let s of t)if(s===R||At.IOGateway.Filtering.valueMatches(s,n))return e}}}function zi(r,e){if(e){let t=r.allowMethods??Gi;if(t===R)return[e];if(At.IOGateway.Filtering.valuesMatch(t,e))return t}}function ji(r,e){if(e===void 0)return;if(e.length==0)return[];let t=r.allowHeaders;if(t===void 0)return;let n=t===R||t.includes(R),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 os(r){return r.endsWith("/")?r.slice(0,-1):r}function Xi(r,e){return e?r.headers.one("access-control-request-method"):r.method}function Ji(r,e){let t=r.headers;return e?t.list("access-control-request-headers"):Array.from(t.keys())}var as=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};var cs=require("@interopio/gateway");function ds(r){let{sockets:e,cors:t}=r,n=r.corsConfig===!1?void 0:ze(rs,r.corsConfig),s=[];for(let[o,a]of e){let c=n;for(let[u,h]of t)cs.IOGateway.Filtering.valueMatches(u,o)&&(h===void 0?c=void 0:c=c===void 0?h:ze(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:ze(c,d),s.push([Ee([de,$(o)]),Rt(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:ze(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),Rt(a)]);return s.push([$(/\/api\/.*/),Rt(n)]),as({mappings:s})}function us(r){return r!==void 0&&typeof r.type=="string"&&typeof r.authenticated=="boolean"}var W=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}},Tt=class extends W{},Pe=class extends W{},Ce=class extends W{constructor(e){super(e)}},je=class extends Ce{constructor(e){super(e)}},Xe=class extends Ce{constructor(e){super(e)}},Je=class extends Ce{constructor(e){super(e)}},Ye=class extends Ce{constructor(e){super(e)}};var ue=class extends Error{},Y=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)}},xe=class extends W{};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)},Yi=()=>U(new T().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Ki=()=>U(new T().add("x-content-type-options","nosniff")),Qi=(r,e,t)=>{let n=`max-age=${r}`;e&&(n+=" ; includeSubDomains"),t&&(n+=" ; preload");let s=U(new T().add("strict-transport-security",n)),i=o=>o.request.URL.protocol==="https:";return async o=>{i(o)&&await s(o)}},Zi=r=>U(new T().add("x-frame-options",r)),eo=r=>U(new T().add("x-xss-protection",r)),to=r=>{let e=r===void 0?void 0:U(new T().add("permissions-policy",r));return async t=>{e!==void 0&&await e(t)}},ro=(r,e)=>{let t=e?"content-security-policy-report-only":"content-security-policy",n=r===void 0?void 0:U(new T().add(t,r));return async s=>{n!==void 0&&await n(s)}},no=(r="no-referrer")=>U(new T().add("referer-policy",r)),so=r=>{let e=r===void 0?void 0:U(new T().add("cross-origin-opener-policy",r));return async t=>{e!==void 0&&await e(t)}},io=r=>{let e=r===void 0?void 0:U(new T().add("cross-origin-embedder-policy",r));return async t=>{e!==void 0&&await e(t)}},oo=r=>{let e=r===void 0?void 0:U(new T().add("cross-origin-resource-policy",r));return async t=>{e!==void 0&&await e(t)}},ao=(...r)=>async e=>{for(let t of r)await t(e)};function Nr(r){let e=[];r?.cache?.disabled||e.push(Yi()),r?.contentType?.disabled||e.push(Ki()),r?.hsts?.disabled||e.push(Qi(r?.hsts?.maxAge??365*24*60*60,r?.hsts?.includeSubDomains??!0,r?.hsts?.preload??!1)),r?.frameOptions?.disabled||e.push(Zi(r?.frameOptions?.mode??"DENY")),r?.xss?.disabled||e.push(eo(r?.xss?.headerValue??"0")),r?.permissionsPolicy?.disabled||e.push(to(r?.permissionsPolicy?.policyDirectives)),r?.contentSecurityPolicy?.disabled||e.push(ro(r?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",r?.contentSecurityPolicy?.reportOnly)),r?.refererPolicy?.disabled||e.push(no(r?.refererPolicy?.policy??"no-referrer")),r?.crossOriginOpenerPolicy?.disabled||e.push(so(r?.crossOriginOpenerPolicy?.policy)),r?.crossOriginEmbedderPolicy?.disabled||e.push(io(r?.crossOriginEmbedderPolicy?.policy)),r?.crossOriginResourcePolicy?.disabled||e.push(oo(r?.crossOriginResourcePolicy?.policy)),r?.writers&&e.push(...r.writers);let t=ao(...e);return{filter:async(n,s)=>(await t(n),s.filter(n))}}var Ae=r=>{let e=r.entryPoint,t=r?.rethrowAuthenticationServiceError??!0;return async({exchange:n},s)=>{if(!t||!(s instanceof xe))return e(n,s);throw s}};var co="Realm",uo=r=>`Basic realm="${r}"`,Re=r=>{let e=uo(r?.realm??co);return async(t,n)=>{let{response:s}=t;s.setStatusCode(b.UNAUTHORIZED),s.headers.set("WWW-Authenticate",e)}};var ls="Basic ",Mt=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<=ls.length?"":s.substring(ls.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}}}};var hs=require("node:async_hooks"),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 hs.AsyncLocalStorage)=>(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 lo(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 ho(a,{exchange:r,chain:e},s,i)}catch(c){throw c instanceof W,c}}async function ho(r,e,t,n){se.withAuthentication(r)(n),await t(e,r)}function ie(r){let e={matcher:ve,successHandler:async({exchange:n,chain:s})=>{await s.filter(n)},converter:Mt({}),failureHandler:Ae({entryPoint:Re({})}),...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 lo(n,s,o,t,e.successHandler,e.storage)}catch(a){if(a instanceof W){await e.failureHandler({exchange:n,chain:s},a);return}throw a}}}}var ps=r=>async(e,t)=>{e.response.setStatusCode(r.httpStatus)};var Te=S("auth.entry-point"),Ht=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(Te.enabledFor("debug")&&Te.debug(`trying to match using: ${s}`),(await s(t)).match)return Te.enabledFor("debug")&&Te.debug(`match found. using default entry point ${i}`),i(t,n);return Te.enabledFor("debug")&&Te.debug(`no match found. using default entry point ${e}`),e(t,n)}};var fs=r=>async({exchange:e,chain:t},n)=>{for(let s of r)await s({exchange:e,chain:t},n)};function Ur(r){let e=async g=>g.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?D():L,t=Ht({entryPoints:[[e,ps({httpStatus:b.UNAUTHORIZED})]],defaultEntryPoint:Re({})}),n=r.entryPoint??t,s=r.manager,i=Ge({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),o=Qn(Ge({mediaTypes:["text/html"]})),a=Ee([o,i]),c=Kn([e,a]);r.defaultEntryPoints.push([c,n]);let d=r.failureHandler??Ae({entryPoint:n}),u=fs(r.successHandlers??r.defaultSuccessHandlers),h=Mt({});return ie({storage:r.storage,manager:s,failureHandler:d,successHandler:u,converter:h})}var gs={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},ms="https://tools.ietf.org/html/rfc6750#section-3.1";function kt(r){return{errorCode:gs.invalid_token,httpStatus:b.UNAUTHORIZED,description:r,uri:ms}}function qr(r){return{errorCode:gs.invalid_request,httpStatus:b.BAD_REQUEST,description:r,uri:ms}}var po="access_token",fo=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,_=class extends W{error;constructor(e,t,n){super(t??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},ys=r=>r.type==="BearerToken",go=r=>async e=>{let{request:t}=e;return Promise.all([yo(t.headers,r?.headerName).then(n=>n!==void 0?[n]:void 0),bo(t,r?.uriQueryParameter),wo(e,r?.formEncodedBodyParameter)]).then(n=>n.filter(s=>s!==void 0).flat(1)).then(mo).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function mo(r){if(r.length===0)return;if(r.length>1){let t=qr("Found multiple access tokens in the request");throw new _(t)}let e=r[0];if(!e||e.length===0){let t=qr("The requested access token parameter is an empty string");throw new _(t)}return e}async function yo(r,e="authorization"){let t=r.one(e);if(!t||!/bearer/i.test(t.substring(0)))return;let n=fo.exec(t);if(n===null){let s=kt("Bearer token is malformed");throw new _(s)}return n.groups?.token}async function bs(r){let e=r.getAll(po);if(e.length!==0)return e}async function bo(r,e=!1){if(!(!e||r.method!=="GET"))return bs(r.URL.searchParams)}async function wo(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 bs(n)}var It=go;function So(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 ws=r=>r.httpStatus!==void 0;function Eo(r){if(r instanceof _){let{error:e}=r;if(ws(e))return e.httpStatus}return b.UNAUTHORIZED}function vo(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),ws(n)&&n.scope&&t.set("scope",n.scope)}return t}var Po=r=>async(e,t)=>{let n=Eo(t),s=vo(t,r?.realmName),i=So(s),{response:o}=e;o.headers.set("WWW-Authenticate",i),o.setStatusCode(n),await o.end()},Wt=Po;var Co=r=>{let e=r?.principalClaimName??"sub";return t=>({type:"JwtToken",authenticated:!0,name:t.getClaimAsString(e)})},xo=r=>async e=>r(e),Me=class extends Error{},Ke=class extends Me{};function Ao(r){if(r instanceof Ke)return new _(kt(r.message),r.message,{cause:r});throw new xe(r.message,{cause:r})}function _r(r){let e=r.decoder,t=r.authConverter??xo(Co({}));return async n=>{if(ys(n)){let s=n.token;try{let i=await e(s);return await t(i)}catch(i){throw i instanceof Me?Ao(i):i}}}}function Br(r){let e=r.entryPoint??Wt({}),t=r?.converter??It({}),n=r.failureHandler??Ae({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??_r(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")}var Vt=require("@interopio/gateway/jose/jwt");async function Ss(r,e,t){let n=new Tt("Full authentication is required to access this resource."),s=new W("Access Denied",{cause:n});e&&(s.authentication=e),await t(r,s)}function Ro(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 Es=r=>{let e=Ro(b.FORBIDDEN),t=r.authenticationEntryPoint??Re();return{filter:async(n,s)=>{try{await s.filter(n)}catch(i){if(i instanceof ue){let o=await n.principal();us(o)?(o.authenticated||await e(n,i),await Ss(n,o,t)):await Ss(n,void 0,t);return}throw i}}}};var To=S("security.auth");function Gr(r){let e=async(t,n)=>{let s;for(let[i,o]of r.mappings)if((await i(n))?.match){To.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 Y(!1),s};return new ne(e)}var Ot=S("security.auth");function Vr(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),Ot.enabledFor("debug")&&Ot.debug("authorization successful")}catch(o){throw o instanceof ue&&Ot.enabledFor("debug")&&Ot.debug(`authorization failed: ${o.message}`),o}await s.filter(n)}}}var zr=class extends St{#e;constructor(e,t){super(e),this.#e=t}async principal(){return(await this.#e())?.authentication}},vs=r=>{let e=r.storage;return{filter:async(t,n)=>{await n.filter(new zr(t,async()=>await se.getContext(e)))}}};var Ps=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 Lt=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 Pe(`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}},He=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)}},Ft=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}};var O=require("@interopio/gateway-server/tools");function Mo(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 Dt=class extends le{#e;#t;#r;#n;#s;constructor(e=O.argon2.DEFAULT_SALT_LENGTH,t=O.argon2.DEFAULT_HASH_LENGTH,n=O.argon2.DEFAULT_PARALLELISM,s=O.argon2.DEFAULT_MEMORY,i=O.argon2.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.argon2.decode(t),s=await O.argon2.createHash(n.algorithm,e,n.hash.length,n.parameters);return Mo(n.hash,s)}catch{return!1}}async encodeDefinedPassword(e){let t=O.keygen.createSalt(this.#e),n={memory:this.#n,passes:this.#s,parallelism:this.#r,nonce:t},s=await O.argon2.createHash("argon2id",e,this.#t,n);return O.argon2.encode({algorithm:"argon2id",version:O.argon2.ARGON2_VERSION,parameters:n,hash:s})}upgradeEncodingDefined(e){let t=O.argon2.decode(e);return t.version<O.argon2.ARGON2_VERSION||t.parameters.memory<this.#n||t.parameters.passes<this.#s}};var jr=4096;function Cs(){let r="argon2id",e=new Map([[r,new Dt],["noop",Ft.instance]]);return new He(r,e,He.DEFAULT_ID_PREFIX,He.DEFAULT_ID_SUFFIX)}var xs={async updatePassword(r,e){return r}},$t=class extends W{username;constructor(e,t,n){super(e,n),this.username=t}},Nt=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 As(r,e){let t=e?.preAuthenticationChecks??(a=>{if(a.accountLocked)throw oe.debug("user account is locked"),new je("User account is locked");if(a.disabled)throw oe.debug("user account is disabled"),new Xe("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 Ye("User credentials have expired")}),s=e?.passwordEncoder??Cs(),i=e?.userDetailsPasswordService??xs,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 Pe("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 Ho(){return r=>{if(r.accountLocked)throw oe.debug("failed to authenticate since user account is locked"),new je("User account is locked");if(r.disabled)throw oe.debug("failed to authenticate user account is disabled"),new Xe("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 Ye("User credentials have expired")}}function Rs(r){let e=r.userDetailsService,t=r.userDetailsChecker??Ho(),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 $t("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 Xr(r){let e=r.manager??Rs({userDetailsService:r.getService("UserDetailsService")}),t=r.extractor??Lt(),n=r.converter??Ps({principalExtractor:t});return ie({storage:r.storage,manager:e,converter:n})}var Ut=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}]`}},qt=class extends Ut{#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}},Qe=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)}},_t=class extends Ut{#e;constructor(e,...t){super(e),this.#e=Qe.of(e,...t)}get filters(){return this.#e.filters}handle(e){return this.#e.filter(e)}};var Bt=class{#e;#t=new Yr;#r=new Jr;#n=new Qr;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 Kr)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}},Jr=class{decorate(e,t){return t=t||[],Qe.of({handle:n=>e.filter(n)},...t)}},Gt=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}},Yr=class{async firewalledExchange(e){return e}},Kr=class extends Error{constructor(e){super(e),this.name="ServerExchangeRejectedError"}},Qr=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"),Ts=(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 As(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]:Ht({entryPoints:this.#t,defaultEntryPoint:this.#t[this.#t.length-1][1]})}build(){if(r.headers!==void 0&&r.headers.disabled!==!0){let d=Nr(r.headers);d[G]=B.http_headers,s.push(d)}if(r.x509!==void 0&&r.x509.disabled!==!0){let d=Xr({storage:e.storage,getService:t,extractor:Lt({principalAltName:r.x509.principalAltName})});d[G]=B.authentication,s.push(d)}if(r.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let d=ns({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},v)=>await g.filter(h)],u=Ur({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=(0,Vt.jwtVerifier)({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 Vt.JwtVerifyError?new Ke(f.message,{cause:f}):new Me("error occurred while attempting to decoding jwt",{cause:f})}},h=It({uriQueryParameter:!0}),g=async p=>{try{return await h(p)===void 0?L:D()}catch{return L}},v=Wt({});this.#t.push([g,v]);let l=Br({storage:e.storage,entryPoint:v,converter:h,jwt:{decoder:u}});l[G]=B.authentication,s.push(l)}let c=vs({storage:e.storage});if(s.push(c),c[G]=B.security_context_server_web_exchange,r.authorize!==void 0){let d=Es({authenticationEntryPoint:this.authenticationEntryPoint});d[G]=B.error_translation,s.push(d);let h=(v=>{let l=[],p=!1;for(let[f,w]of v??[]){let m;if(f==="any-exchange")p=!0,m=ve;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 Y(!0)),y.toString=()=>"AuthorizationManager[permitted]";else if(w.access==="denied")y=new ne(async()=>new Y(!1)),y.toString=()=>"AuthorizationManager[denied]";else if(w.access==="authenticated")y=new ne(async P=>{let C=await P;return C!==void 0?new Y(C.authenticated):new Y(!1)}),y.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(w)}`);l.push([m,y])}return Gr({mappings:l})})(r.authorize),g=Vr({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 Gt(ve,...s)};var zt=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()}};var Ms=require("node:crypto");var jt=S("auth");function ko(r){let e=[],t=r.authConfig?.type,n={access:t!=="none"?"authenticated":"permitted"};jt.enabledFor("info")&&jt.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=Ee([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 Io(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=(0,Ms.randomUUID)().replaceAll("-","");jt.enabledFor("info")&&jt.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>Gr)throw new Error(`Password length exceeds maximum length of ${Gr} 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=Dt.ofUsername(t.name).password(n).roles(...s).build();return new Gt(i)}async function Rs(r){let e=os(r),t=Co(r),n=xo(r),{storage:s}=r;return xs(t,{storage:s,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}var zt=class extends be{};var ks=require("ws");function Ts(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 A;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 Hs(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()}]}var Ms=require("ws"),jt=class extends Ms.WebSocket{constructor(e,t,n){super(null,void 0,n)}connected},Xt=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 Ao(r,e,t,n){return s=>{let{logPrefix:i,request:o}=s,a=yt.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(!zn(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,P)=>{t.emit("connection",m,P)})}}function Ro(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=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 Ws(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,Cn):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new ks.WebSocketServer({noServer:!0,WebSocket:jt,autoPong:!1}),o=new Xt(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;Ro(c,u)}}).on("connection",(c,d)=>{let u=Ts(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=Ao(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)}}var S=require("node:fs"),Qe=require("node:path"),Yt=require("jsrsasign"),Jt=require("@interopio/gateway-server/tools");var He=w("ssl");function Is(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&&(0,S.existsSync)(r.key)&&(0,S.existsSync)(r.cert)){He.info(`using SSL/TLS certificate ${r.cert} with private key in ${r.key}${r.passphrase?" (password-protected)":""}`);let l={key:(0,S.readFileSync)(r.key),cert:(0,S.readFileSync)(r.cert),...t};return r.passphrase&&(l.passphrase=r.passphrase),r.requestCert&&r.ca&&(0,S.existsSync)(r.ca)&&(l.ca=(0,S.readFileSync)(r.ca)),l}if(!r.key&&!r.cert){let l="./gateway-server.key",h="./gateway-server.crt";if((0,S.existsSync)(l)&&(0,S.existsSync)(h)){He.info(`using SSL/TLS certificate ${h} with private key in ${l}${r.passphrase?" (password-protected)":""}`);let p={key:(0,S.readFileSync)(l),cert:(0,S.readFileSync)(h),...t};return r.passphrase&&(p.passphrase=r.passphrase),r.requestCert&&r.ca&&(0,S.existsSync)(r.ca)&&(p.ca=(0,S.readFileSync)(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(!(0,S.existsSync)(n)){if((0,S.existsSync)(s))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${s})`);let l=Jt.mkcert.generateRootCA({name:Jt.mkcert.DEFAULT_CA_NAME,passphrase:i}),h=(0,Qe.dirname)(n);h&&h!=="."&&!(0,S.existsSync)(h)&&(0,S.mkdirSync)(h,{recursive:!0});let p=(0,Qe.dirname)(s);p&&p!=="."&&p!==h&&!(0,S.existsSync)(p)&&(0,S.mkdirSync)(p,{recursive:!0}),(0,S.writeFileSync)(n,l.key,{mode:256}),(0,S.writeFileSync)(s,l.cert,{mode:420}),He.info(`created new local Root CA in ${s}, ${n}${i?" (password-protected)":""}`)}let o=(0,S.readFileSync)(n,"utf8"),a=Yt.KEYUTIL.getKey(o,i),c=(0,S.readFileSync)(s,"utf8"),d=new Yt.X509;d.readCertPEM(c);let u=d.getSubjectString(),f=e.host;He.debug(`generating server certificate signed by: ${u} for host: ${f}`);let m=Jt.mkcert.generateCert(a,u,[f],!1);if(r.key||r.cert){let l=r.key||"./gateway-server.key",h=r.cert||"./gateway-server.crt",p=(0,Qe.dirname)(l);p&&p!=="."&&!(0,S.existsSync)(p)&&(0,S.mkdirSync)(p,{recursive:!0});let g=(0,Qe.dirname)(h);g&&g!=="."&&g!==p&&!(0,S.existsSync)(g)&&(0,S.mkdirSync)(g,{recursive:!0}),(0,S.writeFileSync)(l,m.key,{mode:384}),(0,S.writeFileSync)(h,m.cert,{mode:420}),He.info(`generated server certificate saved to ${h} with private key in ${l}${i?" (password-protected)":""}`)}else He.info(`using in-memory server certificate for host: ${f}`);let P={key:m.key,cert:m.cert,...t};return r.requestCert&&r.ca&&(0,S.existsSync)(s)&&(P.ca=(0,S.readFileSync)(s)),P}function Yr(r){return r?.get("io.gateway.logging.suppress")===!0}var Kt="io.gateway.logging.prefix";function Kr(r){return r?.has(Kt)?r.get(Kt)??"":""}var Me=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}},Qt=class extends Me{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")&&!Yr(n)&&this.#e(s),s}#e(e,t){let n=Kr(t);this.logger.debug(`${n}Encoding value of type ${typeof e} with size ${e.byteLength??e.size??e.length}`)}},Zt=class r extends Me{constructor(...e){super(...e)}canEncode(e,t){return super.canEncode(e,t)&&e==="string"}async encode(e,t,n){if(e=await e,!Yr(n)&&this.logger.enabledFor("debug")){let s=Kr(n),i=this.logger.enabledFor("trace");this.logger.debug(`${s}Writing ${i?`${e}`:`${e.substring(0,100)}...`}`)}return e}static textPlainOnly(){return new r(Cr("text","plain","utf-8"))}static allMimeTypes(){return new r(Cr("text","plain","utf-8"),Fe)}};var le=class{log=w("http.codec");#e=!1;set enableLoggingRequestDetails(e){this.#e=e}get enableLoggingRequestDetails(){return this.#e}};var Ze=class r extends le{static MEDIA_TYPES=Object.freeze([R.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")}},et=class extends le{getReadableMediaTypes(){return[R.MULTIPART_FORM_DATA]}canRead(e,t){return e==="string"||e.name===File.name&&(t===void 0||re(R.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 tt=class r{#e;#t;#r;constructor(e){r.initLogger(e),this.#e=e,this.#t=R.asMediaTypes(...e.encodableMimeTypes()),this.#r=this.#t.find(t=>Pr(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 Me}#n(e,t){let n=ge(e.headers);if(n)return n;let s=this.#r;n=Ho(t,s)?s:t,n&&(n=To(n,s),e.headers.set("Content-Type",n.toString()))}};function To(r,e){if(!r.params.has("charset")&&e!==void 0){let t=e.params.get("charset");if(t){let n=R.parseMediaType(r.toString());return n.params.set("charset",t),n}}return r}function Ho(r,e){return(r===void 0||!Pr(r)||r.essence===R.APPLICATION_OCTET_STREAM.essence)&&e!==void 0}var Qr=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 et;this.addCodec(this.#i,e),this.addCodec(this.#i,new Ze(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 tt(new Qt)),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 tt(Zt.allMimeTypes())),e}addCodec(e,t){this.#c(t),e.push(t)}#c(e){if(e instanceof tt&&(e=e.encoder),e===void 0)return;let t=this.#t,n=this.#r;n!==void 0&&(e instanceof Ze&&(e.enableLoggingRequestDetails=n),e instanceof et&&(e.enableLoggingRequestDetails=n))}},Zr=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}},en=class extends Qr{},tn=class extends Zr{constructor(){super(new en)}};function Mo(){return new tn}var ke={serverConfigurer:{create:Mo}};var Os=require("node:net");function ko({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=(0,Os.createServer)(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 Ls({options:r,logger:e,shutdown:t,info:n}){ko({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()}})}var fn=Oe(require("@interopio/gateway-server/package.json"),1);var Fs=require("node:path"),er=require("node:fs/promises"),Ds=require("node:fs");async function Wo(r){if(r)for(let e of r){let t=(0,Fs.resolve)(e,"index.html");try{return await(0,er.access)(t,Ds.constants.R_OK),t}catch{}}}async function rn(r){let e=await Wo(r),t=Be({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((0,er.readFile)(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()}}var Us=require("node:async_hooks");function nn(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 $s(r,e){return nn(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 sn=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 le&&t.enableLoggingRequestDetails){this.#r=!0;break}}createExchange(e,t){return new wt(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($s(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))})}},tr=class r{#e;#t=[];#r=[];#n=[];#s;#i=new Us.AsyncLocalStorage;#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 Nt(this.#e,...this.#t);t=new Ut(t,...this.#r);let n=new sn(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 rr={create:(r,e)=>new an(r,e)},on=class{#e;constructor(e){this.#e=e}accept(){return R.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}},an=class{exchange;messageReaders;#e;constructor(e,t){this.exchange=e,this.messageReaders=[...t],this.#e=new on(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 v=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 v{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 We=class extends v{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 v.WILDCARD_WEIGHT}toString(){return"Wildcard(*)"}};var K=class extends v{#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=v.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===v.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 v{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 nr=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?rt.EMPTY:new rt(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:""}},rt=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})`}},sr=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 We&&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 nr(e,!1);return this.#i.matches(0,t)}matchAndExtract(e){if(this.#i===void 0)return this.#h(e)&&!this.#p(e)?void 0:rt.EMPTY;if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return;let t=new nr(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=Ne(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}};var Ns=require("node:util"),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"},M=class r extends Error{position;messageType;inserts;#e;static formatMessage(e,t){return(0,Ns.format)(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>jr)throw new Error(`Password length exceeds maximum length of ${jr} 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=Nt.ofUsername(t.name).password(n).roles(...s).build();return new zt(i)}async function Hs(r){let e=ds(r),t=ko(r),n=Io(r),{storage:s}=r;return Ts(t,{storage:s,corsConfigSource:e,userDetailsService:n,userDetailsPasswordService:n})}var Xt=class extends Se{};var Os=require("ws");function ks(r,e){let t=r?.exchange,n=t?.request??new we(r),s=t?.principal,i=s?s.bind(t):async function(){},o=n.URL,a=new T;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 Is(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()}]}var Ws=require("ws"),Jt=class extends Ws.WebSocket{constructor(e,t,n){super(null,void 0,n)}connected},Yt=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 Wo(r,e,t,n){return s=>{let{logPrefix:i,request:o}=s,a=wt.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(!Jn(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,v)=>{t.emit("connection",g,v)})}}function Oo(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=Se.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 Ls(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,Rn):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let i=new Os.WebSocketServer({noServer:!0,WebSocket:Jt,autoPong:!1}),o=new Yt(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;Oo(c,u)}}).on("connection",(c,d)=>{let u=ks(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=Wo(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)}}var E=require("node:fs"),Ze=require("node:path"),Qt=require("jsrsasign"),Kt=require("@interopio/gateway-server/tools");var ke=S("ssl");function Fs(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&&(0,E.existsSync)(r.key)&&(0,E.existsSync)(r.cert)){ke.info(`using SSL/TLS certificate ${r.cert} with private key in ${r.key}${r.passphrase?" (password-protected)":""}`);let l={key:(0,E.readFileSync)(r.key),cert:(0,E.readFileSync)(r.cert),...t};return r.passphrase&&(l.passphrase=r.passphrase),r.requestCert&&r.ca&&(0,E.existsSync)(r.ca)&&(l.ca=(0,E.readFileSync)(r.ca)),l}if(!r.key&&!r.cert){let l="./gateway-server.key",p="./gateway-server.crt";if((0,E.existsSync)(l)&&(0,E.existsSync)(p)){ke.info(`using SSL/TLS certificate ${p} with private key in ${l}${r.passphrase?" (password-protected)":""}`);let f={key:(0,E.readFileSync)(l),cert:(0,E.readFileSync)(p),...t};return r.passphrase&&(f.passphrase=r.passphrase),r.requestCert&&r.ca&&(0,E.existsSync)(r.ca)&&(f.ca=(0,E.readFileSync)(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(!(0,E.existsSync)(n)){if((0,E.existsSync)(s))throw new Error(`CA key file not found: ${n} (CA certificate exists: ${s})`);let l=Kt.mkcert.generateRootCA({name:Kt.mkcert.DEFAULT_CA_NAME,passphrase:i}),p=(0,Ze.dirname)(n);p&&p!=="."&&!(0,E.existsSync)(p)&&(0,E.mkdirSync)(p,{recursive:!0});let f=(0,Ze.dirname)(s);f&&f!=="."&&f!==p&&!(0,E.existsSync)(f)&&(0,E.mkdirSync)(f,{recursive:!0}),(0,E.writeFileSync)(n,l.key,{mode:256}),(0,E.writeFileSync)(s,l.cert,{mode:420}),ke.info(`created new local Root CA in ${s}, ${n}${i?" (password-protected)":""}`)}let o=(0,E.readFileSync)(n,"utf8"),a=Qt.KEYUTIL.getKey(o,i),c=(0,E.readFileSync)(s,"utf8"),d=new Qt.X509;d.readCertPEM(c);let u=d.getSubjectString(),h=e.host;ke.debug(`generating server certificate signed by: ${u} for host: ${h}`);let g=Kt.mkcert.generateCert(a,u,[h],!1);if(r.key||r.cert){let l=r.key||"./gateway-server.key",p=r.cert||"./gateway-server.crt",f=(0,Ze.dirname)(l);f&&f!=="."&&!(0,E.existsSync)(f)&&(0,E.mkdirSync)(f,{recursive:!0});let w=(0,Ze.dirname)(p);w&&w!=="."&&w!==f&&!(0,E.existsSync)(w)&&(0,E.mkdirSync)(w,{recursive:!0}),(0,E.writeFileSync)(l,g.key,{mode:384}),(0,E.writeFileSync)(p,g.cert,{mode:420}),ke.info(`generated server certificate saved to ${p} with private key in ${l}${i?" (password-protected)":""}`)}else ke.info(`using in-memory server certificate for host: ${h}`);let v={key:g.key,cert:g.cert,...t};return r.requestCert&&r.ca&&(0,E.existsSync)(s)&&(v.ca=(0,E.readFileSync)(s)),v}function Zr(r){return r?.get("io.gateway.logging.suppress")===!0}var Zt="io.gateway.logging.prefix";function en(r){return r?.has(Zt)?r.get(Zt)??"":""}var Ie=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}},er=class extends Ie{constructor(){super(De)}canEncode(e,t){return super.canEncode(e,t)}async encode(e,t,n){let s=await e;return this.logger.enabledFor("debug")&&!Zr(n)&&this.#e(s),s}#e(e,t){let n=en(t);this.logger.debug(`${n}Encoding value of type ${typeof e} with size ${e.byteLength??e.size??e.length}`)}},tr=class r extends Ie{constructor(...e){super(...e)}canEncode(e,t){return super.canEncode(e,t)&&e==="string"}async encode(e,t,n){if(e=await e,!Zr(n)&&this.logger.enabledFor("debug")){let s=en(n),i=this.logger.enabledFor("trace");this.logger.debug(`${s}Writing ${i?`${e}`:`${e.substring(0,100)}...`}`)}return e}static textPlainOnly(){return new r(Rr("text","plain","utf-8"))}static allMimeTypes(){return new r(Rr("text","plain","utf-8"),De)}};var he=class{log=S("http.codec");#e=!1;set enableLoggingRequestDetails(e){this.#e=e}get enableLoggingRequestDetails(){return this.#e}};var et=class r extends he{static MEDIA_TYPES=Object.freeze([H.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")}},tt=class extends he{getReadableMediaTypes(){return[H.MULTIPART_FORM_DATA]}canRead(e,t){return e==="string"||e.name===File.name&&(t===void 0||re(H.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 rt=class r{#e;#t;#r;constructor(e){r.initLogger(e),this.#e=e,this.#t=H.asMediaTypes(...e.encodableMimeTypes()),this.#r=this.#t.find(t=>Ar(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 Ie}#n(e,t){let n=ye(e.headers);if(n)return n;let s=this.#r;n=Fo(t,s)?s:t,n&&(n=Lo(n,s),e.headers.set("Content-Type",n.toString()))}};function Lo(r,e){if(!r.params.has("charset")&&e!==void 0){let t=e.params.get("charset");if(t){let n=H.parseMediaType(r.toString());return n.params.set("charset",t),n}}return r}function Fo(r,e){return(r===void 0||!Ar(r)||r.essence===H.APPLICATION_OCTET_STREAM.essence)&&e!==void 0}var tn=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 tt;this.addCodec(this.#i,e),this.addCodec(this.#i,new et(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 rt(new er)),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 rt(tr.allMimeTypes())),e}addCodec(e,t){this.#c(t),e.push(t)}#c(e){if(e instanceof rt&&(e=e.encoder),e===void 0)return;let t=this.#t,n=this.#r;n!==void 0&&(e instanceof et&&(e.enableLoggingRequestDetails=n),e instanceof tt&&(e.enableLoggingRequestDetails=n))}},rn=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}},nn=class extends tn{},sn=class extends rn{constructor(){super(new nn)}};function Do(){return new sn}var We={serverConfigurer:{create:Do}};var Ns=require("node:net"),Us=require("node:fs/promises");var Ds=fe(require("net"),1);function $s(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=Ds.default.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 $o(r){try{return{stale:!1,pid:(await $s({path:r},{command:"info"},{timeout:2e3}))?.pid??0}}catch{return{stale:!0}}}async function No(r,e){if(process.platform!=="win32"&&e)try{await(0,Us.unlink)(e)}catch(t){let n=t.code;n!=="ENOENT"&&r.warn(`[${e}] error while removing the pipe - ${e} (${n})`,t)}}function Uo({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=(0,Ns.createServer)(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 v=JSON.stringify({result:g});r.enabledFor("debug")&&r.debug(`[${s}] command ${h.command} processed successfully. sending : ${v}`),c.write(v,l=>{l&&r.enabledFor("debug")&&r.debug(`[${s}] error while sending response for command ${h.command}`,l)})}).catch(g=>{let v=JSON.stringify({error:g.message});r.error(`[${s}] processing command ${h.command} failed, sending ${v}`,g),c.write(v,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...`),$o(s).then(d=>{if(d.stale)r.info(`[${s}] socket is stale, cleaning up and retrying...`),No(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 qs({options:r,logger:e,shutdown:t,info:n}){return await Uo({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()}})}var yn=fe(require("@interopio/gateway-server/package.json"),1);var _s=require("node:path"),rr=require("node:fs/promises"),Bs=require("node:fs");async function qo(r){if(r)for(let e of r){let t=(0,_s.resolve)(e,"index.html");try{return await(0,rr.access)(t,Bs.constants.R_OK),t}catch{}}}async function on(r){let e=await qo(r),t=Ge({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((0,rr.readFile)(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()}}var Vs=require("node:async_hooks");function an(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 Gs(r,e){return an(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 cn=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=We.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 Et(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(Gs(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))})}},nr=class r{#e;#t=[];#r=[];#n=[];#s;#i=new Vs.AsyncLocalStorage;#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 _t(this.#e,...this.#t);t=new qt(t,...this.#r);let n=new cn(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 sr={create:(r,e)=>new un(r,e)},dn=class{#e;constructor(e){this.#e=e}accept(){return H.parseMediaTypes(...this.#e.list("accept"))}contentLength(){let e=this.#e.one("content-length");return e!==void 0?Number.parseInt(e):void 0}contentType(){return ye(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}},un=class{exchange;messageReaders;#e;constructor(e,t){this.exchange=e,this.messageReaders=[...t],this.#e=new dn(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 x=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 x{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 Oe=class extends x{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 x.WILDCARD_WEIGHT}toString(){return"Wildcard(*)"}};var K=class extends x{#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=x.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===x.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 x{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 ir=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?nt.EMPTY:new nt(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:""}},nt=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})`}},or=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 Oe&&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 ir(e,!1);return this.#i.matches(0,t)}matchAndExtract(e){if(this.#i===void 0)return this.#h(e)&&!this.#p(e)?void 0:nt.EMPTY;if(!this.#h(e))if(this.#i instanceof Q||this.#i instanceof K)e=r.#e;else return;let t=new ir(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=qe(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}};var zs=require("node:util"),_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"},k=class r extends Error{position;messageType;inserts;#e;static formatMessage(e,t){return(0,zs.format)(_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:v.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*v.CAPTURE_VARIABLE_WEIGHT+this.wildcardCount*v.WILDCARD_WEIGHT}toString(){return`Regex(${String.fromCharCode(...this.#e)})`}};var ar=class extends v{#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 cr=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 M.create(this.#n,this.#t,"ILLEGAL_NESTED_CAPTURE");this.#c=!0,this.#u=this.#n}else if(t===125){if(!this.#c)throw M.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 M.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 M.create(this.#n,this.#t,"ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR",String.fromCharCode(t))}}this.#n++}return this.#a!==-1&&this.#m(this.#y()),new sr(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 M.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 ir(this.#a,this.#g(),this.#e.caseSensitive,t)}catch(n){throw n instanceof SyntaxError?M.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 M.create(this.#a,this.#t,"CAPTURE_ALL_IS_STANDALONE_CONSTRUCT");let n=new nt(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 We(this.#a,t):e=new nt(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t):this.#s!==0?e=new or(this.#a,this.#g(),this.#s,this.#e.caseSensitive,t):e=new ar(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 M.create(this.#n,this.#t,"MISSING_REGEX_CONSTRAINT");return}t--}if(s==this.#e.pathOptions.separator&&!n)throw M.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");this.#n++,n=!1}throw M.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 M.create(this.#n,this.#t,"CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS");if(e>1&&t!==this.#r-1)throw M.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 M.create(e,this.#t,"ILLEGAL_DOUBLE_CAPTURE",t);this.#p.push(t)}};var dr=class r{#e=!0;#t=Ar;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 cr(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 qs=w("web.async.fn.router"),cn="io.interop.web.async.fn.router.request",dn="io.interop.web.async.fn.router.variables",_s="io.interop.web.async.fn.router.pattern";function Bs(r){let e={route:r,and:t=>Fo(e,t)};return e}function Fo(r,e){return Bs(async t=>{let n=r.route(t);return n!==void 0?n:e.route(t)})}function Gs(r,e){return Bs(async t=>{if(r.test(t)){if(qs.enabledFor("trace")){let n=t.exchange.logPrefix;qs.debug(`${n}Matched ${r}`)}return e}else return})}var Vs=(function(){let r=w("request.predicates");function e(l){if(J(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),E=h.has(b);return u("Method",`[${[...h].join(", ")}]`,b,E),E};return p.toString=()=>`[${l.join(", ")}]`,t(p)}function c(l){let h=dr.DEFAULT;return l=h.initFullPathPattern(l),d(h)(l)}function d(l){return h=>{let p=l.parse(h),g=b=>{let E=b.requestPath.pathWithinApplication,H=p.matchAndExtract(E);return u("Pattern",p.patternString,E.value,H!==void 0),H!==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=>J(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=[R.ALL]:Dn(g),g}if(l.length===1){let p=l[0],g=b=>{let E=h(b),H=!1;for(let L of E)if(re(L,p)){H=!0;break}return u("Accept",p,E,H),H};return g.toString=()=>`Accept: ${p}`,f(g)}else{let p=g=>{let b=h(g),E=!1;e:for(let H of b)for(let L of l)if(re(H,L)){E=!0;break e}return u("Accept",l,b,E),E};return p.toString=()=>`Accept: ${l.join(", ")}`,f(p)}}function P(l,h){let p=typeof h=="string"?h:void 0,g=typeof h=="string"?E=>E===p:h,b=E=>{let H=E.queryParam(l);return H!=null&&g(H)};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:P}})();async function Do(r){return ur(r.statusCode).headers(e=>{for(let t of r.headers.keys())e.add(t,r.headers.list(t))}).bodyValue(r.body)}function ur(r){return r=typeof r=="number"?pt(r):r,new un(r)}function $o(){return ur(y.OK)}function Uo(r){return ur(y.CREATED).location(r)}var zs={from:Do,status:ur,ok:$o,created:Uo};function No(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 qo(r){return async(e,t)=>No(e,t,Promise.resolve(r),typeof r)}var un=class{#e;#t=new A;#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 hn(this.#e,this.#t,new Map(this.#r),e,t,new Map(this.#n)))}build(e){return e?Promise.resolve(new ln(this.#e,this.#t,this.#r,e)):this.build(async(t,n)=>{await t.response.end()})}},Ie=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 ln=class extends Ie{#e;constructor(e,t,n,s){super(e,t,n),this.#e=s}async writeInternal(e,t){await this.#e(e,t)}},hn=class extends Ie{#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(Kt,e.logPrefix),await this.inserter(e.response,{messageWriters:t,serverRequest:e.request,hints:this.hints})}};var js=require("node:util");var lr=class r extends Error{#e;#t=new A;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 lr{#e;constructor(e,t){super(e,r.problemDetailFor(e,t)),this.#e=t}get reason(){return this.#e}get headers(){return Un}};var st=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)}},pn=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=rr.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 nn(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)}},hr=class r extends pn{static#e=new st;static#t={includes:["status"]};constructor(e,t,n,s={}){super(e,t,n)}getRoutingFunction(e){return Gs(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,Fe),n=this.#s(e,t);return zs.status(n).contentType(new js.MIMEType("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 Xs="io.interop.web.async.handler.handler",Js="io.interop.web.async.handler.pattern";var pr=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(J(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}}},fr=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)||J(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 gr=class{supports(e){return typeof e=="function"}async handle(e,t){let n=t,s=e.attribute(cn);if(!s)throw new Error("ServerRequest is not found in exchange attributes.");return n(s).then(i=>({handler:t,returnValue:i}))}},mr=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 Ie}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})}},yr=class extends fr{#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=rr.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(cn,t),e.set(Xs,n);let s=e.get(_s);s&&e.set(Js,s);let i=e.get(dn);i!==void 0&&e.set(dn,i)}};var T=w("app");async function Bo(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 mt(i),c=o.method==="HEAD"?new zt(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(gn.default.STATUS_CODES[400]),Promise.resolve();throw o}}}function Go(r){return new Promise((e,t)=>{let n=r(s=>{s?t(s):e(n)})})}function Vo(r){if(r)return Bn({memoryLimit:r.memory_limit,dumpLocation:r.dump_location,dumpPrefix:r.dump_prefix,reportInterval:r.report_interval,maxBackups:r.max_backups})}var Qs=`${fn.default.name} - v${fn.default.version}`;async function zo(r){let e=r.storage,t=await Rs(r),n=Hs(r),s=ke.serverConfigurer.create();s.defaultCodecs.enableLoggingRequestDetails(!0);let i=new yr,o=new pr([i],[new gr],[new mr(s.writers)]),a={handle:kn(Vn(Qs,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 rn(r.resourcesConfig?.locations),async({response:c},d)=>{throw new Z(y.NOT_FOUND)})};return new tr(a).filter(new qt(t)).codecConfigurer(s).exceptionHandler(new hr(s.readers,s.writers,new st)).storage(e)}var mn=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)=>Ys.default.createServer({...h,...Is(e,n)},p):(h,p)=>gn.default.createServer(h,p),i=Vo(r.memory),o={middleware:[],corsConfig:r.cors,cors:[],authConfig:r.auth,authorize:[],storage:new Ks.AsyncLocalStorage,sockets:new Map,resourcesConfig:r.resources},a=new ot({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 Or(async p=>{p.socket({path:h,factory:Rn.bind(a),options:r.gateway})},r,o)}r.app&&await Or(r.app,r,o);let c=En(r.port??0),d=h=>T.error(`socket error: ${h}`,h),u=await zo(o),f=await Bo(u,d),P=await new Promise((h,p)=>{let g=s({IncomingMessage:ft,ServerResponse:me,...r.http},f);g.on("error",b=>{if(b.code==="EADDRINUSE"){T.debug(`port ${b.port} already in use on address ${b.address}`);let{value:E}=c.next();E?(T.info(`retry starting server on port ${E} and host ${t??"<unspecified>"}`),g.close(),g.listen(E,t)):(T.warn(`all configured port(s) ${r.port} are in use. closing...`),g.close(),p(b))}else T.error(`server error: ${b.message}`,b),p(b)}),g.on("listening",async()=>{let b=g.address();for(let[E,H]of o.sockets){let L=`${e?"wss":"ws"}://${vn}:${b.port}${E}`;await Ws(E,H,L,o.storage,d)}T.info(`http server listening on ${e?"https":"http"}://${ee(b)}`),h(g)}),g.on("upgrade",(b,E,H)=>{try{f(b,H)}catch(L){T.error(`upgrade error: ${L}`,L)}}).on("close",async()=>{T.info("http server closed.")});try{let{value:b}=c.next();g.listen(b,t)}catch(b){T.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=P.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){T.warn(`error closing route ${h}`,g)}await Go(h=>{P.closeAllConnections(),P.close(h)}),i&&await Gn(i),await a.stop()}};return r.management?.server.path&&Ls({options:r.management.server,info:async()=>({pid:process.pid,type:"gateway-server",...l.gateway.info()}),logger:T.child("management"),shutdown:r.management.commands?.shutdown.enabled?async()=>{T.enabledFor("info")&&T.info("stopping gateway-server..."),await l.close()}:void 0}),l};var jo=mn;0&&(module.exports={GatewayServer});
|
|
20
|
+
`),e.push(this.message),e.join("")}};var ar=class extends x{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 x.CAPTURE_VARIABLE_WEIGHT}toString(){return`CaptureVariable({${this.variableName}${this.#e?":"+this.#e.source:""}})`}};var cr=class extends x{#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 st=class extends x{#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),v=g.indexOf(":"),l,p;v!==-1?(l=g.substring(0,v),p=g.substring(v+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:x.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*x.CAPTURE_VARIABLE_WEIGHT+this.wildcardCount*x.WILDCARD_WEIGHT}toString(){return`Regex(${String.fromCharCode(...this.#e)})`}};var dr=class extends x{#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 ur=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 k.create(this.#n,this.#t,"ILLEGAL_NESTED_CAPTURE");this.#c=!0,this.#u=this.#n}else if(t===125){if(!this.#c)throw k.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 k.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 k.create(this.#n,this.#t,"ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR",String.fromCharCode(t))}}this.#n++}return this.#a!==-1&&this.#m(this.#y()),new or(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 k.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 ar(this.#a,this.#g(),this.#e.caseSensitive,t)}catch(n){throw n instanceof SyntaxError?k.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 k.create(this.#a,this.#t,"CAPTURE_ALL_IS_STANDALONE_CONSTRUCT");let n=new st(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 Oe(this.#a,t):e=new st(this.#a,this.#g(),this.#e.caseSensitive,this.#t,t):this.#s!==0?e=new cr(this.#a,this.#g(),this.#s,this.#e.caseSensitive,t):e=new dr(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 k.create(this.#n,this.#t,"MISSING_REGEX_CONSTRAINT");return}t--}if(s==this.#e.pathOptions.separator&&!n)throw k.create(this.#n,this.#t,"MISSING_CLOSE_CAPTURE");this.#n++,n=!1}throw k.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 k.create(this.#n,this.#t,"CANNOT_HAVE_MANY_MULTISEGMENT_PATH_ELEMENTS");if(e>1&&t!==this.#r-1)throw k.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 k.create(e,this.#t,"ILLEGAL_DOUBLE_CAPTURE",t);this.#p.push(t)}};var lr=class r{#e=!0;#t=Mr;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 ur(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 js=S("web.async.fn.router"),ln="io.interop.web.async.fn.router.request",hn="io.interop.web.async.fn.router.variables",Xs="io.interop.web.async.fn.router.pattern";function Js(r){let e={route:r,and:t=>Vo(e,t)};return e}function Vo(r,e){return Js(async t=>{let n=r.route(t);return n!==void 0?n:e.route(t)})}function Ys(r,e){return Js(async t=>{if(r.test(t)){if(js.enabledFor("trace")){let n=t.exchange.logPrefix;js.debug(`${n}Matched ${r}`)}return e}else return})}var Ks=(function(){let r=S("request.predicates");function e(l){if(J(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=lr.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,P=f.matchAndExtract(y);return u("Pattern",f.patternString,y.value,P!==void 0),P!==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=>J(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=[H.ALL]:Un(w),w}if(l.length===1){let f=l[0],w=m=>{let y=p(m),P=!1;for(let C of y)if(re(C,f)){P=!0;break}return u("Accept",f,y,P),P};return w.toString=()=>`Accept: ${f}`,h(w)}else{let f=w=>{let m=p(w),y=!1;e:for(let P of m)for(let C of l)if(re(P,C)){y=!0;break e}return u("Accept",l,m,y),y};return f.toString=()=>`Accept: ${l.join(", ")}`,h(f)}}function v(l,p){let f=typeof p=="string"?p:void 0,w=typeof p=="string"?y=>y===f:p,m=y=>{let P=y.queryParam(l);return P!=null&&w(P)};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:v}})();async function zo(r){return hr(r.statusCode).headers(e=>{for(let t of r.headers.keys())e.add(t,r.headers.list(t))}).bodyValue(r.body)}function hr(r){return r=typeof r=="number"?gt(r):r,new pn(r)}function jo(){return hr(b.OK)}function Xo(r){return hr(b.CREATED).location(r)}var Qs={from:zo,status:hr,ok:jo,created:Xo};function Jo(r,e,t,n){let s=ye(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 pn=class{#e;#t=new T;#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 gn(this.#e,this.#t,new Map(this.#r),e,t,new Map(this.#n)))}build(e){return e?Promise.resolve(new fn(this.#e,this.#t,this.#r,e)):this.build(async(t,n)=>{await t.response.end()})}},Le=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 fn=class extends Le{#e;constructor(e,t,n,s){super(e,t,n),this.#e=s}async writeInternal(e,t){await this.#e(e,t)}},gn=class extends Le{#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(Zt,e.logPrefix),await this.inserter(e.response,{messageWriters:t,serverRequest:e.request,hints:this.hints})}};var Zs=require("node:util");var pr=class r extends Error{#e;#t=new T;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 pr{#e;constructor(e,t){super(e,r.problemDetailFor(e,t)),this.#e=t}get reason(){return this.#e}get headers(){return _n}};var it=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)}},mn=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=sr.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 an(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)}},fr=class r extends mn{static#e=new it;static#t={includes:["status"]};constructor(e,t,n,s={}){super(e,t,n)}getRoutingFunction(e){return Ys(Ks.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,De),n=this.#s(e,t);return Qs.status(n).contentType(new Zs.MIMEType("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 ei="io.interop.web.async.handler.handler",ti="io.interop.web.async.handler.pattern";var gr=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(J(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}}},mr=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)||J(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 yr=class{supports(e){return typeof e=="function"}async handle(e,t){let n=t,s=e.attribute(ln);if(!s)throw new Error("ServerRequest is not found in exchange attributes.");return n(s).then(i=>({handler:t,returnValue:i}))}},br=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 Le}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})}},wr=class extends mr{#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=We.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=sr.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(ln,t),e.set(ei,n);let s=e.get(Xs);s&&e.set(ti,s);let i=e.get(hn);i!==void 0&&e.set(hn,i)}};var M=S("app");async function Qo(r,e){let t=r.build();return async(n,s)=>{n.socket.addListener("error",e);let i;s instanceof be?i=s:(n.upgradeHead=s,i=new be(n),i.assignSocket(n.socket));try{let o=new we(n),a=new bt(i),c=o.method==="HEAD"?new Xt(a):a,d=t(o,c);try{await d,M.enabledFor("trace")&&M.debug(`${o.id} handling completed.`)}catch(u){if(u instanceof Error&&u.code==="ERR_INVALID_URL")throw u;M.enabledFor("trace")&&M.debug(`${o.id} failed to complete: ${u instanceof Error?u.message:u}`)}}catch(o){if(o instanceof Error&&o.code==="ERR_INVALID_URL")return M.enabledFor("debug")&&M.debug(`failed to get request URI: ${o.message}`),i.statusCode=400,i.end(bn.default.STATUS_CODES[400]),Promise.resolve();throw o}}}function ri(r){return new Promise((e,t)=>{let n=r(s=>{s?t(s):e(n)})})}function Zo(r){if(r)return zn({memoryLimit:r.memory_limit,dumpLocation:r.dump_location,dumpPrefix:r.dump_prefix,reportInterval:r.report_interval,maxBackups:r.max_backups})}var ii=`${yn.default.name} - v${yn.default.version}`;async function ea(r){let e=r.storage,t=await Hs(r),n=Is(r),s=We.serverConfigurer.create();s.defaultCodecs.enableLoggingRequestDetails(!0);let i=new wr,o=new gr([i],[new yr],[new br(s.writers)]),a={handle:On(Xn(ii,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 on(r.resourcesConfig?.locations),async({response:c},d)=>{throw new Z(b.NOT_FOUND)})};return new nr(a).filter(new Bt(t)).codecConfigurer(s).exceptionHandler(new fr(s.readers,s.writers,new it)).storage(e)}var wn=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)=>ni.default.createServer({...m,...Fs(e,n)},y):(m,y)=>bn.default.createServer(m,y),i=Zo(r.memory),o={middleware:[],corsConfig:r.cors,cors:[],authConfig:r.auth,authorize:[],storage:new si.AsyncLocalStorage,sockets:new Map,resourcesConfig:r.resources},a=new ct({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 Dr(async y=>{y.socket({path:m,factory:Hn.bind(a),options:r.gateway})},r,o)}r.app&&await Dr(r.app,r,o);let c=Cn(r.port??0),d=m=>M.error(`socket error: ${m}`,m),u=await ea(o),h=await Qo(u,d),v=await new Promise((m,y)=>{let P=s({IncomingMessage:mt,ServerResponse:be,...r.http},h);P.on("error",C=>{if(C.code==="EADDRINUSE"){M.debug(`port ${C.port} already in use on address ${C.address}`);let{value:ae}=c.next();ae?(M.info(`retry starting server on port ${ae} and host ${t??"<unspecified>"}`),P.close(),P.listen(ae,t)):(M.warn(`all configured port(s) ${r.port} are in use. closing...`),P.close(),y(C))}else M.error(`server error: ${C.message}`,C),y(C)}),P.on("listening",async()=>{let C=P.address();for(let[ae,Sr]of o.sockets){let ot=`${e?"wss":"ws"}://${xn}:${C.port}${ae}`;await Ls(ae,Sr,ot,o.storage,d)}M.info(`http server listening on ${e?"https":"http"}://${ee(C)}`),m(P)}),P.on("upgrade",(C,ae,Sr)=>{try{h(C,Sr)}catch(ot){M.error(`upgrade error: ${ot}`,ot)}}).on("close",async()=>{M.info("http server closed.")});try{let{value:C}=c.next();P.listen(C,t)}catch(C){M.error("error starting web socket server",C),y(C instanceof Error?C:new Error(`listen failed: ${C}`))}}),l=new Array,p=async()=>{for(let[m,y]of o.sockets)try{y.close!==void 0&&await y.close()}catch(P){M.warn(`error closing route ${m}`,P)}},f=async()=>{await ri(m=>{v.closeAllConnections(),v.close(m)})};l.push(p),l.push(f),l.push(async()=>{i&&await jn(i)}),l.push(async()=>{await a.stop()});let w=new class{gateway=a;get address(){let m=v.address();return typeof m=="object"?m:null}async close(){let m=new Array;for(let y of l)try{await y()}catch(P){m.push(P),M.warn("error during server shutdown",P)}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 qs({options:r.management.server,info:async()=>({pid:process.pid,type:"gateway-server",...a.info()}),logger:M.child("management"),shutdown:r.management.commands?.shutdown.enabled?async()=>{M.enabledFor("info")&&M.info("stopping gateway-server..."),await w.close()}:void 0});l.push(async()=>{await ri(y=>{m.close(y)})})}return w};var ta=wn;0&&(module.exports={GatewayServer});
|
|
22
22
|
//# sourceMappingURL=index.cjs.map
|