@interopio/gateway-server 0.17.0 → 0.17.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 +4 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/changelog.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use strict";var ur=Object.create;var se=Object.defineProperty;var lr=Object.getOwnPropertyDescriptor;var hr=Object.getOwnPropertyNames;var pr=Object.getPrototypeOf,fr=Object.prototype.hasOwnProperty;var at=(t,e)=>{for(var r in e)se(t,r,{get:e[r],enumerable:!0})},ct=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of hr(e))!fr.call(t,o)&&o!==r&&se(t,o,{get:()=>e[o],enumerable:!(n=lr(e,o))||n.enumerable});return t};var Z=(t,e,r)=>(r=t!=null?ur(pr(t)):{},ct(e||!t||!t.__esModule?se(r,"default",{value:t,enumerable:!0}):r,t)),gr=t=>ct(se({},"__esModule",{value:!0}),t);var $n={};at($n,{GatewayServer:()=>st,default:()=>In});module.exports=gr($n);var st={};at(st,{Factory:()=>it});var sr=Z(require("node:http"),1),ar=Z(require("node:https"),1),Ne=require("node:fs"),cr=require("node:async_hooks"),dr=require("@interopio/gateway");var Fe=Z(require("@interopio/gateway/logging/core"),1);function b(t){return Fe.getLogger(`gateway.server.${t}`)}function dt(t,e){return e instanceof RegExp?e.toString():e}var ut=require("@interopio/gateway"),lt=require("node:async_hooks"),mr=ut.IOGateway.Encoding,M=b("ws"),yr=mr.json();function Sr(t){let e;if(t.authenticated&&(e=t.name,e===void 0&&t.principal!==void 0)){let r=t.principal;typeof r=="object"&&(e=r.name),e===void 0&&(r===void 0?e="":e=String(r))}return e}function wr(t,e,r){let n=`${r?.address}:${r?.port}`,o=r?.address??"<unknown>",s={key:n,host:o,codec:yr,onAuthenticate:async()=>{let i=await e();if(i?.authenticated)return{type:"success",user:Sr(i)};throw new Error(`no valid client authentication ${n}`)},onPing:()=>{t.ping(i=>{i?M.warn(`failed to ping ${n}`,i):M.info(`ping sent to ${n}`)})},onDisconnect:i=>{switch(i){case"inactive":{M.warn(`no heartbeat (ping) received from ${n}, closing socket`),t.close(4001,"ping expected");break}case"shutdown":{t.close(1001,"shutdown");break}}}};try{return this.client(i=>t.send(i),s)}catch(i){M.warn(`${n} failed to create client`,i)}}async function br(t){return M.info(`starting gateway on ${t.endpoint}`),await this.start(t),async({socket:e,handshake:r})=>{let{logPrefix:n,remoteAddress:o,principal:s}=r;M.info(`${n}connected on gw using ${o?.address}`);let i=wr.call(this,e,s,o);if(!i){M.error(`${n}gw client init failed`),e.terminate();return}e.on("error",c=>{M.error(`${n}websocket error: ${c}`,c)});let a=t.storage!==void 0?lt.AsyncLocalStorage.snapshot():void 0;e.on("message",(c,d)=>{Array.isArray(c)&&(c=Buffer.concat(c)),a!==void 0?a(()=>i.send(c)):i.send(c)}),e.on("close",c=>{M.info(`${n}disconnected from gw. code: ${c}`),i.close()})}}var ht=br;function pt(...t){if(!Array.isArray(t))throw new Error("middleware must be array!");let e=t.flat();for(let r of e)if(typeof r!="function")throw new Error("middleware must be compose of functions!");return async function(r,n){let o=async(s,i)=>{let a=s===e.length?n:e[s];if(a===void 0)return;let c=!1,d=!1,l=await a(i,async g=>{if(c)throw new Error("next() called multiple times");c=!0;try{return await o(s+1,g??i)}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 l};return o(0,r)}}var ue=require("tough-cookie");function vr(t,e){let r=t.get("x-forwarded-for");if(r===void 0){if(r=t.get("x-forwarded-host"),Array.isArray(r)&&(r=r[0]),r){let n=t.one("x-forwarded-port");n&&(r=`${r}:${n}`)}r??=t.one("host")}return Array.isArray(r)&&(r=r[0]),r?r.split(",",1)[0].trim():e}function xr(t,e){let r=t.get("x-forwarded-proto");return Array.isArray(r)&&(r=r[0]),r!==void 0?r.split(",",1)[0].trim():e}var ae=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},ce=class t extends ae{static logIdCounter=0;#e;get id(){return this.#e===void 0&&(this.#e=`${this.initId()}-${++t.logIdCounter}`),this.#e}initId(){return"request"}get cookies(){return Cr(this.headers)}parseHost(e){return vr(this.headers,e)}parseProtocol(e){return xr(this.headers,e)}},de=class extends ae{get cookies(){return Ar(this.headers)}setCookieValue(e){return new ue.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 Er(t){let e=[];{let r=0,n=0;for(let o=0;o<t.length;o++)switch(t.charCodeAt(o)){case 32:r===n&&(r=n=o+1);break;case 44:e.push(t.slice(r,n)),r=n=o+1;break;default:n=n+1;break}e.push(t.slice(r,n))}return e}function ft(t){typeof t=="string"&&(t=[t]),typeof t=="number"&&(t=[String(t)]);let e=[];if(t)for(let r of t)r&&e.push(...Er(r));return e}function Cr(t){return t.list("cookie").map(e=>e.split(";").map(r=>ue.Cookie.parse(r))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function Ar(t){return t.list("set-cookie").map(e=>{let r=ue.Cookie.parse(e);if(r){let n={name:r.key,value:r.value,maxAge:Number(r.maxAge??-1)};return r.httpOnly&&(n.httpOnly=!0),r.domain&&(n.domain=r.domain),r.path&&(n.path=r.path),r.secure&&(n.secure=!0),r.httpOnly&&(n.httpOnly=!0),r.sameSite&&(n.sameSite=r.sameSite),Object.freeze(n)}}).filter(e=>e!==void 0)}var ee=class{constructor(){}toList(e){let r=this.get(e);return ft(r)}},v=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let r=super.get(e.toLowerCase());return ft(r)}set(e,r){return typeof r=="number"&&(r=String(r)),typeof r=="string"&&(r=[r]),r?super.set(e.toLowerCase(),r):(super.delete(e.toLowerCase()),this)}add(e,r){let n=super.get(e.toLowerCase());return typeof r=="string"&&(r=[r]),n&&(r=n.concat(r)),this.set(e,r),this}};var Be=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},f=class t{static CONTINUE=new t(100,"Continue");static SWITCHING_PROTOCOLS=new t(101,"Switching Protocols");static OK=new t(200,"OK");static CREATED=new t(201,"Created");static ACCEPTED=new t(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new t(203,"Non-Authoritative Information");static NO_CONTENT=new t(204,"No Content");static RESET_CONTENT=new t(205,"Reset Content");static PARTIAL_CONTENT=new t(206,"Partial Content");static MULTI_STATUS=new t(207,"Multi-Status");static IM_USED=new t(226,"IM Used");static MULTIPLE_CHOICES=new t(300,"Multiple Choices");static MOVED_PERMANENTLY=new t(301,"Moved Permanently");static BAD_REQUEST=new t(400,"Bad Request");static UNAUTHORIZED=new t(401,"Unauthorized");static FORBIDDEN=new t(403,"Forbidden");static NOT_FOUND=new t(404,"Not Found");static METHOD_NOT_ALLOWED=new t(405,"Method Not Allowed");static NOT_ACCEPTABLE=new t(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new t(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new t(408,"Request Timeout");static CONFLICT=new t(409,"Conflict");static GONE=new t(410,"Gone");static LENGTH_REQUIRED=new t(411,"Length Required");static PRECONDITION_FAILED=new t(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new t(413,"Payload Too Large");static URI_TOO_LONG=new t(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new t(415,"Unsupported Media Type");static EXPECTATION_FAILED=new t(417,"Expectation Failed");static IM_A_TEAPOT=new t(418,"I'm a teapot");static TOO_EARLY=new t(425,"Too Early");static UPGRADE_REQUIRED=new t(426,"Upgrade Required");static PRECONDITION_REQUIRED=new t(428,"Precondition Required");static TOO_MANY_REQUESTS=new t(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new t(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new t(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new t(500,"Internal Server Error");static NOT_IMPLEMENTED=new t(501,"Not Implemented");static BAD_GATEWAY=new t(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new t(503,"Service Unavailable");static GATEWAY_TIMEOUT=new t(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new t(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new t(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new t(507,"Insufficient Storage");static LOOP_DETECTED=new t(508,"Loop Detected");static NOT_EXTENDED=new t(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new t(511,"Network Authentication Required");static#e=[];static{Object.keys(t).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let r=t[e];r instanceof t&&(Object.defineProperty(r,"name",{enumerable:!0,value:e,writable:!1}),t.#e.push(r))})}static resolve(e){for(let r of t.#e)if(r.value===e)return r}#r;#t;constructor(e,r){this.#r=e,this.#t=r}get value(){return this.#r}get phrase(){return this.#t}toString(){return`${this.#r} ${this.name}`}};function gt(t){if(typeof t=="number"){if(t<100||t>999)throw new Error(`status code ${t} should be in range 100-999`);let e=f.resolve(t);return e!==void 0?e:new Be(t)}return t}var Se=Z(require("node:http"),1),le=class extends Se.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},q=class extends Se.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},he=class extends ce{},pe=class extends de{#e=[];#r;#t="new";#o=[];setStatusCode(e){return this.#t==="committed"?!1:(this.#r=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:gt(e))}get statusCode(){return this.#r}addCookie(e){if(this.#t==="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.#o.push(e)}get commited(){let e=this.#t;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let r=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(r))).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 r=this.#t,n=Promise.resolve();if(r==="new")this.#t="committing",this.#o.length>0&&(n=this.#o.reduce((o,s)=>o.then(()=>s()),Promise.resolve()).catch(o=>{this.#t==="committing"&&(this.#t="commit-action-failed")}));else if(r==="commit-action-failed")this.#t="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#t="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},_=class extends he{#e;#r;#t;constructor(e){super(new De(e)),this.#t=e}getNativeRequest(){return this.#t}get upgrade(){return this.#t.upgrade}get http2(){return this.#t.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#t.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#t.method}get host(){let e;return this.#t.httpVersionMajor>=2&&(e=this.#t.headers[":authority"]),e??=this.#t.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#t.httpVersionMajor>2&&(e=this.#t.headers[":scheme"]),e??=this.#t.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#t.socket}get remoteAddress(){let e=this.#t.socket.remoteFamily,r=this.#t.socket.remoteAddress,n=this.#t.socket.remotePort;if(!(!e||!r||!n))return{family:e,address:r,port:n}}get cookies(){return this.#r??=super.cookies,this.#r}get body(){return Se.default.IncomingMessage.toWeb(this.#t)}async blob(){let e=[];if(this.body!==void 0)for await(let r of this.body)e.push(r);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let r=await(await this.blob()).text();return new URLSearchParams(r)}async json(){let e=await this.blob();if(e.size===0)return;let r=await e.text();return JSON.parse(r)}initId(){let e=this.#t.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#t.socket.remotePort}`}},De=class extends ee{#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 r=this.#e.headers[e];return Array.isArray(r)?r[0]:r}keys(){return Object.keys(this.#e.headers).values()}},Ue=class extends ee{#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 r=this.#e.getHeader(e);return Array.isArray(r)?r[0]:r}set(e,r){return this.#e.headersSent||(Array.isArray(r)?r=r.map(n=>typeof n=="number"?String(n):n):typeof r=="number"&&(r=String(r)),r?this.#e.setHeader(e,r):this.#e.removeHeader(e)),this}add(e,r){return this.#e.headersSent||this.#e.appendHeader(e,r),this}list(e){return super.toList(e)}},fe=class extends pe{#e;constructor(e){super(new Ue(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 r=await e;return await new Promise((n,o)=>{try{r===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof r=="string"?this.headers.set("content-length",Buffer.byteLength(r)):r instanceof Blob?this.headers.set("content-length",r.size):this.headers.set("content-length",r.byteLength)),this.#e.end(r,()=>{n(!0)}))}catch(s){o(s instanceof Error?s:new Error(`end failed: ${s}`))}})}}},ge=class t{#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 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 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`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof he)return e.getNativeRequest();if(e instanceof t)return t.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},z=class t{#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`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof pe)return e.getNativeResponse();if(e instanceof t)return t.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},me=class t{#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)}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${t.name} [delegate: ${this.delegate}]`}},ye=class{request;response;#e={};#r;#t="";constructor(e,r){this.#e[mt]=e.id,this.request=e,this.response=r}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes[e]}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(mt);return this.#r!==e&&(this.#r=e,this.#t=e!==void 0?`[${e}] `:""),this.#t}},mt="io.interop.gateway.server.log_id";var yt=require("node:os"),Hr=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function qe(t){if(t>65535)throw new Error(`bad port ${t}`);return t}function*St(t){if(typeof t=="string")for(let e of t.split(",")){let r=e.trim(),n=Hr.exec(r);if(n){let o=parseInt(n[1]),s=parseInt(n[4]??n[1]);for(let i=qe(o);i<qe(s)+1;i++)yield i}else throw new Error(`'${e}' is not a valid port or range.`)}else yield qe(t)}var wt=(()=>{function t(r){return r.length>0?r[0]:void 0}let e=Object.values((0,yt.networkInterfaces)()).flatMap(r=>(r??[]).filter(n=>n.family==="IPv4")).reduce((r,n)=>(r[n.internal?"internal":"external"].push(n),r),{internal:[],external:[]});return(t(e.internal)??t(e.external))?.address})();var we=require("node:v8"),W=require("node:fs/promises"),y=b("monitoring"),Pr={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function Rr(){return(0,we.getHeapStatistics)()}async function bt(t){let e=t.dumpPrefix??"Heap",r=`${t.dumpLocation}/${e}.heapsnapshot`;y.enabledFor("debug")&&y.debug(`starting heap dump in ${r}`),await _e(t.dumpLocation).catch(async o=>{y.enabledFor("debug")&&y.debug(`dump location ${t.dumpLocation} does not exists. Will try to create it`);try{await(0,W.mkdir)(t.dumpLocation,{recursive:!0}),y.info(`dump location dir ${t.dumpLocation} successfully created`)}catch{y.error(`failed to create dump location ${t.dumpLocation}`)}});let n=(0,we.writeHeapSnapshot)(r);y.info("heap dumped");try{y.debug("rolling snapshot backups");let o=`${t.dumpLocation}/${e}.${t.maxBackups}.heapsnapshot`;await _e(o).then(async()=>{y.enabledFor("debug")&&y.debug(`deleting ${o}`);try{await(0,W.unlink)(o)}catch(i){y.warn(`failed to delete ${o}`,i)}}).catch(()=>{});for(let i=t.maxBackups-1;i>0;i--){let a=`${t.dumpLocation}/${e}.${i}.heapsnapshot`,c=`${t.dumpLocation}/${e}.${i+1}.heapsnapshot`;await _e(a).then(async()=>{try{await(0,W.rename)(a,c)}catch(d){y.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let s=`${t.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,W.rename)(n,s)}catch(i){y.warn(`failed to rename ${n} to ${s}`,i)}y.debug("snapshots rolled")}catch(o){throw y.error("error rolling backups",o),o}}async function _e(t){y.enabledFor("trace")&&y.debug(`checking file ${t}`),await(0,W.access)(t)}async function Tr(t,e,r){y.enabledFor("debug")&&y.debug(`processing heap stats ${JSON.stringify(t)}`);let n=Math.min(r.memoryLimit,.95*t.heap_size_limit),o=t.used_heap_size;y.info(`heap stats ${JSON.stringify(t)}`),o>=n?(y.warn(`used heap ${o} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await bt(r)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function vt(t){let e={...Pr,...t},r=!1,n={memoryLimitExceeded:!1},o=async()=>{let a=Rr();await Tr(a,n,e)},s=setInterval(o,e.reportInterval);return{...e,channel:async a=>{if(!r)switch(a??="run",a){case"run":{await o();break}case"dump":{await bt(e);break}case"stop":{r=!0,clearInterval(s),y.info("exit memory diagnostic");break}}return r}}}async function kr({channel:t},e){await t(e)||y.warn(`cannot execute command "${e}" already closed`)}async function xt(t){return await kr(t,"stop")}var ze=Z(require("@interopio/gateway-server/package.json"),1),Mr=t=>(t??=`${ze.default.name} - v${ze.default.version}`,async({response:e},r)=>{t!==!1&&!e.headers.has("server")&&e.headers.set("Server",t),await r()}),Et=t=>Mr(t);var te=require("@interopio/gateway");var Ge=b("gateway.ws.client-verify");function Wr(t){switch(t.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Lr(t,e){let r=t.block??t.blacklist,n=t.allow??t.whitelist;if(r.length>0&&te.IOGateway.Filtering.valuesMatch(r,e))return Ge.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&te.IOGateway.Filtering.valuesMatch(n,e))return Ge.enabledFor("debug")&&Ge.debug(`origin ${e} matches allow filter`),!0}function Ir(t){switch(t.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Ct(t,e){if(!e)return!0;if(t){let r=Lr(e,t);return r||Ir(e)}else return Wr(e)}function At(t){if(t){let e=(t.block??t.blacklist??[]).map(te.IOGateway.Filtering.regexify),r=(t.allow??t.whitelist??[]).map(te.IOGateway.Filtering.regexify);return{non_matched:t.non_matched??"allow",missing:t.missing??"allow",allow:r,block:e}}}var Ht=t=>async e=>{for(let r of t)if((await r(e)).match)return A();return E},G=t=>{let e=async r=>{for(let n of t)if(!(await n(r)).match)return E;return A()};return e.toString=()=>`and(${t.map(r=>r.toString()).join(", ")})`,e},Pt=t=>async e=>(await t(e)).match?E:A(),re=async t=>A();re.toString=()=>"any-exchange";var Rt=Object.freeze({}),E=Object.freeze({match:!1,variables:Rt}),A=(t=Rt)=>({match:!0,variables:t}),H=(t,e)=>{let r=e?.method,n=async o=>{let s=o.request,i=s.path;if(r!==void 0&&s.method!==r)return E;if(typeof t=="string")return i===t?A():E;{let a=t.exec(i);return a===null?E:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${t.toString()}, method=${r??"<any>"})`,n},je=t=>{let e=r=>{if(t.ignoredMediaTypes!==void 0){for(let n of t.ignoredMediaTypes)if(r===n||n==="*/*")return!0}return!1};return async r=>{let n=r.request,o;try{o=n.headers.list("accept")}catch{return E}for(let s of o)if(!e(s)){for(let i of t.mediaTypes)if(s.startsWith(i))return A()}return E}},D=async({request:t})=>t.upgrade&&t.headers.one("upgrade")?.toLowerCase()==="websocket"?A():E;D.toString=()=>"websocket upgrade";var Ve=require("@interopio/gateway");async function Je(t,e,r){let n=(s,i)=>{if(i?.cors){let a=i.cors===!0?{allowOrigins:i.origins?.allow?.map(Ve.IOGateway.Filtering.regexify),allowMethods:s.method===void 0?["*"]:[s.method],allowCredentials:i.authorize?.access!=="permitted"?!0:void 0}:i.cors,c=s.path;r.cors.push([c,a])}},o=new class{handle(...s){s.forEach(({request:i,options:a,handler:c})=>{let d=H(Ve.IOGateway.Filtering.regexify(i.path),{method:i.method});a?.authorize&&r.authorize.push([d,a.authorize]),n(i,a);let u=async(l,g)=>{let{match:p,variables:h}=await d(l);p?await c(l,h):await g()};r.middleware.push(u)})}socket(...s){for(let{path:i,factory:a,options:c}of s){let d=i??"/";r.sockets.set(d,{default:i===void 0,ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:At(c?.origins)})}}};await t(o,e)}var xe=require("@interopio/gateway");function Nr(t){let e=t.headers.one("origin");if(e===void 0)return!0;let r=t.URL,n=r.protocol,o=r.host,s=URL.parse(e),i=s?.host,a=s?.protocol;return n===a&&o===i}function Fr(t){return t.headers.has("origin")&&!Nr(t)}function kt(t){return t.method==="OPTIONS"&&t.headers.has("origin")&&t.headers.has("access-control-request-method")}var Tt=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],Br=(t,e)=>{let{request:r,response:n}=t,o=n.headers;if(!o.has("Vary"))o.set("Vary",Tt.join(", "));else{let i=o.list("Vary");for(let a of Tt)i.find(c=>c===a)||i.push(a);o.set("Vary",i.join(", "))}try{if(!Fr(r))return!0}catch{return P.enabledFor("debug")&&P.debug("reject: origin is malformed"),ne(n),!1}if(o.has("access-control-allow-origin"))return P.enabledFor("trace")&&P.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let s=kt(r);return e?Ur(t,e,s):s?(ne(n),!1):!0},ve=["*"],Qe=["GET","HEAD","POST"],Ot={allowOrigins:ve,allowMethods:Qe,allowHeaders:ve,maxAge:1800};function Ee(t){if(t){let e=t.allowHeaders;e&&e!==S&&(t={...t,allowHeaders:e.map(n=>n.toLowerCase())});let r=t.allowOrigins;return r&&(r==="*"?(Wt(t),Lt(t)):t={...t,allowOrigins:r.map(n=>typeof n=="string"&&n!==S&&(n=xe.IOGateway.Filtering.regexify(n),typeof n=="string")?It(n).toLowerCase():n)}),t}}function be(t,e){if(e===void 0)return t!==void 0?t===S?[S]:t:[];if(t===void 0)return e===S?[S]:e;if(t==ve||t===Qe)return e===S?[S]:e;if(e==ve||e===Qe)return t===S?[S]:t;if(t===S||t.includes(S)||e===S||e.includes(S))return[S];let r=new Set;return t.forEach(n=>r.add(n)),e.forEach(n=>r.add(n)),Array.from(r)}var oe=(t,e)=>e===void 0?t:{allowOrigins:be(t.allowOrigins,e?.allowOrigins),allowMethods:be(t.allowMethods,e?.allowMethods),allowHeaders:be(t.allowHeaders,e?.allowHeaders),exposeHeaders:be(t.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??t.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??t.allowPrivateNetwork,maxAge:e?.maxAge??t.maxAge},Dr=t=>{let e=t.corsConfigSource,r=t.corsProcessor??Br;return async(n,o)=>{let s=await e(n);!r(n,s)||kt(n.request)||await o()}},Mt=Dr,P=b("cors");function ne(t){t.setStatusCode(f.FORBIDDEN)}function Ur(t,e,r){let{request:n,response:o}=t,s=o.headers,i=n.headers.one("origin"),a=_r(e,i);if(a===void 0)return P.enabledFor("debug")&&P.debug(`reject: '${i}' origin is not allowed`),ne(o),!1;let c=jr(n,r),d=zr(e,c);if(d===void 0)return P.enabledFor("debug")&&P.debug(`reject: HTTP '${c}' is not allowed`),ne(o),!1;let u=Vr(n,r),l=Gr(e,u);if(r&&l===void 0)return P.enabledFor("debug")&&P.debug(`reject: headers '${u}' are not allowed`),ne(o),!1;s.set("Access-Control-Allow-Origin",a),r&&s.set("Access-Control-Allow-Methods",d.join(",")),r&&l!==void 0&&l.length>0&&s.set("Access-Control-Allow-Headers",l.join(", "));let g=e.exposeHeaders;return g&&g.length>0&&s.set("Access-Control-Expose-Headers",g.join(", ")),e.allowCredentials&&s.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&s.set("Access-Control-Allow-Private-Network","true"),r&&e.maxAge!==void 0&&s.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var S="*",qr=["GET","HEAD"];function Wt(t){if(t.allowCredentials===!0&&t.allowOrigins===S)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function Lt(t){if(t.allowPrivateNetwork===!0&&t.allowOrigins===S)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function _r(t,e){if(e){let r=t.allowOrigins;if(r){if(r===S)return Wt(t),Lt(t),S;let n=It(e.toLowerCase());for(let o of r)if(o===S||xe.IOGateway.Filtering.valueMatches(o,n))return e}}}function zr(t,e){if(e){let r=t.allowMethods??qr;if(r===S)return[e];if(xe.IOGateway.Filtering.valuesMatch(r,e))return r}}function Gr(t,e){if(e===void 0)return;if(e.length==0)return[];let r=t.allowHeaders;if(r===void 0)return;let n=r===S||r.includes(S),o=[];for(let s of e){let i=s?.trim();if(i){if(n)o.push(i);else for(let a of r)if(i.toLowerCase()===a){o.push(i);break}}}if(o.length>0)return o}function It(t){return t.endsWith("/")?t.slice(0,-1):t}function jr(t,e){return e?t.headers.one("access-control-request-method"):t.method}function Vr(t,e){let r=t.headers;return e?r.list("access-control-request-headers"):Array.from(r.keys())}var $t=t=>async e=>{for(let[r,n]of t.mappings)if((await r(e)).match)return P.debug(`resolved cors config on '${e.request.path}' using ${r}: ${JSON.stringify(n)}`),n};var Nt=require("@interopio/gateway");function Ft(t){let{sockets:e,cors:r}=t,n=t.corsConfig===!1?void 0:oe(Ot,t.corsConfig),o=[];for(let[i,a]of e){let c=n;for(let[u,l]of r)Nt.IOGateway.Filtering.valueMatches(u,i)&&(l===void 0?c=void 0:c=c===void 0?l:oe(c,l));let d=t.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:oe(c,d),o.push([G([D,H(i)]),Ee(c)])}let s=[];for(let[i,a]of r){let[,c]=s.find(([u])=>String(u)===String(i))??[i,n];c=c===void 0?a:oe(c,a);let d=!1;for(let u of s)if(String(u[0])===String(i)){u[1]=c,d=!0;break}d||s.push([i,c])}for(let[i,a]of s)o.push([H(i),Ee(a)]);return o.push([H(/\/api\/.*/),Ee(n)]),$t({mappings:o})}function Bt(t){return t!==void 0&&typeof t.type=="string"&&typeof t.authenticated=="boolean"}var C=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}},Ce=class extends C{},Ae=class extends C{};var U=class extends Error{},L=class{constructor(e){this.granted=e}granted},N=class{#e;constructor(e){this.#e=e}async verify(e,r){if(!(await this.#e(e,r))?.granted)throw new U("Access denied")}async authorize(e,r){return await this.#e(e,r)}},j=class extends C{};var R=t=>async e=>{let r=!0,{response:n}=e;for(let o of t.keys())n.headers.has(o)&&(r=!1);if(r)for(let[o,s]of t)n.headers.set(o,s)},Jr=()=>R(new v().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Qr=()=>R(new v().add("x-content-type-options","nosniff")),Yr=(t,e,r)=>{let n=`max-age=${t}`;e&&(n+=" ; includeSubDomains"),r&&(n+=" ; preload");let o=R(new v().add("strict-transport-security",n)),s=i=>i.request.URL.protocol==="https:";return async i=>{s(i)&&await o(i)}},Kr=t=>R(new v().add("x-frame-options",t)),Xr=t=>R(new v().add("x-xss-protection",t)),Zr=t=>{let e=t===void 0?void 0:R(new v().add("permissions-policy",t));return async r=>{e!==void 0&&await e(r)}},en=(t,e)=>{let r=e?"content-security-policy-report-only":"content-security-policy",n=t===void 0?void 0:R(new v().add(r,t));return async o=>{n!==void 0&&await n(o)}},tn=(t="no-referrer")=>R(new v().add("referer-policy",t)),rn=t=>{let e=t===void 0?void 0:R(new v().add("cross-origin-opener-policy",t));return async r=>{e!==void 0&&await e(r)}},nn=t=>{let e=t===void 0?void 0:R(new v().add("cross-origin-embedder-policy",t));return async r=>{e!==void 0&&await e(r)}},on=t=>{let e=t===void 0?void 0:R(new v().add("cross-origin-resource-policy",t));return async r=>{e!==void 0&&await e(r)}},sn=(...t)=>async e=>{for(let r of t)await r(e)};function Ye(t){let e=[];t?.cache?.disabled||e.push(Jr()),t?.contentType?.disabled||e.push(Qr()),t?.hsts?.disabled||e.push(Yr(t?.hsts?.maxAge??365*24*60*60,t?.hsts?.includeSubDomains??!0,t?.hsts?.preload??!1)),t?.frameOptions?.disabled||e.push(Kr(t?.frameOptions?.mode??"DENY")),t?.xss?.disabled||e.push(Xr(t?.xss?.headerValue??"0")),t?.permissionsPolicy?.disabled||e.push(Zr(t?.permissionsPolicy?.policyDirectives)),t?.contentSecurityPolicy?.disabled||e.push(en(t?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",t?.contentSecurityPolicy?.reportOnly)),t?.refererPolicy?.disabled||e.push(tn(t?.refererPolicy?.policy??"no-referrer")),t?.crossOriginOpenerPolicy?.disabled||e.push(rn(t?.crossOriginOpenerPolicy?.policy)),t?.crossOriginEmbedderPolicy?.disabled||e.push(nn(t?.crossOriginEmbedderPolicy?.policy)),t?.crossOriginResourcePolicy?.disabled||e.push(on(t?.crossOriginResourcePolicy?.policy)),t?.writers&&e.push(...t.writers);let r=sn(...e);return async(n,o)=>{await r(n),await o()}}var V=t=>{let e=t.entryPoint,r=t?.rethrowAuthenticationServiceError??!0;return async({exchange:n},o)=>{if(!r||!(o instanceof j))return e(n,o);throw o}};var an="Realm",cn=t=>`Basic realm="${t}"`,J=t=>{let e=cn(t?.realm??an);return async(r,n)=>{let{response:o}=r;o.setStatusCode(f.UNAUTHORIZED),o.headers.set("WWW-Authenticate",e)}};var Dt="Basic ",He=t=>async e=>{let{request:r}=e,n=r.headers.one("authorization");if(!n||!/basic/i.test(n.substring(0)))return;let o=n.length<=Dt.length?"":n.substring(Dt.length),i=Buffer.from(o,"base64").toString(t?.credentialsEncoding??"utf-8").split(":",2);if(i.length===2)return{type:"UsernamePassword",authenticated:!1,principal:i[0],credentials:i[1]}};var Ut=require("node:async_hooks"),F=class t{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(r=new Ut.AsyncLocalStorage)=>(r.getStore().securityContext=e,r)}static withAuthentication(e){return t.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(t.hasSecurityContext(e))return t.getSecurityContext(e)}};async function dn(t,e,r,n,o,s){let a=await(await n(t))?.(r);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await un(a,{exchange:t,next:e},o,s)}catch(c){throw c instanceof C,c}}async function un(t,e,r,n){F.withAuthentication(t)(n),await r(e,t)}function Q(t){let e={matcher:re,successHandler:async({next:n})=>{await n()},converter:He({}),failureHandler:V({entryPoint:J({})}),...t},r=e.managerResolver;if(r===void 0&&e.manager!==void 0){let n=e.manager;r=async o=>n}if(r===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return async(n,o)=>{let i=(await e.matcher(n)).match?await e.converter(n):void 0;if(i===void 0){await o();return}try{await dn(n,o,i,r,e.successHandler,e.storage)}catch(a){if(a instanceof C){await e.failureHandler({exchange:n,next:o},a);return}throw a}}}var qt=t=>async(e,r)=>{e.response.setStatusCode(t.httpStatus)};var Y=b("auth.entry-point"),Pe=t=>{let e=t.defaultEntryPoint??(async({response:r},n)=>{r.setStatusCode(f.UNAUTHORIZED),await r.end()});return async(r,n)=>{for(let[o,s]of t.entryPoints)if(Y.enabledFor("debug")&&Y.debug(`trying to match using: ${o}`),(await o(r)).match)return Y.enabledFor("debug")&&Y.debug(`match found. using default entry point ${s}`),s(r,n);return Y.enabledFor("debug")&&Y.debug(`no match found. using default entry point ${e}`),e(r,n)}};var _t=t=>async({exchange:e,next:r},n)=>{for(let o of t)await o({exchange:e,next:r},n)};function Ke(t){let e=async g=>g.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?A():E,r=Pe({entryPoints:[[e,qt({httpStatus:f.UNAUTHORIZED})]],defaultEntryPoint:J({})}),n=t.entryPoint??r,o=t.manager,s=je({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),i=Pt(je({mediaTypes:["text/html"]})),a=G([i,s]),c=Ht([e,a]);t.defaultEntryPoints.push([c,n]);let d=t.failureHandler??V({entryPoint:n}),u=_t(t.successHandlers??t.defaultSuccessHandlers),l=He({});return Q({storage:t.storage,manager:o,failureHandler:d,successHandler:u,converter:l})}var zt={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},Gt="https://tools.ietf.org/html/rfc6750#section-3.1";function Re(t){return{errorCode:zt.invalid_token,httpStatus:f.UNAUTHORIZED,description:t,uri:Gt}}function Xe(t){return{errorCode:zt.invalid_request,httpStatus:f.BAD_REQUEST,description:t,uri:Gt}}var ln="access_token",hn=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,k=class extends C{error;constructor(e,r,n){super(r??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},jt=t=>t.type==="BearerToken",pn=t=>async e=>{let{request:r}=e;return Promise.all([gn(r.headers,t?.headerName).then(n=>n!==void 0?[n]:void 0),mn(r,t?.uriQueryParameter),yn(e,t?.formEncodedBodyParameter)]).then(n=>n.filter(o=>o!==void 0).flat(1)).then(fn).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function fn(t){if(t.length===0)return;if(t.length>1){let r=Xe("Found multiple access tokens in the request");throw new k(r)}let e=t[0];if(!e||e.length===0){let r=Xe("The requested access token parameter is an empty string");throw new k(r)}return e}async function gn(t,e="authorization"){let r=t.one(e);if(!r||!/bearer/i.test(r.substring(0)))return;let n=hn.exec(r);if(n===null){let o=Re("Bearer token is malformed");throw new k(o)}return n.groups?.token}async function Vt(t){let e=t.getAll(ln);if(e.length!==0)return e}async function mn(t,e=!1){if(!(!e||t.method!=="GET"))return Vt(t.URL.searchParams)}async function yn(t,e=!1){let{request:r}=t;if(!e||r.headers.one("content-type")!=="application/x-www-form-urlencoded"||r.method!=="POST")return;let n=await t.request.formData();if(n)return Vt(n)}var Te=pn;function Sn(t){let e="Bearer";if(t.size!==0){e+=" ";let r=0;for(let[n,o]of t)e+=`${n}="${o}"`,r!==t.size-1&&(e+=", "),r++}return e}var Jt=t=>t.httpStatus!==void 0;function wn(t){if(t instanceof k){let{error:e}=t;if(Jt(e))return e.httpStatus}return f.UNAUTHORIZED}function bn(t,e){let r=new Map;if(e&&r.set("realm",e),t instanceof k){let{error:n}=t;r.set("error",n.errorCode),n.description&&r.set("error_description",n.description),n.uri&&r.set("error_uri",n.uri),Jt(n)&&n.scope&&r.set("scope",n.scope)}return r}var vn=t=>async(e,r)=>{let n=wn(r),o=bn(r,t?.realmName),s=Sn(o),{response:i}=e;i.headers.set("WWW-Authenticate",s),i.setStatusCode(n),await i.end()},ke=vn;var xn=t=>{let e=t?.principalClaimName??"sub";return r=>({type:"JwtToken",authenticated:!0,name:r.getClaimAsString(e)})},En=t=>async e=>t(e),K=class extends Error{},ie=class extends K{};function Cn(t){if(t instanceof ie)return new k(Re(t.message),t.message,{cause:t});throw new j(t.message,{cause:t})}function Ze(t){let e=t.decoder,r=t.authConverter??En(xn({}));return async n=>{if(jt(n)){let o=n.token;try{let s=await e(o);return await r(s)}catch(s){throw s instanceof K?Cn(s):s}}}}function et(t){let e=t.entryPoint??ke({}),r=t?.converter??Te({}),n=t.failureHandler??V({entryPoint:e});if(t.managerResolver!==void 0)return Q({storage:t.storage,converter:r,failureHandler:n,managerResolver:t.managerResolver});if(t.jwt!==void 0){let o=t.jwt.manager??Ze(t.jwt);return Q({storage:t.storage,converter:r,failureHandler:n,managerResolver:async s=>o})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}var Me=require("@interopio/gateway/jose/jwt");async function Qt(t,e,r){let n=new Ce("Full authentication is required to access this resource."),o=new C("Access Denied",{cause:n});e&&(o.authentication=e),await r(t,o)}function An(t){return async(e,r)=>{e.response.setStatusCode(t),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 Yt=t=>{let e=An(f.FORBIDDEN),r=t.authenticationEntryPoint??J();return async(n,o)=>{try{await o()}catch(s){if(s instanceof U){let i=await n.principal();Bt(i)?(i.authenticated||await e(n,s),await Qt(n,i,r)):await Qt(n,void 0,r);return}throw s}}};var Hn=b("security.auth");function tt(t){let e=async(r,n)=>{let o;for(let[s,i]of t.mappings)if((await s(n))?.match){Hn.debug(`checking authorization on '${n.request.path}' using [${s}, ${i}]`);let a=await i.authorize(r,{exchange:n});if(a!==void 0){o=a;break}}return o??=new L(!1),o};return new N(e)}var Oe=b("security.auth");function rt(t){let{manager:e,storage:r}=t;return async(n,o)=>{let s=F.getContext(r).then(i=>i?.authentication);try{await e.verify(s,n),Oe.enabledFor("debug")&&Oe.debug("authorization successful")}catch(i){throw i instanceof U&&Oe.enabledFor("debug")&&Oe.debug(`authorization failed: ${i.message}`),i}await o()}}var nt=class extends me{#e;constructor(e,r){super(e),this.#e=r}async principal(){return(await this.#e())?.authentication}},Kt=t=>{let e=t.storage;return async(r,n)=>{await n(new nt(r,async()=>await F.getContext(e)))}};var I={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},$=Symbol.for("filterOrder"),Xt=(t,e)=>{let r=[];class n{#e;#r=[];manager;get authenticationEntryPoint(){return this.#e!==void 0||this.#r.length===0?this.#e:this.#r.length===1?this.#r[0][1]:Pe({entryPoints:this.#r,defaultEntryPoint:this.#r[this.#r.length-1][1]})}build(){if(t.headers!==void 0&&t.headers.disabled!==!0){let a=Ye(t.headers);a[$]=I.http_headers,r.push(a)}if(t.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let a=Mt({corsConfigSource:e.corsConfigSource});a[$]=I.cors,r.push(a)}if(t.basic!==void 0&&t.basic?.disabled!==!0){let a=t.basic.user?.name.toLowerCase(),c=t.basic.user?.password??"",d=t.basic.user?.authorities??[],u=async p=>{let h=p.principal,w=p.credentials;if(h.toLowerCase()!==a||w!==c)throw new Ae("Invalid username or password");return{type:"UsernamePassword",authenticated:!0,principal:h,credentials:w,authorities:[...d]}},l=[async({exchange:p,next:h},w)=>h()],g=Ke({storage:e.storage,manager:u,defaultEntryPoints:this.#r,defaultSuccessHandlers:l});g[$]=I.http_basic,r.push(g)}if(t.jwt!==void 0&&t.jwt.disabled!==!0){let a=(0,Me.jwtVerifier)({issuerBaseUri:t.jwt.issuerUri,issuer:t.jwt.issuer,audience:t.jwt.audience}),c=async p=>{try{let{payload:h}=await a(p);return{subject:h.sub,getClaimAsString(w){return h[w]}}}catch(h){throw h instanceof Me.JwtVerifyError?new ie(h.message,{cause:h}):new K("error occurred while attempting to decoding jwt",{cause:h})}},d=Te({uriQueryParameter:!0}),u=async p=>{try{return await d(p)===void 0?E:A()}catch{return E}},l=ke({});this.#r.push([u,l]);let g=et({storage:e.storage,entryPoint:l,converter:d,jwt:{decoder:c}});g[$]=I.authentication,r.push(g)}let i=Kt({storage:e.storage});if(r.push(i),i[$]=I.security_context_server_web_exchange,t.authorize!==void 0){let a=Yt({authenticationEntryPoint:this.authenticationEntryPoint});a[$]=I.error_translation,r.push(a);let d=(l=>{let g=[],p=!1;for(let[h,w]of l??[]){let m;if(h==="any-exchange")p=!0,m=re;else{if(p)throw new Error("Cannot register other matchers after 'any-exchange' matcher");m=h}let x;if(w.access==="permitted")x=new N(async()=>new L(!0)),x.toString=()=>"AuthorizationManager[permitted]";else if(w.access==="denied")x=new N(async()=>new L(!1)),x.toString=()=>"AuthorizationManager[denied]";else if(w.access==="authenticated")x=new N(async X=>{let B=await X;return B!==void 0?new L(B.authenticated):new L(!1)}),x.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(w)}`);g.push([m,x])}return tt({mappings:g})})(t.authorize),u=rt({manager:d,storage:e.storage});u[$]=I.authorization,r.push(u)}r.sort((a,c)=>{let d=a[$]??I.last,u=c[$]??I.last;return d-u})}}return new n().build(),r};function Pn(t){let e=[],r={access:t.authConfig?.type!=="none"?"authenticated":"permitted"};for(let[n,o]of t.sockets){let s=o.authorize??r,i=H(n,{method:"GET"});i=G([D,i]),e.push([i,s])}return e.push([H("/",{method:"GET"}),{access:"permitted"}]),e.push([H("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([H("/health",{method:"GET"}),{access:"permitted"}]),t.authorize.length>0&&e.push(...t.authorize),e.push(["any-exchange",r]),{authorize:e,cors:{disabled:t.corsConfig===!1},basic:{disabled:t.authConfig?.type!=="basic",...t.authConfig?.basic},jwt:{disabled:t.authConfig?.type!=="oauth2",...t.authConfig?.oauth2?.jwt}}}async function Zt(t){let e=Ft(t),r=Pn(t),{storage:n}=t;return Xt(r,{storage:n,corsConfigSource:e})}var er=require("node:async_hooks");var We=class extends z{},ot=class{#e;#r=!1;#t;#o;constructor(e,r){this.#e=e,this.#t=r}createExchange(e,r){return new ye(e,r)}set storage(e){this.#o=e}set enableLoggingRequestDetails(e){this.#r=e}formatHeaders(e){let r="{";for(let n of e.keys())if(this.#r){let o=e.get(n);r+=`"${n}": "${o}", `}else{r+="masked, ";break}return r.endsWith(", ")&&(r=r.slice(0,-2)),r+="}",r}formatRequest(e){let r=e.URL.search;return`HTTP ${e.method} "${e.path}${r}`}logRequest(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${r?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${r?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,r){let{request:n,response:o,logPrefix:s}=e;if(o.setStatusCode(f.INTERNAL_SERVER_ERROR)){this.#e.error(`${s}500 Server Error for ${this.formatRequest(n)}`,r);return}throw this.#e.error(`${s}Error [${r.message} for ${this.formatRequest(n)}, but already ended (${o.statusCode})`,r),r}async web(e){return await this.#t(e)}async http(e,r){let n=this.createExchange(e,r),o=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(s=>{this.handleUnresolvedError(n,s)}).then(async()=>{await n.response.end()}));await new Promise((s,i)=>{this.#o!==void 0?this.#o.run({exchange:n},()=>{o().then(()=>s()).catch(a=>i(a))}):o().then(()=>s()).catch(a=>i(a))})}},Le=class{#e;#r=new er.AsyncLocalStorage;#t;storage(e){return this.#r=e,this}httpHandlerDecorator(e){if(this.#t===void 0)this.#t=e;else{let r=this.#t;this.#t=n=>(n=r(n),e(n))}return this}constructor(e){this.#e=e}build(){let e=b("http"),r=new ot(e,this.#e);this.#r!==void 0&&(r.storage=this.#r),r.enableLoggingRequestDetails=!1;let n=async(o,s)=>r.http(o,s);return this.#t?this.#t(n):n}};var or=require("ws");function tr(t,e){let r=t?.exchange,n=r?.request??new _(t),o=r?.principal,s=o?o.bind(r):async function(){},i=n.URL,a=new v;for(let g of n.headers.keys())a.set(g,n.headers.list(g));let c=n.cookies,d=r?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:i,headers:a,cookies:c,principal:s,protocol:e,remoteAddress:u,logPrefix:d}}function rr(t){return[async(r,n)=>{let s=r.request.path??"/",i=t.sockets,a=i.get(s)??Array.from(i.values()).find(c=>{if(s==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=r,u=await D(r);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(r);return}else throw new Error(`No upgrade strategy defined for route on ${s}`);else{if(a.default){await n();return}d.setStatusCode(f.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let l=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(l)}}else await n()}]}var nr=require("ws"),Ie=class extends nr.WebSocket{constructor(e,r,n){super(null,void 0,n)}connected},$e=class t{static#e=Buffer.alloc(0);static#r=[0,Buffer.alloc(8)];#t;#o;#i;#s=!1;#n;constructor(e,r,n){this.#n=e,this.#o=typeof n=="number"?n:n?.interval,this.#t=typeof n=="number"||n?.data==="timestamp"?()=>t.#d(Date.now()):()=>t.#e,this.#o&&(this.#i=setInterval(()=>{let[o,s]=r();for(let i of s)this.#a(i,o)||this.#c(i,o)},this.#o))}#a(e,r){return e.connected===!1?(this.#n.enabledFor("debug")&&this.#n.debug(`terminating unresponsive ws client on [${r}]`),e.terminate(),!1):!0}#c(e,r){e.connected=!1;let n=this.#t();this.#n.enabledFor("trace")&&this.#n.trace(`pinging ws client on [${r}]`),e.ping(n,this.#s,o=>{o&&this.#n.enabledFor("warn")&&this.#n.warn(`failed to ping ws client on [${r}]`,o)})}static#d(e=Date.now()){if(e-t.#r[0]>0){let r=Buffer.allocUnsafe(8);r.writeBigInt64BE(BigInt(e),0),t.#r=[e,r]}return t.#r[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#i)}handlePing(e,r,n){r.connected=!0,r.pong(n,!1,o=>{o&&this.#n.enabledFor("warn")&&this.#n.warn(`${e.logPrefix}failed to pong ws client [${e.remoteAddress?.address}:${e.remoteAddress?.port}]`,o)})}handlePong(e,r,n){if(r.connected=!0,this.#n.enabledFor("warn")){let o=t.#u(n);if(o>0){let s=Date.now()-o;this.#n.enabledFor("debug")&&this.#n.debug(`${e.logPrefix}ws client [${e.remoteAddress?.address}:${e.remoteAddress?.port}] ping-pong latency: ${s}ms`),this.#o&&s>this.#o/2&&this.#n.enabledFor("warn")&&this.#n.warn(`${e.logPrefix}ws client [${e.remoteAddress?.address}:${e.remoteAddress?.port}] high ping-pong latency: ${s}ms`)}}}};var T=b("ws");function Rn(t,e,r,n){return o=>{let{logPrefix:s,request:i}=o,a=ge.getNativeRequest(i);a.exchange=o;let{socket:c,upgradeHead:d}=a,u=i.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&r.clients?.size>=e.maxConnections){T.warn(`${s}dropping ws connection request on ${u}${t}. max connections exceeded.`),c.destroy();return}let l=i.headers.one("origin");if(!Ct(l,e.originFilters)){T.enabledFor("info")&&T.info(`${s}dropping ws connection request on ${u}${t}. origin ${l??"<missing>"}`),c.destroy();return}T.enabledFor("debug")&&T.debug(`${s}accepted new ws connection request on ${u}${t}`),r.handleUpgrade(a,c,d,(g,p)=>{r.emit("connection",g,p)})}}function Tn(t,e){let r=new Set;t.forEach((o,s)=>{if(s===0&&o.startsWith("HTTP/1.1 101 ")){e.setStatusCode(f.SWITCHING_PROTOCOLS);return}let[i,a]=o.split(": ");e.headers.has(i)?t[s]=`${i}: ${e.headers.one(i)}`:e.headers.set(i,a),r.add(i.toLowerCase())});let n=z.getNativeResponse(e);for(let o of n.getRawHeaderNames()){let s=o.toLowerCase();if(!r.has(s)){let i=e.headers.get(s);i!==void 0&&t.push(`${o}: ${i}`)}}n.markHeadersSent()}async function ir(t,e,r,n,o){try{T.info(`creating ws server for [${t}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,dt):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let s=new or.WebSocketServer({noServer:!0,WebSocket:Ie,autoPong:!1}),i=new $e(T.child("pings"),()=>[t,s.clients],e.ping),a=await e.factory({endpoint:r,storage:n});s.on("error",c=>{T.error(`error starting the ws server for [${t}]`,c)}).on("listening",()=>{T.info(`ws server for [${t}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;Tn(c,u)}}).on("connection",(c,d)=>{let u=tr(d,c.protocol);c.on("pong",l=>{i.handlePong(u,c,l)}),c.on("ping",l=>{i.handlePing(u,c,l)}),a({socket:c,handshake:u})}),s.on("close",()=>{i.close()}),e.upgradeStrategy=Rn(t,e,s,o),e.close=async()=>{await a.close?.call(a),T.info(`stopping ws server for [${t}]. clients: ${s.clients?.size??0}`),s.clients?.forEach(c=>{c.terminate()}),s.close()}}catch(s){T.warn(`failed to init route ${t}`,s)}}var O=b("app");function kn(t){let e={};return t.key&&(e.key=(0,Ne.readFileSync)(t.key)),t.cert&&(e.cert=(0,Ne.readFileSync)(t.cert)),t.ca&&(e.ca=(0,Ne.readFileSync)(t.ca)),e}async function On(t,e){let r=t.build();return async(n,o)=>{n.socket.addListener("error",e);let s;o instanceof q?s=o:(n.upgradeHead=o,s=new q(n),s.assignSocket(n.socket));let i=new _(n),a=new fe(s),c=i.method==="HEAD"?new We(a):a;await r(i,c)}}function Mn(t){return new Promise((e,r)=>{let n=t(o=>{o?r(o):e(n)})})}function Wn(t){if(t)return vt({memoryLimit:t.memory_limit,dumpLocation:t.dump_location,dumpPrefix:t.dump_prefix,reportInterval:t.report_interval,maxBackups:t.max_backups})}async function Ln(t){let e=t.storage,r=await Zt(t),n=rr(t),o=pt(Et(t.serverHeader),...r,...n,...t.middleware,async({request:s,response:i},a)=>{if(s.method==="GET"&&s.path==="/health"){i.setStatusCode(f.OK);let c=Buffer.from("UP","utf-8");i.headers.set("Content-Type","text/plain; charset=utf-8"),await i.body(c)}else await a()},async({request:s,response:i},a)=>{if(s.method==="GET"&&s.path==="/"){i.setStatusCode(f.OK);let c=Buffer.from("io.Gateway Server","utf-8");i.headers.set("Content-Type","text/plain; charset=utf-8"),await i.body(c)}else await a()},async({response:s},i)=>{s.setStatusCode(f.NOT_FOUND),await s.end()});return new Le(o).storage(e)}var it=async t=>{let e=t.ssl,r=e?(p,h)=>ar.default.createServer({...p,...kn(e)},h):(p,h)=>sr.default.createServer(p,h),n=Wn(t.memory),o={middleware:[],corsConfig:t.cors,cors:[],authConfig:t.auth,authorize:[],storage:new cr.AsyncLocalStorage,sockets:new Map},s=dr.IOGateway.Factory({...t.gateway});if(t.gateway){let p=t.gateway;await Je(async h=>{h.socket({path:p.route,factory:ht.bind(s),options:p})},t,o)}t.app&&await Je(t.app,t,o);let i=St(t.port??0),a=t.host,c=p=>O.error(`socket error: ${p}`,p),d=await Ln(o),u=await On(d,c),g=await new Promise((p,h)=>{let w=r({IncomingMessage:le,ServerResponse:q,...t.http},u);w.on("error",m=>{if(m.code==="EADDRINUSE"){O.debug(`port ${m.port} already in use on address ${m.address}`);let{value:x}=i.next();x?(O.info(`retry starting server on port ${x} and host ${a??"<unspecified>"}`),w.close(),w.listen(x,a)):(O.warn(`all configured port(s) ${t.port} are in use. closing...`),w.close(),h(m))}else O.error(`server error: ${m.message}`,m),h(m)}),w.on("listening",async()=>{let m=w.address();for(let[x,X]of o.sockets){let B=`${e?"wss":"ws"}://${wt}:${m.port}${x}`;await ir(x,X,B,o.storage,c)}O.info(`http server listening on ${m.address}:${m.port}`),p(w)}),w.on("upgrade",(m,x,X)=>{try{u(m,X)}catch(B){O.error(`upgrade error: ${B}`,B)}}).on("close",async()=>{O.info("http server closed.")});try{let{value:m}=i.next();w.listen(m,a)}catch(m){O.error("error starting web socket server",m),h(m instanceof Error?m:new Error(`listen failed: ${m}`))}});return new class{gateway=s;async close(){for(let[p,h]of o.sockets)try{h.close!==void 0&&await h.close()}catch(w){O.warn(`error closing route ${p}`,w)}await Mn(p=>{g.closeAllConnections(),g.close(p)}),n&&await xt(n),s&&await s.stop()}}};var In=it;0&&(module.exports={GatewayServer});
|
|
2
|
+
You are probably missing an await or return statement in your middleware function.`);return l};return o(0,r)}}var ue=require("tough-cookie");function vr(t,e){let r=t.get("x-forwarded-for");if(r===void 0){if(r=t.get("x-forwarded-host"),Array.isArray(r)&&(r=r[0]),r){let n=t.one("x-forwarded-port");n&&(r=`${r}:${n}`)}r??=t.one("host")}return Array.isArray(r)&&(r=r[0]),r?r.split(",",1)[0].trim():e}function xr(t,e){let r=t.get("x-forwarded-proto");return Array.isArray(r)&&(r=r[0]),r!==void 0?r.split(",",1)[0].trim():e}var ae=class{#e;constructor(e){this.#e=e}get headers(){return this.#e}},ce=class t extends ae{static logIdCounter=0;#e;get id(){return this.#e===void 0&&(this.#e=`${this.initId()}-${++t.logIdCounter}`),this.#e}initId(){return"request"}get cookies(){return Cr(this.headers)}parseHost(e){return vr(this.headers,e)}parseProtocol(e){return xr(this.headers,e)}},de=class extends ae{get cookies(){return Ar(this.headers)}setCookieValue(e){return new ue.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 Er(t){let e=[];{let r=0,n=0;for(let o=0;o<t.length;o++)switch(t.charCodeAt(o)){case 32:r===n&&(r=n=o+1);break;case 44:e.push(t.slice(r,n)),r=n=o+1;break;default:n=n+1;break}e.push(t.slice(r,n))}return e}function ft(t){typeof t=="string"&&(t=[t]),typeof t=="number"&&(t=[String(t)]);let e=[];if(t)for(let r of t)r&&e.push(...Er(r));return e}function Cr(t){return t.list("cookie").map(e=>e.split(";").map(r=>ue.Cookie.parse(r))).flat(1).filter(e=>e!==void 0).map(e=>Object.freeze({name:e.key,value:e.value}))}function Ar(t){return t.list("set-cookie").map(e=>{let r=ue.Cookie.parse(e);if(r){let n={name:r.key,value:r.value,maxAge:Number(r.maxAge??-1)};return r.httpOnly&&(n.httpOnly=!0),r.domain&&(n.domain=r.domain),r.path&&(n.path=r.path),r.secure&&(n.secure=!0),r.httpOnly&&(n.httpOnly=!0),r.sameSite&&(n.sameSite=r.sameSite),Object.freeze(n)}}).filter(e=>e!==void 0)}var ee=class{constructor(){}toList(e){let r=this.get(e);return ft(r)}},v=class extends Map{get(e){return super.get(e.toLowerCase())}one(e){return this.get(e)?.[0]}list(e){let r=super.get(e.toLowerCase());return ft(r)}set(e,r){return typeof r=="number"&&(r=String(r)),typeof r=="string"&&(r=[r]),r?super.set(e.toLowerCase(),r):(super.delete(e.toLowerCase()),this)}add(e,r){let n=super.get(e.toLowerCase());return typeof r=="string"&&(r=[r]),n&&(r=n.concat(r)),this.set(e,r),this}};var Be=class{#e;constructor(e){this.#e=e}get value(){return this.#e}toString(){return this.#e.toString()}},f=class t{static CONTINUE=new t(100,"Continue");static SWITCHING_PROTOCOLS=new t(101,"Switching Protocols");static OK=new t(200,"OK");static CREATED=new t(201,"Created");static ACCEPTED=new t(202,"Accepted");static NON_AUTHORITATIVE_INFORMATION=new t(203,"Non-Authoritative Information");static NO_CONTENT=new t(204,"No Content");static RESET_CONTENT=new t(205,"Reset Content");static PARTIAL_CONTENT=new t(206,"Partial Content");static MULTI_STATUS=new t(207,"Multi-Status");static IM_USED=new t(226,"IM Used");static MULTIPLE_CHOICES=new t(300,"Multiple Choices");static MOVED_PERMANENTLY=new t(301,"Moved Permanently");static BAD_REQUEST=new t(400,"Bad Request");static UNAUTHORIZED=new t(401,"Unauthorized");static FORBIDDEN=new t(403,"Forbidden");static NOT_FOUND=new t(404,"Not Found");static METHOD_NOT_ALLOWED=new t(405,"Method Not Allowed");static NOT_ACCEPTABLE=new t(406,"Not Acceptable");static PROXY_AUTHENTICATION_REQUIRED=new t(407,"Proxy Authentication Required");static REQUEST_TIMEOUT=new t(408,"Request Timeout");static CONFLICT=new t(409,"Conflict");static GONE=new t(410,"Gone");static LENGTH_REQUIRED=new t(411,"Length Required");static PRECONDITION_FAILED=new t(412,"Precondition Failed");static PAYLOAD_TOO_LARGE=new t(413,"Payload Too Large");static URI_TOO_LONG=new t(414,"URI Too Long");static UNSUPPORTED_MEDIA_TYPE=new t(415,"Unsupported Media Type");static EXPECTATION_FAILED=new t(417,"Expectation Failed");static IM_A_TEAPOT=new t(418,"I'm a teapot");static TOO_EARLY=new t(425,"Too Early");static UPGRADE_REQUIRED=new t(426,"Upgrade Required");static PRECONDITION_REQUIRED=new t(428,"Precondition Required");static TOO_MANY_REQUESTS=new t(429,"Too Many Requests");static REQUEST_HEADER_FIELDS_TOO_LARGE=new t(431,"Request Header Fields Too Large");static UNAVAILABLE_FOR_LEGAL_REASONS=new t(451,"Unavailable For Legal Reasons");static INTERNAL_SERVER_ERROR=new t(500,"Internal Server Error");static NOT_IMPLEMENTED=new t(501,"Not Implemented");static BAD_GATEWAY=new t(502,"Bad Gateway");static SERVICE_UNAVAILABLE=new t(503,"Service Unavailable");static GATEWAY_TIMEOUT=new t(504,"Gateway Timeout");static HTTP_VERSION_NOT_SUPPORTED=new t(505,"HTTP Version Not Supported");static VARIANT_ALSO_NEGOTIATES=new t(506,"Variant Also Negotiates");static INSUFFICIENT_STORAGE=new t(507,"Insufficient Storage");static LOOP_DETECTED=new t(508,"Loop Detected");static NOT_EXTENDED=new t(510,"Not Extended");static NETWORK_AUTHENTICATION_REQUIRED=new t(511,"Network Authentication Required");static#e=[];static{Object.keys(t).filter(e=>e!=="VALUES"&&e!=="resolve").forEach(e=>{let r=t[e];r instanceof t&&(Object.defineProperty(r,"name",{enumerable:!0,value:e,writable:!1}),t.#e.push(r))})}static resolve(e){for(let r of t.#e)if(r.value===e)return r}#r;#t;constructor(e,r){this.#r=e,this.#t=r}get value(){return this.#r}get phrase(){return this.#t}toString(){return`${this.#r} ${this.name}`}};function gt(t){if(typeof t=="number"){if(t<100||t>999)throw new Error(`status code ${t} should be in range 100-999`);let e=f.resolve(t);return e!==void 0?e:new Be(t)}return t}var Se=Z(require("node:http"),1),le=class extends Se.default.IncomingMessage{exchange;upgradeHead;get urlBang(){return this.url}get socketEncrypted(){return this.socket.encrypted===!0}},q=class extends Se.default.ServerResponse{markHeadersSent(){this._header=!0}getRawHeaderNames(){return super.getRawHeaderNames()}},he=class extends ce{},pe=class extends de{#e=[];#r;#t="new";#o=[];setStatusCode(e){return this.#t==="committed"?!1:(this.#r=e,!0)}setRawStatusCode(e){return this.setStatusCode(e===void 0?void 0:gt(e))}get statusCode(){return this.#r}addCookie(e){if(this.#t==="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.#o.push(e)}get commited(){let e=this.#t;return e!=="new"&&e!=="commit-action-failed"}async body(e){if(e instanceof ReadableStream)throw new Error("ReadableStream body not supported yet");let r=await e;try{return await this.doCommit(async()=>await this.bodyInternal(Promise.resolve(r))).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 r=this.#t,n=Promise.resolve();if(r==="new")this.#t="committing",this.#o.length>0&&(n=this.#o.reduce((o,s)=>o.then(()=>s()),Promise.resolve()).catch(o=>{this.#t==="committing"&&(this.#t="commit-action-failed")}));else if(r==="commit-action-failed")this.#t="committing";else return Promise.resolve(!1);return n=n.then(()=>{this.applyStatusCode(),this.applyHeaders(),this.applyCookies(),this.#t="committed"}),n.then(async()=>e!==void 0?await e():!0)}applyStatusCode(){}applyHeaders(){}applyCookies(){}},_=class extends he{#e;#r;#t;constructor(e){super(new De(e)),this.#t=e}getNativeRequest(){return this.#t}get upgrade(){return this.#t.upgrade}get http2(){return this.#t.httpVersionMajor>=2}get path(){return this.URL?.pathname}get URL(){return this.#e??=new URL(this.#t.urlBang,`${this.protocol}://${this.host}`),this.#e}get query(){return this.URL?.search}get method(){return this.#t.method}get host(){let e;return this.#t.httpVersionMajor>=2&&(e=this.#t.headers[":authority"]),e??=this.#t.socket.remoteAddress,super.parseHost(e)}get protocol(){let e;return this.#t.httpVersionMajor>2&&(e=this.#t.headers[":scheme"]),e??=this.#t.socketEncrypted?"https":"http",super.parseProtocol(e)}get socket(){return this.#t.socket}get remoteAddress(){let e=this.#t.socket.remoteFamily,r=this.#t.socket.remoteAddress,n=this.#t.socket.remotePort;if(!(!e||!r||!n))return{family:e,address:r,port:n}}get cookies(){return this.#r??=super.cookies,this.#r}get body(){return Se.default.IncomingMessage.toWeb(this.#t)}async blob(){let e=[];if(this.body!==void 0)for await(let r of this.body)e.push(r);return new Blob(e,{type:this.headers.one("content-type")||"application/octet-stream"})}async text(){return await(await this.blob()).text()}async formData(){let r=await(await this.blob()).text();return new URLSearchParams(r)}async json(){let e=await this.blob();if(e.size===0)return;let r=await e.text();return JSON.parse(r)}initId(){let e=this.#t.socket.remoteAddress;if(!e)throw new Error("Socket has no remote address");return`${e}:${this.#t.socket.remotePort}`}},De=class extends ee{#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 r=this.#e.headers[e];return Array.isArray(r)?r[0]:r}keys(){return Object.keys(this.#e.headers).values()}},Ue=class extends ee{#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 r=this.#e.getHeader(e);return Array.isArray(r)?r[0]:r}set(e,r){return this.#e.headersSent||(Array.isArray(r)?r=r.map(n=>typeof n=="number"?String(n):n):typeof r=="number"&&(r=String(r)),r?this.#e.setHeader(e,r):this.#e.removeHeader(e)),this}add(e,r){return this.#e.headersSent||this.#e.appendHeader(e,r),this}list(e){return super.toList(e)}},fe=class extends pe{#e;constructor(e){super(new Ue(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 r=await e;return await new Promise((n,o)=>{try{r===void 0?this.#e.end(()=>{n(!0)}):(this.headers.has("content-length")||(typeof r=="string"?this.headers.set("content-length",Buffer.byteLength(r)):r instanceof Blob?this.headers.set("content-length",r.size):this.headers.set("content-length",r.byteLength)),this.#e.end(r,()=>{n(!0)}))}catch(s){o(s instanceof Error?s:new Error(`end failed: ${s}`))}})}}},ge=class t{#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 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 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`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeRequest(e){if(e instanceof he)return e.getNativeRequest();if(e instanceof t)return t.getNativeRequest(e.delegate);throw new Error(`Cannot get native request from ${e.constructor.name}`)}},z=class t{#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`${t.name} [delegate: ${this.delegate.toString()}]`}static getNativeResponse(e){if(e instanceof pe)return e.getNativeResponse();if(e instanceof t)return t.getNativeResponse(e.delegate);throw new Error(`Cannot get native response from ${e.constructor.name}`)}},me=class t{#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)}principal(){return this.#e.principal()}get logPrefix(){return this.#e.logPrefix}toString(){return`${t.name} [delegate: ${this.delegate}]`}},ye=class{request;response;#e={};#r;#t="";constructor(e,r){this.#e[mt]=e.id,this.request=e,this.response=r}get method(){return this.request.method}get path(){return this.request.path}get attributes(){return this.#e}attribute(e){return this.attributes[e]}principal(){return Promise.resolve(void 0)}get logPrefix(){let e=this.attribute(mt);return this.#r!==e&&(this.#r=e,this.#t=e!==void 0?`[${e}] `:""),this.#t}},mt="io.interop.gateway.server.log_id";var yt=require("node:os"),Hr=/^(\d+|(0x[\da-f]+))(-(\d+|(0x[\da-f]+)))?$/i;function qe(t){if(t>65535)throw new Error(`bad port ${t}`);return t}function*St(t){if(typeof t=="string")for(let e of t.split(",")){let r=e.trim(),n=Hr.exec(r);if(n){let o=parseInt(n[1]),s=parseInt(n[4]??n[1]);for(let i=qe(o);i<qe(s)+1;i++)yield i}else throw new Error(`'${e}' is not a valid port or range.`)}else yield qe(t)}var wt=(()=>{function t(r){return r.length>0?r[0]:void 0}let e=Object.values((0,yt.networkInterfaces)()).flatMap(r=>(r??[]).filter(n=>n.family==="IPv4")).reduce((r,n)=>(r[n.internal?"internal":"external"].push(n),r),{internal:[],external:[]});return(t(e.internal)??t(e.external))?.address})();var we=require("node:v8"),W=require("node:fs/promises"),y=b("monitoring"),Pr={memoryLimit:1024*1024*1024,reportInterval:600*1e3,dumpLocation:".",maxBackups:10,dumpPrefix:"Heap"};function Rr(){return(0,we.getHeapStatistics)()}async function bt(t){let e=t.dumpPrefix??"Heap",r=`${t.dumpLocation}/${e}.heapsnapshot`;y.enabledFor("debug")&&y.debug(`starting heap dump in ${r}`),await _e(t.dumpLocation).catch(async o=>{y.enabledFor("debug")&&y.debug(`dump location ${t.dumpLocation} does not exists. Will try to create it`);try{await(0,W.mkdir)(t.dumpLocation,{recursive:!0}),y.info(`dump location dir ${t.dumpLocation} successfully created`)}catch{y.error(`failed to create dump location ${t.dumpLocation}`)}});let n=(0,we.writeHeapSnapshot)(r);y.info("heap dumped");try{y.debug("rolling snapshot backups");let o=`${t.dumpLocation}/${e}.${t.maxBackups}.heapsnapshot`;await _e(o).then(async()=>{y.enabledFor("debug")&&y.debug(`deleting ${o}`);try{await(0,W.unlink)(o)}catch(i){y.warn(`failed to delete ${o}`,i)}}).catch(()=>{});for(let i=t.maxBackups-1;i>0;i--){let a=`${t.dumpLocation}/${e}.${i}.heapsnapshot`,c=`${t.dumpLocation}/${e}.${i+1}.heapsnapshot`;await _e(a).then(async()=>{try{await(0,W.rename)(a,c)}catch(d){y.warn(`failed to rename ${a} to ${c}`,d)}}).catch(()=>{})}let s=`${t.dumpLocation}/${e}.1.heapsnapshot`;try{await(0,W.rename)(n,s)}catch(i){y.warn(`failed to rename ${n} to ${s}`,i)}y.debug("snapshots rolled")}catch(o){throw y.error("error rolling backups",o),o}}async function _e(t){y.enabledFor("trace")&&y.debug(`checking file ${t}`),await(0,W.access)(t)}async function Tr(t,e,r){y.enabledFor("debug")&&y.debug(`processing heap stats ${JSON.stringify(t)}`);let n=Math.min(r.memoryLimit,.95*t.heap_size_limit),o=t.used_heap_size;y.info(`heap stats ${JSON.stringify(t)}`),o>=n?(y.warn(`used heap ${o} bytes exceeds memory limit ${n} bytes`),e.memoryLimitExceeded?delete e.snapshot:(e.memoryLimitExceeded=!0,e.snapshot=!0),await bt(r)):(e.memoryLimitExceeded=!1,delete e.snapshot)}function vt(t){let e={...Pr,...t},r=!1,n={memoryLimitExceeded:!1},o=async()=>{let a=Rr();await Tr(a,n,e)},s=setInterval(o,e.reportInterval);return{...e,channel:async a=>{if(!r)switch(a??="run",a){case"run":{await o();break}case"dump":{await bt(e);break}case"stop":{r=!0,clearInterval(s),y.info("exit memory diagnostic");break}}return r}}}async function kr({channel:t},e){await t(e)||y.warn(`cannot execute command "${e}" already closed`)}async function xt(t){return await kr(t,"stop")}var ze=Z(require("@interopio/gateway-server/package.json"),1),Mr=t=>(t??=`${ze.default.name} - v${ze.default.version}`,async({response:e},r)=>{t!==!1&&!e.headers.has("server")&&e.headers.set("Server",t),await r()}),Et=t=>Mr(t);var te=require("@interopio/gateway");var Ge=b("gateway.ws.client-verify");function Wr(t){switch(t.missing){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Lr(t,e){let r=t.block??t.blacklist,n=t.allow??t.whitelist;if(r.length>0&&te.IOGateway.Filtering.valuesMatch(r,e))return Ge.warn(`origin ${e} matches block filter`),!1;if(n.length>0&&te.IOGateway.Filtering.valuesMatch(n,e))return Ge.enabledFor("debug")&&Ge.debug(`origin ${e} matches allow filter`),!0}function Ir(t){switch(t.non_matched){case"allow":case"whitelist":return!0;case"block":case"blacklist":return!1;default:return!1}}function Ct(t,e){if(!e)return!0;if(t){let r=Lr(e,t);return r||Ir(e)}else return Wr(e)}function At(t){if(t){let e=(t.block??t.blacklist??[]).map(te.IOGateway.Filtering.regexify),r=(t.allow??t.whitelist??[]).map(te.IOGateway.Filtering.regexify);return{non_matched:t.non_matched??"allow",missing:t.missing??"allow",allow:r,block:e}}}var Ht=t=>async e=>{for(let r of t)if((await r(e)).match)return A();return E},G=t=>{let e=async r=>{for(let n of t)if(!(await n(r)).match)return E;return A()};return e.toString=()=>`and(${t.map(r=>r.toString()).join(", ")})`,e},Pt=t=>async e=>(await t(e)).match?E:A(),re=async t=>A();re.toString=()=>"any-exchange";var Rt=Object.freeze({}),E=Object.freeze({match:!1,variables:Rt}),A=(t=Rt)=>({match:!0,variables:t}),H=(t,e)=>{let r=e?.method,n=async o=>{let s=o.request,i=s.path;if(r!==void 0&&s.method!==r)return E;if(typeof t=="string")return i===t?A():E;{let a=t.exec(i);return a===null?E:{match:!0,variables:{...a.groups}}}};return n.toString=()=>`pattern(${t.toString()}, method=${r??"<any>"})`,n},je=t=>{let e=r=>{if(t.ignoredMediaTypes!==void 0){for(let n of t.ignoredMediaTypes)if(r===n||n==="*/*")return!0}return!1};return async r=>{let n=r.request,o;try{o=n.headers.list("accept")}catch{return E}for(let s of o)if(!e(s)){for(let i of t.mediaTypes)if(s.startsWith(i))return A()}return E}},D=async({request:t})=>t.upgrade&&t.headers.one("upgrade")?.toLowerCase()==="websocket"?A():E;D.toString=()=>"websocket upgrade";var Ve=require("@interopio/gateway");async function Je(t,e,r){let n=(s,i)=>{if(i?.cors){let a=i.cors===!0?{allowOrigins:i.origins?.allow?.map(Ve.IOGateway.Filtering.regexify),allowMethods:s.method===void 0?["*"]:[s.method],allowCredentials:i.authorize?.access!=="permitted"?!0:void 0}:i.cors,c=s.path;r.cors.push([c,a])}},o=new class{handle(...s){s.forEach(({request:i,options:a,handler:c})=>{let d=H(Ve.IOGateway.Filtering.regexify(i.path),{method:i.method});a?.authorize&&r.authorize.push([d,a.authorize]),n(i,a);let u=async(l,g)=>{let{match:p,variables:h}=await d(l);p?await c(l,h):await g()};r.middleware.push(u)})}socket(...s){for(let{path:i,factory:a,options:c}of s){let d=i??"/";r.sockets.set(d,{default:i===void 0,ping:c?.ping,factory:a,maxConnections:c?.maxConnections,authorize:c?.authorize,originFilters:At(c?.origins)})}}};await t(o,e)}var xe=require("@interopio/gateway");function Nr(t){let e=t.headers.one("origin");if(e===void 0)return!0;let r=t.URL,n=r.protocol,o=r.host,s=URL.parse(e),i=s?.host,a=s?.protocol;return n===a&&o===i}function Fr(t){return t.headers.has("origin")&&!Nr(t)}function kt(t){return t.method==="OPTIONS"&&t.headers.has("origin")&&t.headers.has("access-control-request-method")}var Tt=["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"],Br=(t,e)=>{let{request:r,response:n}=t,o=n.headers;if(!o.has("Vary"))o.set("Vary",Tt.join(", "));else{let i=o.list("Vary");for(let a of Tt)i.find(c=>c===a)||i.push(a);o.set("Vary",i.join(", "))}try{if(!Fr(r))return!0}catch{return P.enabledFor("debug")&&P.debug("reject: origin is malformed"),ne(n),!1}if(o.has("access-control-allow-origin"))return P.enabledFor("trace")&&P.debug('skip: already contains "Access-Control-Allow-Origin"'),!0;let s=kt(r);return e?Ur(t,e,s):s?(ne(n),!1):!0},ve=["*"],Qe=["GET","HEAD","POST"],Ot={allowOrigins:ve,allowMethods:Qe,allowHeaders:ve,maxAge:1800};function Ee(t){if(t){let e=t.allowHeaders;e&&e!==S&&(t={...t,allowHeaders:e.map(n=>n.toLowerCase())});let r=t.allowOrigins;return r&&(r==="*"?(Wt(t),Lt(t)):t={...t,allowOrigins:r.map(n=>typeof n=="string"&&n!==S&&(n=xe.IOGateway.Filtering.regexify(n),typeof n=="string")?It(n).toLowerCase():n)}),t}}function be(t,e){if(e===void 0)return t!==void 0?t===S?[S]:t:[];if(t===void 0)return e===S?[S]:e;if(t==ve||t===Qe)return e===S?[S]:e;if(e==ve||e===Qe)return t===S?[S]:t;if(t===S||t.includes(S)||e===S||e.includes(S))return[S];let r=new Set;return t.forEach(n=>r.add(n)),e.forEach(n=>r.add(n)),Array.from(r)}var oe=(t,e)=>e===void 0?t:{allowOrigins:be(t.allowOrigins,e?.allowOrigins),allowMethods:be(t.allowMethods,e?.allowMethods),allowHeaders:be(t.allowHeaders,e?.allowHeaders),exposeHeaders:be(t.exposeHeaders,e?.exposeHeaders),allowCredentials:e?.allowCredentials??t.allowCredentials,allowPrivateNetwork:e?.allowPrivateNetwork??t.allowPrivateNetwork,maxAge:e?.maxAge??t.maxAge},Dr=t=>{let e=t.corsConfigSource,r=t.corsProcessor??Br;return async(n,o)=>{let s=await e(n);!r(n,s)||kt(n.request)||await o()}},Mt=Dr,P=b("cors");function ne(t){t.setStatusCode(f.FORBIDDEN)}function Ur(t,e,r){let{request:n,response:o}=t,s=o.headers,i=n.headers.one("origin"),a=_r(e,i);if(a===void 0)return P.enabledFor("debug")&&P.debug(`reject: '${i}' origin is not allowed`),ne(o),!1;let c=jr(n,r),d=zr(e,c);if(d===void 0)return P.enabledFor("debug")&&P.debug(`reject: HTTP '${c}' is not allowed`),ne(o),!1;let u=Vr(n,r),l=Gr(e,u);if(r&&l===void 0)return P.enabledFor("debug")&&P.debug(`reject: headers '${u}' are not allowed`),ne(o),!1;s.set("Access-Control-Allow-Origin",a),r&&s.set("Access-Control-Allow-Methods",d.join(",")),r&&l!==void 0&&l.length>0&&s.set("Access-Control-Allow-Headers",l.join(", "));let g=e.exposeHeaders;return g&&g.length>0&&s.set("Access-Control-Expose-Headers",g.join(", ")),e.allowCredentials&&s.set("Access-Control-Allow-Credentials","true"),e.allowPrivateNetwork&&n.headers.one("access-control-request-private-network")==="true"&&s.set("Access-Control-Allow-Private-Network","true"),r&&e.maxAge!==void 0&&s.set("Access-Control-Max-Age",e.maxAge.toString()),!0}var S="*",qr=["GET","HEAD"];function Wt(t){if(t.allowCredentials===!0&&t.allowOrigins===S)throw new Error('when allowCredentials is true allowOrigins cannot be "*"')}function Lt(t){if(t.allowPrivateNetwork===!0&&t.allowOrigins===S)throw new Error('when allowPrivateNetwork is true allowOrigins cannot be "*"')}function _r(t,e){if(e){let r=t.allowOrigins;if(r){if(r===S)return Wt(t),Lt(t),S;let n=It(e.toLowerCase());for(let o of r)if(o===S||xe.IOGateway.Filtering.valueMatches(o,n))return e}}}function zr(t,e){if(e){let r=t.allowMethods??qr;if(r===S)return[e];if(xe.IOGateway.Filtering.valuesMatch(r,e))return r}}function Gr(t,e){if(e===void 0)return;if(e.length==0)return[];let r=t.allowHeaders;if(r===void 0)return;let n=r===S||r.includes(S),o=[];for(let s of e){let i=s?.trim();if(i){if(n)o.push(i);else for(let a of r)if(i.toLowerCase()===a){o.push(i);break}}}if(o.length>0)return o}function It(t){return t.endsWith("/")?t.slice(0,-1):t}function jr(t,e){return e?t.headers.one("access-control-request-method"):t.method}function Vr(t,e){let r=t.headers;return e?r.list("access-control-request-headers"):Array.from(r.keys())}var $t=t=>async e=>{for(let[r,n]of t.mappings)if((await r(e)).match)return P.debug(`resolved cors config on '${e.request.path}' using ${r}: ${JSON.stringify(n)}`),n};var Nt=require("@interopio/gateway");function Ft(t){let{sockets:e,cors:r}=t,n=t.corsConfig===!1?void 0:oe(Ot,t.corsConfig),o=[];for(let[i,a]of e){let c=n;for(let[u,l]of r)Nt.IOGateway.Filtering.valueMatches(u,i)&&(l===void 0?c=void 0:c=c===void 0?l:oe(c,l));let d=t.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:oe(c,d),o.push([G([D,H(i)]),Ee(c)])}let s=[];for(let[i,a]of r){let[,c]=s.find(([u])=>String(u)===String(i))??[i,n];c=c===void 0?a:oe(c,a);let d=!1;for(let u of s)if(String(u[0])===String(i)){u[1]=c,d=!0;break}d||s.push([i,c])}for(let[i,a]of s)o.push([H(i),Ee(a)]);return o.push([H(/\/api\/.*/),Ee(n)]),$t({mappings:o})}function Bt(t){return t!==void 0&&typeof t.type=="string"&&typeof t.authenticated=="boolean"}var C=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}},Ce=class extends C{},Ae=class extends C{};var U=class extends Error{},L=class{constructor(e){this.granted=e}granted},N=class{#e;constructor(e){this.#e=e}async verify(e,r){if(!(await this.#e(e,r))?.granted)throw new U("Access denied")}async authorize(e,r){return await this.#e(e,r)}},j=class extends C{};var R=t=>async e=>{let r=!0,{response:n}=e;for(let o of t.keys())n.headers.has(o)&&(r=!1);if(r)for(let[o,s]of t)n.headers.set(o,s)},Jr=()=>R(new v().add("cache-control","no-cache, no-store, max-age=0, must-revalidate").add("pragma","no-cache").add("expires","0")),Qr=()=>R(new v().add("x-content-type-options","nosniff")),Yr=(t,e,r)=>{let n=`max-age=${t}`;e&&(n+=" ; includeSubDomains"),r&&(n+=" ; preload");let o=R(new v().add("strict-transport-security",n)),s=i=>i.request.URL.protocol==="https:";return async i=>{s(i)&&await o(i)}},Kr=t=>R(new v().add("x-frame-options",t)),Xr=t=>R(new v().add("x-xss-protection",t)),Zr=t=>{let e=t===void 0?void 0:R(new v().add("permissions-policy",t));return async r=>{e!==void 0&&await e(r)}},en=(t,e)=>{let r=e?"content-security-policy-report-only":"content-security-policy",n=t===void 0?void 0:R(new v().add(r,t));return async o=>{n!==void 0&&await n(o)}},tn=(t="no-referrer")=>R(new v().add("referer-policy",t)),rn=t=>{let e=t===void 0?void 0:R(new v().add("cross-origin-opener-policy",t));return async r=>{e!==void 0&&await e(r)}},nn=t=>{let e=t===void 0?void 0:R(new v().add("cross-origin-embedder-policy",t));return async r=>{e!==void 0&&await e(r)}},on=t=>{let e=t===void 0?void 0:R(new v().add("cross-origin-resource-policy",t));return async r=>{e!==void 0&&await e(r)}},sn=(...t)=>async e=>{for(let r of t)await r(e)};function Ye(t){let e=[];t?.cache?.disabled||e.push(Jr()),t?.contentType?.disabled||e.push(Qr()),t?.hsts?.disabled||e.push(Yr(t?.hsts?.maxAge??365*24*60*60,t?.hsts?.includeSubDomains??!0,t?.hsts?.preload??!1)),t?.frameOptions?.disabled||e.push(Kr(t?.frameOptions?.mode??"DENY")),t?.xss?.disabled||e.push(Xr(t?.xss?.headerValue??"0")),t?.permissionsPolicy?.disabled||e.push(Zr(t?.permissionsPolicy?.policyDirectives)),t?.contentSecurityPolicy?.disabled||e.push(en(t?.contentSecurityPolicy?.policyDirectives??"default-src 'self'",t?.contentSecurityPolicy?.reportOnly)),t?.refererPolicy?.disabled||e.push(tn(t?.refererPolicy?.policy??"no-referrer")),t?.crossOriginOpenerPolicy?.disabled||e.push(rn(t?.crossOriginOpenerPolicy?.policy)),t?.crossOriginEmbedderPolicy?.disabled||e.push(nn(t?.crossOriginEmbedderPolicy?.policy)),t?.crossOriginResourcePolicy?.disabled||e.push(on(t?.crossOriginResourcePolicy?.policy)),t?.writers&&e.push(...t.writers);let r=sn(...e);return async(n,o)=>{await r(n),await o()}}var V=t=>{let e=t.entryPoint,r=t?.rethrowAuthenticationServiceError??!0;return async({exchange:n},o)=>{if(!r||!(o instanceof j))return e(n,o);throw o}};var an="Realm",cn=t=>`Basic realm="${t}"`,J=t=>{let e=cn(t?.realm??an);return async(r,n)=>{let{response:o}=r;o.setStatusCode(f.UNAUTHORIZED),o.headers.set("WWW-Authenticate",e)}};var Dt="Basic ",He=t=>async e=>{let{request:r}=e,n=r.headers.one("authorization");if(!n||!/basic/i.test(n.substring(0)))return;let o=n.length<=Dt.length?"":n.substring(Dt.length),i=Buffer.from(o,"base64").toString(t?.credentialsEncoding??"utf-8").split(":",2);if(i.length===2)return{type:"UsernamePassword",authenticated:!1,principal:i[0],credentials:i[1]}};var Ut=require("node:async_hooks"),F=class t{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(r=new Ut.AsyncLocalStorage)=>(r.getStore().securityContext=e,r)}static withAuthentication(e){return t.withSecurityContext(Promise.resolve({authentication:e}))}static async getContext(e){if(t.hasSecurityContext(e))return t.getSecurityContext(e)}};async function dn(t,e,r,n,o,s){let a=await(await n(t))?.(r);if(a===void 0)throw new Error("No authentication manager found for the exchange");try{await un(a,{exchange:t,next:e},o,s)}catch(c){throw c instanceof C,c}}async function un(t,e,r,n){F.withAuthentication(t)(n),await r(e,t)}function Q(t){let e={matcher:re,successHandler:async({next:n})=>{await n()},converter:He({}),failureHandler:V({entryPoint:J({})}),...t},r=e.managerResolver;if(r===void 0&&e.manager!==void 0){let n=e.manager;r=async o=>n}if(r===void 0)throw new Error("Authentication filter requires a managerResolver or a manager");return async(n,o)=>{let i=(await e.matcher(n)).match?await e.converter(n):void 0;if(i===void 0){await o();return}try{await dn(n,o,i,r,e.successHandler,e.storage)}catch(a){if(a instanceof C){await e.failureHandler({exchange:n,next:o},a);return}throw a}}}var qt=t=>async(e,r)=>{e.response.setStatusCode(t.httpStatus)};var Y=b("auth.entry-point"),Pe=t=>{let e=t.defaultEntryPoint??(async({response:r},n)=>{r.setStatusCode(f.UNAUTHORIZED),await r.end()});return async(r,n)=>{for(let[o,s]of t.entryPoints)if(Y.enabledFor("debug")&&Y.debug(`trying to match using: ${o}`),(await o(r)).match)return Y.enabledFor("debug")&&Y.debug(`match found. using default entry point ${s}`),s(r,n);return Y.enabledFor("debug")&&Y.debug(`no match found. using default entry point ${e}`),e(r,n)}};var _t=t=>async({exchange:e,next:r},n)=>{for(let o of t)await o({exchange:e,next:r},n)};function Ke(t){let e=async g=>g.request.headers.list("X-Requested-With").includes("XMLHttpRequest")?A():E,r=Pe({entryPoints:[[e,qt({httpStatus:f.UNAUTHORIZED})]],defaultEntryPoint:J({})}),n=t.entryPoint??r,o=t.manager,s=je({mediaTypes:["application/atom+xml","application/x-www-form-urlencoded","application/json","application/octet-stream","application/xml","multipart/form-data","text/xml"],ignoredMediaTypes:["*/*"]}),i=Pt(je({mediaTypes:["text/html"]})),a=G([i,s]),c=Ht([e,a]);t.defaultEntryPoints.push([c,n]);let d=t.failureHandler??V({entryPoint:n}),u=_t(t.successHandlers??t.defaultSuccessHandlers),l=He({});return Q({storage:t.storage,manager:o,failureHandler:d,successHandler:u,converter:l})}var zt={invalid_request:"invalid_request",invalid_token:"invalid_token",insufficient_scope:"insufficient_scope"},Gt="https://tools.ietf.org/html/rfc6750#section-3.1";function Re(t){return{errorCode:zt.invalid_token,httpStatus:f.UNAUTHORIZED,description:t,uri:Gt}}function Xe(t){return{errorCode:zt.invalid_request,httpStatus:f.BAD_REQUEST,description:t,uri:Gt}}var ln="access_token",hn=/^Bearer\s+(?<token>[a-zA-Z0-9-._~+/]+=*)$/i,k=class extends C{error;constructor(e,r,n){super(r??(typeof e=="string"?void 0:e.description),n),this.error=typeof e=="string"?{errorCode:e}:e}},jt=t=>t.type==="BearerToken",pn=t=>async e=>{let{request:r}=e;return Promise.all([gn(r.headers,t?.headerName).then(n=>n!==void 0?[n]:void 0),mn(r,t?.uriQueryParameter),yn(e,t?.formEncodedBodyParameter)]).then(n=>n.filter(o=>o!==void 0).flat(1)).then(fn).then(n=>{if(n)return{authenticated:!1,type:"BearerToken",token:n}})};async function fn(t){if(t.length===0)return;if(t.length>1){let r=Xe("Found multiple access tokens in the request");throw new k(r)}let e=t[0];if(!e||e.length===0){let r=Xe("The requested access token parameter is an empty string");throw new k(r)}return e}async function gn(t,e="authorization"){let r=t.one(e);if(!r||!/bearer/i.test(r.substring(0)))return;let n=hn.exec(r);if(n===null){let o=Re("Bearer token is malformed");throw new k(o)}return n.groups?.token}async function Vt(t){let e=t.getAll(ln);if(e.length!==0)return e}async function mn(t,e=!1){if(!(!e||t.method!=="GET"))return Vt(t.URL.searchParams)}async function yn(t,e=!1){let{request:r}=t;if(!e||r.headers.one("content-type")!=="application/x-www-form-urlencoded"||r.method!=="POST")return;let n=await t.request.formData();if(n)return Vt(n)}var Te=pn;function Sn(t){let e="Bearer";if(t.size!==0){e+=" ";let r=0;for(let[n,o]of t)e+=`${n}="${o}"`,r!==t.size-1&&(e+=", "),r++}return e}var Jt=t=>t.httpStatus!==void 0;function wn(t){if(t instanceof k){let{error:e}=t;if(Jt(e))return e.httpStatus}return f.UNAUTHORIZED}function bn(t,e){let r=new Map;if(e&&r.set("realm",e),t instanceof k){let{error:n}=t;r.set("error",n.errorCode),n.description&&r.set("error_description",n.description),n.uri&&r.set("error_uri",n.uri),Jt(n)&&n.scope&&r.set("scope",n.scope)}return r}var vn=t=>async(e,r)=>{let n=wn(r),o=bn(r,t?.realmName),s=Sn(o),{response:i}=e;i.headers.set("WWW-Authenticate",s),i.setStatusCode(n),await i.end()},ke=vn;var xn=t=>{let e=t?.principalClaimName??"sub";return r=>({type:"JwtToken",authenticated:!0,name:r.getClaimAsString(e)})},En=t=>async e=>t(e),K=class extends Error{},ie=class extends K{};function Cn(t){if(t instanceof ie)return new k(Re(t.message),t.message,{cause:t});throw new j(t.message,{cause:t})}function Ze(t){let e=t.decoder,r=t.authConverter??En(xn({}));return async n=>{if(jt(n)){let o=n.token;try{let s=await e(o);return await r(s)}catch(s){throw s instanceof K?Cn(s):s}}}}function et(t){let e=t.entryPoint??ke({}),r=t?.converter??Te({}),n=t.failureHandler??V({entryPoint:e});if(t.managerResolver!==void 0)return Q({storage:t.storage,converter:r,failureHandler:n,managerResolver:t.managerResolver});if(t.jwt!==void 0){let o=t.jwt.manager??Ze(t.jwt);return Q({storage:t.storage,converter:r,failureHandler:n,managerResolver:async s=>o})}throw new Error("Invalid resource server configuration: either managerResolver or jwt must be provided")}var Me=require("@interopio/gateway/jose/jwt");async function Qt(t,e,r){let n=new Ce("Full authentication is required to access this resource."),o=new C("Access Denied",{cause:n});e&&(o.authentication=e),await r(t,o)}function An(t){return async(e,r)=>{e.response.setStatusCode(t),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 Yt=t=>{let e=An(f.FORBIDDEN),r=t.authenticationEntryPoint??J();return async(n,o)=>{try{await o()}catch(s){if(s instanceof U){let i=await n.principal();Bt(i)?(i.authenticated||await e(n,s),await Qt(n,i,r)):await Qt(n,void 0,r);return}throw s}}};var Hn=b("security.auth");function tt(t){let e=async(r,n)=>{let o;for(let[s,i]of t.mappings)if((await s(n))?.match){Hn.debug(`checking authorization on '${n.request.path}' using [${s}, ${i}]`);let a=await i.authorize(r,{exchange:n});if(a!==void 0){o=a;break}}return o??=new L(!1),o};return new N(e)}var Oe=b("security.auth");function rt(t){let{manager:e,storage:r}=t;return async(n,o)=>{let s=F.getContext(r).then(i=>i?.authentication);try{await e.verify(s,n),Oe.enabledFor("debug")&&Oe.debug("authorization successful")}catch(i){throw i instanceof U&&Oe.enabledFor("debug")&&Oe.debug(`authorization failed: ${i.message}`),i}await o()}}var nt=class extends me{#e;constructor(e,r){super(e),this.#e=r}async principal(){return(await this.#e())?.authentication}},Kt=t=>{let e=t.storage;return async(r,n)=>{await n(new nt(r,async()=>await F.getContext(e)))}};var I={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},$=Symbol.for("filterOrder"),Xt=(t,e)=>{let r=[];class n{#e;#r=[];manager;get authenticationEntryPoint(){return this.#e!==void 0||this.#r.length===0?this.#e:this.#r.length===1?this.#r[0][1]:Pe({entryPoints:this.#r,defaultEntryPoint:this.#r[this.#r.length-1][1]})}build(){if(t.headers!==void 0&&t.headers.disabled!==!0){let a=Ye(t.headers);a[$]=I.http_headers,r.push(a)}if(t.cors?.disabled!==!0&&e.corsConfigSource!==void 0){let a=Mt({corsConfigSource:e.corsConfigSource});a[$]=I.cors,r.push(a)}if(t.basic!==void 0&&t.basic?.disabled!==!0){let a=t.basic.user?.name.toLowerCase(),c=t.basic.user?.password??"",d=t.basic.user?.authorities??[],u=async p=>{let h=p.principal,w=p.credentials;if(h.toLowerCase()!==a||w!==c)throw new Ae("Invalid username or password");return{type:"UsernamePassword",authenticated:!0,principal:h,credentials:w,authorities:[...d]}},l=[async({exchange:p,next:h},w)=>h()],g=Ke({storage:e.storage,manager:u,defaultEntryPoints:this.#r,defaultSuccessHandlers:l});g[$]=I.http_basic,r.push(g)}if(t.jwt!==void 0&&t.jwt.disabled!==!0){let a=(0,Me.jwtVerifier)({issuerBaseUri:t.jwt.issuerUri,issuer:t.jwt.issuer,audience:t.jwt.audience}),c=async p=>{try{let{payload:h}=await a(p);return{subject:h.sub,getClaimAsString(w){return h[w]}}}catch(h){throw h instanceof Me.JwtVerifyError?new ie(h.message,{cause:h}):new K("error occurred while attempting to decoding jwt",{cause:h})}},d=Te({uriQueryParameter:!0}),u=async p=>{try{return await d(p)===void 0?E:A()}catch{return E}},l=ke({});this.#r.push([u,l]);let g=et({storage:e.storage,entryPoint:l,converter:d,jwt:{decoder:c}});g[$]=I.authentication,r.push(g)}let i=Kt({storage:e.storage});if(r.push(i),i[$]=I.security_context_server_web_exchange,t.authorize!==void 0){let a=Yt({authenticationEntryPoint:this.authenticationEntryPoint});a[$]=I.error_translation,r.push(a);let d=(l=>{let g=[],p=!1;for(let[h,w]of l??[]){let m;if(h==="any-exchange")p=!0,m=re;else{if(p)throw new Error("Cannot register other matchers after 'any-exchange' matcher");m=h}let x;if(w.access==="permitted")x=new N(async()=>new L(!0)),x.toString=()=>"AuthorizationManager[permitted]";else if(w.access==="denied")x=new N(async()=>new L(!1)),x.toString=()=>"AuthorizationManager[denied]";else if(w.access==="authenticated")x=new N(async X=>{let B=await X;return B!==void 0?new L(B.authenticated):new L(!1)}),x.toString=()=>"AuthorizationManager[authenticated]";else throw new Error(`Unknown access type: ${JSON.stringify(w)}`);g.push([m,x])}return tt({mappings:g})})(t.authorize),u=rt({manager:d,storage:e.storage});u[$]=I.authorization,r.push(u)}r.sort((a,c)=>{let d=a[$]??I.last,u=c[$]??I.last;return d-u})}}return new n().build(),r};function Pn(t){let e=[],r={access:t.authConfig?.type!=="none"?"authenticated":"permitted"};for(let[n,o]of t.sockets){let s=o.authorize??r,i=H(n,{method:"GET"});i=G([D,i]),e.push([i,s])}return e.push([H("/",{method:"GET"}),{access:"permitted"}]),e.push([H("/favicon.ico",{method:"GET"}),{access:"permitted"}]),e.push([H("/health",{method:"GET"}),{access:"permitted"}]),t.authorize.length>0&&e.push(...t.authorize),e.push(["any-exchange",r]),{authorize:e,cors:{disabled:t.corsConfig===!1},basic:{disabled:t.authConfig?.type!=="basic",...t.authConfig?.basic},jwt:{disabled:t.authConfig?.type!=="oauth2",...t.authConfig?.oauth2?.jwt}}}async function Zt(t){let e=Ft(t),r=Pn(t),{storage:n}=t;return Xt(r,{storage:n,corsConfigSource:e})}var er=require("node:async_hooks");var We=class extends z{},ot=class{#e;#r=!1;#t;#o;constructor(e,r){this.#e=e,this.#t=r}createExchange(e,r){return new ye(e,r)}set storage(e){this.#o=e}set enableLoggingRequestDetails(e){this.#r=e}formatHeaders(e){let r="{";for(let n of e.keys())if(this.#r){let o=e.get(n);r+=`"${n}": "${o}", `}else{r+="masked, ";break}return r.endsWith(", ")&&(r=r.slice(0,-2)),r+="}",r}formatRequest(e){let r=e.URL.search;return`HTTP ${e.method} "${e.path}${r}`}logRequest(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace");this.#e.debug(`${e.logPrefix}${this.formatRequest(e.request)}${r?`, headers: ${this.formatHeaders(e.request.headers)}`:""}"`)}}logResponse(e){if(this.#e.enabledFor("debug")){let r=this.#e.enabledFor("trace"),n=e.response.statusCode;this.#e.debug(`${e.logPrefix}Completed ${n??"200 OK"}${r?`, headers: ${this.formatHeaders(e.response.headers)}`:""}"`)}}handleUnresolvedError(e,r){let{request:n,response:o,logPrefix:s}=e;if(o.setStatusCode(f.INTERNAL_SERVER_ERROR)){this.#e.error(`${s}500 Server Error for ${this.formatRequest(n)}`,r);return}throw this.#e.error(`${s}Error [${r.message} for ${this.formatRequest(n)}, but already ended (${o.statusCode})`,r),r}async web(e){return await this.#t(e)}async http(e,r){let n=this.createExchange(e,r),o=()=>(this.logRequest(n),this.web(n).then(()=>{this.logResponse(n)}).catch(s=>{this.handleUnresolvedError(n,s)}).then(async()=>{await n.response.end()}));await new Promise((s,i)=>{this.#o!==void 0?this.#o.run({exchange:n},()=>{o().then(()=>s()).catch(a=>i(a))}):o().then(()=>s()).catch(a=>i(a))})}},Le=class{#e;#r=new er.AsyncLocalStorage;#t;storage(e){return this.#r=e,this}httpHandlerDecorator(e){if(this.#t===void 0)this.#t=e;else{let r=this.#t;this.#t=n=>(n=r(n),e(n))}return this}constructor(e){this.#e=e}build(){let e=b("http"),r=new ot(e,this.#e);this.#r!==void 0&&(r.storage=this.#r),r.enableLoggingRequestDetails=!1;let n=async(o,s)=>r.http(o,s);return this.#t?this.#t(n):n}};var or=require("ws");function tr(t,e){let r=t?.exchange,n=r?.request??new _(t),o=r?.principal,s=o?o.bind(r):async function(){},i=n.URL,a=new v;for(let g of n.headers.keys())a.set(g,n.headers.list(g));let c=n.cookies,d=r?.logPrefix??`[${n.id}] `,u=n.remoteAddress;return{url:i,headers:a,cookies:c,principal:s,protocol:e,remoteAddress:u,logPrefix:d}}function rr(t){return[async(r,n)=>{let s=r.request.path??"/",i=t.sockets,a=i.get(s)??Array.from(i.values()).find(c=>{if(s==="/"&&c.default===!0)return!0});if(a!==void 0){let{request:c,response:d}=r,u=await D(r);if((c.method==="GET"||c.method==="CONNECT")&&u.match)if(a.upgradeStrategy!==void 0){a.upgradeStrategy(r);return}else throw new Error(`No upgrade strategy defined for route on ${s}`);else{if(a.default){await n();return}d.setStatusCode(f.UPGRADE_REQUIRED),d.headers.set("Upgrade","websocket").set("Connection","Upgrade").set("Content-Type","text/plain");let l=Buffer.from(`This service [${c.path}] requires use of the websocket protocol.`,"utf-8");await d.body(l)}}else await n()}]}var nr=require("ws"),Ie=class extends nr.WebSocket{constructor(e,r,n){super(null,void 0,n)}connected},$e=class t{static#e=Buffer.alloc(0);static#r=[0,Buffer.alloc(8)];#t;#o;#i;#s=!1;#n;constructor(e,r,n){this.#n=e,this.#o=typeof n=="number"?n:n?.interval,this.#t=typeof n=="number"||n?.data==="timestamp"?()=>t.#d(Date.now()):()=>t.#e,this.#o&&(this.#i=setInterval(()=>{let[o,s]=r();for(let i of s)this.#a(i,o)||this.#c(i,o)},this.#o))}#a(e,r){return e.connected===!1?(this.#n.enabledFor("debug")&&this.#n.debug(`terminating unresponsive ws client on [${r}]`),e.terminate(),!0):!1}#c(e,r){e.connected=!1;let n=this.#t();this.#n.enabledFor("trace")&&this.#n.debug(`pinging ws client on [${r}]`),e.ping(n,this.#s,o=>{o&&this.#n.enabledFor("warn")&&this.#n.warn(`failed to ping ws client on [${r}]`,o)})}static#d(e=Date.now()){if(e-t.#r[0]>0){let r=Buffer.allocUnsafe(8);r.writeBigInt64BE(BigInt(e),0),t.#r=[e,r]}return t.#r[1]}static#u(e){return e.length===8?Number(e.readBigInt64BE(0)):0}close(){clearInterval(this.#i)}handlePing(e,r,n){r.connected=!0,r.pong(n,!1,o=>{o&&this.#n.enabledFor("warn")&&this.#n.warn(`${e.logPrefix}failed to pong ws client [${e.remoteAddress?.address}:${e.remoteAddress?.port}]`,o)})}handlePong(e,r,n){if(r.connected=!0,this.#n.enabledFor("warn")){let o=t.#u(n);if(o>0){let s=Date.now()-o;this.#n.enabledFor("debug")&&this.#n.debug(`${e.logPrefix}ws client [${e.remoteAddress?.address}:${e.remoteAddress?.port}] ping-pong latency: ${s}ms`),this.#o&&s>this.#o/2&&this.#n.enabledFor("warn")&&this.#n.warn(`${e.logPrefix}ws client [${e.remoteAddress?.address}:${e.remoteAddress?.port}] high ping-pong latency: ${s}ms`)}}}};var T=b("ws");function Rn(t,e,r,n){return o=>{let{logPrefix:s,request:i}=o,a=ge.getNativeRequest(i);a.exchange=o;let{socket:c,upgradeHead:d}=a,u=i.host;if(c.removeListener("error",n),e.maxConnections!==void 0&&r.clients?.size>=e.maxConnections){T.warn(`${s}dropping ws connection request on ${u}${t}. max connections exceeded.`),c.destroy();return}let l=i.headers.one("origin");if(!Ct(l,e.originFilters)){T.enabledFor("info")&&T.info(`${s}dropping ws connection request on ${u}${t}. origin ${l??"<missing>"}`),c.destroy();return}T.enabledFor("debug")&&T.debug(`${s}accepted new ws connection request on ${u}${t}`),r.handleUpgrade(a,c,d,(g,p)=>{r.emit("connection",g,p)})}}function Tn(t,e){let r=new Set;t.forEach((o,s)=>{if(s===0&&o.startsWith("HTTP/1.1 101 ")){e.setStatusCode(f.SWITCHING_PROTOCOLS);return}let[i,a]=o.split(": ");e.headers.has(i)?t[s]=`${i}: ${e.headers.one(i)}`:e.headers.set(i,a),r.add(i.toLowerCase())});let n=z.getNativeResponse(e);for(let o of n.getRawHeaderNames()){let s=o.toLowerCase();if(!r.has(s)){let i=e.headers.get(s);i!==void 0&&t.push(`${o}: ${i}`)}}n.markHeadersSent()}async function ir(t,e,r,n,o){try{T.info(`creating ws server for [${t}]. max connections: ${e.maxConnections??"<unlimited>"}, origin filters: ${e.originFilters?JSON.stringify(e.originFilters,dt):"<none>"}, ping: ${typeof e.ping=="number"?e.ping+"ms":e.ping?JSON.stringify(e.ping):"<none>"}`);let s=new or.WebSocketServer({noServer:!0,WebSocket:Ie,autoPong:!1}),i=new $e(T.child("pings"),()=>[t,s.clients],e.ping),a=await e.factory({endpoint:r,storage:n});s.on("error",c=>{T.error(`error starting the ws server for [${t}]`,c)}).on("listening",()=>{T.info(`ws server for [${t}] is listening`)}).on("headers",(c,d)=>{if(d.exchange!==void 0){let{response:u}=d.exchange;Tn(c,u)}}).on("connection",(c,d)=>{let u=tr(d,c.protocol);c.on("pong",l=>{i.handlePong(u,c,l)}),c.on("ping",l=>{i.handlePing(u,c,l)}),a({socket:c,handshake:u})}),s.on("close",()=>{i.close()}),e.upgradeStrategy=Rn(t,e,s,o),e.close=async()=>{await a.close?.call(a),T.info(`stopping ws server for [${t}]. clients: ${s.clients?.size??0}`),s.clients?.forEach(c=>{c.terminate()}),s.close()}}catch(s){T.warn(`failed to init route ${t}`,s)}}var O=b("app");function kn(t){let e={};return t.key&&(e.key=(0,Ne.readFileSync)(t.key)),t.cert&&(e.cert=(0,Ne.readFileSync)(t.cert)),t.ca&&(e.ca=(0,Ne.readFileSync)(t.ca)),e}async function On(t,e){let r=t.build();return async(n,o)=>{n.socket.addListener("error",e);let s;o instanceof q?s=o:(n.upgradeHead=o,s=new q(n),s.assignSocket(n.socket));let i=new _(n),a=new fe(s),c=i.method==="HEAD"?new We(a):a;await r(i,c)}}function Mn(t){return new Promise((e,r)=>{let n=t(o=>{o?r(o):e(n)})})}function Wn(t){if(t)return vt({memoryLimit:t.memory_limit,dumpLocation:t.dump_location,dumpPrefix:t.dump_prefix,reportInterval:t.report_interval,maxBackups:t.max_backups})}async function Ln(t){let e=t.storage,r=await Zt(t),n=rr(t),o=pt(Et(t.serverHeader),...r,...n,...t.middleware,async({request:s,response:i},a)=>{if(s.method==="GET"&&s.path==="/health"){i.setStatusCode(f.OK);let c=Buffer.from("UP","utf-8");i.headers.set("Content-Type","text/plain; charset=utf-8"),await i.body(c)}else await a()},async({request:s,response:i},a)=>{if(s.method==="GET"&&s.path==="/"){i.setStatusCode(f.OK);let c=Buffer.from("io.Gateway Server","utf-8");i.headers.set("Content-Type","text/plain; charset=utf-8"),await i.body(c)}else await a()},async({response:s},i)=>{s.setStatusCode(f.NOT_FOUND),await s.end()});return new Le(o).storage(e)}var it=async t=>{let e=t.ssl,r=e?(p,h)=>ar.default.createServer({...p,...kn(e)},h):(p,h)=>sr.default.createServer(p,h),n=Wn(t.memory),o={middleware:[],corsConfig:t.cors,cors:[],authConfig:t.auth,authorize:[],storage:new cr.AsyncLocalStorage,sockets:new Map},s=dr.IOGateway.Factory({...t.gateway});if(t.gateway){let p=t.gateway;await Je(async h=>{h.socket({path:p.route,factory:ht.bind(s),options:p})},t,o)}t.app&&await Je(t.app,t,o);let i=St(t.port??0),a=t.host,c=p=>O.error(`socket error: ${p}`,p),d=await Ln(o),u=await On(d,c),g=await new Promise((p,h)=>{let w=r({IncomingMessage:le,ServerResponse:q,...t.http},u);w.on("error",m=>{if(m.code==="EADDRINUSE"){O.debug(`port ${m.port} already in use on address ${m.address}`);let{value:x}=i.next();x?(O.info(`retry starting server on port ${x} and host ${a??"<unspecified>"}`),w.close(),w.listen(x,a)):(O.warn(`all configured port(s) ${t.port} are in use. closing...`),w.close(),h(m))}else O.error(`server error: ${m.message}`,m),h(m)}),w.on("listening",async()=>{let m=w.address();for(let[x,X]of o.sockets){let B=`${e?"wss":"ws"}://${wt}:${m.port}${x}`;await ir(x,X,B,o.storage,c)}O.info(`http server listening on ${m.address}:${m.port}`),p(w)}),w.on("upgrade",(m,x,X)=>{try{u(m,X)}catch(B){O.error(`upgrade error: ${B}`,B)}}).on("close",async()=>{O.info("http server closed.")});try{let{value:m}=i.next();w.listen(m,a)}catch(m){O.error("error starting web socket server",m),h(m instanceof Error?m:new Error(`listen failed: ${m}`))}});return new class{gateway=s;async close(){for(let[p,h]of o.sockets)try{h.close!==void 0&&await h.close()}catch(w){O.warn(`error closing route ${p}`,w)}await Mn(p=>{g.closeAllConnections(),g.close(p)}),n&&await xt(n),s&&await s.stop()}}};var In=it;0&&(module.exports={GatewayServer});
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|