craby-gateway 0.14.0 → 0.14.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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`node:util`),b=require(`fs`);b=c(b);let x=require(`path`);x=c(x);let S=require(`module`),C=require(`net`),w=require(`child_process`),T=require(`@anthropic-ai/claude-agent-sdk`);var E={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.14.0`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.86`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@openai/codex":`^0.111.0`,"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const D=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function O(e){let t=e.match(D);return t?t[0]:null}function k(e){return typeof e==`string`?O(e):null}function A(e,t){let n=M(e),r=M(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function j(e,t){return A(e,t)>=0}function M(e){let t=e.match(D);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const ee=E,N=ee.dependencies??{};function te(e){return N[e]??``}const P={packageName:`craby-gateway`,cliName:`craby-gateway`,version:ee.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:te(`@anthropic-ai/claude-agent-sdk`),minimumVersion:k(te(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ne(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=re(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function re(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),ie=o((e=>{var t=F();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),I=o((e=>{var t=F(),n=ie();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`node:child_process`),h=require(`node:module`),g=require(`node:url`),_=require(`node:readline`);_=c(_);let v=require(`node:process`);v=c(v);let y=require(`node:util`),b=require(`fs`);b=c(b);let x=require(`path`);x=c(x);let S=require(`module`),C=require(`net`),w=require(`child_process`),T=require(`@anthropic-ai/claude-agent-sdk`);var E={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.14.1`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:bundle":`tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.86`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@openai/codex":`^0.111.0`,"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const D=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function O(e){let t=e.match(D);return t?t[0]:null}function k(e){return typeof e==`string`?O(e):null}function A(e,t){let n=M(e),r=M(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function j(e,t){return A(e,t)>=0}function M(e){let t=e.match(D);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const ee=E,N=ee.dependencies??{};function te(e){return N[e]??``}const P={packageName:`craby-gateway`,cliName:`craby-gateway`,version:ee.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:te(`@anthropic-ai/claude-agent-sdk`),minimumVersion:k(te(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ne(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=re(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function re(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var F=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),ie=o((e=>{var t=F();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),I=o((e=>{var t=F(),n=ie();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
3
3
  `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),ae=o((e=>{var t=F(),n=ie();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),oe=o((e=>{function t(e,n,r,i){if(i&&typeof i==`object`)if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return e.call(n,r,i)}e.applyReviver=t})),L=o((e=>{var t=F();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),se=o((e=>{var t=oe(),n=F(),r=L();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),ce=o((e=>{var t=ae(),n=ie(),r=F(),i=se(),a=L(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),le=o((e=>{var t=F(),n=se(),r=L();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ue=o((e=>{var t=ce(),n=F(),r=le();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??=c(e),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),de=o((e=>{var t=ue(),n=F(),r=se();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),fe=o((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
4
4
  `)?n(r,t):r.includes(`
5
5
  `)?`
@@ -120,20 +120,20 @@ function nr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.construc
120
120
  `)}const Ac={readInstalledPackageVersion:Mc,readSystemToolVersion:Nc};function jc(e,t){let n=e.minimumVersion,r=e.dependencyName?t.readInstalledPackageVersion(e.dependencyName):null,i=t.readSystemToolVersion(e.systemCommand,e.versionArgs),a=e.dependencyName?`ok`:null,o=`ok`,s=[];return e.dependencyName&&(r?n&&!j(r,n)&&(a=`fail`,s.push(`Bundled dependency ${r} is below required ${n}.`)):(a=`fail`,s.push(`Bundled dependency ${e.dependencyName} could not be resolved.`))),i?n&&!j(i,n)&&(o=e.systemCommandRequired?`fail`:`warn`,s.push(`System ${e.displayName} version ${i} is below required ${n}.`)):(o=e.systemCommandRequired?`fail`:`warn`,s.push(`System command \`${e.systemCommand}\` is not available.`)),{id:e.id,displayName:e.displayName,dependencyName:e.dependencyName,dependencyRange:e.dependencyRange,minimumVersion:n,bundledDependencyVersion:r,systemCommand:e.systemCommand,systemToolVersion:i,bundledStatus:a,systemStatus:o,notes:s}}function Mc(e){try{let t=Fc(e);if(!t)return null;let n=u.default.readFileSync(t,`utf8`),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}function Nc(e,t){try{let n=(0,m.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0});if(n.error)return null;let r=`${n.stdout??``}\n${n.stderr??``}`.trim();return r?O(r):null}catch{return null}}function Pc(e){return e??`missing`}function Fc(e){try{return Tc.resolve(`${e}/package.json`)}catch{}try{let t=Tc.resolve(e),n=u.default.statSync(t).isDirectory()?t:u.default.realpathSync(p.default.dirname(t));for(;;){let t=p.default.join(n,`package.json`);if(u.default.existsSync(t)){let n=u.default.readFileSync(t,`utf8`);if(JSON.parse(n).name===e)return t}let r=p.default.dirname(n);if(r===n)return null;n=r}}catch{}for(let t of[p.default.dirname(Ec),process.cwd()]){let n=Ic(t,e);if(n)return n}return null}function Ic(e,t){let n=e,r=t.split(`/`);for(;;){let e=p.default.join(n,`node_modules`,...r,`package.json`);if(u.default.existsSync(e))return e;let t=p.default.dirname(n);if(t===n)return null;n=t}}function Lc(e,t){let n=[e];return t.configPath&&n.push(`--config`,t.configPath),t.logToConsole&&n.push(`--log`),n}function Rc(e,t,n){let r=Lc(t,n);return e.scriptPath?{command:e.execPath,args:[...e.execArgv,e.scriptPath,...r],cwd:e.cwd}:{command:e.execPath,args:r,cwd:e.cwd}}function zc(e,t,n,r){if(!e.binPath)throw Error(`gateway launch command is unavailable`);return{command:e.binPath,args:Lc(t,n),cwd:r}}var Bc=o(((e,t)=>{t.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}})),Vc=o(((e,t)=>{var n=Bc();function r(e){this.mode=n.MODE_8BIT_BYTE,this.data=e}r.prototype={getLength:function(){return this.data.length},write:function(e){for(var t=0;t<this.data.length;t++)e.put(this.data.charCodeAt(t),8)}},t.exports=r})),Hc=o(((e,t)=>{for(var n={glog:function(e){if(e<1)throw Error(`glog(`+e+`)`);return n.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return n.EXP_TABLE[e]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)},r=0;r<8;r++)n.EXP_TABLE[r]=1<<r;for(var r=8;r<256;r++)n.EXP_TABLE[r]=n.EXP_TABLE[r-4]^n.EXP_TABLE[r-5]^n.EXP_TABLE[r-6]^n.EXP_TABLE[r-8];for(var r=0;r<255;r++)n.LOG_TABLE[n.EXP_TABLE[r]]=r;t.exports=n})),Uc=o(((e,t)=>{var n=Hc();function r(e,t){if(e.length===void 0)throw Error(e.length+`/`+t);for(var n=0;n<e.length&&e[n]===0;)n++;this.num=Array(e.length-n+t);for(var r=0;r<e.length-n;r++)this.num[r]=e[r+n]}r.prototype={get:function(e){return this.num[e]},getLength:function(){return this.num.length},multiply:function(e){for(var t=Array(this.getLength()+e.getLength()-1),i=0;i<this.getLength();i++)for(var a=0;a<e.getLength();a++)t[i+a]^=n.gexp(n.glog(this.get(i))+n.glog(e.get(a)));return new r(t,0)},mod:function(e){if(this.getLength()-e.getLength()<0)return this;for(var t=n.glog(this.get(0))-n.glog(e.get(0)),i=Array(this.getLength()),a=0;a<this.getLength();a++)i[a]=this.get(a);for(var o=0;o<e.getLength();o++)i[o]^=n.gexp(n.glog(e.get(o))+t);return new r(i,0).mod(e)}},t.exports=r})),Wc=o(((e,t)=>{t.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}})),Gc=o(((e,t)=>{var n=Bc(),r=Uc(),i=Hc(),a=Wc(),o={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(e){for(var t=e<<10;o.getBCHDigit(t)-o.getBCHDigit(o.G15)>=0;)t^=o.G15<<o.getBCHDigit(t)-o.getBCHDigit(o.G15);return(e<<10|t)^o.G15_MASK},getBCHTypeNumber:function(e){for(var t=e<<12;o.getBCHDigit(t)-o.getBCHDigit(o.G18)>=0;)t^=o.G18<<o.getBCHDigit(t)-o.getBCHDigit(o.G18);return e<<12|t},getBCHDigit:function(e){for(var t=0;e!==0;)t++,e>>>=1;return t},getPatternPosition:function(e){return o.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case a.PATTERN000:return(t+n)%2==0;case a.PATTERN001:return t%2==0;case a.PATTERN010:return n%3==0;case a.PATTERN011:return(t+n)%3==0;case a.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case a.PATTERN101:return t*n%2+t*n%3==0;case a.PATTERN110:return(t*n%2+t*n%3)%2==0;case a.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw Error(`bad maskPattern:`+e)}},getErrorCorrectPolynomial:function(e){for(var t=new r([1],0),n=0;n<e;n++)t=t.multiply(new r([1,i.gexp(n)],0));return t},getLengthInBits:function(e,t){if(1<=t&&t<10)switch(e){case n.MODE_NUMBER:return 10;case n.MODE_ALPHA_NUM:return 9;case n.MODE_8BIT_BYTE:return 8;case n.MODE_KANJI:return 8;default:throw Error(`mode:`+e)}else if(t<27)switch(e){case n.MODE_NUMBER:return 12;case n.MODE_ALPHA_NUM:return 11;case n.MODE_8BIT_BYTE:return 16;case n.MODE_KANJI:return 10;default:throw Error(`mode:`+e)}else if(t<41)switch(e){case n.MODE_NUMBER:return 14;case n.MODE_ALPHA_NUM:return 13;case n.MODE_8BIT_BYTE:return 16;case n.MODE_KANJI:return 12;default:throw Error(`mode:`+e)}else throw Error(`type:`+t)},getLostPoint:function(e){var t=e.getModuleCount(),n=0,r=0,i=0;for(r=0;r<t;r++)for(i=0;i<t;i++){for(var a=0,o=e.isDark(r,i),s=-1;s<=1;s++)if(!(r+s<0||t<=r+s))for(var c=-1;c<=1;c++)i+c<0||t<=i+c||s===0&&c===0||o===e.isDark(r+s,i+c)&&a++;a>5&&(n+=3+a-5)}for(r=0;r<t-1;r++)for(i=0;i<t-1;i++){var l=0;e.isDark(r,i)&&l++,e.isDark(r+1,i)&&l++,e.isDark(r,i+1)&&l++,e.isDark(r+1,i+1)&&l++,(l===0||l===4)&&(n+=3)}for(r=0;r<t;r++)for(i=0;i<t-6;i++)e.isDark(r,i)&&!e.isDark(r,i+1)&&e.isDark(r,i+2)&&e.isDark(r,i+3)&&e.isDark(r,i+4)&&!e.isDark(r,i+5)&&e.isDark(r,i+6)&&(n+=40);for(i=0;i<t;i++)for(r=0;r<t-6;r++)e.isDark(r,i)&&!e.isDark(r+1,i)&&e.isDark(r+2,i)&&e.isDark(r+3,i)&&e.isDark(r+4,i)&&!e.isDark(r+5,i)&&e.isDark(r+6,i)&&(n+=40);var u=0;for(i=0;i<t;i++)for(r=0;r<t;r++)e.isDark(r,i)&&u++;var d=Math.abs(100*u/t/t-50)/5;return n+=d*10,n}};t.exports=o})),Kc=o(((e,t)=>{t.exports={L:1,M:0,Q:3,H:2}})),qc=o(((e,t)=>{var n=Kc();function r(e,t){this.totalCount=e,this.dataCount=t}r.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],r.getRSBlocks=function(e,t){var n=r.getRsBlockTable(e,t);if(n===void 0)throw Error(`bad rs block @ typeNumber:`+e+`/errorCorrectLevel:`+t);for(var i=n.length/3,a=[],o=0;o<i;o++)for(var s=n[o*3+0],c=n[o*3+1],l=n[o*3+2],u=0;u<s;u++)a.push(new r(c,l));return a},r.getRsBlockTable=function(e,t){switch(t){case n.L:return r.RS_BLOCK_TABLE[(e-1)*4+0];case n.M:return r.RS_BLOCK_TABLE[(e-1)*4+1];case n.Q:return r.RS_BLOCK_TABLE[(e-1)*4+2];case n.H:return r.RS_BLOCK_TABLE[(e-1)*4+3];default:return}},t.exports=r})),Jc=o(((e,t)=>{function n(){this.buffer=[],this.length=0}n.prototype={get:function(e){var t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)==1},put:function(e,t){for(var n=0;n<t;n++)this.putBit((e>>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},t.exports=n})),Yc=c(o(((e,t)=>{var n=Vc(),r=Gc(),i=Uc(),a=qc(),o=Jc();function s(e,t){this.typeNumber=e,this.errorCorrectLevel=t,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}s.prototype={addData:function(e){var t=new n(e);this.dataList.push(t),this.dataCache=null},isDark:function(e,t){if(e<0||this.moduleCount<=e||t<0||this.moduleCount<=t)throw Error(e+`,`+t);return this.modules[e][t]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var e=1;for(e=1;e<40;e++){for(var t=a.getRSBlocks(e,this.errorCorrectLevel),n=new o,i=0,s=0;s<t.length;s++)i+=t[s].dataCount;for(var c=0;c<this.dataList.length;c++){var l=this.dataList[c];n.put(l.mode,4),n.put(l.getLength(),r.getLengthInBits(l.mode,e)),l.write(n)}if(n.getLengthInBits()<=i*8)break}this.typeNumber=e}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(e,t){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var n=0;n<this.moduleCount;n++){this.modules[n]=Array(this.moduleCount);for(var r=0;r<this.moduleCount;r++)this.modules[n][r]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(e,t),this.typeNumber>=7&&this.setupTypeNumber(e),this.dataCache===null&&(this.dataCache=s.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)},setupPositionProbePattern:function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r===0||r===6)||0<=r&&r<=6&&(n===0||n===6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)},getBestMaskPattern:function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var i=r.getLostPoint(this);(n===0||e>i)&&(e=i,t=n)}return t},createMovieClip:function(e,t,n){var r=e.createEmptyMovieClip(t,n),i=1;this.make();for(var a=0;a<this.modules.length;a++)for(var o=a*i,s=0;s<this.modules[a].length;s++){var c=s*i;this.modules[a][s]&&(r.beginFill(0,100),r.moveTo(c,o),r.lineTo(c+i,o),r.lineTo(c+i,o+i),r.lineTo(c,o+i),r.endFill())}return r},setupTimingPattern:function(){for(var e=8;e<this.moduleCount-8;e++)this.modules[e][6]===null&&(this.modules[e][6]=e%2==0);for(var t=8;t<this.moduleCount-8;t++)this.modules[6][t]===null&&(this.modules[6][t]=t%2==0)},setupPositionAdjustPattern:function(){for(var e=r.getPatternPosition(this.typeNumber),t=0;t<e.length;t++)for(var n=0;n<e.length;n++){var i=e[t],a=e[n];if(this.modules[i][a]===null)for(var o=-2;o<=2;o++)for(var s=-2;s<=2;s++)Math.abs(o)===2||Math.abs(s)===2||o===0&&s===0?this.modules[i+o][a+s]=!0:this.modules[i+o][a+s]=!1}},setupTypeNumber:function(e){for(var t=r.getBCHTypeNumber(this.typeNumber),n,i=0;i<18;i++)n=!e&&(t>>i&1)==1,this.modules[Math.floor(i/3)][i%3+this.moduleCount-8-3]=n;for(var a=0;a<18;a++)n=!e&&(t>>a&1)==1,this.modules[a%3+this.moduleCount-8-3][Math.floor(a/3)]=n},setupTypeInfo:function(e,t){for(var n=this.errorCorrectLevel<<3|t,i=r.getBCHTypeInfo(n),a,o=0;o<15;o++)a=!e&&(i>>o&1)==1,o<6?this.modules[o][8]=a:o<8?this.modules[o+1][8]=a:this.modules[this.moduleCount-15+o][8]=a;for(var s=0;s<15;s++)a=!e&&(i>>s&1)==1,s<8?this.modules[8][this.moduleCount-s-1]=a:s<9?this.modules[8][15-s-1+1]=a:this.modules[8][15-s-1]=a;this.modules[this.moduleCount-8][8]=!e},mapData:function(e,t){for(var n=-1,i=this.moduleCount-1,a=7,o=0,s=this.moduleCount-1;s>0;s-=2)for(s===6&&s--;;){for(var c=0;c<2;c++)if(this.modules[i][s-c]===null){var l=!1;o<e.length&&(l=(e[o]>>>a&1)==1),r.getMask(t,i,s-c)&&(l=!l),this.modules[i][s-c]=l,a--,a===-1&&(o++,a=7)}if(i+=n,i<0||this.moduleCount<=i){i-=n,n=-n;break}}}},s.PAD0=236,s.PAD1=17,s.createData=function(e,t,n){for(var i=a.getRSBlocks(e,t),c=new o,l=0;l<n.length;l++){var u=n[l];c.put(u.mode,4),c.put(u.getLength(),r.getLengthInBits(u.mode,e)),u.write(c)}for(var d=0,f=0;f<i.length;f++)d+=i[f].dataCount;if(c.getLengthInBits()>d*8)throw Error(`code length overflow. (`+c.getLengthInBits()+`>`+d*8+`)`);for(c.getLengthInBits()+4<=d*8&&c.put(0,4);c.getLengthInBits()%8!=0;)c.putBit(!1);for(;!(c.getLengthInBits()>=d*8||(c.put(s.PAD0,8),c.getLengthInBits()>=d*8));)c.put(s.PAD1,8);return s.createBytes(c,i)},s.createBytes=function(e,t){for(var n=0,a=0,o=0,s=Array(t.length),c=Array(t.length),l=0;l<t.length;l++){var u=t[l].dataCount,d=t[l].totalCount-u;a=Math.max(a,u),o=Math.max(o,d),s[l]=Array(u);for(var f=0;f<s[l].length;f++)s[l][f]=255&e.buffer[f+n];n+=u;var p=r.getErrorCorrectPolynomial(d),m=new i(s[l],p.getLength()-1).mod(p);c[l]=Array(p.getLength()-1);for(var h=0;h<c[l].length;h++){var g=h+m.getLength()-c[l].length;c[l][h]=g>=0?m.get(g):0}}for(var _=0,v=0;v<t.length;v++)_+=t[v].totalCount;for(var y=Array(_),b=0,x=0;x<a;x++)for(var S=0;S<t.length;S++)x<s[S].length&&(y[b++]=s[S][x]);for(var C=0;C<o;C++)for(var w=0;w<t.length;w++)C<c[w].length&&(y[b++]=c[w][C]);return y},t.exports=s}))(),1),Xc=c(Kc(),1);const Zc={renderQr:tl};function Qc(e){return vo.parse({v:1,gw:lo(e.gatewayId),relay:e.relayBaseUrl,direct:e.bootstrapDirectBaseUrl,pc:e.pairingCode,pkf:ys(e.gatewayIdentityPublicKey)})}function $c(e){return _o.parse({v:1,gw:lo(e.gatewayId),name:e.machineName,relay:e.relayBaseUrl,direct:e.directBaseUrls,gatewayIdentity:e.gatewayIdentity})}function el(e,t=Zc){let n=JSON.stringify(e.descriptor),r=Buffer.from(n,`utf8`).toString(`base64`),i=t.renderQr(n);return[`[gateway] pairing code ${e.descriptor.pc} (expires ${e.expiresAt})`,`[gateway] connection descriptor bundle:`,`[gateway] this descriptor is short-lived; refresh it after pairing succeeds or when it expires.`,`[gateway] raw descriptor JSON:`,n,`[gateway] descriptor base64:`,r,`[gateway] scan this QR from the mobile app:`,i,`[gateway] fallback: if scanning fails, paste the raw descriptor JSON or descriptor base64 into mobile pairing.`].join(`
121
121
  `)}function tl(e){let t=new Yc.default(-1,Xc.default.L);t.addData(e),t.make();let n=t.getModuleCount(),r=t.modules.slice(),i=[];for(let e=-2;e<n+2;e+=2){let t=``;for(let i=-2;i<n+2;i+=1){let a=nl(r,n,e,i,!0,!1),o=nl(r,n,e+1,i,!0,!1);t+=rl(a,o)}i.push(t)}return i.join(`
122
122
  `)}function nl(e,t,n,r,i,a){return n<0||n>=t||r<0||r>=t?a:e[n]?.[r]===i}function rl(e,t){return`\u001b[${e?30:37};${t?40:47}m\u2580\u001b[0m`}function il(){return f.default.hostname()}const al={networkInterfaces:()=>f.default.networkInterfaces()};function ol(e,t=al){if(!sl(e))return[e];let n=new Set([`127.0.0.1`]);for(let e of Object.values(t.networkInterfaces()))for(let t of e??[])t.internal||!cl(t.family)||n.add(t.address);return[...n]}function sl(e){return e===`0.0.0.0`||e===`::`||e===`[::]`}function cl(e){return e===`IPv4`||e===4}const ll={listGatewayListenHosts:ol,renderQr:tl};function ul(e,t=ll){return t.listGatewayListenHosts(e.host).map(t=>`${e.protocol}://${hl(t)}:${e.port}`)}function dl(e){return e.find(e=>!gl(e))??e[0]??``}function fl(e,t=ll){let n=e.relayUrl.trim();if(!n)return``;let r;try{r=new URL(n)}catch{return n}if(!_l(r.hostname))return n;let i=t.listGatewayListenHosts(e.gatewayHost).find(e=>!_l(e));return i?(r.hostname=i,r.toString().replace(/\/$/,``)):n}function pl(e,t=ll){let n=[];e.createdDefaultConfig&&n.push(`[gateway] created default config at ${e.configPath}`),n.push(`[gateway] log file ${e.config.gatewayLogPath}${e.logToConsole?` (console logging enabled)`:``}`),n.push(`[gateway] gatewayId ${e.config.gatewayId}`),n.push(`[gateway] machine ${e.startedServer.machineName}`),n.push(e.config.relayEnabled?`[gateway] relay enabled: ${fl({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t)}`:`[gateway] relay disabled`),n.push(`[gateway] available URLs:`);let r=ul({protocol:e.startedServer.protocol,host:e.config.host,port:e.startedServer.listenPort},t);for(let e of r)n.push(` ${e}`);return e.startedServer.startupPairingCode&&n.push(el({descriptor:Qc({gatewayId:e.config.gatewayId,bootstrapDirectBaseUrl:dl(r),pairingCode:e.startedServer.startupPairingCode.code,gatewayIdentityPublicKey:e.startedServer.gatewayIdentity.publicKey,relayBaseUrl:e.config.relayEnabled?fl({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t):void 0}),expiresAt:e.startedServer.startupPairingCode.expiresAt},{renderQr:t.renderQr??tl})),n.push(...ml(e.doctorReport)),n.join(`
123
- `)}function ml(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function hl(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function gl(e){try{let t=new URL(e).hostname;return _l(t)}catch{return!1}}function _l(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const vl={platform:v.default.platform,now:()=>new Date,currentContext:()=>({pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}),runCommand:(e,t,n={})=>{let r=(0,m.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0,...n});return{status:r.status,stdout:typeof r.stdout==`string`?r.stdout:r.stdout?.toString(`utf8`)??``,stderr:typeof r.stderr==`string`?r.stderr:r.stderr?.toString(`utf8`)??``,...r.error?{error:r.error}:{}}}};function yl(){return p.default.join(nc(),`update-state.json`)}function bl(e){return Fa.parse({type:`gateway.update.status`,payload:e})}var xl=class{packageName;currentVersion;sessionHub;logger;consoleWrite;getRunningSessionCount;requestPreparedUpdate;stateFilePath;checkIntervalMs;runtime;state;scheduledCheckTimer=null;recurringCheckTimer=null;checkPromise=null;applyPromise=null;constructor(e){this.packageName=e.packageName,this.currentVersion=e.currentVersion,this.sessionHub=e.sessionHub,this.logger=e.logger,this.consoleWrite=e.consoleWrite,this.getRunningSessionCount=e.getRunningSessionCount,this.requestPreparedUpdate=e.requestPreparedUpdate,this.stateFilePath=e.stateFilePath??yl(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??vl,this.state=Pa.parse({packageName:this.packageName,currentVersion:this.currentVersion,available:!1,canApply:!1,status:`unknown`,install:{manager:`unknown`,installType:`unknown`,packageName:this.packageName,canSelfUpdate:!1}})}async start(){await this.reconcilePersistedState(),this.scheduledCheckTimer=setTimeout(()=>{this.checkForUpdates(`system`),this.scheduleRecurringChecks()},5e3)}async shutdown(){this.scheduledCheckTimer&&=(clearTimeout(this.scheduledCheckTimer),null),this.recurringCheckTimer&&=(clearInterval(this.recurringCheckTimer),null)}getInfo(){return Pa.parse(this.state)}async getOrCheckInfo(e){if(this.checkPromise)return this.checkPromise;let t=this.getInfo();return t.status===`unknown`||t.status===`failed`?this.checkForUpdates(e):t}async checkForUpdates(e){return this.checkPromise||=(async()=>{let t=this.runtime.now().toISOString(),n=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=wl(this.packageName,this.runtime);if(!r)return this.patchState({status:`failed`,available:!1,canApply:!1,latestVersion:void 0,checkedAt:t,install:n,lastError:`failed to query latest published gateway version`}),this.getInfo();let i=A(r,this.currentVersion)>0,a=i&&n.canSelfUpdate,o=i?a?`available`:`unsupported_install`:`up_to_date`;if(this.patchState({status:o,latestVersion:r,available:i,canApply:a,checkedAt:t,install:n,job:void 0,lastError:void 0}),i&&e!==`mobile`){let e=a?`[gateway] update available ${this.currentVersion} -> ${r}. Type update and press Enter to install and restart.`:`[gateway] update available ${this.currentVersion} -> ${r}, but this installation cannot self-update (${n.reason??`unsupported install`}).`;this.consoleWrite?.(e)}else e===`console`&&this.consoleWrite?.(`[gateway] already up to date at ${this.currentVersion}`);return this.getInfo()})().finally(()=>{this.checkPromise=null}),this.checkPromise}async applyUpdate(e){return this.applyPromise||=(async()=>{let t=await this.checkForUpdates(e);if(!t.available)throw Error(`gateway is already up to date`);if(!t.canApply||t.install.manager===`unknown`)throw Error(t.install.reason??`gateway installation does not support self-update`);if(t.status===`updating`||t.status===`restarting`)return Ia.parse({started:!1,update:t});let n=await this.getRunningSessionCount();if(n>0)throw Error(`gateway update requires idle runtime, found ${n} running session${n===1?``:`s`}`);let r=t.latestVersion;if(!r)throw Error(`latest gateway version is unknown`);let i=this.runtime.currentContext(),a={id:`gwupd_${Date.now()}`,targetVersion:r,requestedBy:e,requestedAt:this.runtime.now().toISOString(),startedAt:this.runtime.now().toISOString()},o={version:1,update:{...t,status:`updating`,job:a,lastError:void 0},helper:{manager:t.install.manager,packageName:this.packageName,targetVersion:r,originalPid:i.pid,restart:Pl(t.install,{cwd:i.cwd,argv:[...i.argv]}),requestedBy:e,requestedAt:a.requestedAt}},s=o.helper;if(!s)throw Error(`gateway update helper state was not prepared`);await Il(this.stateFilePath,o),this.patchState({status:`updating`,job:a,lastError:void 0}),this.consoleWrite?.(`[gateway] updating ${this.packageName} to ${r} via ${t.install.manager}; gateway will restart automatically.`),this.patchState({status:`restarting`,job:a}),this.logger.info?.({job:a,stateFilePath:this.stateFilePath,originalPid:i.pid,install:t.install,restart:s.restart},`gateway update handoff prepared`);try{await this.requestPreparedUpdate?.({stateFilePath:this.stateFilePath,targetVersion:r,requestedBy:e})}catch(e){let t=Pa.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await Il(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(bl(t)),e}return Ia.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=Pa.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(bl(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await Fl(this.stateFilePath);if(!e)return;let t=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime}),n=e.helper?.targetVersion??e.update.job?.targetVersion;if((e.update.status===`updating`||e.update.status===`restarting`)&&n){let r=A(this.currentVersion,n)>=0,i=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,latestVersion:r?this.currentVersion:n,available:!r,canApply:!r&&t.canSelfUpdate,status:r?`up_to_date`:`failed`,checkedAt:this.runtime.now().toISOString(),install:t,job:void 0,...r?{lastError:void 0}:{lastError:e.update.lastError??`gateway restarted before update completed`}});await Il(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Sl(e,t={}){let n=t.runtime??vl,r=t.waitForProcessExit??Ll,i=t.logger,a=await Fl(e);if(!a?.helper)throw Error(`gateway update helper state is missing`);i?.info?.({stateFilePath:e,originalPid:a.helper.originalPid,packageName:a.helper.packageName,targetVersion:a.helper.targetVersion,manager:a.helper.manager,cwd:a.helper.restart.cwd},`gateway update apply starting`);let o=Date.now();await r(a.helper.originalPid);let s=Date.now()-o,c=Rl(a.helper.originalPid);i?.[c?`warn`:`info`]?.({stateFilePath:e,originalPid:a.helper.originalPid,waitDurationMs:s,processStillRunning:c},c?`gateway update original process still running after wait window`:`gateway update original process exited`);let l=Cl(a.helper.manager,a.helper.packageName,a.helper.targetVersion);i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd},`gateway update install starting`);let u=Date.now(),d=n.runCommand(l.command,l.args,{cwd:a.helper.restart.cwd}),f=Date.now()-u;if(d.status!==0){let t={...a,update:{...a.update,status:`failed`,lastError:Bl(l.command,l.args,d)},helper:void 0};return await Il(e,t),i?.error?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status,error:d.error?.message,stderr:d.stderr.trim()||void 0,stdout:d.stdout.trim()||void 0},`gateway update install failed`),{updated:!1,update:Pa.parse(t.update)}}i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status},`gateway update install completed`);let p={...a,update:{...a.update,status:`restarting`,lastError:void 0},helper:void 0};return await Il(e,p),i?.info?.({stateFilePath:e,targetVersion:a.helper.targetVersion},`gateway update apply completed; worker restart may proceed`),{updated:!0,update:Pa.parse(p.update)}}function Cl(e,t,n){switch(e){case`npm`:return{command:`npm`,args:[`install`,`-g`,`${t}@${n}`]};case`pnpm`:return{command:`pnpm`,args:[`add`,`-g`,`${t}@${n}`]};case`yarn`:return{command:`yarn`,args:[`global`,`add`,`${t}@${n}`]}}}function wl(e,t){let n=t.runCommand(`npm`,[`view`,e,`version`,`--json`]);if(n.error||n.status!==0)return null;let r=n.stdout.trim();if(!r)return null;try{let e=JSON.parse(r);return typeof e==`string`&&e.trim()?e.trim():null}catch{return r.replace(/^"+|"+$/g,``)}}function Tl(e){let t=kl(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?Ma.parse({manager:`unknown`,installType:`dev_workspace`,packageName:e.packageName,packageRoot:t.packageRoot,canSelfUpdate:!1,reason:`workspace/development runtime does not support self-update`}):e.currentScriptPath?El(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Dl(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ol(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ma.parse({manager:`unknown`,installType:t.packageName===e.packageName?`unknown`:`standalone_binary`,packageName:e.packageName,...t.packageRoot?{packageRoot:t.packageRoot}:{},canSelfUpdate:!1,reason:t.packageName===e.packageName?`unable to determine global package manager installation`:`gateway is not running from a supported package-manager installation`}):Ma.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function El(e,t,n,r){let i=r.runCommand(`npm`,[`root`,`-g`]),a=r.runCommand(`npm`,[`prefix`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=jl(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),Nl(r.platform)),m=Ml(l,d)?`global_registry`:`global_file`;return Ma.parse({manager:`npm`,installType:m,packageName:e,packageRoot:l,binPath:f,canSelfUpdate:m===`global_registry`,...m===`global_registry`?{}:{reason:`npm file-linked global install is not supported`}})}function Dl(e,t,n,r){let i=r.runCommand(`pnpm`,[`root`,`-g`]),a=r.runCommand(`pnpm`,[`bin`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=Ml(l,jl(p.default.dirname(o)))?`global_registry`:`global_file`;return Ma.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Ol(e,t,n,r){let i=r.runCommand(`yarn`,[`global`,`dir`]),a=r.runCommand(`yarn`,[`global`,`bin`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,`node_modules`,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);return Al(l,t,n)?Ma.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:!0}):null}function kl(e){if(!e)return{packageRoot:null,packageName:null};let t=p.default.dirname(e);for(;;){let e=p.default.join(t,`package.json`);if(u.default.existsSync(e))try{let n=JSON.parse(u.default.readFileSync(e,`utf8`));if(typeof n.name==`string`)return{packageRoot:t,packageName:n.name}}catch{return{packageRoot:t,packageName:null}}let n=p.default.dirname(t);if(n===t)return{packageRoot:null,packageName:null};t=n}}function Al(e,t,n){let r=jl(e),i=t?jl(t):null,a=jl(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function jl(e){try{return u.default.realpathSync(e)}catch{return e}}function Ml(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function Nl(e=v.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function Pl(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function Fl(e){try{let t=await d.default.readFile(e,`utf8`);return Vl(JSON.parse(t))}catch{return null}}async function Il(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0}),await d.default.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}async function Ll(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!Rl(e))return;await zl(500)}}function Rl(e){try{return v.default.kill(e,0),!0}catch{return!1}}function zl(e){return new Promise(t=>setTimeout(t,e))}function Bl(e,t,n){let r=n.stderr.trim(),i=n.stdout.trim(),a=r||i||n.error?.message||`exit code ${String(n.status)}`;return`${e} ${t.join(` `)} failed: ${a}`}function Vl(e){if(!Wl(e)||e.version!==1)return null;let t=Pa.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=Hl(e.helper);return n?{version:1,update:t.data,helper:n}:null}function Hl(e){if(!Wl(e))return null;let t=ka.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=ja.safeParse(e.requestedBy);if(!n.success||!Gl(e.packageName)||!Gl(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!Kl(e.requestedAt))return null;let r=Ul(e.restart);return r?{manager:t.data,packageName:e.packageName,targetVersion:e.targetVersion,originalPid:e.originalPid,restart:r,requestedBy:n.data,requestedAt:e.requestedAt}:null}function Ul(e){return!Wl(e)||!Gl(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!Gl(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function Wl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gl(e){return typeof e==`string`&&e.trim().length>0}function Kl(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}async function ql(e){let t=Yl(),n=Ql(e.loaded.config.gatewayLogPath),r=new Map,i=0,a=null,o=!1,s=null,c=!1,l=null,u=null,d=null,f=null,p=0,h=Rc(t,`__worker`,e.args),g=new Promise((e,t)=>{s=e}),_=()=>{d&&=(clearTimeout(d),null)},y=()=>{f&&=(clearTimeout(f),null)},b=()=>{u&&=(clearTimeout(u),null)},x=Jl({enabled:v.default.stdin.isTTY&&v.default.stdout.isTTY,onUpdate:async()=>{if(!(!a||c))try{let e=await A(`console`);if(e.started){console.log(`[gateway] update accepted; restarting into ${e.update.job?.targetVersion??`latest`}...`);return}console.log(`[gateway] update already ${e.update.status}`)}catch(e){console.error(`[gateway] update failed: ${String(e)}`)}},onRestartCodex:async()=>{if(!(!a||c))try{let e=await j(`console`);console.log(`[gateway] codex app-server restarted; closed ${e.closedRuntimeSessionCount} runtime session${e.closedRuntimeSessionCount===1?``:`s`}.`)}catch(e){console.error(`[gateway] codex app-server restart failed: ${String(e)}`)}}}),S=e=>{for(let t of r.values())t.reject(e);r.clear()},C=e=>{b(),_(),y(),x(),S(Error(`gateway supervisor shutting down`)),n.close(),v.default.exit(e)},w=(e,t)=>{if(c||l||f)return;p+=1;let r=Math.min(p-1,4),i=Math.min(15e3,1e3*2**r);n.warn({...t,reason:e,delayMs:i,restartAttempt:p,invocation:h,initialReadyReceived:o},`gateway supervisor scheduling worker restart`),console.error(`[gateway] worker exited unexpectedly; restarting in ${i}ms (attempt ${p}).`),f=setTimeout(()=>{f=null,k(h)},i)},T=e=>{if(a){n.info({reason:e,workerPid:a.pid??void 0,preparedUpdate:l},`gateway supervisor requested worker shutdown`);try{a.send?.({type:`supervisor.shutdown`,reason:e})}catch(t){n.warn({reason:e,workerPid:a.pid??void 0,error:t},`gateway supervisor failed to send graceful shutdown message; sending SIGTERM`),a.kill(`SIGTERM`)}_(),d=setTimeout(()=>{a?.kill(`SIGTERM`)},1e4)}},E=async r=>{n.info(r,`gateway supervisor continuing prepared update`),console.log(`[gateway] applying update to ${r.targetVersion}...`);let i=await Sl(r.stateFilePath,{logger:n}),a=i.updated&&i.update.install.binPath?zc(i.update.install,`__worker`,e.args,t.cwd):Rc(t,`__worker`,e.args);n.info({updated:i.updated,update:i.update,nextInvocation:a},`gateway supervisor prepared next worker invocation`),!i.updated&&i.update.lastError&&console.error(`[gateway] update failed: ${i.update.lastError}`),i.updated?console.log(`[gateway] update installed; restarting worker...`):console.log(`[gateway] relaunching current worker after failed update.`),l=null,h=a,k(a)},D=(e,t)=>{if(_(),b(),n.info({workerPid:a?.pid??void 0,code:e,signal:t,preparedUpdate:l,shuttingDown:c},`gateway supervisor observed worker exit`),a=null,l){S(Error(`gateway worker restarting for update`)),E(l).catch(e=>{n.error({error:e,preparedUpdate:l},`gateway update handoff failed`),console.error(`[gateway] update handoff failed: ${String(e)}`),C(1)});return}if(c){C(0);return}S(Error(`gateway worker exited`)),t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),w(`worker_exit`,{code:e,signal:t})},O=t=>{switch(t.type){case`worker.ready`:if(p=0,y(),!o){o=!0,n.info(t.payload,`gateway supervisor received initial worker ready`),console.log(pl({configPath:e.loaded.configPath,createdDefaultConfig:e.loaded.createdDefaultConfig,config:e.loaded.config,doctorReport:e.doctorReport,startedServer:t.payload,logToConsole:e.args.logToConsole})),s?.(),s=null;return}n.info(t.payload,`gateway supervisor received worker ready after update`),console.log(`[gateway] worker ready after update.`);return;case`worker.response`:{let e=r.get(t.id);if(!e)return;r.delete(t.id),t.ok?e.resolve(t.result):e.reject(Error(t.error));return}case`worker.update.prepared`:if(l)return;l=t.payload,n.info(t.payload,`gateway supervisor received worker update prepared`),b(),u=setTimeout(()=>{T(`update`)},250);return}},k=e=>{h=e,y(),n.info(e,`gateway supervisor spawning worker`);let t=(0,m.spawn)(e.command,e.args,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0});a=t,n.info({workerPid:t.pid??void 0,invocation:e},`gateway supervisor spawned worker`),t.stdout&&t.stdout.pipe(v.default.stdout),t.stderr&&t.stderr.pipe(v.default.stderr),t.on(`message`,e=>{let t=Xl(e);t&&O(t)}),t.on(`exit`,(e,n)=>{a===t&&(t.stdout&&t.stdout.unpipe(v.default.stdout),t.stderr&&t.stderr.unpipe(v.default.stderr),D(e,n))}),t.on(`error`,r=>{a===t&&(t.stdout&&t.stdout.unpipe(v.default.stdout),t.stderr&&t.stderr.unpipe(v.default.stderr),a=null,n.error({error:r,invocation:e},`gateway supervisor failed to launch worker`),console.error(`[gateway] failed to launch worker: ${String(r)}`),w(`worker_launch_error`,{error:r}))})},A=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`gateway.update.apply`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},j=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`codex.appServer.restart`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},M=e=>{if(!c){if(c=!0,n.info({signal:e},`gateway supervisor received shutdown signal`),console.log(`[gateway] received ${e}; shutting down...`),!a){C(0);return}T(`signal`)}};v.default.on(`SIGINT`,M),v.default.on(`SIGTERM`,M),k(h),await g}function Jl(e){if(!e.enabled)return()=>{};let t=_.default.createInterface({input:v.default.stdin,output:v.default.stdout,terminal:!0});return t.on(`line`,t=>{let n=t.trim().toLowerCase();if(n===`update`){e.onUpdate();return}if(n===`restart codex`||n===`codex restart`){e.onRestartCodex();return}}),()=>{t.close()}}function Yl(){return{pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}}function Xl(e){if(!Zl(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return Zl(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||typeof e.ok!=`boolean`?null:e.ok?(e.method,{type:`worker.response`,id:e.id,method:e.method,ok:!0,result:e.result}):typeof e.error==`string`?{type:`worker.response`,id:e.id,method:e.method,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!Zl(e.payload)||typeof e.payload.stateFilePath!=`string`||typeof e.payload.targetVersion!=`string`||e.payload.requestedBy!==`console`&&e.payload.requestedBy!==`mobile`&&e.payload.requestedBy!==`system`?null:{type:`worker.update.prepared`,payload:{stateFilePath:e.payload.stateFilePath,targetVersion:e.payload.targetVersion,requestedBy:e.payload.requestedBy}};default:return null}}function Zl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ql(e){let t=f.default.hostname();u.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=(n,r,i)=>{let a={level:n,time:Date.now(),pid:v.default.pid,hostname:t,...$l(r),msg:i??``};try{u.default.appendFileSync(e,`${JSON.stringify(a,eu)}\n`,`utf8`)}catch{}};return{info:(e,t)=>{n(30,e,t)},warn:(e,t)=>{n(40,e,t)},error:(e,t)=>{n(50,e,t)},close:()=>{}}}function $l(e){return Zl(e)?e:{detail:e}}function eu(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t==`bigint`?t.toString():t}async function tu(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function nu(e,t){let n=t.httpsEnabled?t.httpsPort:t.port,r=t.httpsEnabled?`https`:`http`,i=e;return i?.code===`EADDRINUSE`?`[gateway] failed to start: ${r.toUpperCase()} ${t.host}:${n} is already in use.`:i?.code===`EACCES`?`[gateway] failed to start: permission denied for ${r.toUpperCase()} ${t.host}:${n}.`:i?.code===`ENOENT`||i?.code===`EISDIR`?`[gateway] failed to start: log path is invalid or unavailable: ${t.gatewayLogPath}`:i instanceof Error?`[gateway] failed to start: ${i.message}`:`[gateway] failed to start: ${String(e)}`}var ru=o(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),iu=o(((e,t)=>{var n=ru();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:w,abort:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(){var e=s;for(s=null,c=null;e;){var t=e.next,n=e.callback,r=e.errorHandler,a=e.value,o=e.context;e.value=null,e.callback=i,e.errorHandler=null,r&&r(Error(`abort`),a),n.call(o,Error(`abort`)),e.release(e),e=t}d.drain=i}function w(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),au=o(((e,t)=>{let{format:n}=require(`node:util`);function r(){return`${this.name} [${this.code}]: ${this.message}`}let i=Symbol.for(`fastify-error-generic`);function a(e,t,o=500,s=Error,c=a.captureStackTrace){let l=e===i;if(l&&(e=`FST_ERR`),!e)throw Error(`Fastify error code must not be empty`);if(!t)throw Error(`Fastify error message must not be empty`);e=e.toUpperCase(),!o&&(o=void 0);let u=Symbol.for(`fastify-error ${e}`);function d(...r){if(!new.target)return new d(...r);this.code=e,this.name=`FastifyError`,this.statusCode=o;let i=r.length-1;i!==-1&&r[i]&&typeof r[i]==`object`&&`cause`in r[i]&&(this.cause=r.pop().cause),this.message=n(t,...r),Error.stackTraceLimit&&c&&Error.captureStackTrace(this,d)}return d.prototype=Object.create(s.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0},[i]:{value:!0,enumerable:!1,writable:!1,configurable:!1},[u]:{value:!0,enumerable:!1,writable:!1,configurable:!1}}),l?Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[i]},configurable:!1,writable:!1,enumerable:!1}):Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[u]},configurable:!1,writable:!1,enumerable:!1}),d.prototype[Symbol.toStringTag]=`Error`,d.prototype.toString=r,d}a.captureStackTrace=!0;let o=a(i,`Fastify Error`,500,Error);t.exports=a,t.exports.FastifyError=o,t.exports.default=a,t.exports.createError=a})),ou=o(((e,t)=>{let{createError:n}=au();t.exports={AVV_ERR_EXPOSE_ALREADY_DEFINED:n(`AVV_ERR_EXPOSE_ALREADY_DEFINED`,`'%s' is already defined, specify an expose option for '%s'`),AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:n(`AVV_ERR_ATTRIBUTE_ALREADY_DEFINED`,`'%s' is already defined`),AVV_ERR_CALLBACK_NOT_FN:n(`AVV_ERR_CALLBACK_NOT_FN`,`Callback for '%s' hook is not a function. Received: '%s'`),AVV_ERR_PLUGIN_NOT_VALID:n(`AVV_ERR_PLUGIN_NOT_VALID`,`Plugin must be a function or a promise. Received: '%s'`),AVV_ERR_ROOT_PLG_BOOTED:n(`AVV_ERR_ROOT_PLG_BOOTED`,`Root plugin has already booted`),AVV_ERR_PARENT_PLG_LOADED:n(`AVV_ERR_PARENT_PLG_LOADED`,`Impossible to load '%s' plugin because the parent '%s' was already loaded`),AVV_ERR_READY_TIMEOUT:n(`AVV_ERR_READY_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`),AVV_ERR_PLUGIN_EXEC_TIMEOUT:n(`AVV_ERR_PLUGIN_EXEC_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`)}})),su=o(((e,t)=>{t.exports={kAvvio:Symbol(`avvio.Boot`),kIsOnCloseHandler:Symbol(`isOnCloseHandler`),kThenifyDoNotWrap:Symbol(`avvio.ThenifyDoNotWrap`),kUntrackNode:Symbol(`avvio.TimeTree.untrackNode`),kTrackNode:Symbol(`avvio.TimeTree.trackNode`),kGetParent:Symbol(`avvio.TimeTree.getParent`),kGetNode:Symbol(`avvio.TimeTree.getNode`),kAddNode:Symbol(`avvio.TimeTree.addNode`),kPluginMeta:Symbol.for(`plugin-meta`)}})),cu=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=su();var s=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[r](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[n](e){this.tableId.delete(e.id);let t=this.tableLabel.get(e.label);t.pop(),t.length===0&&this.tableLabel.delete(e.label)}[i](e){if(e===null)return null;if(this.tableLabel.has(e)){let t=this.tableLabel.get(e);return t[t.length-1]}else return null}[a](e){return this.tableId.get(e)}[o](e,t,n){let a=this[i](e);if(a===null)return this.root={parent:null,id:`root`,label:t,nodes:[],start:n,stop:null,diff:-1},this[r](this.root),this.root.id;let o=`${t}-${Math.random()}`,s={parent:e,id:o,label:t,nodes:[],start:n,stop:null,diff:-1};return a.nodes.push(s),this[r](s),o}start(e,t,n=Date.now()){return this[o](e,t,n)}stop(e,t=Date.now()){let r=this[a](e);r&&(r.stop=t,r.diff=r.stop-r.start||0,this[n](r))}toJSON(){return Object.assign({},this.root)}prettyPrint(){return c(this.toJSON())}};function c(e,t=``){let n=t,r=e.nodes.length,i=r-1;n+=`${e.label} ${e.diff} ms\n`;for(let a=0;a<r;++a){let r=e.nodes[a],o=t+(a===i?` `:`│ `);n+=t,n+=a===i?`└─`:`├─`,n+=r.nodes.length===0?`─ `:`┬ `,n+=c(r,o).slice(t.length+2)}return n}t.exports={TimeTree:s}})),lu=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),uu=o(((e,t)=>{function n(){let e={resolve:null,reject:null,promise:null};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}t.exports={createPromise:n}})),du=o(((e,t)=>{let{kPluginMeta:n}=su();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
124
- `).slice(0,2).map(e=>e.trim()).join(` -- `)}t.exports={getPluginName:r}})),fu=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}t.exports={isPromiseLike:n}})),pu=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{inherits:r}=require(`node:util`),{debug:i}=lu(),{createPromise:a}=uu(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:o}=ou(),{getPluginName:s}=du(),{isPromiseLike:c}=fu();function l(e,t,n,r,i){this.queue=e,this.func=t,this.options=n,this.isAfter=r,this.timeout=i,this.started=!1,this.name=s(t,n),this.queue.pause(),this._error=null,this.loaded=!1,this._promise=null,this.startTime=null}r(l,n),l.prototype.exec=function(e,t){i(`exec`,this.name),this.server=e;let n=this.func,r=this.name,a=!1;this.options=typeof this.options==`function`?this.options(this.server):this.options;let s=null,l=e=>{if(a){i(`loading complete`,r);return}this._error=e,i(e?`exec errored`:`exec completed`,r),a=!0,s&&clearTimeout(s),t(e)};this.timeout>0&&(i(`setting up timeout`,r,this.timeout),s=setTimeout(function(){i(`timed out`,r),s=null;let e=new o(r);e.fn=n,l(e)},this.timeout)),this.started=!0,this.startTime=Date.now(),this.emit(`start`,this.server?this.server.name:null,this.name,Date.now());let u=n(this.server,this.options,l);c(u)?(i(`exec: resolving promise`,r),u.then(()=>process.nextTick(l),e=>process.nextTick(l,e))):n.length<3&&l()},l.prototype.loadedSoFar=function(){if(i(`loadedSoFar`,this.name),this.loaded)return Promise.resolve();let e=()=>{this.server.after((e,t)=>{this._error=e,this.queue.pause(),this._promise&&=(e?(i(`rejecting promise`,this.name,e),this._promise.reject(e)):(i(`resolving promise`,this.name),this._promise.resolve()),null),process.nextTick(t,e)}),this.queue.resume()},t;return this._promise?t=Promise.resolve():(this._promise=a(),t=this._promise.promise,this.server?e():this.on(`start`,e)),t},l.prototype.enqueue=function(e,t){i(`enqueue`,this.name,e.name),this.emit(`enqueue`,this.server?this.server.name:null,this.name,Date.now()),this.queue.push(e,t)},l.prototype.finish=function(e,t){i(`finish`,this.name,e);let n=()=>{this.loaded||(i(`loaded`,this.name),this.emit(`loaded`,this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,t(e))};if(e){this._promise&&=(this._promise.reject(e),null),n();return}let r=()=>{if(i(`check`,this.name,this.queue.length(),this.queue.running(),this._promise),this.queue.length()===0&&this.queue.running()===0)if(this._promise){let e=()=>{i(`wrap`),queueMicrotask(r)};this._promise.resolve(),this._promise.promise.then(e,e),this._promise=null}else n();else i(`delayed`,this.name),this.queue.drain=()=>{i(`drain`,this.name),this.queue.drain=u,queueMicrotask(r)}};queueMicrotask(r),this.queue.resume()};function u(){}t.exports={Plugin:l}})),mu=o(((e,t)=>{let{AVV_ERR_PLUGIN_NOT_VALID:n}=ou();function r(e){if(!(e&&(typeof e==`function`||typeof e.then==`function`)))throw Array.isArray(e)?new n(`array`):e===null?new n(`null`):new n(typeof e)}t.exports={validatePlugin:r}})),hu=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.default==`function`}t.exports={isBundledOrTypescriptPlugin:n}})),gu=o(((e,t)=>{let{debug:n}=lu(),{kThenifyDoNotWrap:r}=su();function i(){if(this.booted){n(`thenify returning undefined because we are already booted`);return}if(this[r]){this[r]=!1;return}return n(`thenify`),(e,t)=>this._loadRegistered().then(()=>(this[r]=!0,e(this._server)),t)}t.exports={thenify:i}})),_u=o(((e,t)=>{let{isPromiseLike:n}=fu(),{kAvvio:r}=su();function i(e,t,i){let a;try{a=e.apply(e,t)}catch(e){i&&process.nextTick(i,e);return}n(a)&&!a[r]?a.then(()=>process.nextTick(i),e=>process.nextTick(i,e)):i&&process.nextTick(i)}t.exports={executeWithThenable:i}})),vu=o(((e,t)=>{let n=iu(),r=require(`node:events`).EventEmitter,i=require(`node:util`).inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:a,AVV_ERR_CALLBACK_NOT_FN:o,AVV_ERR_ROOT_PLG_BOOTED:s,AVV_ERR_READY_TIMEOUT:c,AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:l}=ou(),{kAvvio:u,kIsOnCloseHandler:d}=su(),{TimeTree:f}=cu(),{Plugin:p}=pu(),{debug:m}=lu(),{validatePlugin:h}=mu(),{isBundledOrTypescriptPlugin:g}=hu(),{isPromiseLike:_}=fu(),{thenify:v}=gu(),{executeWithThenable:y}=_u();function b(e,t,r){if(typeof e==`function`&&arguments.length===1&&(r=e,t={},e=null),typeof t==`function`&&(r=t,t={}),t||={},t.autostart=t.autostart!==!1,t.timeout=Number(t.timeout)||0,t.expose=t.expose||{},!new.target)return new b(e,t,r);this._server=e||this,this._opts=t,e&&this._expose(),this._current=[],this._error=null,this._lastUsed=null,this.setMaxListeners(0),r&&this.once(`start`,r),this.started=!1,this.booted=!1,this.pluginTree=new f,this._readyQ=n(this,S,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit(`start`),this._readyQ.drain=x},this._closeQ=n(this,w,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit(`close`),this._closeQ.drain=x},this._doStart=null;let i=this;this._root=new p(n(this,this._loadPluginNextTick,1),function(e,t,n){i._doStart=n,t.autostart&&i.start()},t,!1,0),this._trackPluginLoading(this._root),this._loadPlugin(this._root,e=>{m(`root plugin ready`);try{this.emit(`preReady`),this._root=null}catch(t){e=e||this._error||t}if(e){if(this._error=e,this._readyQ.length()===0)throw e}else this.booted=!0;this._readyQ.resume()})}i(b,r),`asyncDispose`in Symbol&&(b.prototype[Symbol.asyncDispose]=function(){return new Promise((e,t)=>{this.close(n=>{if(n)return t(n);e()})})}),b.prototype.start=function(){return this.started=!0,process.nextTick(this._doStart),this},b.prototype.override=function(e,t,n){return e},b.prototype[u]=!0,b.prototype.use=function(e,t){return this._lastUsed=this._addPlugin(e,t,!1),this},b.prototype._loadRegistered=function(){let e=this._current[0];return!this.started&&!this.booted&&process.nextTick(()=>this._root.queue.resume()),e?e.loadedSoFar():Promise.resolve()},Object.defineProperty(b.prototype,`then`,{get:v}),b.prototype._addPlugin=function(e,t,r){if(g(e)&&(e=e.default),h(e),t||={},this.booted)throw new s;let i=this._current[0],a=this._opts.timeout;if(!i.loaded&&i.timeout>0){let e=Date.now()-i.startTime;a=i.timeout-(e+3)}let o=new p(n(this,this._loadPluginNextTick,1),e,t,r,a);if(this._trackPluginLoading(o),i.loaded)throw Error(o.name,i.name);return i.enqueue(o,e=>{e&&(this._error=e)}),o},b.prototype._expose=function(){let e=this,t=e._server,{use:n=`use`,after:r=`after`,ready:i=`ready`,onClose:s=`onClose`,close:c=`close`}=this._opts.expose;if(t[n])throw new a(n,`use`);if(t[n]=function(t,n){return e.use(t,n),this},t[r])throw new a(r,`after`);if(t[r]=function(t){return typeof t==`function`?(e.after(E(t,this)),this):e._loadRegistered()},t[i])throw new a(i,`ready`);if(t[i]=function(t){if(t&&typeof t!=`function`)throw new o(i,typeof t);return e.ready(t?E(t,this):void 0)},t[s])throw new a(s,`onClose`);if(t[s]=function(t){if(typeof t!=`function`)throw new o(s,typeof t);return e.onClose(T(t,this)),this},t[c])throw new a(c,`close`);if(t[c]=function(t){if(t&&typeof t!=`function`)throw new o(c,typeof t);return t?(e.close(E(t,this)),this):e.close()},t.then)throw new l(`then`);Object.defineProperty(t,`then`,{get:v.bind(e)}),t[u]=!0},b.prototype.after=function(e){if(!e)return this._loadRegistered();this._addPlugin(t.bind(this),{},!0);function t(t,n,r){S.call(this,e,r)}return this},b.prototype.onClose=function(e){if(typeof e!=`function`)throw new o(`onClose`,typeof e);return e[d]=!0,this._closeQ.unshift(e,e=>{e&&(this._error=e)}),this},b.prototype.close=function(e){let t;if(e){if(typeof e!=`function`)throw new o(`close`,typeof e)}else t=new Promise(function(t,n){e=function(e){if(e)return n(e);t()}});return this.ready(()=>{this._error=null,this._closeQ.push(e),process.nextTick(this._closeQ.resume.bind(this._closeQ))}),t},b.prototype.ready=function(e){if(e){if(typeof e!=`function`)throw new o(`ready`,typeof e);this._readyQ.push(e),queueMicrotask(this.start.bind(this));return}return new Promise((e,t)=>{this._readyQ.push(r),this.start();let n=this._current[0].server;function r(r,i,a){r?t(r):e(n),process.nextTick(a)}})},b.prototype._trackPluginLoading=function(e){let t=this._current[0]?.name||null;e.once(`start`,(n,r,i)=>{let a=this.pluginTree.start(t||null,r,i);e.once(`loaded`,(e,t,n)=>{this.pluginTree.stop(a,n)})})},b.prototype.prettyPrint=function(){return this.pluginTree.prettyPrint()},b.prototype.toJSON=function(){return this.pluginTree.toJSON()},b.prototype._loadPlugin=function(e,t){let n=this;if(_(e.func)){e.func.then(n=>{typeof n.default==`function`&&(n=n.default),e.func=n,this._loadPlugin(e,t)},t);return}let r=n._current[0];if(n._current.unshift(e),n._error&&!e.isAfter){m(`skipping loading of plugin as instance errored and it is not an after`,e.name),process.nextTick(a);return}let i=r?.server||n._server;if(!e.isAfter)try{i=n.override(i,e.func,e.options)}catch(t){return m(`override errored`,e.name),a(t)}e.exec(i,a);function a(r){e.finish(r,e=>{n._current.shift(),t(e)})}},b.prototype._loadPluginNextTick=function(e,t){process.nextTick(this._loadPlugin.bind(this),e,t)};function x(){}function S(e,t){let n=this._server,r=this._error;if(this._error=null,e.length===0)this._error=r,y(e,[],t);else if(e.length===1)y(e,[r],t);else if(this._opts.timeout===0){let i=e=>{this._error=e,t(this._error)};e.length===2?e(r,i):e(r,n,i)}else C.call(this,e,r,n,t)}function C(e,t,n,r){let i=e.unwrappedName??e.name;m(`setting up ready timeout`,i,this._opts.timeout);let a=setTimeout(()=>{m(`timed out`,i),a=null;let t=new c(i);t.fn=e,this._error=t,r(t)},this._opts.timeout);e.length===2?e(t,o.bind(this)):e(t,n,o.bind(this));function o(e){a&&(clearTimeout(a),this._error=e,r(this._error))}}function w(e,t){let n=this._server,r=e[d];if(e.length===0||e.length===1){let i;i=e(r?n:this._error),i&&typeof i.then==`function`?(m(`resolving close/onClose promise`),i.then(()=>process.nextTick(t),e=>process.nextTick(t,e))):process.nextTick(t)}else e.length===2?e(r?n:this._error,t):r?e(n,t):e(this._error,n,t)}function T(e,t){return n.bind(t);function n(t,n){let r;e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===1?(r=e(this),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e(this,n)}}function E(e,t){let n=r.bind(t);return n.unwrappedName=e.name,n;function r(t,n){let r;e?e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n,t)},n):process.nextTick(n,t)):e.length===1?(r=e(t),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===2?e(t,n):e(t,this,n):process.nextTick(n)}}t.exports=b})),yu=o(((e,t)=>{t.exports={kAvvioBoot:Symbol(`fastify.avvioBoot`),kChildren:Symbol(`fastify.children`),kServerBindings:Symbol(`fastify.serverBindings`),kBodyLimit:Symbol(`fastify.bodyLimit`),kSupportedHTTPMethods:Symbol(`fastify.acceptedHTTPMethods`),kRoutePrefix:Symbol(`fastify.routePrefix`),kLogLevel:Symbol(`fastify.logLevel`),kLogSerializers:Symbol(`fastify.logSerializers`),kHooks:Symbol(`fastify.hooks`),kContentTypeParser:Symbol(`fastify.contentTypeParser`),kState:Symbol(`fastify.state`),kOptions:Symbol(`fastify.options`),kDisableRequestLogging:Symbol(`fastify.disableRequestLogging`),kPluginNameChain:Symbol(`fastify.pluginNameChain`),kRouteContext:Symbol(`fastify.context`),kGenReqId:Symbol(`fastify.genReqId`),kHttp2ServerSessions:Symbol(`fastify.http2ServerSessions`),kSchemaController:Symbol(`fastify.schemaController`),kSchemaHeaders:Symbol(`headers-schema`),kSchemaParams:Symbol(`params-schema`),kSchemaQuerystring:Symbol(`querystring-schema`),kSchemaBody:Symbol(`body-schema`),kSchemaResponse:Symbol(`response-schema`),kSchemaErrorFormatter:Symbol(`fastify.schemaErrorFormatter`),kSchemaVisited:Symbol(`fastify.schemas.visited`),kRequest:Symbol(`fastify.Request`),kRequestPayloadStream:Symbol(`fastify.RequestPayloadStream`),kRequestAcceptVersion:Symbol(`fastify.RequestAcceptVersion`),kRequestCacheValidateFns:Symbol(`fastify.request.cache.validateFns`),kRequestOriginalUrl:Symbol(`fastify.request.originalUrl`),kFourOhFour:Symbol(`fastify.404`),kCanSetNotFoundHandler:Symbol(`fastify.canSetNotFoundHandler`),kFourOhFourLevelInstance:Symbol(`fastify.404LogLevelInstance`),kFourOhFourContext:Symbol(`fastify.404ContextKey`),kDefaultJsonParse:Symbol(`fastify.defaultJSONParse`),kReply:Symbol(`fastify.Reply`),kReplySerializer:Symbol(`fastify.reply.serializer`),kReplyIsError:Symbol(`fastify.reply.isError`),kReplyHeaders:Symbol(`fastify.reply.headers`),kReplyTrailers:Symbol(`fastify.reply.trailers`),kReplyHasStatusCode:Symbol(`fastify.reply.hasStatusCode`),kReplyHijacked:Symbol(`fastify.reply.hijacked`),kReplyStartTime:Symbol(`fastify.reply.startTime`),kReplyNextErrorHandler:Symbol(`fastify.reply.nextErrorHandler`),kReplyEndTime:Symbol(`fastify.reply.endTime`),kReplyErrorHandlerCalled:Symbol(`fastify.reply.errorHandlerCalled`),kReplyIsRunningOnErrorHook:Symbol(`fastify.reply.isRunningOnErrorHook`),kReplySerializerDefault:Symbol(`fastify.replySerializerDefault`),kReplyCacheSerializeFns:Symbol(`fastify.reply.cache.serializeFns`),kTestInternals:Symbol(`fastify.testInternals`),kErrorHandler:Symbol(`fastify.errorHandler`),kErrorHandlerAlreadySet:Symbol(`fastify.errorHandlerAlreadySet`),kChildLoggerFactory:Symbol(`fastify.childLoggerFactory`),kHasBeenDecorated:Symbol(`fastify.hasBeenDecorated`),kKeepAliveConnections:Symbol(`fastify.keepAliveConnections`),kRouteByFastify:Symbol(`fastify.routeByFastify`)}})),bu=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),xu=o(((e,t)=>{let{createWarning:n}=bu();t.exports={FSTWRN001:n({name:`FastifyWarning`,code:`FSTWRN001`,message:`The %s schema for %s: %s is missing. This may indicate the schema is not well specified.`,unlimited:!0}),FSTWRN003:n({name:`FastifyWarning`,code:`FSTWRN003`,message:`The %s mixes async and callback styles that may lead to unhandled rejections. Please use only one of them.`,unlimited:!0}),FSTWRN004:n({name:`FastifyWarning`,code:`FSTWRN004`,message:`It seems that you are overriding an errorHandler in the same scope, which can lead to subtle bugs.`,unlimited:!0}),FSTSEC001:n({name:`FastifySecurity`,code:`FSTSEC001`,message:`You are using /%s/ Content-Type which may be vulnerable to CORS attack. Please make sure your RegExp start with "^" or include ";?" to proper detection of the essence MIME type.`,unlimited:!0}),FSTDEP022:n({name:`FastifyWarning`,code:`FSTDEP022`,message:'The router options for %s property access is deprecated. Please use "options.routerOptions" instead for accessing router options. The router options will be removed in `fastify@6`.',unlimited:!0})}})),Su=o(((e,t)=>{let n=au(),r={FST_ERR_NOT_FOUND:n(`FST_ERR_NOT_FOUND`,`Not Found`,404),FST_ERR_OPTIONS_NOT_OBJ:n(`FST_ERR_OPTIONS_NOT_OBJ`,`Options must be an object`,500,TypeError),FST_ERR_QSP_NOT_FN:n(`FST_ERR_QSP_NOT_FN`,`querystringParser option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:n(`FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN`,`schemaController.bucket option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:n(`FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN`,`schemaErrorFormatter option should be a non async function. Instead got '%s'.`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ`,`ajv.customOptions option should be an object, instead got '%s'`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR`,`ajv.plugins option should be an array, instead got '%s'`,500,TypeError),FST_ERR_VALIDATION:n(`FST_ERR_VALIDATION`,`%s`,400),FST_ERR_LISTEN_OPTIONS_INVALID:n(`FST_ERR_LISTEN_OPTIONS_INVALID`,`Invalid listen options: '%s'`,500,TypeError),FST_ERR_ERROR_HANDLER_NOT_FN:n(`FST_ERR_ERROR_HANDLER_NOT_FN`,`Error Handler must be a function`,500,TypeError),FST_ERR_ERROR_HANDLER_ALREADY_SET:n(`FST_ERR_ERROR_HANDLER_ALREADY_SET`,`Error Handler already set in this scope. Set 'allowErrorHandlerOverride: true' to allow overriding.`,500,TypeError),FST_ERR_CTP_ALREADY_PRESENT:n(`FST_ERR_CTP_ALREADY_PRESENT`,`Content type parser '%s' already present.`),FST_ERR_CTP_INVALID_TYPE:n(`FST_ERR_CTP_INVALID_TYPE`,`The content type should be a string or a RegExp`,500,TypeError),FST_ERR_CTP_EMPTY_TYPE:n(`FST_ERR_CTP_EMPTY_TYPE`,`The content type cannot be an empty string`,500,TypeError),FST_ERR_CTP_INVALID_HANDLER:n(`FST_ERR_CTP_INVALID_HANDLER`,`The content type handler should be a function`,500,TypeError),FST_ERR_CTP_INVALID_PARSE_TYPE:n(`FST_ERR_CTP_INVALID_PARSE_TYPE`,`The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.`,500,TypeError),FST_ERR_CTP_BODY_TOO_LARGE:n(`FST_ERR_CTP_BODY_TOO_LARGE`,`Request body is too large`,413,RangeError),FST_ERR_CTP_INVALID_MEDIA_TYPE:n(`FST_ERR_CTP_INVALID_MEDIA_TYPE`,`Unsupported Media Type: %s`,415),FST_ERR_CTP_INVALID_CONTENT_LENGTH:n(`FST_ERR_CTP_INVALID_CONTENT_LENGTH`,`Request body size did not match Content-Length`,400,RangeError),FST_ERR_CTP_EMPTY_JSON_BODY:n(`FST_ERR_CTP_EMPTY_JSON_BODY`,`Body cannot be empty when content-type is set to 'application/json'`,400),FST_ERR_CTP_INVALID_JSON_BODY:n(`FST_ERR_CTP_INVALID_JSON_BODY`,`Body is not valid JSON but content-type is set to 'application/json'`,400),FST_ERR_CTP_INSTANCE_ALREADY_STARTED:n(`FST_ERR_CTP_INSTANCE_ALREADY_STARTED`,`Cannot call "%s" when fastify instance is already started!`,400),FST_ERR_DEC_ALREADY_PRESENT:n(`FST_ERR_DEC_ALREADY_PRESENT`,`The decorator '%s' has already been added!`),FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:n(`FST_ERR_DEC_DEPENDENCY_INVALID_TYPE`,`The dependencies of decorator '%s' must be of type Array.`,500,TypeError),FST_ERR_DEC_MISSING_DEPENDENCY:n(`FST_ERR_DEC_MISSING_DEPENDENCY`,`The decorator is missing dependency '%s'.`),FST_ERR_DEC_AFTER_START:n(`FST_ERR_DEC_AFTER_START`,`The decorator '%s' has been added after start!`),FST_ERR_DEC_REFERENCE_TYPE:n(`FST_ERR_DEC_REFERENCE_TYPE`,`The decorator '%s' of type '%s' is a reference type. Use the { getter, setter } interface instead.`),FST_ERR_DEC_UNDECLARED:n(`FST_ERR_DEC_UNDECLARED`,`No decorator '%s' has been declared on %s.`),FST_ERR_HOOK_INVALID_TYPE:n(`FST_ERR_HOOK_INVALID_TYPE`,`The hook name must be a string`,500,TypeError),FST_ERR_HOOK_INVALID_HANDLER:n(`FST_ERR_HOOK_INVALID_HANDLER`,`%s hook should be a function, instead got %s`,500,TypeError),FST_ERR_HOOK_INVALID_ASYNC_HANDLER:n(`FST_ERR_HOOK_INVALID_ASYNC_HANDLER`,`Async function has too many arguments. Async hooks should not use the 'done' argument.`,500,TypeError),FST_ERR_HOOK_NOT_SUPPORTED:n(`FST_ERR_HOOK_NOT_SUPPORTED`,`%s hook not supported!`,500,TypeError),FST_ERR_MISSING_MIDDLEWARE:n(`FST_ERR_MISSING_MIDDLEWARE`,`You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.`,500),FST_ERR_HOOK_TIMEOUT:n(`FST_ERR_HOOK_TIMEOUT`,`A callback for '%s' hook%s timed out. You may have forgotten to call 'done' function or to resolve a Promise`),FST_ERR_LOG_INVALID_DESTINATION:n(`FST_ERR_LOG_INVALID_DESTINATION`,`Cannot specify both logger.stream and logger.file options`),FST_ERR_LOG_INVALID_LOGGER:n(`FST_ERR_LOG_INVALID_LOGGER`,`Invalid logger object provided. The logger instance should have these functions(s): '%s'.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_INSTANCE:n(`FST_ERR_LOG_INVALID_LOGGER_INSTANCE`,`loggerInstance only accepts a logger instance.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_CONFIG:n(`FST_ERR_LOG_INVALID_LOGGER_CONFIG`,`logger options only accepts a configuration object.`,500,TypeError),FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:n(`FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED`,`You cannot provide both logger and loggerInstance. Please provide only one.`,500,TypeError),FST_ERR_REP_INVALID_PAYLOAD_TYPE:n(`FST_ERR_REP_INVALID_PAYLOAD_TYPE`,`Attempted to send payload of invalid type '%s'. Expected a string or Buffer.`,500,TypeError),FST_ERR_REP_RESPONSE_BODY_CONSUMED:n(`FST_ERR_REP_RESPONSE_BODY_CONSUMED`,`Response.body is already consumed.`),FST_ERR_REP_READABLE_STREAM_LOCKED:n(`FST_ERR_REP_READABLE_STREAM_LOCKED`,`ReadableStream was locked. You should call releaseLock() method on reader before sending.`),FST_ERR_REP_ALREADY_SENT:n(`FST_ERR_REP_ALREADY_SENT`,`Reply was already sent, did you forget to "return reply" in "%s" (%s)?`),FST_ERR_REP_SENT_VALUE:n(`FST_ERR_REP_SENT_VALUE`,`The only possible value for reply.sent is true.`,500,TypeError),FST_ERR_SEND_INSIDE_ONERR:n(`FST_ERR_SEND_INSIDE_ONERR`,"You cannot use `send` inside the `onError` hook"),FST_ERR_SEND_UNDEFINED_ERR:n(`FST_ERR_SEND_UNDEFINED_ERR`,`Undefined error has occurred`),FST_ERR_BAD_STATUS_CODE:n(`FST_ERR_BAD_STATUS_CODE`,`Called reply with an invalid status code: %s`),FST_ERR_BAD_TRAILER_NAME:n(`FST_ERR_BAD_TRAILER_NAME`,`Called reply.trailer with an invalid header name: %s`),FST_ERR_BAD_TRAILER_VALUE:n(`FST_ERR_BAD_TRAILER_VALUE`,`Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function.`),FST_ERR_FAILED_ERROR_SERIALIZATION:n(`FST_ERR_FAILED_ERROR_SERIALIZATION`,`Failed to serialize an error. Error: %s. Original error: %s`),FST_ERR_MISSING_SERIALIZATION_FN:n(`FST_ERR_MISSING_SERIALIZATION_FN`,`Missing serialization function. Key "%s"`),FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:n(`FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN`,`Missing serialization function. Key "%s:%s"`),FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:n(`FST_ERR_REQ_INVALID_VALIDATION_INVOCATION`,`Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.`),FST_ERR_SCH_MISSING_ID:n(`FST_ERR_SCH_MISSING_ID`,`Missing schema $id property`),FST_ERR_SCH_ALREADY_PRESENT:n(`FST_ERR_SCH_ALREADY_PRESENT`,`Schema with id '%s' already declared!`),FST_ERR_SCH_CONTENT_MISSING_SCHEMA:n(`FST_ERR_SCH_CONTENT_MISSING_SCHEMA`,`Schema is missing for the content type '%s'`),FST_ERR_SCH_DUPLICATE:n(`FST_ERR_SCH_DUPLICATE`,`Schema with '%s' already present!`),FST_ERR_SCH_VALIDATION_BUILD:n(`FST_ERR_SCH_VALIDATION_BUILD`,`Failed building the validation schema for %s: %s, due to error %s`),FST_ERR_SCH_SERIALIZATION_BUILD:n(`FST_ERR_SCH_SERIALIZATION_BUILD`,`Failed building the serialization schema for %s: %s, due to error %s`),FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:n(`FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX`,`response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }`),FST_ERR_INIT_OPTS_INVALID:n(`FST_ERR_INIT_OPTS_INVALID`,`Invalid initialization options: '%s'`),FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:n(`FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE`,`Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method`),FST_ERR_DUPLICATED_ROUTE:n(`FST_ERR_DUPLICATED_ROUTE`,`Method '%s' already declared for route '%s'`),FST_ERR_BAD_URL:n(`FST_ERR_BAD_URL`,`'%s' is not a valid url component`,400,URIError),FST_ERR_ASYNC_CONSTRAINT:n(`FST_ERR_ASYNC_CONSTRAINT`,`Unexpected error from async constraint`,500),FST_ERR_INVALID_URL:n(`FST_ERR_INVALID_URL`,`URL must be a string. Received '%s'`,400,TypeError),FST_ERR_ROUTE_OPTIONS_NOT_OBJ:n(`FST_ERR_ROUTE_OPTIONS_NOT_OBJ`,`Options for "%s:%s" route must be an object`,500,TypeError),FST_ERR_ROUTE_DUPLICATED_HANDLER:n(`FST_ERR_ROUTE_DUPLICATED_HANDLER`,`Duplicate handler for "%s:%s" route is not allowed!`,500),FST_ERR_ROUTE_HANDLER_NOT_FN:n(`FST_ERR_ROUTE_HANDLER_NOT_FN`,`Error Handler for %s:%s route, if defined, must be a function`,500,TypeError),FST_ERR_ROUTE_MISSING_HANDLER:n(`FST_ERR_ROUTE_MISSING_HANDLER`,`Missing handler function for "%s:%s" route.`,500),FST_ERR_ROUTE_METHOD_INVALID:n(`FST_ERR_ROUTE_METHOD_INVALID`,`Provided method is invalid!`,500,TypeError),FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:n(`FST_ERR_ROUTE_METHOD_NOT_SUPPORTED`,`%s method is not supported.`,500),FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:n(`FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED`,`Body validation schema for %s:%s route is not supported!`,500),FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:n(`FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT`,`'bodyLimit' option must be an integer > 0. Got '%s'`,500,TypeError),FST_ERR_ROUTE_REWRITE_NOT_STR:n(`FST_ERR_ROUTE_REWRITE_NOT_STR`,`Rewrite url for "%s" needs to be of type "string" but received "%s"`,500,TypeError),FST_ERR_REOPENED_CLOSE_SERVER:n(`FST_ERR_REOPENED_CLOSE_SERVER`,`Fastify has already been closed and cannot be reopened`),FST_ERR_REOPENED_SERVER:n(`FST_ERR_REOPENED_SERVER`,`Fastify is already listening`),FST_ERR_INSTANCE_ALREADY_LISTENING:n(`FST_ERR_INSTANCE_ALREADY_LISTENING`,`Fastify instance is already listening. %s`),FST_ERR_PLUGIN_VERSION_MISMATCH:n(`FST_ERR_PLUGIN_VERSION_MISMATCH`,`fastify-plugin: %s - expected '%s' fastify version, '%s' is installed`),FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:n(`FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE`,`The decorator '%s'%s is not present in %s`),FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:n(`FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER`,`The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.`,500,TypeError),FST_ERR_PLUGIN_CALLBACK_NOT_FN:n(`FST_ERR_PLUGIN_CALLBACK_NOT_FN`,`fastify-plugin: %s`,500,TypeError),FST_ERR_PLUGIN_NOT_VALID:n(`FST_ERR_PLUGIN_NOT_VALID`,`fastify-plugin: %s`),FST_ERR_ROOT_PLG_BOOTED:n(`FST_ERR_ROOT_PLG_BOOTED`,`fastify-plugin: %s`),FST_ERR_PARENT_PLUGIN_BOOTED:n(`FST_ERR_PARENT_PLUGIN_BOOTED`,`fastify-plugin: %s`),FST_ERR_PLUGIN_TIMEOUT:n(`FST_ERR_PLUGIN_TIMEOUT`,`fastify-plugin: %s`)};function i(e,t){return t.cause=e,t}t.exports=r,t.exports.appendStackTrace=i,t.exports.AVVIO_ERRORS_MAP={AVV_ERR_CALLBACK_NOT_FN:r.FST_ERR_PLUGIN_CALLBACK_NOT_FN,AVV_ERR_PLUGIN_NOT_VALID:r.FST_ERR_PLUGIN_NOT_VALID,AVV_ERR_ROOT_PLG_BOOTED:r.FST_ERR_ROOT_PLG_BOOTED,AVV_ERR_PARENT_PLG_LOADED:r.FST_ERR_PARENT_PLUGIN_BOOTED,AVV_ERR_READY_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT,AVV_ERR_PLUGIN_EXEC_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT}})),Cu=o(((e,t)=>{let n=[`onRoute`,`onRegister`,`onReady`,`onListen`,`preClose`,`onClose`],r=[`onTimeout`,`onRequest`,`preParsing`,`preValidation`,`preSerialization`,`preHandler`,`onSend`,`onResponse`,`onError`,`onRequestAbort`],i=r.concat(n),{FST_ERR_HOOK_INVALID_TYPE:a,FST_ERR_HOOK_INVALID_HANDLER:o,FST_ERR_SEND_UNDEFINED_ERR:s,FST_ERR_HOOK_TIMEOUT:c,FST_ERR_HOOK_NOT_SUPPORTED:l,AVVIO_ERRORS_MAP:u,appendStackTrace:d}=Su(),{kChildren:f,kHooks:p,kRequestPayloadStream:m}=yu();function h(){this.onRequest=[],this.preParsing=[],this.preValidation=[],this.preSerialization=[],this.preHandler=[],this.onResponse=[],this.onSend=[],this.onError=[],this.onRoute=[],this.onRegister=[],this.onReady=[],this.onListen=[],this.onTimeout=[],this.onRequestAbort=[],this.preClose=[]}h.prototype=Object.create(null),h.prototype.validate=function(e,t){if(typeof e!=`string`)throw new a;if(Array.isArray(this[e])===!1)throw new l(e);if(typeof t!=`function`)throw new o(e,Object.prototype.toString.call(t))},h.prototype.add=function(e,t){this.validate(e,t),this[e].push(t)};function g(e){let t=new h;return t.onRequest=e.onRequest.slice(),t.preParsing=e.preParsing.slice(),t.preValidation=e.preValidation.slice(),t.preSerialization=e.preSerialization.slice(),t.preHandler=e.preHandler.slice(),t.onSend=e.onSend.slice(),t.onResponse=e.onResponse.slice(),t.onError=e.onError.slice(),t.onRoute=e.onRoute.slice(),t.onRegister=e.onRegister.slice(),t.onTimeout=e.onTimeout.slice(),t.onRequestAbort=e.onRequestAbort.slice(),t.onReady=[],t.onListen=[],t.preClose=[],t}function _(e,t,n,r){let i=n[p][e],a=0,o=0;l();function s(t){let n=i[a-1]?.name,o=n?` "${n}"`:``;if(t){t=t.code===`AVV_ERR_READY_TIMEOUT`?d(t,new c(e,o)):u[t.code]==null?t:d(t,new u[t.code](t.message)),r(t);return}r()}function l(r){if(r){s(r);return}if(a===i.length&&o===n[f].length){a===0&&o===0?s():t(function(e,t){s(e),t(e)});return}if(a===i.length&&o<n[f].length){let r=n[f][o++];_(e,t,r,l);return}t(m(i[a++],n)),l()}function m(e,t){return function(n,r){if(n){r(n);return}if(e.length===1){try{e.call(t,r)}catch(e){r(e)}return}try{let n=e.call(t);if(n&&typeof n.then==`function`){n.then(r,r);return}}catch(e){n=e}r(n)}}}function v(e){let t=e[p].onListen,n=t.length,r=0,i=0;a();function a(s){if(s&&e.log.error(s),r===n){for(;i<e[f].length;){let t=e[f][i++];v(t)}return}o(t[r++],e,a)}async function o(e,t,n){if(e.length===1){try{e.call(t,n)}catch(e){n(e)}return}try{let r=e.call(t);if(r&&typeof r.then==`function`){r.then(n,n);return}n()}catch(e){n(e)}}}function y(e){return function(t,n,r,i){let a=0;function o(s){if(s||a===t.length){i(s,n,r);return}let u;try{u=e(t[a++],n,r,o)}catch(e){i(e,n,r);return}u&&typeof u.then==`function`&&u.then(c,l)}function c(){o()}function l(e){e||=new s,i(e,n,r)}o()}}function b(e,t,n,r){return e(t,n,r)}let x=y(b),S=y(A),C=y(A),w=y(A),T=y(A);function E(e,t,n,r,i){let a=0;function o(s,u){if(s){i(s,t,n,r);return}if(u!==void 0&&(r=u),a===e.length){i(null,t,n,r);return}let d;try{d=e[a++](t,n,r,o)}catch(e){i(e,t,n);return}d&&typeof d.then==`function`&&d.then(c,l)}function c(e){o(null,e)}function l(e){e||=new s,i(e,t,n,r)}o()}let D=E;function O(e,t,n,r){let i=0;function a(s,l){if(n.sent)return;if(l!==void 0&&(t[m]=l),s||i===e.length){r(s,t,n);return}let u;try{u=e[i++](t,n,t[m],a)}catch(e){r(e,t,n);return}u&&typeof u.then==`function`&&u.then(o,c)}function o(e){a(null,e)}function c(e){e||=new s,r(e,t,n)}a()}function k(e,t,n){let r=0;function i(s){if(s||r===e.length){n(s,t);return}let c;try{c=e[r++](t,i)}catch(e){n(e,t);return}c&&typeof c.then==`function`&&c.then(a,o)}function a(){i()}function o(e){e||=new s,n(e,t)}i()}function A(e,t,n,r){if(n.sent!==!0)return e(t,n,r)}t.exports={Hooks:h,buildHooks:g,hookRunnerGenerator:y,preParsingHookRunner:O,onResponseHookRunner:x,onSendHookRunner:E,preSerializationHookRunner:D,onRequestAbortHookRunner:k,hookIterator:A,hookRunnerApplication:_,onListenHookRunner:v,preHandlerHookRunner:C,preValidationHookRunner:S,onRequestHookRunner:T,onTimeoutHookRunner:w,lifecycleHooks:r,supportedHooks:i}})),wu=o(((e,t)=>{t.exports=function(){return{[Symbol.iterator]:function*(){},add(){},delete(){},has(){return!0}}}})),Tu=o(((e,t)=>{let{kTestInternals:n}=yu();function r(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}t.exports={withResolvers:typeof Promise.withResolvers==`function`?Promise.withResolvers.bind(Promise):r,[n]:{withResolvers:r}}})),Eu=o(((e,t)=>{let n=require(`node:http`),r=require(`node:https`),i=require(`node:http2`),a=require(`node:dns`),o=require(`node:os`),{kState:s,kOptions:c,kServerBindings:l,kHttp2ServerSessions:u}=yu(),{FSTWRN003:d}=xu(),{onListenHookRunner:f}=Cu(),{FST_ERR_REOPENED_CLOSE_SERVER:p,FST_ERR_REOPENED_SERVER:m,FST_ERR_LISTEN_OPTIONS_INVALID:h,FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:g}=Su(),_=wu(),v=Tu();t.exports.createServer=b;function y(e){return`Server listening at ${e}`}function b(e,t){let n=w(e,t);function r(r={port:0,host:`localhost`},i=void 0){if(typeof i==`function`&&(i.constructor.name===`AsyncFunction`&&d(`listen method`),r.cb=i),r.signal){if(typeof r.signal.on!=`function`&&typeof r.signal.addEventListener!=`function`)throw new h(`Invalid options.signal`);if(this[s].aborted=r.signal.aborted,this[s].aborted)return this.close();r.signal.addEventListener(`abort`,()=>{this[s].aborted=!0,this.close()},{once:!0})}let a;if(a=r.path==null?r.host??`localhost`:r.host,(!Object.hasOwn(r,`host`)||r.host==null)&&(r.host=a),a===`localhost`?r.cb=(a,o)=>{if(a){i(a,o);return}x.call(this,n,t,e,r,()=>{this[s].listening=!0,i(null,o),f(this)})}:r.cb=(e,t)=>{if(e){i(e,t);return}this[s].listening=!0,i(null,t),f(this)},i===void 0)return C.call(this,n,r).then(i=>{let{promise:o,resolve:c}=v.withResolvers();return a===`localhost`?x.call(this,n,t,e,r,()=>{this[s].listening=!0,c(i),f(this)}):(c(i),f(this)),o});this.ready(S.call(this,n,r))}let i=typeof n.closeAllConnections==`function`,a=typeof n.closeIdleConnections==`function`,o=typeof n.closeHttp2Sessions==`function`,c=e.forceCloseConnections;if(c===`idle`&&!a)throw new g;typeof c!=`boolean`&&(c=a?`idle`:!1);let l=!i&&c===!0?new Set:_();return{server:n,listen:r,forceCloseConnections:c,serverHasCloseAllConnections:i,serverHasCloseHttp2Sessions:o,keepAliveConnections:l}}function x(e,t,n,r,i){this[s].listening=!1,a.lookup(r.host,{all:!0},(a,o)=>{if(a||this[s].aborted){i();return}let c=e.listening&&n.serverFactory,u=0,d=0;if(!c){let a=e.address();for(let c of o)if(c.address!==a.address){u++;let o=Object.assign({},r,{host:c.address,port:a.port,cb:e=>{d++,e||this[l].push(f),d===u&&i()}}),f=w(n,t),p=()=>{f.close(()=>{}),typeof f.closeAllConnections==`function`&&n.forceCloseConnections===!0&&f.closeAllConnections(),typeof f.closeHttp2Sessions==`function`&&f.closeHttp2Sessions()};f.on(`upgrade`,e.emit.bind(e,`upgrade`)),e.on(`unref`,p),e.on(`close`,p),e.on(`error`,p),this[s].listening=!1,S.call(this,f,o)()}}if(u===0){i();return}let f=e.unref;e.unref=function(){f.call(e),e.emit(`unref`)}})}function S(e,t){let n=r=>{if(e.removeListener(`error`,n),e.removeListener(`listening`,n),r)this[s].listening=!1,t.cb(r,null);else{let n=E.call(this,e,t.listenTextResolver||y);t.cb(null,n)}};return r=>{if(r!=null)return t.cb(r);if(this[s].listening&&this[s].closing)return t.cb(new p,null);if(this[s].listening)return t.cb(new m,null);e.once(`error`,n),this[s].closing||(e.once(`listening`,n),e.listen(t),this[s].listening=!0)}}function C(e,t){return this[s].listening&&this[s].closing?Promise.reject(new p):this[s].listening?Promise.reject(new m):this.ready().then(()=>{if(this[s].aborted)return;let{promise:n,resolve:r,reject:i}=v.withResolvers(),a=e=>{c(),this[s].listening=!1,i(e)},o=()=>{c(),this[s].listening=!0,r(E.call(this,e,t.listenTextResolver||y))};function c(){e.removeListener(`error`,a),e.removeListener(`listening`,o)}return e.once(`error`,a),e.once(`listening`,o),e.listen(t),n})}function w(e,t){if(e.serverFactory)return e.serverFactory(t,e);let a=e.https===!0?{}:e.https;if(e.http2){let n=typeof a==`object`?i.createSecureServer(a,t):i.createServer(e.http,t);return n.on(`session`,t=>t.setTimeout(e.http2SessionTimeout,()=>{t.close()})),e.forceCloseConnections===!0&&(n.closeHttp2Sessions=D(n)),n.setTimeout(e.connectionTimeout),n}let o=a?r.createServer(a,t):n.createServer(e.http,t);return o.keepAliveTimeout=e.keepAliveTimeout,o.requestTimeout=e.requestTimeout,o.setTimeout(e.connectionTimeout),e.maxRequestsPerSocket>0&&(o.maxRequestsPerSocket=e.maxRequestsPerSocket),o}function T(e){return e.address===`0.0.0.0`?Object.values(o.networkInterfaces()).flatMap(e=>e.filter(e=>e.family===`IPv4`)).sort(e=>e.internal?-1:1).map(e=>e.address):[e.address]}function E(e,t){let n;typeof e.address()==`string`?n=[e.address()]:(n=e.address().address.indexOf(`:`)===-1?T(e.address()).map(t=>t+`:`+e.address().port):[`[`+e.address().address+`]:`+e.address().port],n=n.map(e=>`http`+(this[c].https?`s`:``)+`://`+e));for(let e of n)this.log.info(t(e));return n[0]}function D(e){return e[u]=new Set,e.on(`session`,function(t){t.once(`connect`,function(){e[u].add(t)}),t.once(`close`,function(){e[u].delete(t)}),t.once(`frameError`,function(n,r,i){i===0&&e[u].delete(t)}),t.once(`goaway`,function(){e[u].delete(t)})}),function(){if(e[u].size!==0)for(let t of e[u])t.close()}}})),Du=o(((e,t)=>{let n=/([\w!#$%&'*+.^`|~-]+)=([^;]*)/gm,r=/^[\w!#$%&'*+.^`|~-]+$/,i=/^[\w!#$%&'*+.^`|~-]+\s*/;t.exports=class{#e=!1;#t=!0;#n=``;#r=``;#i=new Map;#a;constructor(e){if(e==null||e===``||e===`undefined`)return;let t=e.indexOf(`;`);if(t===-1){if(t=e.indexOf(`/`),t===-1)return;let n=e.slice(0,t).trimStart().toLowerCase(),a=e.slice(t+1).trimEnd().toLowerCase();r.test(n)===!0&&i.test(a)===!0&&(this.#e=!0,this.#t=!1,this.#n=n,this.#r=a);return}let a=e.slice(0,t).toLowerCase(),o=e.slice(t+1).trim();if(t=a.indexOf(`/`),t===-1)return;let s=a.slice(0,t).trimStart(),c=a.slice(t+1).trimEnd();if(r.test(s)===!1||i.test(c)===!1)return;this.#n=s,this.#r=c,this.#e=!0,this.#t=!1;let l=n.exec(o);for(;l;){let e=l[1],t=l[2];if(t[0]===`"`){if(t.at(-1)!==`"`){this.#i.set(e,`invalid quoted string`),l=n.exec(o);continue}this.#i.set(e,t.slice(1,t.length-1))}else this.#i.set(e,t);l=n.exec(o)}}get[Symbol.toStringTag](){return`ContentType`}get isEmpty(){return this.#t}get isValid(){return this.#e}get mediaType(){return`${this.#n}/${this.#r}`}get type(){return this.#n}get subtype(){return this.#r}get parameters(){return this.#i}toString(){if(this.#a)return this.#a;let e=[];for(let[t,n]of this.#i.entries())e.push(`${t}="${n}"`);let t=[this.#n,`/`,this.#r];return e.length>0&&(t.push(`; `),t.push(e.join(`; `))),this.#a=t.join(``),this.#a}}})),Ou=o(((e,t)=>{let{kReplyHasStatusCode:n}=yu();function r(e,t){if(!e[n]||e.statusCode===200){let n=t&&(t.statusCode||t.status);e.code(n>=400?n:500)}}t.exports={setErrorStatusCode:r}})),ku=o(((e,t)=>{let{kReplyIsError:n,kReplyHijacked:r}=yu(),{setErrorStatusCode:i}=Ou(),a=require(`node:diagnostics_channel`).tracingChannel(`fastify.request.handler`);function o(e,t,o){o&&(o.async=!0),e.then(function(e){if(t[r]!==!0){o&&a.asyncStart.publish(o);try{if(e!==void 0||t.sent===!1&&t.raw.headersSent===!1&&t.request.raw.aborted===!1&&t.request.socket&&!t.request.socket.destroyed)try{t.send(e)}catch(e){t[n]=!0,t.send(e)}}finally{o&&a.asyncEnd.publish(o)}}},function(e){o&&(o.error=e,i(t,e),a.error.publish(o),a.asyncStart.publish(o));try{if(t.sent===!0){t.log.error({err:e},`Promise errored, but reply.sent = true was set`);return}t[n]=!0,t.send(e)}catch(e){t.send(e)}finally{o&&a.asyncEnd.publish(o)}})}t.exports=o})),Au=o(((e,t)=>{let{kSchemaHeaders:n,kSchemaParams:r,kSchemaQuerystring:i,kSchemaBody:a,kSchemaResponse:o}=yu(),s=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:c}=Su(),{FSTWRN001:l}=xu();function u(e,t){if(!e.schema||!e.schema.response)return;let{method:n,url:r}=e.config||{};e[o]=Object.keys(e.schema.response).reduce(function(i,a){let o=e.schema.response[a];if(a=a.toLowerCase(),!s.test(a))throw new c;if(o.content){let e={};for(let i of Object.keys(o.content)){let s=o.content[i].schema;e[i]=t({schema:s,url:r,method:n,httpStatus:a,contentType:i})}i[a]=e}else i[a]=t({schema:o,url:r,method:n,httpStatus:a});return i},{})}function d(e,t,o){let{schema:s}=e;if(!s)return;let{method:c,url:u}=e.config||{},d=s.headers;if(d&&(o||Object.getPrototypeOf(d)!==Object.prototype))e[n]=t({schema:d,method:c,url:u,httpPart:`headers`});else if(d){let r={};Object.keys(d).forEach(e=>{r[e]=d[e]}),r.required instanceof Array&&(r.required=r.required.map(e=>e.toLowerCase())),d.properties&&(r.properties={},Object.keys(d.properties).forEach(e=>{r.properties[e.toLowerCase()]=d.properties[e]})),e[n]=t({schema:r,method:c,url:u,httpPart:`headers`})}else Object.hasOwn(s,`headers`)&&l(`headers`,c,u);if(s.body){let n=s.body.content;if(n){let r={};for(let e of Object.keys(n)){let i=n[e].schema;r[e]=t({schema:i,method:c,url:u,httpPart:`body`,contentType:e})}e[a]=r}else e[a]=t({schema:s.body,method:c,url:u,httpPart:`body`})}else Object.hasOwn(s,`body`)&&l(`body`,c,u);s.querystring?e[i]=t({schema:s.querystring,method:c,url:u,httpPart:`querystring`}):Object.hasOwn(s,`querystring`)&&l(`querystring`,c,u),s.params?e[r]=t({schema:s.params,method:c,url:u,httpPart:`params`}):Object.hasOwn(s,`params`)&&l(`params`,c,u)}function f(e,t,n){let r=t[n]===void 0,i;try{i=e?.(r?null:t[n])}catch(e){return e.statusCode=500,e}if(i&&typeof i.then==`function`)return i.then(e=>a(e)).catch(e=>e);return a(i);function a(r){return r===!1?e.errors:r&&r.error?r.error:(r&&r.value&&(t[n]=r.value),!1)}}function p(e,t,o){let s=o===void 0;if(s||!o.skipParams){let n=f(e[r],t,`params`);if(n)return typeof n.then==`function`?m(n,e,t):v(n,`params`,e.schemaErrorFormatter)}if(s||!o.skipBody){let n=null;if(typeof e[a]==`function`)n=e[a];else if(e[a]){let r=y(t.headers[`content-type`]),i=e[a][r];i&&(n=i)}let r=f(n,t,`body`);if(r)return typeof r.then==`function`?h(r,e,t):v(r,`body`,e.schemaErrorFormatter)}if(s||!o.skipQuery){let n=f(e[i],t,`query`);if(n)return typeof n.then==`function`?g(n,e,t):v(n,`querystring`,e.schemaErrorFormatter)}let c=f(e[n],t,`headers`);return c?typeof c.then==`function`?_(c,e,t):v(c,`headers`,e.schemaErrorFormatter):!1}function m(e,t,n){return e.then(e=>e?v(e,`params`,t.schemaErrorFormatter):p(t,n,{skipParams:!0}))}function h(e,t,n){return e.then(e=>e?v(e,`body`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0}))}function g(e,t,n){return e.then(e=>e?v(e,`querystring`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0,skipQuery:!0}))}function _(e,t,n){return e.then(e=>e?v(e,`headers`,t.schemaErrorFormatter):!1)}function v(e,t,n){if(e instanceof Error)return e.statusCode=e.statusCode||400,e.code=e.code||`FST_ERR_VALIDATION`,e.validationContext=e.validationContext||t,e;let r=n(e,t);return r.statusCode=r.statusCode||400,r.code=r.code||`FST_ERR_VALIDATION`,r.validation=e,r.validationContext=t,r}function y(e){return e?e.split(/[ ;]/,1)[0].trim().toLowerCase():``}t.exports={symbols:{bodySchema:a,querystringSchema:i,responseSchema:o,paramsSchema:r,headersSchema:n},compileSchemasForValidation:d,compileSchemasForSerialization:u,validate:p}})),ju=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Du(),i=ku(),{validate:a}=Au(),{preValidationHookRunner:o,preHandlerHookRunner:s}=Cu(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:c}=Su(),{setErrorStatusCode:l}=Ou(),{kReplyIsError:u,kRouteContext:d,kFourOhFourContext:f,kSupportedHTTPMethods:p}=yu(),m=n.tracingChannel(`fastify.request.handler`);function h(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let i=t.method;if(this[p].bodyless.has(i)){g(t,n);return}if(this[p].bodywith.has(i)){let e=t.headers,i=e[`content-type`];if(i===void 0){let r=e[`content-length`];if(e[`transfer-encoding`]===void 0&&(r===void 0||r===`0`)){g(t,n);return}t[d].contentTypeParser.run(``,g,t,n);return}let a=new r(i);if(a.isValid===!1){n[u]=!0,n.status(415).send(new c);return}t[d].contentTypeParser.run(a.toString(),g,t,n);return}g(t,n)}function g(e,t){try{e[d].preValidation===null?_(null,e,t):o(e[d].preValidation,e,t,_)}catch(n){_(n,e,t)}}function _(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let r=a(n[d],t);if(r&&typeof r.then==`function`){let e=v.bind(null,t,n);r.then(e,e)}else v(t,n,r)}function v(e,t,n){if(n){if(t[d].attachValidation===!1){t.send(n);return}t.request.validationError=n}e[d].preHandler===null?y(null,e,t):s(e[d].preHandler,e,t,y)}function y(e,t,n){if(n.sent)return;let r=t[d];if(!m.hasSubscribers||r[f]===null)b(e,t,n);else{let i={request:t,reply:n,async:!1,route:{url:r.config.url,method:r.config.method}};m.start.runStores(i,b,void 0,e,t,n,i)}}function b(e,t,n,r){let a=t[d];try{if(e!=null){n[u]=!0,r&&(r.error=e,l(n,e),m.error.publish(r)),n.send(e);return}let o;try{o=a.handler(t,n)}catch(e){r&&(r.error=e,l(n,e),m.error.publish(r)),n[u]=!0,n.send(e);return}o!==void 0&&(o!==null&&typeof o.then==`function`?i(o,n,r):n.send(o))}finally{r&&m.end.publish(r)}}t.exports=h,t.exports[Symbol.for(`internals`)]={handler:g,preHandlerCallback:y}})),Mu=o(((e,t)=>{function n(){}let r={fatal:n,error:n,warn:n,info:n,debug:n,trace:n};Object.defineProperty(t,`exports`,{get(){return Object.create(r)}})})),Nu=o(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
123
+ `)}function ml(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function hl(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function gl(e){try{let t=new URL(e).hostname;return _l(t)}catch{return!1}}function _l(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const vl={platform:v.default.platform,now:()=>new Date,currentContext:()=>({pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}),runCommand:(e,t,n={})=>{let r=(0,m.spawnSync)(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0,...n});return{status:r.status,stdout:typeof r.stdout==`string`?r.stdout:r.stdout?.toString(`utf8`)??``,stderr:typeof r.stderr==`string`?r.stderr:r.stderr?.toString(`utf8`)??``,...r.error?{error:r.error}:{}}}};function yl(){return p.default.join(nc(),`update-state.json`)}function bl(e){return Fa.parse({type:`gateway.update.status`,payload:e})}var xl=class{packageName;currentVersion;sessionHub;logger;consoleWrite;getRunningSessionCount;requestPreparedUpdate;stateFilePath;checkIntervalMs;runtime;state;scheduledCheckTimer=null;recurringCheckTimer=null;checkPromise=null;applyPromise=null;constructor(e){this.packageName=e.packageName,this.currentVersion=e.currentVersion,this.sessionHub=e.sessionHub,this.logger=e.logger,this.consoleWrite=e.consoleWrite,this.getRunningSessionCount=e.getRunningSessionCount,this.requestPreparedUpdate=e.requestPreparedUpdate,this.stateFilePath=e.stateFilePath??yl(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??vl,this.state=Pa.parse({packageName:this.packageName,currentVersion:this.currentVersion,available:!1,canApply:!1,status:`unknown`,install:{manager:`unknown`,installType:`unknown`,packageName:this.packageName,canSelfUpdate:!1}})}async start(){await this.reconcilePersistedState(),this.scheduledCheckTimer=setTimeout(()=>{this.checkForUpdates(`system`),this.scheduleRecurringChecks()},5e3)}async shutdown(){this.scheduledCheckTimer&&=(clearTimeout(this.scheduledCheckTimer),null),this.recurringCheckTimer&&=(clearInterval(this.recurringCheckTimer),null)}getInfo(){return Pa.parse(this.state)}async getOrCheckInfo(e){if(this.checkPromise)return this.checkPromise;let t=this.getInfo();return t.status===`unknown`||t.status===`failed`?this.checkForUpdates(e):t}async checkForUpdates(e){return this.checkPromise||=(async()=>{let t=this.runtime.now().toISOString(),n=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=wl(this.packageName,this.runtime);if(!r)return this.patchState({status:`failed`,available:!1,canApply:!1,latestVersion:void 0,checkedAt:t,install:n,lastError:`failed to query latest published gateway version`}),this.getInfo();let i=A(r,this.currentVersion)>0,a=i&&n.canSelfUpdate,o=i?a?`available`:`unsupported_install`:`up_to_date`;if(this.patchState({status:o,latestVersion:r,available:i,canApply:a,checkedAt:t,install:n,job:void 0,lastError:void 0}),i&&e!==`mobile`){let e=a?`[gateway] update available ${this.currentVersion} -> ${r}. Type update and press Enter to install and restart.`:`[gateway] update available ${this.currentVersion} -> ${r}, but this installation cannot self-update (${n.reason??`unsupported install`}).`;this.consoleWrite?.(e)}else e===`console`&&this.consoleWrite?.(`[gateway] already up to date at ${this.currentVersion}`);return this.getInfo()})().finally(()=>{this.checkPromise=null}),this.checkPromise}async applyUpdate(e){return this.applyPromise||=(async()=>{let t=await this.checkForUpdates(e);if(!t.available)throw Error(`gateway is already up to date`);if(!t.canApply||t.install.manager===`unknown`)throw Error(t.install.reason??`gateway installation does not support self-update`);if(t.status===`updating`||t.status===`restarting`)return Ia.parse({started:!1,update:t});let n=await this.getRunningSessionCount();if(n>0)throw Error(`gateway update requires idle runtime, found ${n} running session${n===1?``:`s`}`);let r=t.latestVersion;if(!r)throw Error(`latest gateway version is unknown`);let i=this.runtime.currentContext(),a={id:`gwupd_${Date.now()}`,targetVersion:r,requestedBy:e,requestedAt:this.runtime.now().toISOString(),startedAt:this.runtime.now().toISOString()},o={version:1,update:{...t,status:`updating`,job:a,lastError:void 0},helper:{manager:t.install.manager,packageName:this.packageName,targetVersion:r,originalPid:i.pid,restart:Pl(t.install,{cwd:i.cwd,argv:[...i.argv]}),requestedBy:e,requestedAt:a.requestedAt}},s=o.helper;if(!s)throw Error(`gateway update helper state was not prepared`);await Il(this.stateFilePath,o),this.patchState({status:`updating`,job:a,lastError:void 0}),this.consoleWrite?.(`[gateway] updating ${this.packageName} to ${r} via ${t.install.manager}; gateway will restart automatically.`),this.patchState({status:`restarting`,job:a}),this.logger.info?.({job:a,stateFilePath:this.stateFilePath,originalPid:i.pid,install:t.install,restart:s.restart},`gateway update handoff prepared`);try{await this.requestPreparedUpdate?.({stateFilePath:this.stateFilePath,targetVersion:r,requestedBy:e})}catch(e){let t=Pa.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await Il(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(bl(t)),e}return Ia.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=Pa.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(bl(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await Fl(this.stateFilePath);if(!e)return;let t=Tl({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime}),n=e.helper?.targetVersion??e.update.job?.targetVersion;if((e.update.status===`updating`||e.update.status===`restarting`)&&n){let r=A(this.currentVersion,n)>=0,i=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,latestVersion:r?this.currentVersion:n,available:!r,canApply:!r&&t.canSelfUpdate,status:r?`up_to_date`:`failed`,checkedAt:this.runtime.now().toISOString(),install:t,job:void 0,...r?{lastError:void 0}:{lastError:e.update.lastError??`gateway restarted before update completed`}});await Il(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=Pa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Sl(e,t={}){let n=t.runtime??vl,r=t.waitForProcessExit??Ll,i=t.logger,a=await Fl(e);if(!a?.helper)throw Error(`gateway update helper state is missing`);i?.info?.({stateFilePath:e,originalPid:a.helper.originalPid,packageName:a.helper.packageName,targetVersion:a.helper.targetVersion,manager:a.helper.manager,cwd:a.helper.restart.cwd},`gateway update apply starting`);let o=Date.now();await r(a.helper.originalPid);let s=Date.now()-o,c=Rl(a.helper.originalPid);i?.[c?`warn`:`info`]?.({stateFilePath:e,originalPid:a.helper.originalPid,waitDurationMs:s,processStillRunning:c},c?`gateway update original process still running after wait window`:`gateway update original process exited`);let l=Cl(a.helper.manager,a.helper.packageName,a.helper.targetVersion);i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd},`gateway update install starting`);let u=Date.now(),d=n.runCommand(l.command,l.args,{cwd:a.helper.restart.cwd}),f=Date.now()-u;if(d.status!==0){let t={...a,update:{...a.update,status:`failed`,lastError:Bl(l.command,l.args,d)},helper:void 0};return await Il(e,t),i?.error?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status,error:d.error?.message,stderr:d.stderr.trim()||void 0,stdout:d.stdout.trim()||void 0},`gateway update install failed`),{updated:!1,update:Pa.parse(t.update)}}i?.info?.({stateFilePath:e,command:l.command,args:l.args,cwd:a.helper.restart.cwd,installDurationMs:f,status:d.status},`gateway update install completed`);let p={...a,update:{...a.update,status:`restarting`,lastError:void 0},helper:void 0};return await Il(e,p),i?.info?.({stateFilePath:e,targetVersion:a.helper.targetVersion},`gateway update apply completed; worker restart may proceed`),{updated:!0,update:Pa.parse(p.update)}}function Cl(e,t,n){switch(e){case`npm`:return{command:`npm`,args:[`install`,`-g`,`${t}@${n}`]};case`pnpm`:return{command:`pnpm`,args:[`add`,`-g`,`${t}@${n}`]};case`yarn`:return{command:`yarn`,args:[`global`,`add`,`${t}@${n}`]}}}function wl(e,t){let n=t.runCommand(`npm`,[`view`,e,`version`,`--json`]);if(n.error||n.status!==0)return null;let r=n.stdout.trim();if(!r)return null;try{let e=JSON.parse(r);return typeof e==`string`&&e.trim()?e.trim():null}catch{return r.replace(/^"+|"+$/g,``)}}function Tl(e){let t=kl(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?Ma.parse({manager:`unknown`,installType:`dev_workspace`,packageName:e.packageName,packageRoot:t.packageRoot,canSelfUpdate:!1,reason:`workspace/development runtime does not support self-update`}):e.currentScriptPath?El(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Dl(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ol(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Ma.parse({manager:`unknown`,installType:t.packageName===e.packageName?`unknown`:`standalone_binary`,packageName:e.packageName,...t.packageRoot?{packageRoot:t.packageRoot}:{},canSelfUpdate:!1,reason:t.packageName===e.packageName?`unable to determine global package manager installation`:`gateway is not running from a supported package-manager installation`}):Ma.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function El(e,t,n,r){let i=r.runCommand(`npm`,[`root`,`-g`]),a=r.runCommand(`npm`,[`prefix`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=jl(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),Nl(r.platform)),m=Ml(l,d)?`global_registry`:`global_file`;return Ma.parse({manager:`npm`,installType:m,packageName:e,packageRoot:l,binPath:f,canSelfUpdate:m===`global_registry`,...m===`global_registry`?{}:{reason:`npm file-linked global install is not supported`}})}function Dl(e,t,n,r){let i=r.runCommand(`pnpm`,[`root`,`-g`]),a=r.runCommand(`pnpm`,[`bin`,`-g`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);if(!Al(l,t,n))return null;let d=Ml(l,jl(p.default.dirname(o)))?`global_registry`:`global_file`;return Ma.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Ol(e,t,n,r){let i=r.runCommand(`yarn`,[`global`,`dir`]),a=r.runCommand(`yarn`,[`global`,`bin`]);if(i.status!==0||a.status!==0)return null;let o=i.stdout.trim(),s=a.stdout.trim();if(!o||!s)return null;let c=p.default.join(o,`node_modules`,e);if(!u.default.existsSync(p.default.join(c,`package.json`)))return null;let l=jl(c);return Al(l,t,n)?Ma.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,Nl(r.platform)),canSelfUpdate:!0}):null}function kl(e){if(!e)return{packageRoot:null,packageName:null};let t=p.default.dirname(e);for(;;){let e=p.default.join(t,`package.json`);if(u.default.existsSync(e))try{let n=JSON.parse(u.default.readFileSync(e,`utf8`));if(typeof n.name==`string`)return{packageRoot:t,packageName:n.name}}catch{return{packageRoot:t,packageName:null}}let n=p.default.dirname(t);if(n===t)return{packageRoot:null,packageName:null};t=n}}function Al(e,t,n){let r=jl(e),i=t?jl(t):null,a=jl(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function jl(e){try{return u.default.realpathSync(e)}catch{return e}}function Ml(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function Nl(e=v.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function Pl(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function Fl(e){try{let t=await d.default.readFile(e,`utf8`);return Vl(JSON.parse(t))}catch{return null}}async function Il(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0}),await d.default.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}async function Ll(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!Rl(e))return;await zl(500)}}function Rl(e){try{return v.default.kill(e,0),!0}catch{return!1}}function zl(e){return new Promise(t=>setTimeout(t,e))}function Bl(e,t,n){let r=n.stderr.trim(),i=n.stdout.trim(),a=r||i||n.error?.message||`exit code ${String(n.status)}`;return`${e} ${t.join(` `)} failed: ${a}`}function Vl(e){if(!Wl(e)||e.version!==1)return null;let t=Pa.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=Hl(e.helper);return n?{version:1,update:t.data,helper:n}:null}function Hl(e){if(!Wl(e))return null;let t=ka.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=ja.safeParse(e.requestedBy);if(!n.success||!Gl(e.packageName)||!Gl(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!Kl(e.requestedAt))return null;let r=Ul(e.restart);return r?{manager:t.data,packageName:e.packageName,targetVersion:e.targetVersion,originalPid:e.originalPid,restart:r,requestedBy:n.data,requestedAt:e.requestedAt}:null}function Ul(e){return!Wl(e)||!Gl(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!Gl(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function Wl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gl(e){return typeof e==`string`&&e.trim().length>0}function Kl(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}const ql=3e4;async function Jl(e){let t=Xl(),n=$l(e.loaded.config.gatewayLogPath),r=new Map,i=0,a=null,o=!1,s=null,c=null,l=!1,u=null,d=null,f=null,p=null,h=null,g=0,_=0,y=!1,b=Rc(t,`__worker`,e.args),x=new Promise((e,t)=>{s=e,c=t}),S=()=>{f&&=(clearTimeout(f),null)},C=()=>{p&&=(clearTimeout(p),null)},w=()=>{h&&=(clearTimeout(h),null)},T=()=>{d&&=(clearTimeout(d),null)},E=Yl({enabled:v.default.stdin.isTTY&&v.default.stdout.isTTY,onUpdate:async()=>{if(!(!a||l))try{let e=await ne(`console`);if(e.started){console.log(`[gateway] update accepted; restarting into ${e.update.job?.targetVersion??`latest`}...`);return}console.log(`[gateway] update already ${e.update.status}`)}catch(e){console.error(`[gateway] update failed: ${String(e)}`)}},onRestartCodex:async()=>{if(!(!a||l))try{let e=await re(`console`);console.log(`[gateway] codex app-server restarted; closed ${e.closedRuntimeSessionCount} runtime session${e.closedRuntimeSessionCount===1?``:`s`}.`)}catch(e){console.error(`[gateway] codex app-server restart failed: ${String(e)}`)}}}),D=e=>{for(let t of r.values())t.reject(e);r.clear()},O=e=>{w(),T(),S(),C(),E(),D(Error(`gateway supervisor shutting down`)),n.close(),v.default.exit(e)},k=e=>{e.stdout&&e.stdout.unpipe(v.default.stdout),e.stderr&&e.stderr.unpipe(v.default.stderr)},A=()=>{if(o||y)return;y=!0,w(),T(),S(),C();let e=Error(`Gateway worker did not report ready within ${ql}ms after ${_} launch attempt${_===1?``:`s`}.`);n.error({error:e,workerPid:a?.pid??void 0,workerLaunchCount:_,workerRestartAttempt:g,invocation:b},`gateway supervisor initial worker ready timed out`),console.error(`[gateway] ${e.message}`);let t=a;if(a=null,t){k(t),t.removeAllListeners();try{t.kill(`SIGTERM`)}catch{}}c?.(e),s=null,c=null},j=(e,t)=>{if(l||y||u||p)return;g+=1;let r=Math.min(g-1,4),i=Math.min(15e3,1e3*2**r);n.warn({...t,reason:e,delayMs:i,restartAttempt:g,invocation:b,initialReadyReceived:o},`gateway supervisor scheduling worker restart`),console.error(`[gateway] worker exited unexpectedly; restarting in ${i}ms (attempt ${g}).`),p=setTimeout(()=>{p=null,P(b)},i)},M=e=>{if(a){n.info({reason:e,workerPid:a.pid??void 0,preparedUpdate:u},`gateway supervisor requested worker shutdown`);try{a.send?.({type:`supervisor.shutdown`,reason:e})}catch(t){n.warn({reason:e,workerPid:a.pid??void 0,error:t},`gateway supervisor failed to send graceful shutdown message; sending SIGTERM`),a.kill(`SIGTERM`)}S(),f=setTimeout(()=>{a?.kill(`SIGTERM`)},1e4)}},ee=async r=>{n.info(r,`gateway supervisor continuing prepared update`),console.log(`[gateway] applying update to ${r.targetVersion}...`);let i=await Sl(r.stateFilePath,{logger:n}),a=i.updated&&i.update.install.binPath?zc(i.update.install,`__worker`,e.args,t.cwd):Rc(t,`__worker`,e.args);n.info({updated:i.updated,update:i.update,nextInvocation:a},`gateway supervisor prepared next worker invocation`),!i.updated&&i.update.lastError&&console.error(`[gateway] update failed: ${i.update.lastError}`),i.updated?console.log(`[gateway] update installed; restarting worker...`):console.log(`[gateway] relaunching current worker after failed update.`),u=null,b=a,P(a)},N=(e,t)=>{if(S(),T(),n.info({workerPid:a?.pid??void 0,code:e,signal:t,preparedUpdate:u,shuttingDown:l},`gateway supervisor observed worker exit`),a=null,u){D(Error(`gateway worker restarting for update`)),ee(u).catch(e=>{n.error({error:e,preparedUpdate:u},`gateway update handoff failed`),console.error(`[gateway] update handoff failed: ${String(e)}`),O(1)});return}if(l){O(0);return}D(Error(`gateway worker exited`)),t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),j(`worker_exit`,{code:e,signal:t})},te=t=>{switch(t.type){case`worker.ready`:if(g=0,C(),!o){o=!0,w(),n.info(t.payload,`gateway supervisor received initial worker ready`),console.log(pl({configPath:e.loaded.configPath,createdDefaultConfig:e.loaded.createdDefaultConfig,config:e.loaded.config,doctorReport:e.doctorReport,startedServer:t.payload,logToConsole:e.args.logToConsole})),s?.(),s=null,c=null;return}n.info(t.payload,`gateway supervisor received worker ready after update`),console.log(`[gateway] worker ready after update.`);return;case`worker.response`:{let e=r.get(t.id);if(!e)return;r.delete(t.id),t.ok?e.resolve(t.result):e.reject(Error(t.error));return}case`worker.update.prepared`:if(u)return;u=t.payload,n.info(t.payload,`gateway supervisor received worker update prepared`),T(),d=setTimeout(()=>{M(`update`)},250);return}},P=e=>{b=e,C(),_+=1,n.info(e,`gateway supervisor spawning worker`);let t=(0,m.spawn)(e.command,e.args,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0});a=t,n.info({workerPid:t.pid??void 0,invocation:e},`gateway supervisor spawned worker`),t.stdout&&t.stdout.pipe(v.default.stdout),t.stderr&&t.stderr.pipe(v.default.stderr),t.on(`message`,e=>{let t=Zl(e);t&&te(t)}),t.on(`exit`,(e,n)=>{a===t&&(k(t),N(e,n))}),t.on(`error`,r=>{a===t&&(k(t),a=null,n.error({error:r,invocation:e},`gateway supervisor failed to launch worker`),console.error(`[gateway] failed to launch worker: ${String(r)}`),j(`worker_launch_error`,{error:r}))})},ne=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`gateway.update.apply`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},re=e=>{let t=a;if(!t?.send)throw Error(`gateway worker is unavailable`);let n=`worker_req_${i+=1}`;return new Promise((i,a)=>{r.set(n,{resolve:e=>i(e),reject:a});try{t.send?.({type:`supervisor.request`,id:n,method:`codex.appServer.restart`,requestedBy:e})}catch(e){r.delete(n),a(e instanceof Error?e:Error(String(e)))}})},F=e=>{if(!l){if(l=!0,n.info({signal:e},`gateway supervisor received shutdown signal`),console.log(`[gateway] received ${e}; shutting down...`),!a){O(0);return}M(`signal`)}};v.default.on(`SIGINT`,F),v.default.on(`SIGTERM`,F),h=setTimeout(()=>{A()},ql),P(b);try{await x}catch(e){throw v.default.removeListener(`SIGINT`,F),v.default.removeListener(`SIGTERM`,F),w(),T(),S(),C(),D(Error(`gateway supervisor failed to start`)),E(),n.close(),e}}function Yl(e){if(!e.enabled)return()=>{};let t=_.default.createInterface({input:v.default.stdin,output:v.default.stdout,terminal:!0});return t.on(`line`,t=>{let n=t.trim().toLowerCase();if(n===`update`){e.onUpdate();return}if(n===`restart codex`||n===`codex restart`){e.onRestartCodex();return}}),()=>{t.close()}}function Xl(){return{pid:v.default.pid,cwd:v.default.cwd(),argv:v.default.argv.slice(2),execArgv:[...v.default.execArgv],execPath:v.default.execPath,scriptPath:v.default.argv[1]??null}}function Zl(e){if(!Ql(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return Ql(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||typeof e.ok!=`boolean`?null:e.ok?(e.method,{type:`worker.response`,id:e.id,method:e.method,ok:!0,result:e.result}):typeof e.error==`string`?{type:`worker.response`,id:e.id,method:e.method,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!Ql(e.payload)||typeof e.payload.stateFilePath!=`string`||typeof e.payload.targetVersion!=`string`||e.payload.requestedBy!==`console`&&e.payload.requestedBy!==`mobile`&&e.payload.requestedBy!==`system`?null:{type:`worker.update.prepared`,payload:{stateFilePath:e.payload.stateFilePath,targetVersion:e.payload.targetVersion,requestedBy:e.payload.requestedBy}};default:return null}}function Ql(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $l(e){let t=f.default.hostname();u.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=(n,r,i)=>{let a={level:n,time:Date.now(),pid:v.default.pid,hostname:t,...eu(r),msg:i??``};try{u.default.appendFileSync(e,`${JSON.stringify(a,tu)}\n`,`utf8`)}catch{}};return{info:(e,t)=>{n(30,e,t)},warn:(e,t)=>{n(40,e,t)},error:(e,t)=>{n(50,e,t)},close:()=>{}}}function eu(e){return Ql(e)?e:{detail:e}}function tu(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t==`bigint`?t.toString():t}async function nu(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function ru(e,t){let n=t.httpsEnabled?t.httpsPort:t.port,r=t.httpsEnabled?`https`:`http`,i=e;return i?.code===`EADDRINUSE`?`[gateway] failed to start: ${r.toUpperCase()} ${t.host}:${n} is already in use.`:i?.code===`EACCES`?`[gateway] failed to start: permission denied for ${r.toUpperCase()} ${t.host}:${n}.`:i?.code===`ENOENT`||i?.code===`EISDIR`?`[gateway] failed to start: log path is invalid or unavailable: ${t.gatewayLogPath}`:i instanceof Error?`[gateway] failed to start: ${i.message}`:`[gateway] failed to start: ${String(e)}`}var iu=o(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),au=o(((e,t)=>{var n=iu();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:w,abort:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(){var e=s;for(s=null,c=null;e;){var t=e.next,n=e.callback,r=e.errorHandler,a=e.value,o=e.context;e.value=null,e.callback=i,e.errorHandler=null,r&&r(Error(`abort`),a),n.call(o,Error(`abort`)),e.release(e),e=t}d.drain=i}function w(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),ou=o(((e,t)=>{let{format:n}=require(`node:util`);function r(){return`${this.name} [${this.code}]: ${this.message}`}let i=Symbol.for(`fastify-error-generic`);function a(e,t,o=500,s=Error,c=a.captureStackTrace){let l=e===i;if(l&&(e=`FST_ERR`),!e)throw Error(`Fastify error code must not be empty`);if(!t)throw Error(`Fastify error message must not be empty`);e=e.toUpperCase(),!o&&(o=void 0);let u=Symbol.for(`fastify-error ${e}`);function d(...r){if(!new.target)return new d(...r);this.code=e,this.name=`FastifyError`,this.statusCode=o;let i=r.length-1;i!==-1&&r[i]&&typeof r[i]==`object`&&`cause`in r[i]&&(this.cause=r.pop().cause),this.message=n(t,...r),Error.stackTraceLimit&&c&&Error.captureStackTrace(this,d)}return d.prototype=Object.create(s.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0},[i]:{value:!0,enumerable:!1,writable:!1,configurable:!1},[u]:{value:!0,enumerable:!1,writable:!1,configurable:!1}}),l?Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[i]},configurable:!1,writable:!1,enumerable:!1}):Object.defineProperty(d,Symbol.hasInstance,{value(e){return e&&e[u]},configurable:!1,writable:!1,enumerable:!1}),d.prototype[Symbol.toStringTag]=`Error`,d.prototype.toString=r,d}a.captureStackTrace=!0;let o=a(i,`Fastify Error`,500,Error);t.exports=a,t.exports.FastifyError=o,t.exports.default=a,t.exports.createError=a})),su=o(((e,t)=>{let{createError:n}=ou();t.exports={AVV_ERR_EXPOSE_ALREADY_DEFINED:n(`AVV_ERR_EXPOSE_ALREADY_DEFINED`,`'%s' is already defined, specify an expose option for '%s'`),AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:n(`AVV_ERR_ATTRIBUTE_ALREADY_DEFINED`,`'%s' is already defined`),AVV_ERR_CALLBACK_NOT_FN:n(`AVV_ERR_CALLBACK_NOT_FN`,`Callback for '%s' hook is not a function. Received: '%s'`),AVV_ERR_PLUGIN_NOT_VALID:n(`AVV_ERR_PLUGIN_NOT_VALID`,`Plugin must be a function or a promise. Received: '%s'`),AVV_ERR_ROOT_PLG_BOOTED:n(`AVV_ERR_ROOT_PLG_BOOTED`,`Root plugin has already booted`),AVV_ERR_PARENT_PLG_LOADED:n(`AVV_ERR_PARENT_PLG_LOADED`,`Impossible to load '%s' plugin because the parent '%s' was already loaded`),AVV_ERR_READY_TIMEOUT:n(`AVV_ERR_READY_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`),AVV_ERR_PLUGIN_EXEC_TIMEOUT:n(`AVV_ERR_PLUGIN_EXEC_TIMEOUT`,`Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise`)}})),cu=o(((e,t)=>{t.exports={kAvvio:Symbol(`avvio.Boot`),kIsOnCloseHandler:Symbol(`isOnCloseHandler`),kThenifyDoNotWrap:Symbol(`avvio.ThenifyDoNotWrap`),kUntrackNode:Symbol(`avvio.TimeTree.untrackNode`),kTrackNode:Symbol(`avvio.TimeTree.trackNode`),kGetParent:Symbol(`avvio.TimeTree.getParent`),kGetNode:Symbol(`avvio.TimeTree.getNode`),kAddNode:Symbol(`avvio.TimeTree.addNode`),kPluginMeta:Symbol.for(`plugin-meta`)}})),lu=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=cu();var s=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[r](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[n](e){this.tableId.delete(e.id);let t=this.tableLabel.get(e.label);t.pop(),t.length===0&&this.tableLabel.delete(e.label)}[i](e){if(e===null)return null;if(this.tableLabel.has(e)){let t=this.tableLabel.get(e);return t[t.length-1]}else return null}[a](e){return this.tableId.get(e)}[o](e,t,n){let a=this[i](e);if(a===null)return this.root={parent:null,id:`root`,label:t,nodes:[],start:n,stop:null,diff:-1},this[r](this.root),this.root.id;let o=`${t}-${Math.random()}`,s={parent:e,id:o,label:t,nodes:[],start:n,stop:null,diff:-1};return a.nodes.push(s),this[r](s),o}start(e,t,n=Date.now()){return this[o](e,t,n)}stop(e,t=Date.now()){let r=this[a](e);r&&(r.stop=t,r.diff=r.stop-r.start||0,this[n](r))}toJSON(){return Object.assign({},this.root)}prettyPrint(){return c(this.toJSON())}};function c(e,t=``){let n=t,r=e.nodes.length,i=r-1;n+=`${e.label} ${e.diff} ms\n`;for(let a=0;a<r;++a){let r=e.nodes[a],o=t+(a===i?` `:`│ `);n+=t,n+=a===i?`└─`:`├─`,n+=r.nodes.length===0?`─ `:`┬ `,n+=c(r,o).slice(t.length+2)}return n}t.exports={TimeTree:s}})),uu=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),du=o(((e,t)=>{function n(){let e={resolve:null,reject:null,promise:null};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}t.exports={createPromise:n}})),fu=o(((e,t)=>{let{kPluginMeta:n}=cu();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
124
+ `).slice(0,2).map(e=>e.trim()).join(` -- `)}t.exports={getPluginName:r}})),pu=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}t.exports={isPromiseLike:n}})),mu=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{inherits:r}=require(`node:util`),{debug:i}=uu(),{createPromise:a}=du(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:o}=su(),{getPluginName:s}=fu(),{isPromiseLike:c}=pu();function l(e,t,n,r,i){this.queue=e,this.func=t,this.options=n,this.isAfter=r,this.timeout=i,this.started=!1,this.name=s(t,n),this.queue.pause(),this._error=null,this.loaded=!1,this._promise=null,this.startTime=null}r(l,n),l.prototype.exec=function(e,t){i(`exec`,this.name),this.server=e;let n=this.func,r=this.name,a=!1;this.options=typeof this.options==`function`?this.options(this.server):this.options;let s=null,l=e=>{if(a){i(`loading complete`,r);return}this._error=e,i(e?`exec errored`:`exec completed`,r),a=!0,s&&clearTimeout(s),t(e)};this.timeout>0&&(i(`setting up timeout`,r,this.timeout),s=setTimeout(function(){i(`timed out`,r),s=null;let e=new o(r);e.fn=n,l(e)},this.timeout)),this.started=!0,this.startTime=Date.now(),this.emit(`start`,this.server?this.server.name:null,this.name,Date.now());let u=n(this.server,this.options,l);c(u)?(i(`exec: resolving promise`,r),u.then(()=>process.nextTick(l),e=>process.nextTick(l,e))):n.length<3&&l()},l.prototype.loadedSoFar=function(){if(i(`loadedSoFar`,this.name),this.loaded)return Promise.resolve();let e=()=>{this.server.after((e,t)=>{this._error=e,this.queue.pause(),this._promise&&=(e?(i(`rejecting promise`,this.name,e),this._promise.reject(e)):(i(`resolving promise`,this.name),this._promise.resolve()),null),process.nextTick(t,e)}),this.queue.resume()},t;return this._promise?t=Promise.resolve():(this._promise=a(),t=this._promise.promise,this.server?e():this.on(`start`,e)),t},l.prototype.enqueue=function(e,t){i(`enqueue`,this.name,e.name),this.emit(`enqueue`,this.server?this.server.name:null,this.name,Date.now()),this.queue.push(e,t)},l.prototype.finish=function(e,t){i(`finish`,this.name,e);let n=()=>{this.loaded||(i(`loaded`,this.name),this.emit(`loaded`,this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,t(e))};if(e){this._promise&&=(this._promise.reject(e),null),n();return}let r=()=>{if(i(`check`,this.name,this.queue.length(),this.queue.running(),this._promise),this.queue.length()===0&&this.queue.running()===0)if(this._promise){let e=()=>{i(`wrap`),queueMicrotask(r)};this._promise.resolve(),this._promise.promise.then(e,e),this._promise=null}else n();else i(`delayed`,this.name),this.queue.drain=()=>{i(`drain`,this.name),this.queue.drain=u,queueMicrotask(r)}};queueMicrotask(r),this.queue.resume()};function u(){}t.exports={Plugin:l}})),hu=o(((e,t)=>{let{AVV_ERR_PLUGIN_NOT_VALID:n}=su();function r(e){if(!(e&&(typeof e==`function`||typeof e.then==`function`)))throw Array.isArray(e)?new n(`array`):e===null?new n(`null`):new n(typeof e)}t.exports={validatePlugin:r}})),gu=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.default==`function`}t.exports={isBundledOrTypescriptPlugin:n}})),_u=o(((e,t)=>{let{debug:n}=uu(),{kThenifyDoNotWrap:r}=cu();function i(){if(this.booted){n(`thenify returning undefined because we are already booted`);return}if(this[r]){this[r]=!1;return}return n(`thenify`),(e,t)=>this._loadRegistered().then(()=>(this[r]=!0,e(this._server)),t)}t.exports={thenify:i}})),vu=o(((e,t)=>{let{isPromiseLike:n}=pu(),{kAvvio:r}=cu();function i(e,t,i){let a;try{a=e.apply(e,t)}catch(e){i&&process.nextTick(i,e);return}n(a)&&!a[r]?a.then(()=>process.nextTick(i),e=>process.nextTick(i,e)):i&&process.nextTick(i)}t.exports={executeWithThenable:i}})),yu=o(((e,t)=>{let n=au(),r=require(`node:events`).EventEmitter,i=require(`node:util`).inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:a,AVV_ERR_CALLBACK_NOT_FN:o,AVV_ERR_ROOT_PLG_BOOTED:s,AVV_ERR_READY_TIMEOUT:c,AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:l}=su(),{kAvvio:u,kIsOnCloseHandler:d}=cu(),{TimeTree:f}=lu(),{Plugin:p}=mu(),{debug:m}=uu(),{validatePlugin:h}=hu(),{isBundledOrTypescriptPlugin:g}=gu(),{isPromiseLike:_}=pu(),{thenify:v}=_u(),{executeWithThenable:y}=vu();function b(e,t,r){if(typeof e==`function`&&arguments.length===1&&(r=e,t={},e=null),typeof t==`function`&&(r=t,t={}),t||={},t.autostart=t.autostart!==!1,t.timeout=Number(t.timeout)||0,t.expose=t.expose||{},!new.target)return new b(e,t,r);this._server=e||this,this._opts=t,e&&this._expose(),this._current=[],this._error=null,this._lastUsed=null,this.setMaxListeners(0),r&&this.once(`start`,r),this.started=!1,this.booted=!1,this.pluginTree=new f,this._readyQ=n(this,S,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit(`start`),this._readyQ.drain=x},this._closeQ=n(this,w,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit(`close`),this._closeQ.drain=x},this._doStart=null;let i=this;this._root=new p(n(this,this._loadPluginNextTick,1),function(e,t,n){i._doStart=n,t.autostart&&i.start()},t,!1,0),this._trackPluginLoading(this._root),this._loadPlugin(this._root,e=>{m(`root plugin ready`);try{this.emit(`preReady`),this._root=null}catch(t){e=e||this._error||t}if(e){if(this._error=e,this._readyQ.length()===0)throw e}else this.booted=!0;this._readyQ.resume()})}i(b,r),`asyncDispose`in Symbol&&(b.prototype[Symbol.asyncDispose]=function(){return new Promise((e,t)=>{this.close(n=>{if(n)return t(n);e()})})}),b.prototype.start=function(){return this.started=!0,process.nextTick(this._doStart),this},b.prototype.override=function(e,t,n){return e},b.prototype[u]=!0,b.prototype.use=function(e,t){return this._lastUsed=this._addPlugin(e,t,!1),this},b.prototype._loadRegistered=function(){let e=this._current[0];return!this.started&&!this.booted&&process.nextTick(()=>this._root.queue.resume()),e?e.loadedSoFar():Promise.resolve()},Object.defineProperty(b.prototype,`then`,{get:v}),b.prototype._addPlugin=function(e,t,r){if(g(e)&&(e=e.default),h(e),t||={},this.booted)throw new s;let i=this._current[0],a=this._opts.timeout;if(!i.loaded&&i.timeout>0){let e=Date.now()-i.startTime;a=i.timeout-(e+3)}let o=new p(n(this,this._loadPluginNextTick,1),e,t,r,a);if(this._trackPluginLoading(o),i.loaded)throw Error(o.name,i.name);return i.enqueue(o,e=>{e&&(this._error=e)}),o},b.prototype._expose=function(){let e=this,t=e._server,{use:n=`use`,after:r=`after`,ready:i=`ready`,onClose:s=`onClose`,close:c=`close`}=this._opts.expose;if(t[n])throw new a(n,`use`);if(t[n]=function(t,n){return e.use(t,n),this},t[r])throw new a(r,`after`);if(t[r]=function(t){return typeof t==`function`?(e.after(E(t,this)),this):e._loadRegistered()},t[i])throw new a(i,`ready`);if(t[i]=function(t){if(t&&typeof t!=`function`)throw new o(i,typeof t);return e.ready(t?E(t,this):void 0)},t[s])throw new a(s,`onClose`);if(t[s]=function(t){if(typeof t!=`function`)throw new o(s,typeof t);return e.onClose(T(t,this)),this},t[c])throw new a(c,`close`);if(t[c]=function(t){if(t&&typeof t!=`function`)throw new o(c,typeof t);return t?(e.close(E(t,this)),this):e.close()},t.then)throw new l(`then`);Object.defineProperty(t,`then`,{get:v.bind(e)}),t[u]=!0},b.prototype.after=function(e){if(!e)return this._loadRegistered();this._addPlugin(t.bind(this),{},!0);function t(t,n,r){S.call(this,e,r)}return this},b.prototype.onClose=function(e){if(typeof e!=`function`)throw new o(`onClose`,typeof e);return e[d]=!0,this._closeQ.unshift(e,e=>{e&&(this._error=e)}),this},b.prototype.close=function(e){let t;if(e){if(typeof e!=`function`)throw new o(`close`,typeof e)}else t=new Promise(function(t,n){e=function(e){if(e)return n(e);t()}});return this.ready(()=>{this._error=null,this._closeQ.push(e),process.nextTick(this._closeQ.resume.bind(this._closeQ))}),t},b.prototype.ready=function(e){if(e){if(typeof e!=`function`)throw new o(`ready`,typeof e);this._readyQ.push(e),queueMicrotask(this.start.bind(this));return}return new Promise((e,t)=>{this._readyQ.push(r),this.start();let n=this._current[0].server;function r(r,i,a){r?t(r):e(n),process.nextTick(a)}})},b.prototype._trackPluginLoading=function(e){let t=this._current[0]?.name||null;e.once(`start`,(n,r,i)=>{let a=this.pluginTree.start(t||null,r,i);e.once(`loaded`,(e,t,n)=>{this.pluginTree.stop(a,n)})})},b.prototype.prettyPrint=function(){return this.pluginTree.prettyPrint()},b.prototype.toJSON=function(){return this.pluginTree.toJSON()},b.prototype._loadPlugin=function(e,t){let n=this;if(_(e.func)){e.func.then(n=>{typeof n.default==`function`&&(n=n.default),e.func=n,this._loadPlugin(e,t)},t);return}let r=n._current[0];if(n._current.unshift(e),n._error&&!e.isAfter){m(`skipping loading of plugin as instance errored and it is not an after`,e.name),process.nextTick(a);return}let i=r?.server||n._server;if(!e.isAfter)try{i=n.override(i,e.func,e.options)}catch(t){return m(`override errored`,e.name),a(t)}e.exec(i,a);function a(r){e.finish(r,e=>{n._current.shift(),t(e)})}},b.prototype._loadPluginNextTick=function(e,t){process.nextTick(this._loadPlugin.bind(this),e,t)};function x(){}function S(e,t){let n=this._server,r=this._error;if(this._error=null,e.length===0)this._error=r,y(e,[],t);else if(e.length===1)y(e,[r],t);else if(this._opts.timeout===0){let i=e=>{this._error=e,t(this._error)};e.length===2?e(r,i):e(r,n,i)}else C.call(this,e,r,n,t)}function C(e,t,n,r){let i=e.unwrappedName??e.name;m(`setting up ready timeout`,i,this._opts.timeout);let a=setTimeout(()=>{m(`timed out`,i),a=null;let t=new c(i);t.fn=e,this._error=t,r(t)},this._opts.timeout);e.length===2?e(t,o.bind(this)):e(t,n,o.bind(this));function o(e){a&&(clearTimeout(a),this._error=e,r(this._error))}}function w(e,t){let n=this._server,r=e[d];if(e.length===0||e.length===1){let i;i=e(r?n:this._error),i&&typeof i.then==`function`?(m(`resolving close/onClose promise`),i.then(()=>process.nextTick(t),e=>process.nextTick(t,e))):process.nextTick(t)}else e.length===2?e(r?n:this._error,t):r?e(n,t):e(this._error,n,t)}function T(e,t){return n.bind(t);function n(t,n){let r;e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===1?(r=e(this),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e(this,n)}}function E(e,t){let n=r.bind(t);return n.unwrappedName=e.name,n;function r(t,n){let r;e?e.length===0?(r=e(),r?.then?r.then(function(){process.nextTick(n,t)},n):process.nextTick(n,t)):e.length===1?(r=e(t),r?.then?r.then(function(){process.nextTick(n)},n):process.nextTick(n)):e.length===2?e(t,n):e(t,this,n):process.nextTick(n)}}t.exports=b})),bu=o(((e,t)=>{t.exports={kAvvioBoot:Symbol(`fastify.avvioBoot`),kChildren:Symbol(`fastify.children`),kServerBindings:Symbol(`fastify.serverBindings`),kBodyLimit:Symbol(`fastify.bodyLimit`),kSupportedHTTPMethods:Symbol(`fastify.acceptedHTTPMethods`),kRoutePrefix:Symbol(`fastify.routePrefix`),kLogLevel:Symbol(`fastify.logLevel`),kLogSerializers:Symbol(`fastify.logSerializers`),kHooks:Symbol(`fastify.hooks`),kContentTypeParser:Symbol(`fastify.contentTypeParser`),kState:Symbol(`fastify.state`),kOptions:Symbol(`fastify.options`),kDisableRequestLogging:Symbol(`fastify.disableRequestLogging`),kPluginNameChain:Symbol(`fastify.pluginNameChain`),kRouteContext:Symbol(`fastify.context`),kGenReqId:Symbol(`fastify.genReqId`),kHttp2ServerSessions:Symbol(`fastify.http2ServerSessions`),kSchemaController:Symbol(`fastify.schemaController`),kSchemaHeaders:Symbol(`headers-schema`),kSchemaParams:Symbol(`params-schema`),kSchemaQuerystring:Symbol(`querystring-schema`),kSchemaBody:Symbol(`body-schema`),kSchemaResponse:Symbol(`response-schema`),kSchemaErrorFormatter:Symbol(`fastify.schemaErrorFormatter`),kSchemaVisited:Symbol(`fastify.schemas.visited`),kRequest:Symbol(`fastify.Request`),kRequestPayloadStream:Symbol(`fastify.RequestPayloadStream`),kRequestAcceptVersion:Symbol(`fastify.RequestAcceptVersion`),kRequestCacheValidateFns:Symbol(`fastify.request.cache.validateFns`),kRequestOriginalUrl:Symbol(`fastify.request.originalUrl`),kFourOhFour:Symbol(`fastify.404`),kCanSetNotFoundHandler:Symbol(`fastify.canSetNotFoundHandler`),kFourOhFourLevelInstance:Symbol(`fastify.404LogLevelInstance`),kFourOhFourContext:Symbol(`fastify.404ContextKey`),kDefaultJsonParse:Symbol(`fastify.defaultJSONParse`),kReply:Symbol(`fastify.Reply`),kReplySerializer:Symbol(`fastify.reply.serializer`),kReplyIsError:Symbol(`fastify.reply.isError`),kReplyHeaders:Symbol(`fastify.reply.headers`),kReplyTrailers:Symbol(`fastify.reply.trailers`),kReplyHasStatusCode:Symbol(`fastify.reply.hasStatusCode`),kReplyHijacked:Symbol(`fastify.reply.hijacked`),kReplyStartTime:Symbol(`fastify.reply.startTime`),kReplyNextErrorHandler:Symbol(`fastify.reply.nextErrorHandler`),kReplyEndTime:Symbol(`fastify.reply.endTime`),kReplyErrorHandlerCalled:Symbol(`fastify.reply.errorHandlerCalled`),kReplyIsRunningOnErrorHook:Symbol(`fastify.reply.isRunningOnErrorHook`),kReplySerializerDefault:Symbol(`fastify.replySerializerDefault`),kReplyCacheSerializeFns:Symbol(`fastify.reply.cache.serializeFns`),kTestInternals:Symbol(`fastify.testInternals`),kErrorHandler:Symbol(`fastify.errorHandler`),kErrorHandlerAlreadySet:Symbol(`fastify.errorHandlerAlreadySet`),kChildLoggerFactory:Symbol(`fastify.childLoggerFactory`),kHasBeenDecorated:Symbol(`fastify.hasBeenDecorated`),kKeepAliveConnections:Symbol(`fastify.keepAliveConnections`),kRouteByFastify:Symbol(`fastify.routeByFastify`)}})),xu=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),Su=o(((e,t)=>{let{createWarning:n}=xu();t.exports={FSTWRN001:n({name:`FastifyWarning`,code:`FSTWRN001`,message:`The %s schema for %s: %s is missing. This may indicate the schema is not well specified.`,unlimited:!0}),FSTWRN003:n({name:`FastifyWarning`,code:`FSTWRN003`,message:`The %s mixes async and callback styles that may lead to unhandled rejections. Please use only one of them.`,unlimited:!0}),FSTWRN004:n({name:`FastifyWarning`,code:`FSTWRN004`,message:`It seems that you are overriding an errorHandler in the same scope, which can lead to subtle bugs.`,unlimited:!0}),FSTSEC001:n({name:`FastifySecurity`,code:`FSTSEC001`,message:`You are using /%s/ Content-Type which may be vulnerable to CORS attack. Please make sure your RegExp start with "^" or include ";?" to proper detection of the essence MIME type.`,unlimited:!0}),FSTDEP022:n({name:`FastifyWarning`,code:`FSTDEP022`,message:'The router options for %s property access is deprecated. Please use "options.routerOptions" instead for accessing router options. The router options will be removed in `fastify@6`.',unlimited:!0})}})),Cu=o(((e,t)=>{let n=ou(),r={FST_ERR_NOT_FOUND:n(`FST_ERR_NOT_FOUND`,`Not Found`,404),FST_ERR_OPTIONS_NOT_OBJ:n(`FST_ERR_OPTIONS_NOT_OBJ`,`Options must be an object`,500,TypeError),FST_ERR_QSP_NOT_FN:n(`FST_ERR_QSP_NOT_FN`,`querystringParser option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:n(`FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN`,`schemaController.bucket option should be a function, instead got '%s'`,500,TypeError),FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:n(`FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN`,`schemaErrorFormatter option should be a non async function. Instead got '%s'.`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ`,`ajv.customOptions option should be an object, instead got '%s'`,500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:n(`FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR`,`ajv.plugins option should be an array, instead got '%s'`,500,TypeError),FST_ERR_VALIDATION:n(`FST_ERR_VALIDATION`,`%s`,400),FST_ERR_LISTEN_OPTIONS_INVALID:n(`FST_ERR_LISTEN_OPTIONS_INVALID`,`Invalid listen options: '%s'`,500,TypeError),FST_ERR_ERROR_HANDLER_NOT_FN:n(`FST_ERR_ERROR_HANDLER_NOT_FN`,`Error Handler must be a function`,500,TypeError),FST_ERR_ERROR_HANDLER_ALREADY_SET:n(`FST_ERR_ERROR_HANDLER_ALREADY_SET`,`Error Handler already set in this scope. Set 'allowErrorHandlerOverride: true' to allow overriding.`,500,TypeError),FST_ERR_CTP_ALREADY_PRESENT:n(`FST_ERR_CTP_ALREADY_PRESENT`,`Content type parser '%s' already present.`),FST_ERR_CTP_INVALID_TYPE:n(`FST_ERR_CTP_INVALID_TYPE`,`The content type should be a string or a RegExp`,500,TypeError),FST_ERR_CTP_EMPTY_TYPE:n(`FST_ERR_CTP_EMPTY_TYPE`,`The content type cannot be an empty string`,500,TypeError),FST_ERR_CTP_INVALID_HANDLER:n(`FST_ERR_CTP_INVALID_HANDLER`,`The content type handler should be a function`,500,TypeError),FST_ERR_CTP_INVALID_PARSE_TYPE:n(`FST_ERR_CTP_INVALID_PARSE_TYPE`,`The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.`,500,TypeError),FST_ERR_CTP_BODY_TOO_LARGE:n(`FST_ERR_CTP_BODY_TOO_LARGE`,`Request body is too large`,413,RangeError),FST_ERR_CTP_INVALID_MEDIA_TYPE:n(`FST_ERR_CTP_INVALID_MEDIA_TYPE`,`Unsupported Media Type: %s`,415),FST_ERR_CTP_INVALID_CONTENT_LENGTH:n(`FST_ERR_CTP_INVALID_CONTENT_LENGTH`,`Request body size did not match Content-Length`,400,RangeError),FST_ERR_CTP_EMPTY_JSON_BODY:n(`FST_ERR_CTP_EMPTY_JSON_BODY`,`Body cannot be empty when content-type is set to 'application/json'`,400),FST_ERR_CTP_INVALID_JSON_BODY:n(`FST_ERR_CTP_INVALID_JSON_BODY`,`Body is not valid JSON but content-type is set to 'application/json'`,400),FST_ERR_CTP_INSTANCE_ALREADY_STARTED:n(`FST_ERR_CTP_INSTANCE_ALREADY_STARTED`,`Cannot call "%s" when fastify instance is already started!`,400),FST_ERR_DEC_ALREADY_PRESENT:n(`FST_ERR_DEC_ALREADY_PRESENT`,`The decorator '%s' has already been added!`),FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:n(`FST_ERR_DEC_DEPENDENCY_INVALID_TYPE`,`The dependencies of decorator '%s' must be of type Array.`,500,TypeError),FST_ERR_DEC_MISSING_DEPENDENCY:n(`FST_ERR_DEC_MISSING_DEPENDENCY`,`The decorator is missing dependency '%s'.`),FST_ERR_DEC_AFTER_START:n(`FST_ERR_DEC_AFTER_START`,`The decorator '%s' has been added after start!`),FST_ERR_DEC_REFERENCE_TYPE:n(`FST_ERR_DEC_REFERENCE_TYPE`,`The decorator '%s' of type '%s' is a reference type. Use the { getter, setter } interface instead.`),FST_ERR_DEC_UNDECLARED:n(`FST_ERR_DEC_UNDECLARED`,`No decorator '%s' has been declared on %s.`),FST_ERR_HOOK_INVALID_TYPE:n(`FST_ERR_HOOK_INVALID_TYPE`,`The hook name must be a string`,500,TypeError),FST_ERR_HOOK_INVALID_HANDLER:n(`FST_ERR_HOOK_INVALID_HANDLER`,`%s hook should be a function, instead got %s`,500,TypeError),FST_ERR_HOOK_INVALID_ASYNC_HANDLER:n(`FST_ERR_HOOK_INVALID_ASYNC_HANDLER`,`Async function has too many arguments. Async hooks should not use the 'done' argument.`,500,TypeError),FST_ERR_HOOK_NOT_SUPPORTED:n(`FST_ERR_HOOK_NOT_SUPPORTED`,`%s hook not supported!`,500,TypeError),FST_ERR_MISSING_MIDDLEWARE:n(`FST_ERR_MISSING_MIDDLEWARE`,`You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.`,500),FST_ERR_HOOK_TIMEOUT:n(`FST_ERR_HOOK_TIMEOUT`,`A callback for '%s' hook%s timed out. You may have forgotten to call 'done' function or to resolve a Promise`),FST_ERR_LOG_INVALID_DESTINATION:n(`FST_ERR_LOG_INVALID_DESTINATION`,`Cannot specify both logger.stream and logger.file options`),FST_ERR_LOG_INVALID_LOGGER:n(`FST_ERR_LOG_INVALID_LOGGER`,`Invalid logger object provided. The logger instance should have these functions(s): '%s'.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_INSTANCE:n(`FST_ERR_LOG_INVALID_LOGGER_INSTANCE`,`loggerInstance only accepts a logger instance.`,500,TypeError),FST_ERR_LOG_INVALID_LOGGER_CONFIG:n(`FST_ERR_LOG_INVALID_LOGGER_CONFIG`,`logger options only accepts a configuration object.`,500,TypeError),FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:n(`FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED`,`You cannot provide both logger and loggerInstance. Please provide only one.`,500,TypeError),FST_ERR_REP_INVALID_PAYLOAD_TYPE:n(`FST_ERR_REP_INVALID_PAYLOAD_TYPE`,`Attempted to send payload of invalid type '%s'. Expected a string or Buffer.`,500,TypeError),FST_ERR_REP_RESPONSE_BODY_CONSUMED:n(`FST_ERR_REP_RESPONSE_BODY_CONSUMED`,`Response.body is already consumed.`),FST_ERR_REP_READABLE_STREAM_LOCKED:n(`FST_ERR_REP_READABLE_STREAM_LOCKED`,`ReadableStream was locked. You should call releaseLock() method on reader before sending.`),FST_ERR_REP_ALREADY_SENT:n(`FST_ERR_REP_ALREADY_SENT`,`Reply was already sent, did you forget to "return reply" in "%s" (%s)?`),FST_ERR_REP_SENT_VALUE:n(`FST_ERR_REP_SENT_VALUE`,`The only possible value for reply.sent is true.`,500,TypeError),FST_ERR_SEND_INSIDE_ONERR:n(`FST_ERR_SEND_INSIDE_ONERR`,"You cannot use `send` inside the `onError` hook"),FST_ERR_SEND_UNDEFINED_ERR:n(`FST_ERR_SEND_UNDEFINED_ERR`,`Undefined error has occurred`),FST_ERR_BAD_STATUS_CODE:n(`FST_ERR_BAD_STATUS_CODE`,`Called reply with an invalid status code: %s`),FST_ERR_BAD_TRAILER_NAME:n(`FST_ERR_BAD_TRAILER_NAME`,`Called reply.trailer with an invalid header name: %s`),FST_ERR_BAD_TRAILER_VALUE:n(`FST_ERR_BAD_TRAILER_VALUE`,`Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function.`),FST_ERR_FAILED_ERROR_SERIALIZATION:n(`FST_ERR_FAILED_ERROR_SERIALIZATION`,`Failed to serialize an error. Error: %s. Original error: %s`),FST_ERR_MISSING_SERIALIZATION_FN:n(`FST_ERR_MISSING_SERIALIZATION_FN`,`Missing serialization function. Key "%s"`),FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:n(`FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN`,`Missing serialization function. Key "%s:%s"`),FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:n(`FST_ERR_REQ_INVALID_VALIDATION_INVOCATION`,`Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.`),FST_ERR_SCH_MISSING_ID:n(`FST_ERR_SCH_MISSING_ID`,`Missing schema $id property`),FST_ERR_SCH_ALREADY_PRESENT:n(`FST_ERR_SCH_ALREADY_PRESENT`,`Schema with id '%s' already declared!`),FST_ERR_SCH_CONTENT_MISSING_SCHEMA:n(`FST_ERR_SCH_CONTENT_MISSING_SCHEMA`,`Schema is missing for the content type '%s'`),FST_ERR_SCH_DUPLICATE:n(`FST_ERR_SCH_DUPLICATE`,`Schema with '%s' already present!`),FST_ERR_SCH_VALIDATION_BUILD:n(`FST_ERR_SCH_VALIDATION_BUILD`,`Failed building the validation schema for %s: %s, due to error %s`),FST_ERR_SCH_SERIALIZATION_BUILD:n(`FST_ERR_SCH_SERIALIZATION_BUILD`,`Failed building the serialization schema for %s: %s, due to error %s`),FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:n(`FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX`,`response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }`),FST_ERR_INIT_OPTS_INVALID:n(`FST_ERR_INIT_OPTS_INVALID`,`Invalid initialization options: '%s'`),FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:n(`FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE`,`Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method`),FST_ERR_DUPLICATED_ROUTE:n(`FST_ERR_DUPLICATED_ROUTE`,`Method '%s' already declared for route '%s'`),FST_ERR_BAD_URL:n(`FST_ERR_BAD_URL`,`'%s' is not a valid url component`,400,URIError),FST_ERR_ASYNC_CONSTRAINT:n(`FST_ERR_ASYNC_CONSTRAINT`,`Unexpected error from async constraint`,500),FST_ERR_INVALID_URL:n(`FST_ERR_INVALID_URL`,`URL must be a string. Received '%s'`,400,TypeError),FST_ERR_ROUTE_OPTIONS_NOT_OBJ:n(`FST_ERR_ROUTE_OPTIONS_NOT_OBJ`,`Options for "%s:%s" route must be an object`,500,TypeError),FST_ERR_ROUTE_DUPLICATED_HANDLER:n(`FST_ERR_ROUTE_DUPLICATED_HANDLER`,`Duplicate handler for "%s:%s" route is not allowed!`,500),FST_ERR_ROUTE_HANDLER_NOT_FN:n(`FST_ERR_ROUTE_HANDLER_NOT_FN`,`Error Handler for %s:%s route, if defined, must be a function`,500,TypeError),FST_ERR_ROUTE_MISSING_HANDLER:n(`FST_ERR_ROUTE_MISSING_HANDLER`,`Missing handler function for "%s:%s" route.`,500),FST_ERR_ROUTE_METHOD_INVALID:n(`FST_ERR_ROUTE_METHOD_INVALID`,`Provided method is invalid!`,500,TypeError),FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:n(`FST_ERR_ROUTE_METHOD_NOT_SUPPORTED`,`%s method is not supported.`,500),FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:n(`FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED`,`Body validation schema for %s:%s route is not supported!`,500),FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:n(`FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT`,`'bodyLimit' option must be an integer > 0. Got '%s'`,500,TypeError),FST_ERR_ROUTE_REWRITE_NOT_STR:n(`FST_ERR_ROUTE_REWRITE_NOT_STR`,`Rewrite url for "%s" needs to be of type "string" but received "%s"`,500,TypeError),FST_ERR_REOPENED_CLOSE_SERVER:n(`FST_ERR_REOPENED_CLOSE_SERVER`,`Fastify has already been closed and cannot be reopened`),FST_ERR_REOPENED_SERVER:n(`FST_ERR_REOPENED_SERVER`,`Fastify is already listening`),FST_ERR_INSTANCE_ALREADY_LISTENING:n(`FST_ERR_INSTANCE_ALREADY_LISTENING`,`Fastify instance is already listening. %s`),FST_ERR_PLUGIN_VERSION_MISMATCH:n(`FST_ERR_PLUGIN_VERSION_MISMATCH`,`fastify-plugin: %s - expected '%s' fastify version, '%s' is installed`),FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:n(`FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE`,`The decorator '%s'%s is not present in %s`),FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:n(`FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER`,`The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.`,500,TypeError),FST_ERR_PLUGIN_CALLBACK_NOT_FN:n(`FST_ERR_PLUGIN_CALLBACK_NOT_FN`,`fastify-plugin: %s`,500,TypeError),FST_ERR_PLUGIN_NOT_VALID:n(`FST_ERR_PLUGIN_NOT_VALID`,`fastify-plugin: %s`),FST_ERR_ROOT_PLG_BOOTED:n(`FST_ERR_ROOT_PLG_BOOTED`,`fastify-plugin: %s`),FST_ERR_PARENT_PLUGIN_BOOTED:n(`FST_ERR_PARENT_PLUGIN_BOOTED`,`fastify-plugin: %s`),FST_ERR_PLUGIN_TIMEOUT:n(`FST_ERR_PLUGIN_TIMEOUT`,`fastify-plugin: %s`)};function i(e,t){return t.cause=e,t}t.exports=r,t.exports.appendStackTrace=i,t.exports.AVVIO_ERRORS_MAP={AVV_ERR_CALLBACK_NOT_FN:r.FST_ERR_PLUGIN_CALLBACK_NOT_FN,AVV_ERR_PLUGIN_NOT_VALID:r.FST_ERR_PLUGIN_NOT_VALID,AVV_ERR_ROOT_PLG_BOOTED:r.FST_ERR_ROOT_PLG_BOOTED,AVV_ERR_PARENT_PLG_LOADED:r.FST_ERR_PARENT_PLUGIN_BOOTED,AVV_ERR_READY_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT,AVV_ERR_PLUGIN_EXEC_TIMEOUT:r.FST_ERR_PLUGIN_TIMEOUT}})),wu=o(((e,t)=>{let n=[`onRoute`,`onRegister`,`onReady`,`onListen`,`preClose`,`onClose`],r=[`onTimeout`,`onRequest`,`preParsing`,`preValidation`,`preSerialization`,`preHandler`,`onSend`,`onResponse`,`onError`,`onRequestAbort`],i=r.concat(n),{FST_ERR_HOOK_INVALID_TYPE:a,FST_ERR_HOOK_INVALID_HANDLER:o,FST_ERR_SEND_UNDEFINED_ERR:s,FST_ERR_HOOK_TIMEOUT:c,FST_ERR_HOOK_NOT_SUPPORTED:l,AVVIO_ERRORS_MAP:u,appendStackTrace:d}=Cu(),{kChildren:f,kHooks:p,kRequestPayloadStream:m}=bu();function h(){this.onRequest=[],this.preParsing=[],this.preValidation=[],this.preSerialization=[],this.preHandler=[],this.onResponse=[],this.onSend=[],this.onError=[],this.onRoute=[],this.onRegister=[],this.onReady=[],this.onListen=[],this.onTimeout=[],this.onRequestAbort=[],this.preClose=[]}h.prototype=Object.create(null),h.prototype.validate=function(e,t){if(typeof e!=`string`)throw new a;if(Array.isArray(this[e])===!1)throw new l(e);if(typeof t!=`function`)throw new o(e,Object.prototype.toString.call(t))},h.prototype.add=function(e,t){this.validate(e,t),this[e].push(t)};function g(e){let t=new h;return t.onRequest=e.onRequest.slice(),t.preParsing=e.preParsing.slice(),t.preValidation=e.preValidation.slice(),t.preSerialization=e.preSerialization.slice(),t.preHandler=e.preHandler.slice(),t.onSend=e.onSend.slice(),t.onResponse=e.onResponse.slice(),t.onError=e.onError.slice(),t.onRoute=e.onRoute.slice(),t.onRegister=e.onRegister.slice(),t.onTimeout=e.onTimeout.slice(),t.onRequestAbort=e.onRequestAbort.slice(),t.onReady=[],t.onListen=[],t.preClose=[],t}function _(e,t,n,r){let i=n[p][e],a=0,o=0;l();function s(t){let n=i[a-1]?.name,o=n?` "${n}"`:``;if(t){t=t.code===`AVV_ERR_READY_TIMEOUT`?d(t,new c(e,o)):u[t.code]==null?t:d(t,new u[t.code](t.message)),r(t);return}r()}function l(r){if(r){s(r);return}if(a===i.length&&o===n[f].length){a===0&&o===0?s():t(function(e,t){s(e),t(e)});return}if(a===i.length&&o<n[f].length){let r=n[f][o++];_(e,t,r,l);return}t(m(i[a++],n)),l()}function m(e,t){return function(n,r){if(n){r(n);return}if(e.length===1){try{e.call(t,r)}catch(e){r(e)}return}try{let n=e.call(t);if(n&&typeof n.then==`function`){n.then(r,r);return}}catch(e){n=e}r(n)}}}function v(e){let t=e[p].onListen,n=t.length,r=0,i=0;a();function a(s){if(s&&e.log.error(s),r===n){for(;i<e[f].length;){let t=e[f][i++];v(t)}return}o(t[r++],e,a)}async function o(e,t,n){if(e.length===1){try{e.call(t,n)}catch(e){n(e)}return}try{let r=e.call(t);if(r&&typeof r.then==`function`){r.then(n,n);return}n()}catch(e){n(e)}}}function y(e){return function(t,n,r,i){let a=0;function o(s){if(s||a===t.length){i(s,n,r);return}let u;try{u=e(t[a++],n,r,o)}catch(e){i(e,n,r);return}u&&typeof u.then==`function`&&u.then(c,l)}function c(){o()}function l(e){e||=new s,i(e,n,r)}o()}}function b(e,t,n,r){return e(t,n,r)}let x=y(b),S=y(A),C=y(A),w=y(A),T=y(A);function E(e,t,n,r,i){let a=0;function o(s,u){if(s){i(s,t,n,r);return}if(u!==void 0&&(r=u),a===e.length){i(null,t,n,r);return}let d;try{d=e[a++](t,n,r,o)}catch(e){i(e,t,n);return}d&&typeof d.then==`function`&&d.then(c,l)}function c(e){o(null,e)}function l(e){e||=new s,i(e,t,n,r)}o()}let D=E;function O(e,t,n,r){let i=0;function a(s,l){if(n.sent)return;if(l!==void 0&&(t[m]=l),s||i===e.length){r(s,t,n);return}let u;try{u=e[i++](t,n,t[m],a)}catch(e){r(e,t,n);return}u&&typeof u.then==`function`&&u.then(o,c)}function o(e){a(null,e)}function c(e){e||=new s,r(e,t,n)}a()}function k(e,t,n){let r=0;function i(s){if(s||r===e.length){n(s,t);return}let c;try{c=e[r++](t,i)}catch(e){n(e,t);return}c&&typeof c.then==`function`&&c.then(a,o)}function a(){i()}function o(e){e||=new s,n(e,t)}i()}function A(e,t,n,r){if(n.sent!==!0)return e(t,n,r)}t.exports={Hooks:h,buildHooks:g,hookRunnerGenerator:y,preParsingHookRunner:O,onResponseHookRunner:x,onSendHookRunner:E,preSerializationHookRunner:D,onRequestAbortHookRunner:k,hookIterator:A,hookRunnerApplication:_,onListenHookRunner:v,preHandlerHookRunner:C,preValidationHookRunner:S,onRequestHookRunner:T,onTimeoutHookRunner:w,lifecycleHooks:r,supportedHooks:i}})),Tu=o(((e,t)=>{t.exports=function(){return{[Symbol.iterator]:function*(){},add(){},delete(){},has(){return!0}}}})),Eu=o(((e,t)=>{let{kTestInternals:n}=bu();function r(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}t.exports={withResolvers:typeof Promise.withResolvers==`function`?Promise.withResolvers.bind(Promise):r,[n]:{withResolvers:r}}})),Du=o(((e,t)=>{let n=require(`node:http`),r=require(`node:https`),i=require(`node:http2`),a=require(`node:dns`),o=require(`node:os`),{kState:s,kOptions:c,kServerBindings:l,kHttp2ServerSessions:u}=bu(),{FSTWRN003:d}=Su(),{onListenHookRunner:f}=wu(),{FST_ERR_REOPENED_CLOSE_SERVER:p,FST_ERR_REOPENED_SERVER:m,FST_ERR_LISTEN_OPTIONS_INVALID:h,FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:g}=Cu(),_=Tu(),v=Eu();t.exports.createServer=b;function y(e){return`Server listening at ${e}`}function b(e,t){let n=w(e,t);function r(r={port:0,host:`localhost`},i=void 0){if(typeof i==`function`&&(i.constructor.name===`AsyncFunction`&&d(`listen method`),r.cb=i),r.signal){if(typeof r.signal.on!=`function`&&typeof r.signal.addEventListener!=`function`)throw new h(`Invalid options.signal`);if(this[s].aborted=r.signal.aborted,this[s].aborted)return this.close();r.signal.addEventListener(`abort`,()=>{this[s].aborted=!0,this.close()},{once:!0})}let a;if(a=r.path==null?r.host??`localhost`:r.host,(!Object.hasOwn(r,`host`)||r.host==null)&&(r.host=a),a===`localhost`?r.cb=(a,o)=>{if(a){i(a,o);return}x.call(this,n,t,e,r,()=>{this[s].listening=!0,i(null,o),f(this)})}:r.cb=(e,t)=>{if(e){i(e,t);return}this[s].listening=!0,i(null,t),f(this)},i===void 0)return C.call(this,n,r).then(i=>{let{promise:o,resolve:c}=v.withResolvers();return a===`localhost`?x.call(this,n,t,e,r,()=>{this[s].listening=!0,c(i),f(this)}):(c(i),f(this)),o});this.ready(S.call(this,n,r))}let i=typeof n.closeAllConnections==`function`,a=typeof n.closeIdleConnections==`function`,o=typeof n.closeHttp2Sessions==`function`,c=e.forceCloseConnections;if(c===`idle`&&!a)throw new g;typeof c!=`boolean`&&(c=a?`idle`:!1);let l=!i&&c===!0?new Set:_();return{server:n,listen:r,forceCloseConnections:c,serverHasCloseAllConnections:i,serverHasCloseHttp2Sessions:o,keepAliveConnections:l}}function x(e,t,n,r,i){this[s].listening=!1,a.lookup(r.host,{all:!0},(a,o)=>{if(a||this[s].aborted){i();return}let c=e.listening&&n.serverFactory,u=0,d=0;if(!c){let a=e.address();for(let c of o)if(c.address!==a.address){u++;let o=Object.assign({},r,{host:c.address,port:a.port,cb:e=>{d++,e||this[l].push(f),d===u&&i()}}),f=w(n,t),p=()=>{f.close(()=>{}),typeof f.closeAllConnections==`function`&&n.forceCloseConnections===!0&&f.closeAllConnections(),typeof f.closeHttp2Sessions==`function`&&f.closeHttp2Sessions()};f.on(`upgrade`,e.emit.bind(e,`upgrade`)),e.on(`unref`,p),e.on(`close`,p),e.on(`error`,p),this[s].listening=!1,S.call(this,f,o)()}}if(u===0){i();return}let f=e.unref;e.unref=function(){f.call(e),e.emit(`unref`)}})}function S(e,t){let n=r=>{if(e.removeListener(`error`,n),e.removeListener(`listening`,n),r)this[s].listening=!1,t.cb(r,null);else{let n=E.call(this,e,t.listenTextResolver||y);t.cb(null,n)}};return r=>{if(r!=null)return t.cb(r);if(this[s].listening&&this[s].closing)return t.cb(new p,null);if(this[s].listening)return t.cb(new m,null);e.once(`error`,n),this[s].closing||(e.once(`listening`,n),e.listen(t),this[s].listening=!0)}}function C(e,t){return this[s].listening&&this[s].closing?Promise.reject(new p):this[s].listening?Promise.reject(new m):this.ready().then(()=>{if(this[s].aborted)return;let{promise:n,resolve:r,reject:i}=v.withResolvers(),a=e=>{c(),this[s].listening=!1,i(e)},o=()=>{c(),this[s].listening=!0,r(E.call(this,e,t.listenTextResolver||y))};function c(){e.removeListener(`error`,a),e.removeListener(`listening`,o)}return e.once(`error`,a),e.once(`listening`,o),e.listen(t),n})}function w(e,t){if(e.serverFactory)return e.serverFactory(t,e);let a=e.https===!0?{}:e.https;if(e.http2){let n=typeof a==`object`?i.createSecureServer(a,t):i.createServer(e.http,t);return n.on(`session`,t=>t.setTimeout(e.http2SessionTimeout,()=>{t.close()})),e.forceCloseConnections===!0&&(n.closeHttp2Sessions=D(n)),n.setTimeout(e.connectionTimeout),n}let o=a?r.createServer(a,t):n.createServer(e.http,t);return o.keepAliveTimeout=e.keepAliveTimeout,o.requestTimeout=e.requestTimeout,o.setTimeout(e.connectionTimeout),e.maxRequestsPerSocket>0&&(o.maxRequestsPerSocket=e.maxRequestsPerSocket),o}function T(e){return e.address===`0.0.0.0`?Object.values(o.networkInterfaces()).flatMap(e=>e.filter(e=>e.family===`IPv4`)).sort(e=>e.internal?-1:1).map(e=>e.address):[e.address]}function E(e,t){let n;typeof e.address()==`string`?n=[e.address()]:(n=e.address().address.indexOf(`:`)===-1?T(e.address()).map(t=>t+`:`+e.address().port):[`[`+e.address().address+`]:`+e.address().port],n=n.map(e=>`http`+(this[c].https?`s`:``)+`://`+e));for(let e of n)this.log.info(t(e));return n[0]}function D(e){return e[u]=new Set,e.on(`session`,function(t){t.once(`connect`,function(){e[u].add(t)}),t.once(`close`,function(){e[u].delete(t)}),t.once(`frameError`,function(n,r,i){i===0&&e[u].delete(t)}),t.once(`goaway`,function(){e[u].delete(t)})}),function(){if(e[u].size!==0)for(let t of e[u])t.close()}}})),Ou=o(((e,t)=>{let n=/([\w!#$%&'*+.^`|~-]+)=([^;]*)/gm,r=/^[\w!#$%&'*+.^`|~-]+$/,i=/^[\w!#$%&'*+.^`|~-]+\s*/;t.exports=class{#e=!1;#t=!0;#n=``;#r=``;#i=new Map;#a;constructor(e){if(e==null||e===``||e===`undefined`)return;let t=e.indexOf(`;`);if(t===-1){if(t=e.indexOf(`/`),t===-1)return;let n=e.slice(0,t).trimStart().toLowerCase(),a=e.slice(t+1).trimEnd().toLowerCase();r.test(n)===!0&&i.test(a)===!0&&(this.#e=!0,this.#t=!1,this.#n=n,this.#r=a);return}let a=e.slice(0,t).toLowerCase(),o=e.slice(t+1).trim();if(t=a.indexOf(`/`),t===-1)return;let s=a.slice(0,t).trimStart(),c=a.slice(t+1).trimEnd();if(r.test(s)===!1||i.test(c)===!1)return;this.#n=s,this.#r=c,this.#e=!0,this.#t=!1;let l=n.exec(o);for(;l;){let e=l[1],t=l[2];if(t[0]===`"`){if(t.at(-1)!==`"`){this.#i.set(e,`invalid quoted string`),l=n.exec(o);continue}this.#i.set(e,t.slice(1,t.length-1))}else this.#i.set(e,t);l=n.exec(o)}}get[Symbol.toStringTag](){return`ContentType`}get isEmpty(){return this.#t}get isValid(){return this.#e}get mediaType(){return`${this.#n}/${this.#r}`}get type(){return this.#n}get subtype(){return this.#r}get parameters(){return this.#i}toString(){if(this.#a)return this.#a;let e=[];for(let[t,n]of this.#i.entries())e.push(`${t}="${n}"`);let t=[this.#n,`/`,this.#r];return e.length>0&&(t.push(`; `),t.push(e.join(`; `))),this.#a=t.join(``),this.#a}}})),ku=o(((e,t)=>{let{kReplyHasStatusCode:n}=bu();function r(e,t){if(!e[n]||e.statusCode===200){let n=t&&(t.statusCode||t.status);e.code(n>=400?n:500)}}t.exports={setErrorStatusCode:r}})),Au=o(((e,t)=>{let{kReplyIsError:n,kReplyHijacked:r}=bu(),{setErrorStatusCode:i}=ku(),a=require(`node:diagnostics_channel`).tracingChannel(`fastify.request.handler`);function o(e,t,o){o&&(o.async=!0),e.then(function(e){if(t[r]!==!0){o&&a.asyncStart.publish(o);try{if(e!==void 0||t.sent===!1&&t.raw.headersSent===!1&&t.request.raw.aborted===!1&&t.request.socket&&!t.request.socket.destroyed)try{t.send(e)}catch(e){t[n]=!0,t.send(e)}}finally{o&&a.asyncEnd.publish(o)}}},function(e){o&&(o.error=e,i(t,e),a.error.publish(o),a.asyncStart.publish(o));try{if(t.sent===!0){t.log.error({err:e},`Promise errored, but reply.sent = true was set`);return}t[n]=!0,t.send(e)}catch(e){t.send(e)}finally{o&&a.asyncEnd.publish(o)}})}t.exports=o})),ju=o(((e,t)=>{let{kSchemaHeaders:n,kSchemaParams:r,kSchemaQuerystring:i,kSchemaBody:a,kSchemaResponse:o}=bu(),s=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:c}=Cu(),{FSTWRN001:l}=Su();function u(e,t){if(!e.schema||!e.schema.response)return;let{method:n,url:r}=e.config||{};e[o]=Object.keys(e.schema.response).reduce(function(i,a){let o=e.schema.response[a];if(a=a.toLowerCase(),!s.test(a))throw new c;if(o.content){let e={};for(let i of Object.keys(o.content)){let s=o.content[i].schema;e[i]=t({schema:s,url:r,method:n,httpStatus:a,contentType:i})}i[a]=e}else i[a]=t({schema:o,url:r,method:n,httpStatus:a});return i},{})}function d(e,t,o){let{schema:s}=e;if(!s)return;let{method:c,url:u}=e.config||{},d=s.headers;if(d&&(o||Object.getPrototypeOf(d)!==Object.prototype))e[n]=t({schema:d,method:c,url:u,httpPart:`headers`});else if(d){let r={};Object.keys(d).forEach(e=>{r[e]=d[e]}),r.required instanceof Array&&(r.required=r.required.map(e=>e.toLowerCase())),d.properties&&(r.properties={},Object.keys(d.properties).forEach(e=>{r.properties[e.toLowerCase()]=d.properties[e]})),e[n]=t({schema:r,method:c,url:u,httpPart:`headers`})}else Object.hasOwn(s,`headers`)&&l(`headers`,c,u);if(s.body){let n=s.body.content;if(n){let r={};for(let e of Object.keys(n)){let i=n[e].schema;r[e]=t({schema:i,method:c,url:u,httpPart:`body`,contentType:e})}e[a]=r}else e[a]=t({schema:s.body,method:c,url:u,httpPart:`body`})}else Object.hasOwn(s,`body`)&&l(`body`,c,u);s.querystring?e[i]=t({schema:s.querystring,method:c,url:u,httpPart:`querystring`}):Object.hasOwn(s,`querystring`)&&l(`querystring`,c,u),s.params?e[r]=t({schema:s.params,method:c,url:u,httpPart:`params`}):Object.hasOwn(s,`params`)&&l(`params`,c,u)}function f(e,t,n){let r=t[n]===void 0,i;try{i=e?.(r?null:t[n])}catch(e){return e.statusCode=500,e}if(i&&typeof i.then==`function`)return i.then(e=>a(e)).catch(e=>e);return a(i);function a(r){return r===!1?e.errors:r&&r.error?r.error:(r&&r.value&&(t[n]=r.value),!1)}}function p(e,t,o){let s=o===void 0;if(s||!o.skipParams){let n=f(e[r],t,`params`);if(n)return typeof n.then==`function`?m(n,e,t):v(n,`params`,e.schemaErrorFormatter)}if(s||!o.skipBody){let n=null;if(typeof e[a]==`function`)n=e[a];else if(e[a]){let r=y(t.headers[`content-type`]),i=e[a][r];i&&(n=i)}let r=f(n,t,`body`);if(r)return typeof r.then==`function`?h(r,e,t):v(r,`body`,e.schemaErrorFormatter)}if(s||!o.skipQuery){let n=f(e[i],t,`query`);if(n)return typeof n.then==`function`?g(n,e,t):v(n,`querystring`,e.schemaErrorFormatter)}let c=f(e[n],t,`headers`);return c?typeof c.then==`function`?_(c,e,t):v(c,`headers`,e.schemaErrorFormatter):!1}function m(e,t,n){return e.then(e=>e?v(e,`params`,t.schemaErrorFormatter):p(t,n,{skipParams:!0}))}function h(e,t,n){return e.then(e=>e?v(e,`body`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0}))}function g(e,t,n){return e.then(e=>e?v(e,`querystring`,t.schemaErrorFormatter):p(t,n,{skipParams:!0,skipBody:!0,skipQuery:!0}))}function _(e,t,n){return e.then(e=>e?v(e,`headers`,t.schemaErrorFormatter):!1)}function v(e,t,n){if(e instanceof Error)return e.statusCode=e.statusCode||400,e.code=e.code||`FST_ERR_VALIDATION`,e.validationContext=e.validationContext||t,e;let r=n(e,t);return r.statusCode=r.statusCode||400,r.code=r.code||`FST_ERR_VALIDATION`,r.validation=e,r.validationContext=t,r}function y(e){return e?e.split(/[ ;]/,1)[0].trim().toLowerCase():``}t.exports={symbols:{bodySchema:a,querystringSchema:i,responseSchema:o,paramsSchema:r,headersSchema:n},compileSchemasForValidation:d,compileSchemasForSerialization:u,validate:p}})),Mu=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Ou(),i=Au(),{validate:a}=ju(),{preValidationHookRunner:o,preHandlerHookRunner:s}=wu(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:c}=Cu(),{setErrorStatusCode:l}=ku(),{kReplyIsError:u,kRouteContext:d,kFourOhFourContext:f,kSupportedHTTPMethods:p}=bu(),m=n.tracingChannel(`fastify.request.handler`);function h(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let i=t.method;if(this[p].bodyless.has(i)){g(t,n);return}if(this[p].bodywith.has(i)){let e=t.headers,i=e[`content-type`];if(i===void 0){let r=e[`content-length`];if(e[`transfer-encoding`]===void 0&&(r===void 0||r===`0`)){g(t,n);return}t[d].contentTypeParser.run(``,g,t,n);return}let a=new r(i);if(a.isValid===!1){n[u]=!0,n.status(415).send(new c);return}t[d].contentTypeParser.run(a.toString(),g,t,n);return}g(t,n)}function g(e,t){try{e[d].preValidation===null?_(null,e,t):o(e[d].preValidation,e,t,_)}catch(n){_(n,e,t)}}function _(e,t,n){if(n.sent===!0)return;if(e!=null){n[u]=!0,n.send(e);return}let r=a(n[d],t);if(r&&typeof r.then==`function`){let e=v.bind(null,t,n);r.then(e,e)}else v(t,n,r)}function v(e,t,n){if(n){if(t[d].attachValidation===!1){t.send(n);return}t.request.validationError=n}e[d].preHandler===null?y(null,e,t):s(e[d].preHandler,e,t,y)}function y(e,t,n){if(n.sent)return;let r=t[d];if(!m.hasSubscribers||r[f]===null)b(e,t,n);else{let i={request:t,reply:n,async:!1,route:{url:r.config.url,method:r.config.method}};m.start.runStores(i,b,void 0,e,t,n,i)}}function b(e,t,n,r){let a=t[d];try{if(e!=null){n[u]=!0,r&&(r.error=e,l(n,e),m.error.publish(r)),n.send(e);return}let o;try{o=a.handler(t,n)}catch(e){r&&(r.error=e,l(n,e),m.error.publish(r)),n[u]=!0,n.send(e);return}o!==void 0&&(o!==null&&typeof o.then==`function`?i(o,n,r):n.send(o))}finally{r&&m.end.publish(r)}}t.exports=h,t.exports[Symbol.for(`internals`)]={handler:g,preHandlerCallback:y}})),Nu=o(((e,t)=>{function n(){}let r={fatal:n,error:n,warn:n,info:n,debug:n,trace:n};Object.defineProperty(t,`exports`,{get(){return Object.create(r)}})})),Pu=o(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
125
125
  causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
126
- caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),Pu=o(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),Fu=o(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=Nu(),{pinoErrProto:a,pinoErrorSymbols:o}=Pu(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),Iu=o(((e,t)=>{t.exports=s;let{isErrorLike:n}=Nu(),{pinoErrProto:r,pinoErrorSymbols:i}=Pu(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),Lu=o(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),Ru=o(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),zu=o(((e,t)=>{let n=Fu(),r=Iu(),i=Lu(),a=Ru();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),Bu=o(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),Vu=o(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),Hu=o(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),Uu=o(((e,t)=>{let n=Vu(),{redactFmtSym:r,wildcardFirstSym:i}=Hu(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),Wu=o(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),Gu=o(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),Ku=o(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),qu=o(((e,t)=>{let n=require(`fs`),r=require(`events`),i=require(`util`).inherits,a=require(`path`),o=Ku(),s=require(`assert`),c=Buffer.allocUnsafe(0),l=`buffer`,u=`utf8`,[d,f]=(process.versions.node||`0.0`).split(`.`).map(Number),p=d>=22&&f>=7;function m(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,o=t.mode;if(t.sync)try{t.mkdir&&n.mkdirSync(a.dirname(e),{recursive:!0}),r(null,n.openSync(e,i,o))}catch(e){throw r(e),e}else t.mkdir?n.mkdir(a.dirname(e),{recursive:!0},t=>{if(t)return r(t);n.open(e,i,o,r)}):n.open(e,i,o,r)}function h(e){if(!(this instanceof h))return new h(e);let{fd:t,dest:r,minLength:i,maxLength:a,maxWrite:s,periodicFlush:d,sync:f,append:p=!0,mkdir:v,retryEAGAIN:x,fsync:k,contentMode:A,mode:j}=e||{};t||=r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=s||16384,this._periodicFlush=d||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=k||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=x||(()=>!0),this.mkdir=v||!1;let M,ee;if(A===l)this._writingBuf=c,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>n.writeSync(this.fd,this._writingBuf),ee=()=>n.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===u)this._writingBuf=``,this.write=y,this.flush=S,this.flushSync=w,this._actualWrite=E,M=()=>Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`),ee=()=>Buffer.isBuffer(this._writingBuf)?n.write(this.fd,this._writingBuf,this.release):n.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${u}" and "${l}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)m(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{o(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(ee,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let r=g(this._writingBuf,this._len,t);if(this._len=r.len,this._writingBuf=r.writingBuf,this._writingBuf.length){if(!this.sync){ee();return}try{do{let e=M(),t=g(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&n.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,O(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(_,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function g(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function _(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}i(h,r);function v(e,t){return e.length===0?c:e.length===1?e[0]:Buffer.concat(e,t)}function y(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{n.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,r)},r=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,r)}function S(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}h.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&n.close(t,e=>{if(e)return this.emit(`error`,e)})}),m(this.file,this)},h.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():O(this)))};function w(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?n.writeSync(this.fd,e):n.writeSync(this.fd,e,`utf8`),r=g(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}try{n.fsyncSync(this.fd)}catch{}}function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=c);let e=c;for(;this._bufs.length||e.length;){e.length<=0&&(e=v(this._bufs[0],this._lens[0]));try{let t=n.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}}h.prototype.destroy=function(){this.destroyed||O(this)};function E(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else n.write(this.fd,this._writingBuf,e)}function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:v(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,n.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else p&&(this._writingBuf=Buffer.from(this._writingBuf)),n.write(this.fd,this._writingBuf,e)}function O(e){if(e.fd===-1){e.once(`ready`,O.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],s(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{n.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?n.close(e.fd,r):r()}function r(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}h.SonicBoom=h,h.default=h,t.exports=h})),Ju=o(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),Yu=o(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),Xu=o(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),Zu=o(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),Qu=o(((e,t)=>{let{version:n}=Yu(),{EventEmitter:r}=require(`events`),{Worker:i}=require(`worker_threads`),{join:a}=require(`path`),{pathToFileURL:o}=require(`url`),{wait:s}=Xu(),{WRITE_INDEX:c,READ_INDEX:l}=Zu(),u=require(`buffer`),d=require(`assert`),f=Symbol(`kImpl`),p=u.constants.MAX_STRING_LENGTH;var m=class{constructor(e){this._value=e}deref(){return this._value}},h=class{register(){}unregister(){}};let g=process.env.NODE_V8_COVERAGE?h:global.FinalizationRegistry||h,_=process.env.NODE_V8_COVERAGE?m:global.WeakRef||m,v=new g(e=>{e.exited||e.terminate()});function y(e,t){let{filename:r,workerData:s}=t,c=new i((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||a(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf(`file://`)===0?r:o(r).href,dataBuf:e[f].dataBuf,stateBuf:e[f].stateBuf,workerData:{$context:{threadStreamVersion:n},...s}}});return c.stream=new m(e),c.on(`message`,S),c.on(`exit`,C),v.register(e,c),c}function b(e){d(!e[f].sync),e[f].needDrain&&(e[f].needDrain=!1,e.emit(`drain`))}function x(e){let t=Atomics.load(e[f].state,c),n=e[f].data.length-t;if(n>0){if(e[f].buf.length===0){e[f].flushing=!1,e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e);return}let t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);r>e[f].data.length;)n/=2,t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))}})}else if(n===0){if(t===0&&e[f].buf.length===0)return;e.flush(()=>{Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l),x(e)})}else E(e,Error(`overwritten`))}function S(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new _(t),t.flush(()=>{t[f].ready=!0,t.emit(`ready`)});break;case`ERROR`:E(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:E(t,Error(`this should not happen: `+e.code))}}function C(e){let t=this.stream.deref();t!==void 0&&(v.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,C),E(t,e===0?null:Error(`the worker thread exited`)))}var w=class extends r{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[f]={},this[f].stateBuf=new SharedArrayBuffer(128),this[f].state=new Int32Array(this[f].stateBuf),this[f].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[f].data=Buffer.from(this[f].dataBuf),this[f].sync=e.sync||!1,this[f].ending=!1,this[f].ended=!1,this[f].needDrain=!1,this[f].destroyed=!1,this[f].flushing=!1,this[f].ready=!1,this[f].finished=!1,this[f].errored=null,this[f].closed=!1,this[f].buf=``,this.worker=y(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[f].destroyed)return T(this,Error(`the worker has exited`)),!1;if(this[f].ending)return T(this,Error(`the worker is ending`)),!1;if(this[f].flushing&&this[f].buf.length+e.length>=p)try{k(this),this[f].flushing=!0}catch(e){return E(this,e),!1}if(this[f].buf+=e,this[f].sync)try{return k(this),!0}catch(e){return E(this,e),!1}return this[f].flushing||(this[f].flushing=!0,setImmediate(x,this)),this[f].needDrain=this[f].data.length-this[f].buf.length-Atomics.load(this[f].state,c)<=0,!this[f].needDrain}end(){this[f].destroyed||(this[f].ending=!0,O(this))}flush(e){if(this[f].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[f].state,c);s(this[f].state,l,t,1/0,(t,n)=>{if(t){E(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[f].destroyed||(k(this),A(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[f].ready}get destroyed(){return this[f].destroyed}get closed(){return this[f].closed}get writable(){return!this[f].destroyed&&!this[f].ending}get writableEnded(){return this[f].ending}get writableFinished(){return this[f].finished}get writableNeedDrain(){return this[f].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[f].errored}};function T(e,t){setImmediate(()=>{e.emit(`error`,t)})}function E(e,t){e[f].destroyed||(e[f].destroyed=!0,t&&(e[f].errored=t,T(e,t)),e.worker.exited?setImmediate(()=>{e[f].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[f].closed=!0,e.emit(`close`)}))}function D(e,t,n){let r=Atomics.load(e[f].state,c),i=Buffer.byteLength(t);return e[f].data.write(t,r),Atomics.store(e[f].state,c,r+i),Atomics.notify(e[f].state,c),n(),!0}function O(e){if(!(e[f].ended||!e[f].ending||e[f].flushing)){e[f].ended=!0;try{e.flushSync();let t=Atomics.load(e[f].state,l);Atomics.store(e[f].state,c,-1),Atomics.notify(e[f].state,c);let n=0;for(;t!==-1;){if(Atomics.wait(e[f].state,l,t,1e3),t=Atomics.load(e[f].state,l),t===-2){E(e,Error(`end() failed`));return}if(++n===10){E(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[f].finished=!0,e.emit(`finish`)})}catch(t){E(e,t)}}}function k(e){let t=()=>{e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e)};for(e[f].flushing=!1;e[f].buf.length!==0;){let n=Atomics.load(e[f].state,c),r=e[f].data.length-n;if(r===0){A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);continue}else if(r<0)throw Error(`overwritten`);let i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[f].buf=e[f].buf.slice(r),D(e,i,t);else{for(A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);a>e[f].buf.length;)r/=2,i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);e[f].buf=e[f].buf.slice(r),D(e,i,t)}}}function A(e){if(e[f].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[f].state,c),n=0;for(;;){let r=Atomics.load(e[f].state,l);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[f].state,l,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=w})),$u=o(((e,t)=>{let{createRequire:n}=require(`module`),{existsSync:r}=require(`node:fs`),i=Bu(),{join:a,isAbsolute:o,sep:s}=require(`node:path`),{fileURLToPath:c}=require(`node:url`),l=Ku(),u=Ju(),d=Qu();function f(e){u.register(e,v),u.registerBeforeExit(e,y),e.on(`close`,function(){u.unregister(e)})}function p(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function m(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&h(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&h(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function h(e){let t=g(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=c(n)}catch{return!1}return o(n)&&!r(n)}function g(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function _(e,t,n,r,i){if(!n.execArgv&&p()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let e=m(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:e}})}n={...n,name:i};let a=new d({filename:e,workerData:t,workerOpts:n,sync:r});a.on(`ready`,o),a.on(`close`,function(){process.removeListener(`exit`,s)}),process.on(`exit`,s);function o(){process.removeListener(`exit`,s),a.unref(),n.autoEnd!==!1&&f(a)}function s(){a.closed||(a.flushSync(),l(100),a.end())}return a}function v(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function y(e){e.flushSync()}function b(e){let{pipeline:t,targets:r,levels:c,dedupe:l,worker:u={},caller:d=i(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&r)throw Error(`only one of target or targets can be specified`);r?(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.targets=r.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=r.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),c&&(p.levels=c),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let v=r||t?`pino.transport`:g;return _(y(g),p,u,f,v);function y(e){if(e=h[e]||e,o(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return a(__dirname,`..`,`file.js`);let t;for(let r of m)try{t=n(r===`node:repl`?process.cwd()+s:r).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=b})),ed=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Gu(),{mapHttpRequest:i,mapHttpResponse:a}=zu(),o=qu(),s=Ju(),{lsCacheSym:c,chindingsSym:l,writeSym:u,serializersSym:d,formatOptsSym:f,endSym:p,stringifiersSym:m,stringifySym:h,stringifySafeSym:g,wildcardFirstSym:_,nestedKeySym:v,formattersSym:y,messageKeySym:b,errorKeySym:x,nestedKeyStrSym:S,msgPrefixSym:C}=Hu(),{isMainThread:w}=require(`worker_threads`),T=$u(),[E]=process.versions.node.split(`.`).map(e=>Number(e)),D=n.tracingChannel(`pino_asJson`),O=E>=25?e=>JSON.stringify(e):j;function k(){}function A(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let o=t;t!==null&&(t.method&&t.headers&&t.socket?t=i(t):typeof t.setHeader==`function`&&(t=a(t)));let s;o===null&&n.length===0?s=[null]:(o=n.shift(),s=n),typeof this[C]==`string`&&o!=null&&(o=this[C]+o),this[u](t,r(o,s,this[f]),e)}else{let i=t===void 0?n.shift():t;typeof this[C]==`string`&&i!=null&&(i=this[C]+i),this[u](null,r(i,n,this[f]),e)}}}function j(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function M(e,t,n,r){if(D.hasSubscribers===!1)return ee.call(this,e,t,n,r);let i={instance:this,arguments};return D.traceSync(ee,i,this,e,t,n,r)}function ee(e,t,n,r){let i=this[h],a=this[g],o=this[m],s=this[p],u=this[l],f=this[d],C=this[y],w=this[b],T=this[x],E=this[c][n]+r;E+=u;let D;C.log&&(e=C.log(e));let k=o[_],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){f[t]?D=f[t](D):t===T&&f.err&&(D=f.err(D));let e=o[t]||k;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||O)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=O(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=f[w]?f[w](t):t;let e=o[w]||k;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||O)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[v]&&A?E+this[S]+A.slice(1)+`}`+j+s:E+A+j+s}function N(e,t){let n,r=e[l],i=e[h],a=e[g],o=e[m],s=o[_],c=e[d],u=e[y].bindings;t=u(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function te(e){return e.write!==e.constructor.prototype.write}function P(e){let t=new o(e);return t.on(`error`,n),!e.sync&&w&&(s.register(t,ne),t.on(`close`,function(){s.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=k,t.end=k,t.flushSync=k,t.destroy=k;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function ne(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function re(e){return function(t,n,r={},i){if(typeof r==`string`)i=P({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=P({dest:i})}else if(r instanceof o||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof o||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=T({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:s}=r;return a===!1&&(r.level=`silent`),s||(r.onChild=k),i||=te(process.stdout)?process.stdout:P({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function F(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[g])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ie(e,t,n){return{level:e,bindings:t,log:n}}function I(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:k,buildSafeSonicBoom:P,asChindings:N,asJson:M,genLog:A,createArgsNormalizer:re,stringify:F,buildFormatters:ie,normalizeDestFileDescriptor:I}})),td=o(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),nd=o(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=Hu(),{noop:l,genLog:u}=ed(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=td(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),rd=o(((e,t)=>{t.exports={version:`10.3.1`}})),id=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{lsCacheSym:r,levelValSym:i,setLevelSym:a,getLevelSym:o,chindingsSym:s,mixinSym:c,asJsonSym:l,writeSym:u,mixinMergeStrategySym:d,timeSym:f,timeSliceIndexSym:p,streamSym:m,serializersSym:h,formattersSym:g,errorKeySym:_,messageKeySym:v,useOnlyCustomLevelsSym:y,needsMetadataGsym:b,redactFmtSym:x,stringifySym:S,formatOptsSym:C,stringifiersSym:w,msgPrefixSym:T,hooksSym:E}=Hu(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:ee}=nd(),{asChindings:N,asJson:te,buildFormatters:P,stringify:ne,noop:re}=ed(),{version:F}=rd(),ie=Uu(),I={constructor:class{},child:oe,bindings:L,setBindings:se,flush:ue,isLevelEnabled:k,version:F,get level(){return this[o]()},set level(e){this[a](e)},get levelVal(){return this[i]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[T]},get[Symbol.toStringTag](){return`Pino`},[r]:j,[u]:le,[l]:te,[o]:D,[a]:O};Object.setPrototypeOf(I,n.prototype),t.exports=function(){return Object.create(I)};let ae=e=>e;function oe(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[h],r=this[g],i=Object.create(this);if(t==null)return i[g].bindings!==ae&&(i[g]=P(r.level,ae,r.log)),i[s]=N(i,e),this.onChild!==re&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[h]=Object.create(null);for(let e in n)i[h][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var o=0;o<e.length;o++){let t=e[o];i[h][t]=n[t]}for(let e in t.serializers)i[h][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var c=0;c<r.length;c++){let e=r[c];i[h][e]=t.serializers[e]}}else i[h]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[g]=P(e||r.level,n||ae,a||r.log)}else i[g]=P(r.level,ae,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(ee(this.levels,t.customLevels),i.levels=A(t.customLevels,i[y]),M(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=ie(i.redact,ne),n={stringify:e[x]};i[S]=ne,i[w]=e,i[C]=n}if(typeof t.msgPrefix==`string`&&(i[T]=(this[T]||``)+t.msgPrefix),i[s]=N(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[a](e)}return this.onChild(i),i}function L(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function se(e){this[s]=N(this,e)}function ce(e,t){return Object.assign(t,e)}function le(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||ce,u,h=this[E].streamWrite;e==null?u={}:e instanceof Error?(u={[a]:e},t===void 0&&(t=e.message)):(u=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(u=s(u,i(u,n,this)));let g=this[l](u,t,n,r),y=this[m];y[b]===!0&&(y.lastLevel=n,y.lastObj=u,y.lastMsg=t,y.lastTime=r.slice(this[p]),y.lastLogger=this),y.write(h?h(g):g)}function ue(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[m];typeof t.flush==`function`?t.flush(e||re):e&&e()}})),ad=o(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),od=o(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=td(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),sd=o(((e,t)=>{let n=require(`node:os`),r=zu(),i=Bu(),a=Uu(),o=Wu(),s=id(),c=Hu(),{configure:l}=ad(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=nd(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=td(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=ed(),{version:w}=rd(),{chindingsSym:T,redactFmtSym:E,serializersSym:D,timeSym:O,timeSliceIndexSym:k,streamSym:A,stringifySym:j,stringifySafeSym:M,stringifiersSym:ee,setLevelSym:N,endSym:te,formatOptsSym:P,messageKeySym:ne,errorKeySym:re,nestedKeySym:F,mixinSym:ie,levelCompSym:I,useOnlyCustomLevelsSym:ae,formattersSym:oe,hooksSym:L,nestedKeyStrSym:se,mixinMergeStrategySym:ce,msgPrefixSym:le}=c,{epochTime:ue,nullTime:de}=o,{pid:fe}=process,pe=n.hostname(),me=r.err,he=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:fe,hostname:pe},serializers:Object.assign(Object.create(null),{err:me}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ue,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),ge=Object.assign(Object.create(null),r);function _e(...e){let t={},{opts:n,stream:r}=he(t,i(),...e);n.level&&typeof n.level==`string`&&h[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:o,crlf:c,serializers:g,timestamp:_,messageKey:y,errorKey:S,nestedKey:w,base:fe,name:pe,level:me,customLevels:ge,levelComparison:_e,mixin:ve,mixinMergeStrategy:ye,useOnlyCustomLevels:be,formatters:xe,hooks:Se,depthLimit:Ce,edgeLimit:we,onChild:Te,msgPrefix:Ee}=n,De=l({maximumDepth:Ce,maximumBreadth:we}),Oe=b(xe.level,xe.bindings,xe.log),ke=x.bind({[M]:De}),Ae=o?a(o,ke):{},je=o?{stringify:Ae[E]}:{stringify:ke},Me=`}`+(c?`\r
126
+ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),Fu=o(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),Iu=o(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=Pu(),{pinoErrProto:a,pinoErrorSymbols:o}=Fu(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),Lu=o(((e,t)=>{t.exports=s;let{isErrorLike:n}=Pu(),{pinoErrProto:r,pinoErrorSymbols:i}=Fu(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),Ru=o(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),zu=o(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),Bu=o(((e,t)=>{let n=Iu(),r=Lu(),i=Ru(),a=zu();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),Vu=o(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),Hu=o(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),Uu=o(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),Wu=o(((e,t)=>{let n=Hu(),{redactFmtSym:r,wildcardFirstSym:i}=Uu(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),Gu=o(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),Ku=o(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),qu=o(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),Ju=o(((e,t)=>{let n=require(`fs`),r=require(`events`),i=require(`util`).inherits,a=require(`path`),o=qu(),s=require(`assert`),c=Buffer.allocUnsafe(0),l=`buffer`,u=`utf8`,[d,f]=(process.versions.node||`0.0`).split(`.`).map(Number),p=d>=22&&f>=7;function m(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,o=t.mode;if(t.sync)try{t.mkdir&&n.mkdirSync(a.dirname(e),{recursive:!0}),r(null,n.openSync(e,i,o))}catch(e){throw r(e),e}else t.mkdir?n.mkdir(a.dirname(e),{recursive:!0},t=>{if(t)return r(t);n.open(e,i,o,r)}):n.open(e,i,o,r)}function h(e){if(!(this instanceof h))return new h(e);let{fd:t,dest:r,minLength:i,maxLength:a,maxWrite:s,periodicFlush:d,sync:f,append:p=!0,mkdir:v,retryEAGAIN:x,fsync:k,contentMode:A,mode:j}=e||{};t||=r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=s||16384,this._periodicFlush=d||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=k||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=x||(()=>!0),this.mkdir=v||!1;let M,ee;if(A===l)this._writingBuf=c,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>n.writeSync(this.fd,this._writingBuf),ee=()=>n.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===u)this._writingBuf=``,this.write=y,this.flush=S,this.flushSync=w,this._actualWrite=E,M=()=>Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`),ee=()=>Buffer.isBuffer(this._writingBuf)?n.write(this.fd,this._writingBuf,this.release):n.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${u}" and "${l}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)m(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{o(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(ee,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let r=g(this._writingBuf,this._len,t);if(this._len=r.len,this._writingBuf=r.writingBuf,this._writingBuf.length){if(!this.sync){ee();return}try{do{let e=M(),t=g(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&n.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,O(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(_,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function g(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function _(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}i(h,r);function v(e,t){return e.length===0?c:e.length===1?e[0]:Buffer.concat(e,t)}function y(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{n.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,r)},r=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,r)}function S(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&x.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}h.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&n.close(t,e=>{if(e)return this.emit(`error`,e)})}),m(this.file,this)},h.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():O(this)))};function w(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?n.writeSync(this.fd,e):n.writeSync(this.fd,e,`utf8`),r=g(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}try{n.fsyncSync(this.fd)}catch{}}function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=c);let e=c;for(;this._bufs.length||e.length;){e.length<=0&&(e=v(this._bufs[0],this._lens[0]));try{let t=n.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}}h.prototype.destroy=function(){this.destroyed||O(this)};function E(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else n.write(this.fd,this._writingBuf,e)}function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:v(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,n.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else p&&(this._writingBuf=Buffer.from(this._writingBuf)),n.write(this.fd,this._writingBuf,e)}function O(e){if(e.fd===-1){e.once(`ready`,O.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],s(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{n.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?n.close(e.fd,r):r()}function r(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}h.SonicBoom=h,h.default=h,t.exports=h})),Yu=o(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),Xu=o(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),Zu=o(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),Qu=o(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),$u=o(((e,t)=>{let{version:n}=Xu(),{EventEmitter:r}=require(`events`),{Worker:i}=require(`worker_threads`),{join:a}=require(`path`),{pathToFileURL:o}=require(`url`),{wait:s}=Zu(),{WRITE_INDEX:c,READ_INDEX:l}=Qu(),u=require(`buffer`),d=require(`assert`),f=Symbol(`kImpl`),p=u.constants.MAX_STRING_LENGTH;var m=class{constructor(e){this._value=e}deref(){return this._value}},h=class{register(){}unregister(){}};let g=process.env.NODE_V8_COVERAGE?h:global.FinalizationRegistry||h,_=process.env.NODE_V8_COVERAGE?m:global.WeakRef||m,v=new g(e=>{e.exited||e.terminate()});function y(e,t){let{filename:r,workerData:s}=t,c=new i((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||a(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf(`file://`)===0?r:o(r).href,dataBuf:e[f].dataBuf,stateBuf:e[f].stateBuf,workerData:{$context:{threadStreamVersion:n},...s}}});return c.stream=new m(e),c.on(`message`,S),c.on(`exit`,C),v.register(e,c),c}function b(e){d(!e[f].sync),e[f].needDrain&&(e[f].needDrain=!1,e.emit(`drain`))}function x(e){let t=Atomics.load(e[f].state,c),n=e[f].data.length-t;if(n>0){if(e[f].buf.length===0){e[f].flushing=!1,e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e);return}let t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);r>e[f].data.length;)n/=2,t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))}})}else if(n===0){if(t===0&&e[f].buf.length===0)return;e.flush(()=>{Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l),x(e)})}else E(e,Error(`overwritten`))}function S(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new _(t),t.flush(()=>{t[f].ready=!0,t.emit(`ready`)});break;case`ERROR`:E(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:E(t,Error(`this should not happen: `+e.code))}}function C(e){let t=this.stream.deref();t!==void 0&&(v.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,C),E(t,e===0?null:Error(`the worker thread exited`)))}var w=class extends r{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[f]={},this[f].stateBuf=new SharedArrayBuffer(128),this[f].state=new Int32Array(this[f].stateBuf),this[f].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[f].data=Buffer.from(this[f].dataBuf),this[f].sync=e.sync||!1,this[f].ending=!1,this[f].ended=!1,this[f].needDrain=!1,this[f].destroyed=!1,this[f].flushing=!1,this[f].ready=!1,this[f].finished=!1,this[f].errored=null,this[f].closed=!1,this[f].buf=``,this.worker=y(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[f].destroyed)return T(this,Error(`the worker has exited`)),!1;if(this[f].ending)return T(this,Error(`the worker is ending`)),!1;if(this[f].flushing&&this[f].buf.length+e.length>=p)try{k(this),this[f].flushing=!0}catch(e){return E(this,e),!1}if(this[f].buf+=e,this[f].sync)try{return k(this),!0}catch(e){return E(this,e),!1}return this[f].flushing||(this[f].flushing=!0,setImmediate(x,this)),this[f].needDrain=this[f].data.length-this[f].buf.length-Atomics.load(this[f].state,c)<=0,!this[f].needDrain}end(){this[f].destroyed||(this[f].ending=!0,O(this))}flush(e){if(this[f].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[f].state,c);s(this[f].state,l,t,1/0,(t,n)=>{if(t){E(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[f].destroyed||(k(this),A(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[f].ready}get destroyed(){return this[f].destroyed}get closed(){return this[f].closed}get writable(){return!this[f].destroyed&&!this[f].ending}get writableEnded(){return this[f].ending}get writableFinished(){return this[f].finished}get writableNeedDrain(){return this[f].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[f].errored}};function T(e,t){setImmediate(()=>{e.emit(`error`,t)})}function E(e,t){e[f].destroyed||(e[f].destroyed=!0,t&&(e[f].errored=t,T(e,t)),e.worker.exited?setImmediate(()=>{e[f].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[f].closed=!0,e.emit(`close`)}))}function D(e,t,n){let r=Atomics.load(e[f].state,c),i=Buffer.byteLength(t);return e[f].data.write(t,r),Atomics.store(e[f].state,c,r+i),Atomics.notify(e[f].state,c),n(),!0}function O(e){if(!(e[f].ended||!e[f].ending||e[f].flushing)){e[f].ended=!0;try{e.flushSync();let t=Atomics.load(e[f].state,l);Atomics.store(e[f].state,c,-1),Atomics.notify(e[f].state,c);let n=0;for(;t!==-1;){if(Atomics.wait(e[f].state,l,t,1e3),t=Atomics.load(e[f].state,l),t===-2){E(e,Error(`end() failed`));return}if(++n===10){E(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[f].finished=!0,e.emit(`finish`)})}catch(t){E(e,t)}}}function k(e){let t=()=>{e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e)};for(e[f].flushing=!1;e[f].buf.length!==0;){let n=Atomics.load(e[f].state,c),r=e[f].data.length-n;if(r===0){A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);continue}else if(r<0)throw Error(`overwritten`);let i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[f].buf=e[f].buf.slice(r),D(e,i,t);else{for(A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);a>e[f].buf.length;)r/=2,i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);e[f].buf=e[f].buf.slice(r),D(e,i,t)}}}function A(e){if(e[f].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[f].state,c),n=0;for(;;){let r=Atomics.load(e[f].state,l);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[f].state,l,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=w})),ed=o(((e,t)=>{let{createRequire:n}=require(`module`),{existsSync:r}=require(`node:fs`),i=Vu(),{join:a,isAbsolute:o,sep:s}=require(`node:path`),{fileURLToPath:c}=require(`node:url`),l=qu(),u=Yu(),d=$u();function f(e){u.register(e,v),u.registerBeforeExit(e,y),e.on(`close`,function(){u.unregister(e)})}function p(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function m(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&h(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&h(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function h(e){let t=g(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=c(n)}catch{return!1}return o(n)&&!r(n)}function g(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function _(e,t,n,r,i){if(!n.execArgv&&p()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let e=m(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:e}})}n={...n,name:i};let a=new d({filename:e,workerData:t,workerOpts:n,sync:r});a.on(`ready`,o),a.on(`close`,function(){process.removeListener(`exit`,s)}),process.on(`exit`,s);function o(){process.removeListener(`exit`,s),a.unref(),n.autoEnd!==!1&&f(a)}function s(){a.closed||(a.flushSync(),l(100),a.end())}return a}function v(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function y(e){e.flushSync()}function b(e){let{pipeline:t,targets:r,levels:c,dedupe:l,worker:u={},caller:d=i(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&r)throw Error(`only one of target or targets can be specified`);r?(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.targets=r.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=r.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),c&&(p.levels=c),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let v=r||t?`pino.transport`:g;return _(y(g),p,u,f,v);function y(e){if(e=h[e]||e,o(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return a(__dirname,`..`,`file.js`);let t;for(let r of m)try{t=n(r===`node:repl`?process.cwd()+s:r).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=b})),td=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Ku(),{mapHttpRequest:i,mapHttpResponse:a}=Bu(),o=Ju(),s=Yu(),{lsCacheSym:c,chindingsSym:l,writeSym:u,serializersSym:d,formatOptsSym:f,endSym:p,stringifiersSym:m,stringifySym:h,stringifySafeSym:g,wildcardFirstSym:_,nestedKeySym:v,formattersSym:y,messageKeySym:b,errorKeySym:x,nestedKeyStrSym:S,msgPrefixSym:C}=Uu(),{isMainThread:w}=require(`worker_threads`),T=ed(),[E]=process.versions.node.split(`.`).map(e=>Number(e)),D=n.tracingChannel(`pino_asJson`),O=E>=25?e=>JSON.stringify(e):j;function k(){}function A(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let o=t;t!==null&&(t.method&&t.headers&&t.socket?t=i(t):typeof t.setHeader==`function`&&(t=a(t)));let s;o===null&&n.length===0?s=[null]:(o=n.shift(),s=n),typeof this[C]==`string`&&o!=null&&(o=this[C]+o),this[u](t,r(o,s,this[f]),e)}else{let i=t===void 0?n.shift():t;typeof this[C]==`string`&&i!=null&&(i=this[C]+i),this[u](null,r(i,n,this[f]),e)}}}function j(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function M(e,t,n,r){if(D.hasSubscribers===!1)return ee.call(this,e,t,n,r);let i={instance:this,arguments};return D.traceSync(ee,i,this,e,t,n,r)}function ee(e,t,n,r){let i=this[h],a=this[g],o=this[m],s=this[p],u=this[l],f=this[d],C=this[y],w=this[b],T=this[x],E=this[c][n]+r;E+=u;let D;C.log&&(e=C.log(e));let k=o[_],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){f[t]?D=f[t](D):t===T&&f.err&&(D=f.err(D));let e=o[t]||k;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||O)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=O(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=f[w]?f[w](t):t;let e=o[w]||k;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||O)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[v]&&A?E+this[S]+A.slice(1)+`}`+j+s:E+A+j+s}function N(e,t){let n,r=e[l],i=e[h],a=e[g],o=e[m],s=o[_],c=e[d],u=e[y].bindings;t=u(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function te(e){return e.write!==e.constructor.prototype.write}function P(e){let t=new o(e);return t.on(`error`,n),!e.sync&&w&&(s.register(t,ne),t.on(`close`,function(){s.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=k,t.end=k,t.flushSync=k,t.destroy=k;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function ne(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function re(e){return function(t,n,r={},i){if(typeof r==`string`)i=P({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=P({dest:i})}else if(r instanceof o||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof o||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=T({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:s}=r;return a===!1&&(r.level=`silent`),s||(r.onChild=k),i||=te(process.stdout)?process.stdout:P({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function F(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[g])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ie(e,t,n){return{level:e,bindings:t,log:n}}function I(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:k,buildSafeSonicBoom:P,asChindings:N,asJson:M,genLog:A,createArgsNormalizer:re,stringify:F,buildFormatters:ie,normalizeDestFileDescriptor:I}})),nd=o(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),rd=o(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=Uu(),{noop:l,genLog:u}=td(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=nd(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),id=o(((e,t)=>{t.exports={version:`10.3.1`}})),ad=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{lsCacheSym:r,levelValSym:i,setLevelSym:a,getLevelSym:o,chindingsSym:s,mixinSym:c,asJsonSym:l,writeSym:u,mixinMergeStrategySym:d,timeSym:f,timeSliceIndexSym:p,streamSym:m,serializersSym:h,formattersSym:g,errorKeySym:_,messageKeySym:v,useOnlyCustomLevelsSym:y,needsMetadataGsym:b,redactFmtSym:x,stringifySym:S,formatOptsSym:C,stringifiersSym:w,msgPrefixSym:T,hooksSym:E}=Uu(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:ee}=rd(),{asChindings:N,asJson:te,buildFormatters:P,stringify:ne,noop:re}=td(),{version:F}=id(),ie=Wu(),I={constructor:class{},child:oe,bindings:L,setBindings:se,flush:ue,isLevelEnabled:k,version:F,get level(){return this[o]()},set level(e){this[a](e)},get levelVal(){return this[i]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[T]},get[Symbol.toStringTag](){return`Pino`},[r]:j,[u]:le,[l]:te,[o]:D,[a]:O};Object.setPrototypeOf(I,n.prototype),t.exports=function(){return Object.create(I)};let ae=e=>e;function oe(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[h],r=this[g],i=Object.create(this);if(t==null)return i[g].bindings!==ae&&(i[g]=P(r.level,ae,r.log)),i[s]=N(i,e),this.onChild!==re&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[h]=Object.create(null);for(let e in n)i[h][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var o=0;o<e.length;o++){let t=e[o];i[h][t]=n[t]}for(let e in t.serializers)i[h][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var c=0;c<r.length;c++){let e=r[c];i[h][e]=t.serializers[e]}}else i[h]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[g]=P(e||r.level,n||ae,a||r.log)}else i[g]=P(r.level,ae,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(ee(this.levels,t.customLevels),i.levels=A(t.customLevels,i[y]),M(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=ie(i.redact,ne),n={stringify:e[x]};i[S]=ne,i[w]=e,i[C]=n}if(typeof t.msgPrefix==`string`&&(i[T]=(this[T]||``)+t.msgPrefix),i[s]=N(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[a](e)}return this.onChild(i),i}function L(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function se(e){this[s]=N(this,e)}function ce(e,t){return Object.assign(t,e)}function le(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||ce,u,h=this[E].streamWrite;e==null?u={}:e instanceof Error?(u={[a]:e},t===void 0&&(t=e.message)):(u=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(u=s(u,i(u,n,this)));let g=this[l](u,t,n,r),y=this[m];y[b]===!0&&(y.lastLevel=n,y.lastObj=u,y.lastMsg=t,y.lastTime=r.slice(this[p]),y.lastLogger=this),y.write(h?h(g):g)}function ue(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[m];typeof t.flush==`function`?t.flush(e||re):e&&e()}})),od=o(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),sd=o(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=nd(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),cd=o(((e,t)=>{let n=require(`node:os`),r=Bu(),i=Vu(),a=Wu(),o=Gu(),s=ad(),c=Uu(),{configure:l}=od(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=rd(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=nd(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=td(),{version:w}=id(),{chindingsSym:T,redactFmtSym:E,serializersSym:D,timeSym:O,timeSliceIndexSym:k,streamSym:A,stringifySym:j,stringifySafeSym:M,stringifiersSym:ee,setLevelSym:N,endSym:te,formatOptsSym:P,messageKeySym:ne,errorKeySym:re,nestedKeySym:F,mixinSym:ie,levelCompSym:I,useOnlyCustomLevelsSym:ae,formattersSym:oe,hooksSym:L,nestedKeyStrSym:se,mixinMergeStrategySym:ce,msgPrefixSym:le}=c,{epochTime:ue,nullTime:de}=o,{pid:fe}=process,pe=n.hostname(),me=r.err,he=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:fe,hostname:pe},serializers:Object.assign(Object.create(null),{err:me}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ue,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),ge=Object.assign(Object.create(null),r);function _e(...e){let t={},{opts:n,stream:r}=he(t,i(),...e);n.level&&typeof n.level==`string`&&h[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:o,crlf:c,serializers:g,timestamp:_,messageKey:y,errorKey:S,nestedKey:w,base:fe,name:pe,level:me,customLevels:ge,levelComparison:_e,mixin:ve,mixinMergeStrategy:ye,useOnlyCustomLevels:be,formatters:xe,hooks:Se,depthLimit:Ce,edgeLimit:we,onChild:Te,msgPrefix:Ee}=n,De=l({maximumDepth:Ce,maximumBreadth:we}),Oe=b(xe.level,xe.bindings,xe.log),ke=x.bind({[M]:De}),Ae=o?a(o,ke):{},je=o?{stringify:Ae[E]}:{stringify:ke},Me=`}`+(c?`\r
127
127
  `:`
128
- `),Ne=v.bind(null,{[T]:``,[D]:g,[ee]:Ae,[j]:x,[M]:De,[oe]:Oe}),Pe=``;fe!==null&&(Pe=Ne(pe===void 0?fe:Object.assign({},fe,{name:pe})));let Fe=_ instanceof Function?_:_?ue:de,Ie=Fe().indexOf(`:`)+1;if(be&&!ge)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(ve&&typeof ve!=`function`)throw Error(`Unknown mixin type "${typeof ve}" - expected "function"`);if(Ee&&typeof Ee!=`string`)throw Error(`Unknown msgPrefix type "${typeof Ee}" - expected "string"`);u(me,ge,be);let Le=d(ge,be);typeof r.emit==`function`&&r.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Le,messageKey:y,errorKey:S}}),m(_e);let Re=p(_e);return Object.assign(t,{levels:Le,[I]:Re,[ae]:be,[A]:r,[O]:Fe,[k]:Ie,[j]:x,[M]:De,[ee]:Ae,[te]:Me,[P]:je,[ne]:y,[re]:S,[F]:w,[se]:w?`,${JSON.stringify(w)}:{`:``,[D]:g,[ie]:ve,[ce]:ye,[T]:Pe,[oe]:Oe,[L]:Se,silent:C,onChild:Te,[le]:Ee}),Object.setPrototypeOf(t,s()),f(t),t[N](me),t}t.exports=_e,t.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=S(e.dest||process.stdout.fd),y(e)):y({dest:S(e),minLength:0}),t.exports.transport=$u(),t.exports.multistream=od(),t.exports.levels=d(),t.exports.stdSerializers=ge,t.exports.stdTimeFunctions=Object.assign({},o),t.exports.symbols=c,t.exports.version=w,t.exports.default=_e,t.exports.pino=_e})),cd=o(((e,t)=>{let n=sd(),{serializersSym:r}=n.symbols,{FST_ERR_LOG_INVALID_DESTINATION:i}=Su();function a(e){if(e.stream&&e.file)throw new i;e.file&&(e.stream=n.destination(e.file),delete e.file);let t=e.logger,a=e.genReqId,o=null;return t?(e.logger=void 0,e.genReqId=void 0,t[r]&&(e.serializers=Object.assign({},e.serializers,t[r])),o=t.child({},e),e.logger=t,e.genReqId=a):o=n(e,e.stream),o}t.exports={serializers:{req:function(e){return{method:e.method,url:e.url,version:e.headers&&e.headers[`accept-version`],host:e.host,remoteAddress:e.ip,remotePort:e.socket?e.socket.remotePort:void 0}},err:n.stdSerializers.err,res:function(e){return{statusCode:e.statusCode}}},createPinoLogger:a}})),ld=o(((e,t)=>{let{FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:n,FST_ERR_LOG_INVALID_LOGGER_CONFIG:r,FST_ERR_LOG_INVALID_LOGGER_INSTANCE:i,FST_ERR_LOG_INVALID_LOGGER:a}=Su();function o(e,t,n,r,i){let a={[e.requestIdLogLabel]:r},o=e.childLoggerFactory.call(e.server,t,a,i||{},n);return e.childLoggerFactory!==s&&c(o,!0),o}function s(e,t,n){return e.child(t,n)}function c(e,t){let n=[`info`,`error`,`debug`,`fatal`,`warn`,`trace`,`child`],r=e?n.filter(t=>!e[t]||typeof e[t]!=`function`):n;if(!r.length)return!0;if(r.length===n.length&&!t)return!1;throw a(r.join(`,`))}function l(e){if(e.logger&&e.loggerInstance)throw new n;if(!e.loggerInstance&&!e.logger){let e=Mu();return e.child=()=>e,{logger:e,hasLogger:!1}}let{createPinoLogger:t,serializers:a}=cd();if(c(e.loggerInstance))return{logger:t({logger:e.loggerInstance,serializers:Object.assign({},a,e.loggerInstance.serializers)}),hasLogger:!0};if(c(e.logger))throw r();if(e.loggerInstance)throw i();let o={};return Object.prototype.toString.call(e.logger)===`[object Object]`&&Reflect.ownKeys(e.logger).forEach(t=>{Object.defineProperty(o,t,{value:e.logger[t],writable:!0,enumerable:!0,configurable:!0})}),o.level=o.level||`info`,o.serializers=Object.assign({},a,o.serializers),e.logger=o,{logger:t(e.logger),hasLogger:!0}}function u(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}t.exports={createChildLogger:o,defaultChildLoggerFactory:s,createLogger:l,validateLogger:c,now:u}})),ud=o(((e,t)=>{t.exports=r;function n(e){return e instanceof Buffer?Buffer.from(e):new e.constructor(e.buffer.slice(),e.byteOffset,e.length)}function r(e){if(e||={},e.circles)return i(e);let t=new Map;if(t.set(Date,e=>new Date(e)),t.set(Map,(e,t)=>new Map(a(Array.from(e),t))),t.set(Set,(e,t)=>new Set(a(Array.from(e),t))),e.constructorHandlers)for(let n of e.constructorHandlers)t.set(n[0],n[1]);let r=null;return e.proto?s:o;function a(e,i){let a=Object.keys(e),o=Array(a.length);for(let s=0;s<a.length;s++){let c=a[s],l=e[c];typeof l!=`object`||!l?o[c]=l:l.constructor!==Object&&(r=t.get(l.constructor))?o[c]=r(l,i):ArrayBuffer.isView(l)?o[c]=n(l):o[c]=i(l)}return o}function o(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return a(e,o);if(e.constructor!==Object&&(r=t.get(e.constructor)))return r(e,o);let i={};for(let a in e){if(Object.hasOwnProperty.call(e,a)===!1)continue;let s=e[a];typeof s!=`object`||!s?i[a]=s:s.constructor!==Object&&(r=t.get(s.constructor))?i[a]=r(s,o):ArrayBuffer.isView(s)?i[a]=n(s):i[a]=o(s)}return i}function s(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return a(e,s);if(e.constructor!==Object&&(r=t.get(e.constructor)))return r(e,s);let i={};for(let a in e){let o=e[a];typeof o!=`object`||!o?i[a]=o:o.constructor!==Object&&(r=t.get(o.constructor))?i[a]=r(o,s):ArrayBuffer.isView(o)?i[a]=n(o):i[a]=s(o)}return i}}function i(e){let t=[],r=[],i=new Map;if(i.set(Date,e=>new Date(e)),i.set(Map,(e,t)=>new Map(o(Array.from(e),t))),i.set(Set,(e,t)=>new Set(o(Array.from(e),t))),e.constructorHandlers)for(let t of e.constructorHandlers)i.set(t[0],t[1]);let a=null;return e.proto?c:s;function o(e,o){let s=Object.keys(e),c=Array(s.length);for(let l=0;l<s.length;l++){let u=s[l],d=e[u];if(typeof d!=`object`||!d)c[u]=d;else if(d.constructor!==Object&&(a=i.get(d.constructor)))c[u]=a(d,o);else if(ArrayBuffer.isView(d))c[u]=n(d);else{let e=t.indexOf(d);e===-1?c[u]=o(d):c[u]=r[e]}}return c}function s(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return o(e,s);if(e.constructor!==Object&&(a=i.get(e.constructor)))return a(e,s);let c={};t.push(e),r.push(c);for(let o in e){if(Object.hasOwnProperty.call(e,o)===!1)continue;let l=e[o];if(typeof l!=`object`||!l)c[o]=l;else if(l.constructor!==Object&&(a=i.get(l.constructor)))c[o]=a(l,s);else if(ArrayBuffer.isView(l))c[o]=n(l);else{let e=t.indexOf(l);e===-1?c[o]=s(l):c[o]=r[e]}}return t.pop(),r.pop(),c}function c(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return o(e,c);if(e.constructor!==Object&&(a=i.get(e.constructor)))return a(e,c);let s={};t.push(e),r.push(s);for(let o in e){let l=e[o];if(typeof l!=`object`||!l)s[o]=l;else if(l.constructor!==Object&&(a=i.get(l.constructor)))s[o]=a(l,c);else if(ArrayBuffer.isView(l))s[o]=n(l);else{let e=t.indexOf(l);e===-1?s[o]=c(l):s[o]=r[e]}}return t.pop(),r.pop(),s}}})),dd=o(((e,t)=>{let n=ud()({circles:!1,proto:!0}),{kSchemaVisited:r,kSchemaResponse:i}=yu(),a=Symbol.for(`fluent-schema-object`),{FST_ERR_SCH_MISSING_ID:o,FST_ERR_SCH_ALREADY_PRESENT:s,FST_ERR_SCH_DUPLICATE:c,FST_ERR_SCH_CONTENT_MISSING_SCHEMA:l}=Su(),u=[`params`,`body`,`querystring`,`query`,`headers`];function d(e){this.store=e||{}}d.prototype.add=function(e){let t=n(e.isFluentSchema||e.isFluentJSONSchema||e[a]?e.valueOf():e),r=t.$id;if(!r)throw new o;if(this.store[r])throw new s(r);this.store[r]=t},d.prototype.getSchemas=function(){return Object.assign({},this.store)},d.prototype.getSchema=function(e){return this.store[e]};function f(e){return typeof e==`object`&&Object.getPrototypeOf(e)!==Object.prototype}function p(e,t){if(e[r])return e;if(e.query){if(e.querystring)throw new c(`querystring`);e.querystring=e.query}m(e);for(let t of u){let n=e[t];if(n&&!f(n)&&t===`body`&&n.content){let e=n.content,t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(!e[r].schema)throw new l(r)}continue}}if(e.response){let t=Object.keys(e.response);for(let n of t){if(f(e.response[n]))continue;let t=e.response[n].content;if(t){let e=Object.keys(t);for(let n=0;n<e.length;n++){let r=e[n];if(!t[r].schema)throw new l(r)}}}}return e[r]=!0,e}function m(e){for(let t of u)e[t]&&(e[t].isFluentSchema||e[t][a])&&(e[t]=e[t].valueOf());if(e.response){let t=Object.keys(e.response);for(let n of t)(e.response[n].isFluentSchema||e.response[n][a])&&(e.response[n]=e.response[n].valueOf())}}function h(e,t,n){let r=e[i];if(!r)return!1;if(r[t]){if(r[t].constructor===Object&&n){let e=n.split(`;`,1)[0];return r[t][e]?r[t][e]:r[t][`*/*`]?r[t][`*/*`]:!1}return r[t]}let a=(t+``)[0]+`xx`;if(r[a]){if(r[a].constructor===Object&&n){let e=n.split(`;`,1)[0];return r[a][e]?r[a][e]:r[a][`*/*`]?r[a][`*/*`]:!1}return r[a]}if(r.default){if(r.default.constructor===Object&&n){let e=n.split(`;`,1)[0];return r.default[e]?r.default[e]:r.default[`*/*`]?r.default[`*/*`]:!1}return r.default}return!1}t.exports={buildSchemas(e){return new d(e)},getSchemaSerializer:h,normalizeSchema:p}})),fd=o(((e,t)=>{let n=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;t.exports=class e{constructor(e){switch(e&&e.rounding){case`floor`:this.parseInteger=Math.floor;break;case`ceil`:this.parseInteger=Math.ceil;break;case`round`:this.parseInteger=Math.round;break;default:this.parseInteger=Math.trunc;break}this._options=e}asInteger(e){if(Number.isInteger(e))return``+e;if(typeof e==`bigint`)return e.toString();let t=this.parseInteger(e);if(t===1/0||t===-1/0||t!==t)throw Error(`The value "${e}" cannot be converted to an integer.`);return``+t}asNumber(e){let t=Number(e);if(t!==t)throw Error(`The value "${e}" cannot be converted to a number.`);return t===1/0||t===-1/0?`null`:``+t}asBoolean(e){return e&&`true`||`false`}asDateTime(e){if(e===null)return`""`;if(e instanceof Date)return`"`+e.toISOString()+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a date-time.`)}asDate(e){if(e===null)return`""`;if(e instanceof Date)return`"`+new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,10)+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a date.`)}asTime(e){if(e===null)return`""`;if(e instanceof Date)return`"`+new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(11,19)+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a time.`)}asString(e){let t=e.length;if(t===0)return`""`;if(t<42){let n=``,r=-1,i=255;for(let a=0;a<t;a++)if(i=e.charCodeAt(a),i===34||i===92)r===-1&&(r=0),n+=e.slice(r,a)+`\\`,r=a;else if(i<32||i>=55296&&i<=57343)return JSON.stringify(e);return r===-1&&`"`+e+`"`||`"`+n+e.slice(r)+`"`}else if(t<5e3&&n.test(e)===!1)return`"`+e+`"`;else return JSON.stringify(e)}asUnsafeString(e){return`"`+e+`"`}getState(){return this._options}static restoreFromState(t){return new e(t)}}})),pd=o(((e,t)=>{t.exports=function(e,t){let{asString:n,asNumber:r,asBoolean:i,asDateTime:a,asDate:o,asTime:s,asUnsafeString:c}=t;t.asInteger.bind(t);function l(e){let t=e&&typeof e.toJSON==`function`?e.toJSON():e;if(t===null)return`{}`;let i,a=`{`,o=!1;return i=t.statusCode,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"statusCode":`,a+=r(i)),i=t.code,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"code":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),i=t.error,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"error":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),i=t.message,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"message":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),a+`}`}return l}(null,fd().restoreFromState({mode:`standalone`}))})),md=o(((e,t)=>{let n=require(`node:http`).STATUS_CODES,r=ku(),{setErrorStatusCode:i}=Ou(),{kReplyHeaders:a,kReplyNextErrorHandler:o,kReplyIsRunningOnErrorHook:s,kRouteContext:c,kDisableRequestLogging:l}=yu(),{FST_ERR_REP_INVALID_PAYLOAD_TYPE:u,FST_ERR_FAILED_ERROR_SERIALIZATION:d}=Su(),{getSchemaSerializer:f}=dd(),p=pd(),m={func:g,toJSON(){return this.func.name.toString()+`()`}};function h(e,t,n){e[s]=!1;let i=e[c];if(e[o]===!1){_(t,e,function(e,t){try{e.raw.writeHead(e.raw.statusCode,e[a])}catch(t){e.log[l]||e.log.warn({req:e.request,res:e,err:t},t?.message),e.raw.writeHead(e.raw.statusCode)}e.raw.end(t)});return}let u=e[o]||i.errorHandler;e[o]=Object.getPrototypeOf(u),delete e[a][`content-type`],delete e[a][`content-length`];let d=u.func;if(!d){e[o]=!1,_(t,e,n);return}try{let n=d(t,e.request,e);n!==void 0&&(n!==null&&typeof n.then==`function`?r(n,e):e.send(n))}catch(t){e.send(t)}}function g(e,t,n){y(e,n),i(n,e),n.statusCode<500?n.log[l]||n.log.info({res:n,err:e},e?.message):n.log[l]||n.log.error({req:t,res:n,err:e},e?.message),n.send(e)}function _(e,t,r){let i=t.raw,o=t.statusCode;t[a][`content-type`]=t[a][`content-type`]??`application/json; charset=utf-8`;let s;try{let r=f(t[c],o,t[a][`content-type`]);s=r===!1?p({error:n[o+``],code:e.code,message:e.message,statusCode:o}):r(Object.create(e,{error:{value:n[o+``]},message:{value:e.message},statusCode:{value:o}}))}catch(n){t.log[l]||t.log.error({err:n,statusCode:i.statusCode},`The serializer for the given status code failed`),t.code(500),s=p(new d(n.message,e.message))}typeof s!=`string`&&!Buffer.isBuffer(s)&&(s=p(new u(typeof s))),t[a][`content-length`]=``+Buffer.byteLength(s),r(t,s)}function v(e=m,t){if(!t)return e;let n=Object.create(e);return n.func=t,n}function y(e,t){let n=t.raw,r=n.statusCode;r=r>=400?r:500,e!=null&&(e.headers!==void 0&&t.headers(e.headers),e.status>=400?r=e.status:e.statusCode>=400&&(r=e.statusCode)),n.statusCode=r}t.exports={buildErrorHandler:v,handleError:h}})),hd=o(((e,t)=>{let{kReply:n,kRequest:r,kState:i,kHasBeenDecorated:a}=yu(),{FST_ERR_DEC_ALREADY_PRESENT:o,FST_ERR_DEC_MISSING_DEPENDENCY:s,FST_ERR_DEC_AFTER_START:c,FST_ERR_DEC_REFERENCE_TYPE:l,FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:u,FST_ERR_DEC_UNDECLARED:d}=Su();function f(e,t,n,r){if(Object.hasOwn(e,t))throw new o(t);x(e,t,r),n&&(typeof n.getter==`function`||typeof n.setter==`function`)?Object.defineProperty(e,t,{get:n.getter,set:n.setter}):e[t]=n}function p(e){if(!_(this,e))throw new d(e,`instance`);return typeof this[e]==`function`?this[e].bind(this):this[e]}function m(e,t,n,r){let i=e.prototype;if(Object.hasOwn(i,t)||v(e,t))throw new o(t);e[a]=!0,x(e,t,r),n&&(typeof n.getter==`function`||typeof n.setter==`function`)?Object.defineProperty(i,t,{get:n.getter,set:n.setter}):typeof n==`function`?i[t]=n:e.props.push({key:t,value:n})}function h(e,t){if(typeof t==`object`&&t&&!(typeof t.getter==`function`||typeof t.setter==`function`))throw new l(e,typeof t)}function g(e,t,n){return w(this,e),f(this,e,t,n),this}function _(e,t){return t?t in e||e.prototype&&t in e.prototype||v(e,t):e in this}function v(e,t){return e.props?e.props.find(({key:e})=>e===t):!1}function y(e){return e&&v(this[r],e)?!0:_(this[r].prototype,e)}function b(e){return e&&v(this[n],e)?!0:_(this[n].prototype,e)}function x(e,t,n){if(n!=null){if(!Array.isArray(n))throw new u(t);for(let t=0;t!==n.length;++t)if(!_(e,n[t]))throw new s(n[t])}}function S(e,t,r){return w(this,e),h(e,t),m(this[n],e,t,r),this}function C(e,t,n){return w(this,e),h(e,t),m(this[r],e,t,n),this}function w(e,t){if(e[i].started)throw new c(t)}t.exports={add:g,exist:_,existRequest:y,existReply:b,dependencies:x,decorateReply:S,decorateRequest:C,getInstanceDecorator:p,hasKey:v}})),gd=o(((e,t)=>{let n=require(`node:stream`).finished,{kFourOhFourContext:r,kReplyErrorHandlerCalled:i,kReplyHijacked:a,kReplyStartTime:o,kReplyEndTime:s,kReplySerializer:c,kReplySerializerDefault:l,kReplyIsError:u,kReplyHeaders:d,kReplyTrailers:f,kReplyHasStatusCode:p,kReplyIsRunningOnErrorHook:m,kReplyNextErrorHandler:h,kDisableRequestLogging:g,kSchemaResponse:_,kReplyCacheSerializeFns:v,kSchemaController:y,kOptions:b,kRouteContext:x}=yu(),{onSendHookRunner:S,onResponseHookRunner:C,preHandlerHookRunner:w,preSerializationHookRunner:T}=Cu(),E=ju()[Symbol.for(`internals`)],D=ld().now,{handleError:O}=md(),{getSchemaSerializer:k}=dd(),A={JSON:`application/json; charset=utf-8`,PLAIN:`text/plain; charset=utf-8`,OCTET:`application/octet-stream`},{FST_ERR_REP_INVALID_PAYLOAD_TYPE:j,FST_ERR_REP_RESPONSE_BODY_CONSUMED:M,FST_ERR_REP_READABLE_STREAM_LOCKED:ee,FST_ERR_REP_ALREADY_SENT:N,FST_ERR_SEND_INSIDE_ONERR:te,FST_ERR_BAD_STATUS_CODE:P,FST_ERR_BAD_TRAILER_NAME:ne,FST_ERR_BAD_TRAILER_VALUE:re,FST_ERR_MISSING_SERIALIZATION_FN:F,FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:ie,FST_ERR_DEC_UNDECLARED:I}=Su(),ae=hd(),oe=Object.prototype.toString;function L(e,t,n){this.raw=e,this[c]=null,this[i]=!1,this[u]=!1,this[m]=!1,this.request=t,this[d]={},this[f]=null,this[p]=!1,this[o]=void 0,this.log=n}L.props=[],Object.defineProperties(L.prototype,{[x]:{get(){return this.request[x]}},elapsedTime:{get(){return this[o]===void 0?0:(this[s]||D())-this[o]}},server:{get(){return this.request[x].server}},sent:{enumerable:!0,get(){return(this[a]||this.raw.writableEnded)===!0}},statusCode:{get(){return this.raw.statusCode},set(e){this.code(e)}},routeOptions:{get(){return this.request.routeOptions}}}),L.prototype.writeEarlyHints=function(e,t){return this.raw.writeEarlyHints(e,t),this},L.prototype.hijack=function(){return this[a]=!0,this},L.prototype.send=function(e){if(this[m])throw new te;if(this.sent===!0)return this.log.warn({err:new N(this.request.url,this.request.method)}),this;if(this[u]||e instanceof Error)return this[u]=!1,be(this,e,de),this;if(e===void 0)return de(this,e),this;let t=this.getHeader(`content-type`),n=t!==void 0;if(e!==null){if(typeof e.pipe==`function`||typeof e.getReader==`function`||oe.call(e)===`[object Response]`)return de(this,e),this;if(e.buffer instanceof ArrayBuffer){n||(this[d][`content-type`]=A.OCTET);let t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength);return de(this,t),this}if(!n&&typeof e==`string`)return this[d][`content-type`]=A.PLAIN,de(this,e),this}if(this[c]!==null){if(typeof e!=`string`)return ce(this,e),this;e=this[c](e)}else if(!n||t.indexOf(`json`)!==-1){if(!n)this[d][`content-type`]=A.JSON;else if(t.indexOf(`charset`)===-1){let e=t.trim();e.endsWith(`;`)?this[d][`content-type`]=`${e} charset=utf-8`:this[d][`content-type`]=`${e}; charset=utf-8`}if(typeof e!=`string`)return ce(this,e),this}return de(this,e),this},L.prototype.getHeader=function(e){e=e.toLowerCase();let t=this[d][e];return t===void 0?this.raw.getHeader(e):t},L.prototype.getHeaders=function(){return{...this.raw.getHeaders(),...this[d]}},L.prototype.hasHeader=function(e){return e=e.toLowerCase(),this[d][e]!==void 0||this.raw.hasHeader(e)},L.prototype.removeHeader=function(e){return delete this[d][e.toLowerCase()],this},L.prototype.header=function(e,t=``){return e=e.toLowerCase(),this[d][e]&&e===`set-cookie`?(typeof this[d][e]==`string`&&(this[d][e]=[this[d][e]]),Array.isArray(t)?Array.prototype.push.apply(this[d][e],t):this[d][e].push(t)):this[d][e]=t,this},L.prototype.headers=function(e){let t=Object.keys(e);for(let n=0;n!==t.length;++n){let r=t[n];this.header(r,e[r])}return this};let se=new Set([`transfer-encoding`,`content-length`,`host`,`cache-control`,`max-forwards`,`te`,`authorization`,`set-cookie`,`content-encoding`,`content-type`,`content-range`,`trailer`]);L.prototype.trailer=function(e,t){if(e=e.toLowerCase(),se.has(e))throw new ne(e);if(typeof t!=`function`)throw new re(e,typeof t);return this[f]===null&&(this[f]={}),this[f][e]=t,this},L.prototype.hasTrailer=function(e){return this[f]?.[e.toLowerCase()]!==void 0},L.prototype.removeTrailer=function(e){return this[f]===null||(this[f][e.toLowerCase()]=void 0),this},L.prototype.code=function(e){let t=+e;if(!(t>=100&&t<=599))throw new P(e||String(e));return this.raw.statusCode=t,this[p]=!0,this},L.prototype.status=L.prototype.code,L.prototype.getSerializationFunction=function(e,t){let n;return typeof e==`string`||typeof e==`number`?n=typeof t==`string`?this[x][_]?.[e]?.[t]:this[x][_]?.[e]:typeof e==`object`&&(n=this[x][v]?.get(e)),n},L.prototype.compileSerializationSchema=function(e,t=null,n=null){let{request:r}=this,{method:i,url:a}=r;if(this[x][v]?.has(e))return this[x][v].get(e);let o=(this[x].serializerCompiler||this.server[y].serializerCompiler||this.server[y].setupSerializer(this.server[b])||this.server[y].serializerCompiler)({schema:e,method:i,url:a,httpStatus:t,contentType:n});return this[x][v]??(this[x][v]=new WeakMap),this[x][v].set(e,o),o},L.prototype.serializeInput=function(e,t,n,r){let i=n,a;if(n=typeof t==`string`||typeof t==`number`?t:n,r=n&&i!==n?i:r,n!=null){if(a=r==null?this[x][_]?.[n]:this[x][_]?.[n]?.[r],a==null)throw r?new ie(n,r):new F(n)}else a=this[x][v]?.has(t)?this[x][v].get(t):this.compileSerializationSchema(t,n,r);return a(e)},L.prototype.serialize=function(e){return this[c]===null?this[x]&&this[x][l]?this[x][l](e,this.raw.statusCode):Te(this[x],e,this.raw.statusCode):this[c](e)},L.prototype.serializer=function(e){return this[c]=e,this},L.prototype.type=function(e){return this[d][`content-type`]=e,this},L.prototype.redirect=function(e,t){return t||=this[p]?this.raw.statusCode:302,this.header(`location`,e).code(t).send()},L.prototype.callNotFound=function(){return we(this),this},L.prototype.then=function(e,t){if(this.sent){e();return}n(this.raw,n=>{n&&n.code!==`ERR_STREAM_PREMATURE_CLOSE`?t?t(n):this.log&&this.log.warn(`unhandled rejection on reply.then`):e()})},L.prototype.getDecorator=function(e){if(!ae.hasKey(this,e)&&!ae.exist(this,e))throw new I(e,`reply`);let t=this[e];return typeof t==`function`?t.bind(this):t};function ce(e,t){e[x].preSerialization===null?le(null,void 0,e,t):T(e[x].preSerialization,e.request,e,t,le)}function le(e,t,n,r){if(e!=null){be(n,e);return}try{r=n[c]===null?n[x]&&n[x][l]?n[x][l](r,n.raw.statusCode):Te(n[x],r,n.raw.statusCode,n[d][`content-type`]):n[c](r)}catch(e){ue(e,n),be(n,e);return}de(n,r)}function ue(e,t){e.serialization=t[x].config}function de(e,t){e[x].onSend===null?me(e,t):S(e[x].onSend,e.request,e,t,fe)}function fe(e,t,n,r){e==null?me(n,r):be(n,e)}function pe(e,t){let n=e.raw;try{n.writeHead(t,e[d])}catch(t){throw t.code===`ERR_HTTP_HEADERS_SENT`&&e.log.warn(`Reply was already sent, did you forget to "return reply" in the "${e.request.raw.url}" (${e.request.raw.method}) route?`),t}}function me(e,t){let n=e.raw,r=e.request;if(e[f]!==null){let t=Object.keys(e[f]),n=``;for(let r of t)typeof e[f][r]==`function`&&(n+=` `,n+=r);e.header(`Transfer-Encoding`,`chunked`),e.header(`Trailer`,n.trim())}if(oe.call(t)===`[object Response]`){if(typeof t.status==`number`&&e.code(t.status),typeof t.headers==`object`&&typeof t.headers.forEach==`function`)for(let[n,r]of t.headers)e.header(n,r);if(t.body!==null&&t.bodyUsed)throw new M;t=t.body}let i=n.statusCode;if(t==null){i>=200&&i!==204&&i!==304&&r.method!==`HEAD`&&e[f]===null&&(e[d][`content-length`]=`0`),pe(e,i),ve(t,n,e);return}if(i>=100&&i<200||i===204){e.removeHeader(`content-type`),e.removeHeader(`content-length`),pe(e,i),ve(void 0,n,e),typeof t.resume==`function`&&(t.on(`error`,Ee),t.resume());return}if(typeof t.pipe==`function`){_e(t,n,e);return}if(typeof t.getReader==`function`){ge(t,n,e);return}if(typeof t!=`string`&&!Buffer.isBuffer(t))throw new j(typeof t);if(e[f]===null){let n=e[d][`content-length`];(!n||r.raw.method!==`HEAD`&&Number(n)!==Buffer.byteLength(t))&&(e[d][`content-length`]=``+Buffer.byteLength(t))}pe(e,i),n.write(t),ve(t,n,e)}function he(e,t,n){t.code===`ERR_STREAM_PREMATURE_CLOSE`?e[g]||e.info({res:n},`stream closed prematurely`):e.warn({err:t},`response terminated with an error with headers already sent`)}function ge(e,t,r){if(e.locked)throw new ee;let i=!0,a=!1,o=!1,s=e.getReader();if(n(t,function(e){i&&(e!=null&&t.headersSent&&!a&&(a=!0,he(r.log,e,t)),s.cancel().catch(Ee))}),t.headersSent)r.log.warn(`response will send, but you shouldn't use res.writeHead in stream mode`);else for(let e in r[d])t.setHeader(e,r[d][e]);function c(e){if(e.done){i=!1,ve(null,t,r);return}if(t.destroyed){i=!1,s.cancel().catch(Ee);return}if(t.write(e.value)===!1){o=!0,t.once(`drain`,l);return}s.read().then(c,u)}function l(){!o||!i||t.destroyed||(o=!1,s.read().then(c,u))}function u(e){i=!1,t.headersSent||r.request.raw.aborted===!0?(a||(a=!0,he(r.log,e,r)),t.destroy()):be(r,e)}s.read().then(c,u)}function _e(e,t,r){let i=!0,a=!1;if(ye(e,t,r),n(e,{readable:!0,writable:!1},function(e){i=!1,e!=null&&(t.headersSent||r.request.raw.aborted===!0?(a||(a=!0,he(r.log,e,r)),t.destroy()):be(r,e))}),n(t,function(n){i&&(n!=null&&t.headersSent&&!a&&(a=!0,he(r.log,n,t)),typeof e.destroy==`function`?e.destroy():typeof e.close==`function`?e.close(Ee):typeof e.abort==`function`?e.abort():r.log.warn(`stream payload does not end properly`))}),t.headersSent)r.log.warn(`response will send, but you shouldn't use res.writeHead in stream mode`);else for(let e in r[d])t.setHeader(e,r[d][e]);e.pipe(t)}function ve(e,t,n){if(n[f]===null){t.end(null,null,null);return}let r=Object.keys(n[f]),i={},a=0,o=!0;function s(){a===0&&(t.addTrailers(i),t.end(null,null,null))}for(let t of r){if(typeof n[f][t]!=`function`)continue;o=!1,a--;function r(e,r){a++,e?n.log.debug(e):i[t]=r,process.nextTick(s)}let c=n[f][t](n,e,r);typeof c==`object`&&typeof c.then==`function`&&c.then(e=>r(null,e),r)}o&&t.end(null,null,null)}function ye(e,t,n){n[f]!==null&&e.on(`end`,()=>ve(null,t,n))}function be(e,t,n){e[x].onError!==null&&!e[h]?(e[m]=!0,S(e[x].onError,e.request,e,t,()=>O(e,t,n))):O(e,t,n)}function xe(e){e[o]=D();let t=n=>{e[s]=D(),e.raw.removeListener(`finish`,t),e.raw.removeListener(`error`,t);let r=e[x];r&&r.onResponse!==null?C(r.onResponse,e.request,e,Se):Se(n,e.request,e)};e.raw.on(`finish`,t),e.raw.on(`error`,t)}function Se(e,t,n){if(n.log[g])return;let r=n.elapsedTime;if(e!=null){n.log.error({res:n,err:e,responseTime:r},`request errored`);return}n.log.info({res:n,responseTime:r},`request completed`)}function Ce(e){let t=e.props.slice();function n(e,n,r){this.raw=e,this[u]=!1,this[i]=!1,this[a]=!1,this[c]=null,this.request=n,this[d]={},this[f]=null,this[o]=void 0,this[s]=void 0,this.log=r;let l;for(let e=0;e<t.length;e++)l=t[e],this[l.key]=l.value}return Object.setPrototypeOf(n.prototype,e.prototype),Object.setPrototypeOf(n,e),n.parent=e,n.props=t,n}function we(e){if(e[x][r]===null){e.log.warn(`Trying to send a NotFound error inside a 404 handler. Sending basic 404 response.`),e.code(404).send(`404 Not Found`);return}e.request[x]=e[x][r],e[x].preHandler===null?E.preHandlerCallback(null,e.request,e):w(e[x].preHandler,e.request,e,E.preHandlerCallback)}function Te(e,t,n,r){let i=k(e,n,r);return i?i(t):JSON.stringify(t)}function Ee(){}t.exports=L,t.exports.buildReply=Ce,t.exports.setupResponseListeners=xe})),_d=o(((e,t)=>{function n(e){if(!e)throw TypeError(`argument req is required`);let t=e.headers[`x-forwarded-for`],n=e.socket.remoteAddress;if(!t||typeof t!=`string`)return[n];if(t.indexOf(`,`)===-1){let e=t.trim();return e.length?[n,e]:[n]}else return r(t,n)}function r(e,t){let n=[t],r=e.length,i=r,a,o;for(o=r-1;o>=0;--o)a=e[o],a===` `?i===r&&(i=r=o):a===`,`?(i!==r&&n.push(e.slice(i,r)),i=r=o):i=o;return i!==r&&n.push(e.substring(i,r)),n}t.exports=n,t.exports.default=n,t.exports.forwarded=n})),vd=o(((e,t)=>{(function(e){"use strict";let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=RegExp(`^0[0-7]+$`,`i`),a=RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:new RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function l(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function u(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function d(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function f(e,t){for(;e.length<t;)e=`0${e}`;return e}let p={};p.IPv4=(function(){function e(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return`ipv4`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return u(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(`.`)},e})(),p.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.isIPv4=function(e){return this.parser(e)!==null},p.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},p.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(e){return!!(p.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!p.IPv4.isValidCIDR(e)||!t?!1:p.IPv4.isValidFourPartDecimal(t[1])},p.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},p.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,`toString`,{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},p.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(d(n));return r})();if(t=e.match(r.longValue)){if(i=d(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}else if(t=e.match(r.twoOctet))return(function(){let e=t.slice(1,4),n=[];if(i=d(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})();else if(t=e.match(r.threeOctet))return(function(){let e=t.slice(1,5),n=[];if(i=d(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(d(e[1])),n.push(i>>8&255),n.push(i&255),n})();else return null},p.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.IPv6=(function(){function e(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecated:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},e.prototype.kind=function(){return`ipv6`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return u(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},e.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(f(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new p.IPv4([t>>8,t&255,n>>8,n&255])},e.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString(),n=0,r=-1,i;for(;i=e.exec(t);)i[0].length>r&&(n=i.index,r=i[0].length);return r<0?t:`${t.substring(0,n)}::${t.substring(n+r)}`},e.prototype.toString=function(){return this.toRFC5952String()},e})(),p.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.isIPv6=function(e){return this.parser(e)!==null},p.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},p.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.parse=function(e){let t=this.parser(e);if(t.parts===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},p.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,`toString`,{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},p.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return l(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=l(t+o,6),t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.fromByteArray=function(e){let t=e.length;if(t===4)return new p.IPv4(e);if(t===16)return new p.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},p.isValid=function(e){return p.IPv6.isValid(e)||p.IPv4.isValid(e)},p.isValidCIDR=function(e){return p.IPv6.isValidCIDR(e)||p.IPv4.isValidCIDR(e)},p.parse=function(e){if(p.IPv6.isValid(e))return p.IPv6.parse(e);if(p.IPv4.isValid(e))return p.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},p.parseCIDR=function(e){try{return p.IPv6.parseCIDR(e)}catch{try{return p.IPv4.parseCIDR(e)}catch{throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`)}}},p.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},p.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=p:e.ipaddr=p})(e)})),yd=o(((e,t)=>{t.exports=m,t.exports.default=m,t.exports.proxyaddr=m,t.exports.all=c,t.exports.compile=l;let n=_d(),r=vd(),i=/^\d+$/u,a=r.isValid,o=r.parse,s={linklocal:[`169.254.0.0/16`,`fe80::/10`],loopback:[`127.0.0.1/8`,`::1/128`],uniquelocal:[`10.0.0.0/8`,`172.16.0.0/12`,`192.168.0.0/16`,`fc00::/7`]};function c(e,t){let r=n(e);if(!t)return r;typeof t!=`function`&&(t=l(t));for(let e=0;e<r.length-1;e++)t(r[e],e)||(r.length=e+1);return r}function l(e){if(!e)throw TypeError(`argument is required`);let t;if(typeof e==`string`)t=[e];else if(Array.isArray(e))t=e.slice();else throw TypeError(`unsupported trust argument`);for(let n=0;n<t.length;n++)e=t[n],Object.hasOwn(s,e)&&(e=s[e],t.splice.apply(t,[n,1].concat(e)),n+=e.length-1);return d(u(t))}function u(e){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=f(e[n]);return t}function d(e){let t=e.length;return t===0?h:t===1?_(e[0]):g(e)}function f(e){let t=e.lastIndexOf(`/`),n=t===-1?e:e.substring(0,t);if(!a(n))throw TypeError(`invalid IP address: `+n);let r=o(n);t===-1&&r.kind()===`ipv6`&&r.isIPv4MappedAddress()&&(r=r.toIPv4Address());let s=r.kind()===`ipv6`?128:32,c=t===-1?null:e.substring(t+1,e.length);if(c=c===null?s:i.test(c)?parseInt(c,10):r.kind()===`ipv4`&&a(c)?p(c):null,c<=0||c>s)throw TypeError(`invalid range on address: `+e);return[r,c]}function p(e){let t=o(e);return t.kind()===`ipv4`?t.prefixLengthFromSubnetMask():null}function m(e,t){if(!e)throw TypeError(`req argument is required`);if(!t)throw TypeError(`trust argument is required`);let n=c(e,t);return n[n.length-1]}function h(){return!1}function g(e){return function(t){if(!a(t))return!1;let n=o(t),r,i=n.kind();for(let t=0;t<e.length;t++){let a=e[t],o=a[0],s=o.kind(),c=a[1],l=n;if(i!==s){let e=s===`ipv4`;if(e&&!n.isIPv4MappedAddress())continue;r||=e?n.toIPv4Address():n.toIPv4MappedAddress(),l=r}if(l.match(o,c))return!0}return!1}}function _(e){let t=e[0],n=t.kind(),r=n===`ipv4`,i=e[1];return function(e){if(!a(e))return!1;let s=o(e);if(s.kind()!==n){if(r&&!s.isIPv4MappedAddress())return!1;s=r?s.toIPv4Address():s.toIPv4MappedAddress()}return s.match(t,i)}}})),bd=o(((e,t)=>{let n=yd(),{kHasBeenDecorated:r,kSchemaBody:i,kSchemaHeaders:a,kSchemaParams:o,kSchemaQuerystring:s,kSchemaController:c,kOptions:l,kRequestCacheValidateFns:u,kRouteContext:d,kRequestOriginalUrl:f}=yu(),{FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:p,FST_ERR_DEC_UNDECLARED:m}=Su(),h=hd(),g={body:i,headers:a,params:o,querystring:s,query:s};function _(e,t,n,r,i,a){this.id=e,this[d]=a,this.params=t,this.raw=n,this.query=r,this.log=i,this.body=void 0}_.props=[];function v(e){if(typeof e==`function`)return e;if(e===!0)return null;if(typeof e==`number`)return function(t,n){return n<e};if(typeof e==`string`){let t=e.split(`,`).map(e=>e.trim());return n.compile(t)}return n.compile(e)}function y(e,t){return t?S(e,t):b(e)}function b(e){let t=e.props.slice();function n(e,n,r,i,a,o){this.id=e,this[d]=o,this.params=n,this.raw=r,this.query=i,this.log=a,this.body=void 0;let s;for(let e=0;e<t.length;e++)s=t[e],this[s.key]=s.value}return Object.setPrototypeOf(n.prototype,e.prototype),Object.setPrototypeOf(n,e),n.props=t,n.parent=e,n}function x(e){let t=e.lastIndexOf(`,`);return t===-1?e.trim():e.slice(t+1).trim()}function S(e,t){let i=b(e),a=v(t);return i[r]=!0,Object.defineProperties(i.prototype,{ip:{get(){let e=n.all(this.raw,a);return e[e.length-1]}},ips:{get(){return n.all(this.raw,a)}},host:{get(){return this.ip!==void 0&&this.headers[`x-forwarded-host`]?x(this.headers[`x-forwarded-host`]):this.headers.host??this.headers[`:authority`]??``}},protocol:{get(){if(this.headers[`x-forwarded-proto`])return x(this.headers[`x-forwarded-proto`]);if(this.socket)return this.socket.encrypted?`https`:`http`}}}),i}function C(e,t){if(!h.hasKey(e,t)&&!h.exist(e,t))throw new m(t,`request`)}Object.defineProperties(_.prototype,{server:{get(){return this[d].server}},url:{get(){return this.raw.url}},originalUrl:{get(){return this[f]||(this[f]=this.raw.originalUrl||this.raw.url),this[f]}},method:{get(){return this.raw.method}},routeOptions:{get(){let e=this[d],t=e._parserOptions.limit,n=e.server.initialConfig.bodyLimit,r=e.server.hasConstraintStrategy(`version`)?this.raw.headers[`accept-version`]:void 0;return{method:e.config?.method,url:e.config?.url,bodyLimit:t||n,attachValidation:e.attachValidation,logLevel:e.logLevel,exposeHeadRoute:e.exposeHeadRoute,prefixTrailingSlash:e.prefixTrailingSlash,handler:e.handler,config:e.config,schema:e.schema,version:r}}},is404:{get(){return this[d].config?.url===void 0}},socket:{get(){return this.raw.socket}},ip:{get(){if(this.socket)return this.socket.remoteAddress}},host:{get(){return this.raw.headers.host??this.raw.headers[`:authority`]??``}},hostname:{get(){return this.host[0]===`[`?this.host.slice(0,this.host.indexOf(`]`)+1):this.host.split(`:`,1)[0]}},port:{get(){let e=parseInt(this.host.split(`:`).slice(-1)[0]);if(!isNaN(e))return e;let t=this.headers.host??this.headers[`:authority`]??``,n=parseInt(t.split(`:`).slice(-1)[0]);return isNaN(n)?null:n}},protocol:{get(){if(this.socket)return this.socket.encrypted?`https`:`http`}},headers:{get(){return this.additionalHeaders?Object.assign({},this.raw.headers,this.additionalHeaders):this.raw.headers},set(e){this.additionalHeaders=e}},getValidationFunction:{value:function(e){if(typeof e==`string`){let t=g[e];return this[d][t]}else if(typeof e==`object`)return this[d][u]?.get(e)}},compileValidationSchema:{value:function(e,t=null){let{method:n,url:r}=this;if(this[d][u]?.has(e))return this[d][u].get(e);let i=(this[d].validatorCompiler||this.server[c].validatorCompiler||this.server[c].setupValidator(this.server[l])||this.server[c].validatorCompiler)({schema:e,method:n,url:r,httpPart:t});return this[d][u]??(this[d][u]=new WeakMap),this[d][u].set(e,i),i}},validateInput:{value:function(e,t,n){n=typeof t==`string`?t:n;let r=n!=null&&typeof n==`string`&&g[n],i;if(r&&(i=this[d][r]),i==null&&(typeof t!=`object`||!t||Array.isArray(t)))throw new p(n);return i??=this[d][u]?.has(t)?this[d][u].get(t):this.compileValidationSchema(t,n),i(e)}},getDecorator:{value:function(e){C(this,e);let t=this[e];return typeof t==`function`?t.bind(this):t}},setDecorator:{value:function(e,t){C(this,e),this[e]=t}}}),t.exports=_,t.exports.buildRequest=y})),xd=o(((e,t)=>{let{kFourOhFourContext:n,kReplySerializerDefault:r,kSchemaErrorFormatter:i,kErrorHandler:a,kChildLoggerFactory:o,kOptions:s,kReply:c,kRequest:l,kBodyLimit:u,kLogLevel:d,kContentTypeParser:f,kRouteByFastify:p,kRequestCacheValidateFns:m,kReplyCacheSerializeFns:h}=yu();function g({schema:e,handler:t,config:g,requestIdLogLabel:v,childLoggerFactory:y,errorHandler:b,bodyLimit:x,logLevel:S,logSerializers:C,attachValidation:w,validatorCompiler:T,serializerCompiler:E,replySerializer:D,schemaErrorFormatter:O,exposeHeadRoute:k,prefixTrailingSlash:A,server:j,isFastify:M}){this.schema=e,this.handler=t,this.Reply=j[c],this.Request=j[l],this.contentTypeParser=j[f],this.onRequest=null,this.onSend=null,this.onError=null,this.onTimeout=null,this.preHandler=null,this.onResponse=null,this.preSerialization=null,this.onRequestAbort=null,this.config=g,this.errorHandler=b||j[a],this.requestIdLogLabel=v||j[s].requestIdLogLabel,this.childLoggerFactory=y||j[o],this._middie=null,this._parserOptions={limit:x||j[u]},this.exposeHeadRoute=k,this.prefixTrailingSlash=A,this.logLevel=S||j[d],this.logSerializers=C,this[n]=null,this.attachValidation=w,this[r]=D,this.schemaErrorFormatter=O||j[i]||_,this[p]=M,this[m]=null,this[h]=null,this.validatorCompiler=T||null,this.serializerCompiler=E||null,this.server=j}function _(e,t){let n=``;for(let r=0;r!==e.length;++r){let i=e[r];n+=t+(i.instancePath||``)+` `+i.message+`, `}return Error(n.slice(0,-2))}t.exports=g})),Sd=o((e=>{var t=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=t}get size(){return this.items.size}clear(){this.items=new Map,this.first=null,this.last=null}delete(e){if(this.items.has(e)){let t=this.items.get(e);this.items.delete(e),t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(this.items.has(e))return this.items.get(e).expiry}get(e){if(this.items.has(e)){let t=this.items.get(e);if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return this.items.keys()}set(e,t){if(this.items.has(e)){let n=this.items.get(e);n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items.set(e,n),this.size===1?this.first=n:this.last.next=n,this.last=n}},n=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=t}get size(){return this.items.size}bumpLru(e){if(this.last===e)return;let t=this.last,n=e.next,r=e.prev;this.first===e&&(this.first=n),e.next=null,e.prev=t,t.next=e,r!==null&&(r.next=n),n!==null&&(n.prev=r),this.last=e}clear(){this.items=new Map,this.first=null,this.last=null}delete(e){if(this.items.has(e)){let t=this.items.get(e);this.items.delete(e),t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(this.items.has(e))return this.items.get(e).expiry}get(e){if(this.items.has(e)){let t=this.items.get(e);if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(t),t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return this.items.keys()}set(e,t){if(this.items.has(e)){let n=this.items.get(e);n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.last!==n&&this.bumpLru(n);return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items.set(e,n),this.size===1?this.first=n:this.last.next=n,this.last=n}},r=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=t}bumpLru(e){if(this.last===e)return;let t=this.last,n=e.next,r=e.prev;this.first===e&&(this.first=n),e.next=null,e.prev=t,t.next=e,r!==null&&(r.next=n),n!==null&&(n.prev=r),this.last=e}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(Object.prototype.hasOwnProperty.call(this.items,e))return this.items[e].expiry}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(t),t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return Object.keys(this.items)}set(e,t){if(Object.prototype.hasOwnProperty.call(this.items,e)){let n=this.items[e];n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.last!==n&&this.bumpLru(n);return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items[e]=n,++this.size===1?this.first=n:this.last.next=n,this.last=n}},i=class{constructor(){this.records={}}initForCache(e,t){this.records[e]={[t]:{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}}resetForCache(e){for(let t of Object.keys(this.records[e]))this.records[e][t]={cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}getStatistics(){return this.records}};function a(e){return`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,`0`)}-${e.getDate().toString().padStart(2,`0`)}`}var o=class{constructor(e,t,n){this.cacheId=e,this.statisticTtlInHours=t,this.collectionStart=new Date,this.currentTimeStamp=a(this.collectionStart),this.records=n||new i,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){return this.records.records[this.cacheId][this.currentTimeStamp]||(this.records.records[this.cacheId][this.currentTimeStamp]={cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,sets:0,invalidateOne:0,invalidateAll:0}),this.records.records[this.cacheId][this.currentTimeStamp]}hoursPassed(){return(Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++}setCacheSize(e){this.archiveIfNeeded(),this.currentRecord.cacheSize=e}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){this.hoursPassed()>=this.statisticTtlInHours&&(this.collectionStart=new Date,this.currentTimeStamp=a(this.collectionStart),this.records.initForCache(this.cacheId,this.currentTimeStamp))}},s=class extends r{constructor(e,t,n,r,i){if(super(e||1e3,t||0),!n)throw Error(`Cache id is mandatory`);this.hitStatistics=new o(n,i===void 0?24:i,r)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,t){super.set(e,t),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){super.evict(),this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,t=!1){super.delete(e),t||this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(t),t.value||this.hitStatistics.addFalsyHit(),(t.value===void 0||t.value===null||t.value===``)&&this.hitStatistics.addEmptyHit(),this.hitStatistics.addHit(),t.value}this.hitStatistics.addMiss()}},c=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=t}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(Object.prototype.hasOwnProperty.call(this.items,e))return this.items[e].expiry}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return Object.keys(this.items)}set(e,t){if(Object.prototype.hasOwnProperty.call(this.items,e)){let n=this.items[e];n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items[e]=n,++this.size===1?this.first=n:this.last.next=n,this.last=n}};e.Fifo=c,e.FifoMap=t,e.FifoObject=c,e.HitStatisticsRecord=i,e.Lru=r,e.LruHitStatistics=s,e.LruMap=n,e.LruObject=r,e.LruObjectHitStatistics=s})),Cd=o(((e,t)=>{let n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),wd=o(((e,t)=>{let{AsyncResource:n}=require(`node:async_hooks`),{FifoMap:r}=Sd(),{parse:i}=Cd(),a=Du(),{kDefaultJsonParse:o,kContentTypeParser:s,kBodyLimit:c,kRequestPayloadStream:l,kState:u,kTestInternals:d,kReplyIsError:f,kRouteContext:p}=yu(),{FST_ERR_CTP_INVALID_TYPE:m,FST_ERR_CTP_EMPTY_TYPE:h,FST_ERR_CTP_ALREADY_PRESENT:g,FST_ERR_CTP_INVALID_HANDLER:_,FST_ERR_CTP_INVALID_PARSE_TYPE:v,FST_ERR_CTP_BODY_TOO_LARGE:y,FST_ERR_CTP_INVALID_MEDIA_TYPE:b,FST_ERR_CTP_INVALID_CONTENT_LENGTH:x,FST_ERR_CTP_EMPTY_JSON_BODY:S,FST_ERR_CTP_INSTANCE_ALREADY_STARTED:C,FST_ERR_CTP_INVALID_JSON_BODY:w}=Su(),{FSTSEC001:T}=xu();function E(e,t,n){this[o]=O(t,n),this.customParsers=new Map,this.customParsers.set(`application/json`,new A(!0,!1,e,this[o])),this.customParsers.set(`text/plain`,new A(!0,!1,e,k)),this.parserList=[`application/json`,`text/plain`],this.parserRegExpList=[],this.cache=new r(100)}E.prototype.add=function(e,t,n){let r=typeof e==`string`;if(r){if(e=e.trim().toLowerCase(),e.length===0)throw new h}else if(!(e instanceof RegExp))throw new m;if(typeof n!=`function`)throw new _;if(this.existingParser(e))throw new g(e);if(t.parseAs!==void 0&&t.parseAs!==`string`&&t.parseAs!==`buffer`)throw new v(t.parseAs);let i=new A(t.parseAs===`string`,t.parseAs===`buffer`,t.bodyLimit,n);if(e===`*`)this.customParsers.set(``,i);else if(r){let t=new a(e);if(t.isValid===!1)throw new m;let n=t.toString();this.parserList.unshift(n),this.customParsers.set(n,i)}else P(e),this.parserRegExpList.unshift(e),this.customParsers.set(e.toString(),i)},E.prototype.hasParser=function(e){if(typeof e==`string`)e=new a(e).toString();else{if(!(e instanceof RegExp))throw new m;e=e.toString()}return this.customParsers.has(e)},E.prototype.existingParser=function(e){if(typeof e==`string`){let t=new a(e).toString();if(e===`application/json`&&this.customParsers.has(e))return this.customParsers.get(t).fn!==this[o];if(e===`text/plain`&&this.customParsers.has(e))return this.customParsers.get(t).fn!==k}return this.hasParser(e)},E.prototype.getParser=function(e){typeof e==`string`&&(e=new a(e));let t=e.toString(),n=this.cache.get(t);if(n!==void 0)return n;if(n=this.customParsers.get(t),n!==void 0)return this.cache.set(t,n),n;if(n=this.customParsers.get(e.mediaType),n!==void 0)return n;for(let e=0;e!==this.parserRegExpList.length;++e){let r=this.parserRegExpList[e];if(r.test(t))return n=this.customParsers.get(r.toString()),this.cache.set(t,n),n}return this.customParsers.get(``)},E.prototype.removeAll=function(){this.customParsers=new Map,this.parserRegExpList=[],this.parserList=[],this.cache=new r(100)},E.prototype.remove=function(e){let t;if(typeof e==`string`)e=new a(e).toString(),t=this.parserList;else{if(!(e instanceof RegExp))throw new m;e=e.toString(),t=this.parserRegExpList}let n=this.customParsers.delete(e),r=t.findIndex(t=>t.toString()===e);return r>-1&&t.splice(r,1),n||r>-1},E.prototype.run=function(e,t,r,i){let a=this.getParser(e);if(a===void 0){if(r.is404===!0){t(r,i);return}i[f]=!0,i.send(new b(e||void 0));return}let o=new n(`content-type-parser:run`,r),s=o.bind(u);if(a.asString===!0||a.asBuffer===!0){D(r,i,i[p]._parserOptions,a,s);return}let c=a.fn(r,r[l],s);c&&typeof c.then==`function`&&c.then(e=>{s(null,e)},s);function u(e,n){if(o.emitDestroy(),e!=null){i.header(`connection`,`close`),i[f]=!0,i.send(e);return}r.body=n,t(r,i)}};function D(e,t,n,r,i){let a=r.asString===!0,o=n.limit===null?r.bodyLimit:n.limit,s=Number(e.headers[`content-length`]);if(s>o){i(new y,void 0);return}let c=0,u=a?``:[],d=e[l]||e.raw;a&&d.setEncoding(`utf8`),d.on(`data`,f),d.on(`end`,p),d.on(`error`,p),d.resume();function f(e){c+=a?Buffer.byteLength(e):e.length;let{receivedEncodedLength:t=0}=d;if(c>o||t>o){d.removeListener(`data`,f),d.removeListener(`end`,p),d.removeListener(`error`,p),i(new y,void 0);return}a?u+=e:u.push(e)}function p(t){if(d.removeListener(`data`,f),d.removeListener(`end`,p),d.removeListener(`error`,p),t!=null){typeof t.statusCode==`number`&&t.statusCode>=400||(t.statusCode=400),i(t,void 0);return}if(!Number.isNaN(s)&&(d.receivedEncodedLength||c)!==s){i(new x,void 0);return}a||(u=Buffer.concat(u));let n=r.fn(e,u,i);n&&typeof n.then==`function`&&n.then(e=>{i(null,e)},i)}}function O(e,t){let n={protoAction:e,constructorAction:t};return r;function r(e,t,r){if(t.length===0){r(new S,void 0);return}try{r(null,i(t,n))}catch{r(new w,void 0)}}}function k(e,t,n){n(null,t)}function A(e,t,n,r){this.asString=e,this.asBuffer=t,this.bodyLimit=n,this.fn=r}function j(e){let t=new E;return t[o]=e[o],t.customParsers=new Map(e.customParsers.entries()),t.parserList=e.parserList.slice(),t.parserRegExpList=e.parserRegExpList.slice(),t}function M(e,t,n){if(this[u].started)throw new C(`addContentTypeParser`);return typeof t==`function`&&(n=t,t={}),t||={},t.bodyLimit||=this[c],Array.isArray(e)?e.forEach(e=>this[s].add(e,t,n)):this[s].add(e,t,n),this}function ee(e){return this[s].hasParser(e)}function N(e){if(this[u].started)throw new C(`removeContentTypeParser`);if(Array.isArray(e))for(let t of e)this[s].remove(t);else this[s].remove(e)}function te(){if(this[u].started)throw new C(`removeAllContentTypeParsers`);this[s].removeAll()}function P(e){e.source[0]!==`^`&&e.source.includes(`;?`)===!1&&T(e.source)}t.exports=E,t.exports.helpers={buildContentTypeParser:j,addContentTypeParser:M,hasContentTypeParser:ee,removeContentTypeParser:N,removeAllContentTypeParsers:te},t.exports.defaultParsers={getDefaultJsonParser:O,defaultTextParser:k},t.exports[d]={rawBody:D}})),Td=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Ed=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Td();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),X=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Td(),n=Ed();var r=Td();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=Ed();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=k(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=k(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=k(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(A(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>D(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(j(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=k(this.condition,e,t),this}get names(){let e=super.names;return O(e,this.condition),this.else&&D(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=k(this.iteration,e,t),this}get names(){return D(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return O(O(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=k(this.iterable,e,t),this}get names(){return D(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&D(e,this.catch.names),this.finally&&D(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
129
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new E,this.code(n)),this._endBlockNode(T,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function D(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function O(e,n){return n instanceof t._CodeOrName?D(e,n.names):e}function k(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function A(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function j(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ne(e)}`}e.not=j;let M=P(e.operators.AND);function ee(...e){return e.reduce(M)}e.and=ee;let N=P(e.operators.OR);function te(...e){return e.reduce(N)}e.or=te;function P(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ne(n)} ${e} ${ne(r)}`}function ne(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Z=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=X(),n=Td();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Dd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Od=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=X(),n=Z(),r=Dd();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),kd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Od(),n=X(),r=Dd(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Ad=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),jd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Md=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Ad(),n=jd(),r=Od(),i=X(),a=Z();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
128
+ `),Ne=v.bind(null,{[T]:``,[D]:g,[ee]:Ae,[j]:x,[M]:De,[oe]:Oe}),Pe=``;fe!==null&&(Pe=Ne(pe===void 0?fe:Object.assign({},fe,{name:pe})));let Fe=_ instanceof Function?_:_?ue:de,Ie=Fe().indexOf(`:`)+1;if(be&&!ge)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(ve&&typeof ve!=`function`)throw Error(`Unknown mixin type "${typeof ve}" - expected "function"`);if(Ee&&typeof Ee!=`string`)throw Error(`Unknown msgPrefix type "${typeof Ee}" - expected "string"`);u(me,ge,be);let Le=d(ge,be);typeof r.emit==`function`&&r.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Le,messageKey:y,errorKey:S}}),m(_e);let Re=p(_e);return Object.assign(t,{levels:Le,[I]:Re,[ae]:be,[A]:r,[O]:Fe,[k]:Ie,[j]:x,[M]:De,[ee]:Ae,[te]:Me,[P]:je,[ne]:y,[re]:S,[F]:w,[se]:w?`,${JSON.stringify(w)}:{`:``,[D]:g,[ie]:ve,[ce]:ye,[T]:Pe,[oe]:Oe,[L]:Se,silent:C,onChild:Te,[le]:Ee}),Object.setPrototypeOf(t,s()),f(t),t[N](me),t}t.exports=_e,t.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=S(e.dest||process.stdout.fd),y(e)):y({dest:S(e),minLength:0}),t.exports.transport=ed(),t.exports.multistream=sd(),t.exports.levels=d(),t.exports.stdSerializers=ge,t.exports.stdTimeFunctions=Object.assign({},o),t.exports.symbols=c,t.exports.version=w,t.exports.default=_e,t.exports.pino=_e})),ld=o(((e,t)=>{let n=cd(),{serializersSym:r}=n.symbols,{FST_ERR_LOG_INVALID_DESTINATION:i}=Cu();function a(e){if(e.stream&&e.file)throw new i;e.file&&(e.stream=n.destination(e.file),delete e.file);let t=e.logger,a=e.genReqId,o=null;return t?(e.logger=void 0,e.genReqId=void 0,t[r]&&(e.serializers=Object.assign({},e.serializers,t[r])),o=t.child({},e),e.logger=t,e.genReqId=a):o=n(e,e.stream),o}t.exports={serializers:{req:function(e){return{method:e.method,url:e.url,version:e.headers&&e.headers[`accept-version`],host:e.host,remoteAddress:e.ip,remotePort:e.socket?e.socket.remotePort:void 0}},err:n.stdSerializers.err,res:function(e){return{statusCode:e.statusCode}}},createPinoLogger:a}})),ud=o(((e,t)=>{let{FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:n,FST_ERR_LOG_INVALID_LOGGER_CONFIG:r,FST_ERR_LOG_INVALID_LOGGER_INSTANCE:i,FST_ERR_LOG_INVALID_LOGGER:a}=Cu();function o(e,t,n,r,i){let a={[e.requestIdLogLabel]:r},o=e.childLoggerFactory.call(e.server,t,a,i||{},n);return e.childLoggerFactory!==s&&c(o,!0),o}function s(e,t,n){return e.child(t,n)}function c(e,t){let n=[`info`,`error`,`debug`,`fatal`,`warn`,`trace`,`child`],r=e?n.filter(t=>!e[t]||typeof e[t]!=`function`):n;if(!r.length)return!0;if(r.length===n.length&&!t)return!1;throw a(r.join(`,`))}function l(e){if(e.logger&&e.loggerInstance)throw new n;if(!e.loggerInstance&&!e.logger){let e=Nu();return e.child=()=>e,{logger:e,hasLogger:!1}}let{createPinoLogger:t,serializers:a}=ld();if(c(e.loggerInstance))return{logger:t({logger:e.loggerInstance,serializers:Object.assign({},a,e.loggerInstance.serializers)}),hasLogger:!0};if(c(e.logger))throw r();if(e.loggerInstance)throw i();let o={};return Object.prototype.toString.call(e.logger)===`[object Object]`&&Reflect.ownKeys(e.logger).forEach(t=>{Object.defineProperty(o,t,{value:e.logger[t],writable:!0,enumerable:!0,configurable:!0})}),o.level=o.level||`info`,o.serializers=Object.assign({},a,o.serializers),e.logger=o,{logger:t(e.logger),hasLogger:!0}}function u(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}t.exports={createChildLogger:o,defaultChildLoggerFactory:s,createLogger:l,validateLogger:c,now:u}})),dd=o(((e,t)=>{t.exports=r;function n(e){return e instanceof Buffer?Buffer.from(e):new e.constructor(e.buffer.slice(),e.byteOffset,e.length)}function r(e){if(e||={},e.circles)return i(e);let t=new Map;if(t.set(Date,e=>new Date(e)),t.set(Map,(e,t)=>new Map(a(Array.from(e),t))),t.set(Set,(e,t)=>new Set(a(Array.from(e),t))),e.constructorHandlers)for(let n of e.constructorHandlers)t.set(n[0],n[1]);let r=null;return e.proto?s:o;function a(e,i){let a=Object.keys(e),o=Array(a.length);for(let s=0;s<a.length;s++){let c=a[s],l=e[c];typeof l!=`object`||!l?o[c]=l:l.constructor!==Object&&(r=t.get(l.constructor))?o[c]=r(l,i):ArrayBuffer.isView(l)?o[c]=n(l):o[c]=i(l)}return o}function o(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return a(e,o);if(e.constructor!==Object&&(r=t.get(e.constructor)))return r(e,o);let i={};for(let a in e){if(Object.hasOwnProperty.call(e,a)===!1)continue;let s=e[a];typeof s!=`object`||!s?i[a]=s:s.constructor!==Object&&(r=t.get(s.constructor))?i[a]=r(s,o):ArrayBuffer.isView(s)?i[a]=n(s):i[a]=o(s)}return i}function s(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return a(e,s);if(e.constructor!==Object&&(r=t.get(e.constructor)))return r(e,s);let i={};for(let a in e){let o=e[a];typeof o!=`object`||!o?i[a]=o:o.constructor!==Object&&(r=t.get(o.constructor))?i[a]=r(o,s):ArrayBuffer.isView(o)?i[a]=n(o):i[a]=s(o)}return i}}function i(e){let t=[],r=[],i=new Map;if(i.set(Date,e=>new Date(e)),i.set(Map,(e,t)=>new Map(o(Array.from(e),t))),i.set(Set,(e,t)=>new Set(o(Array.from(e),t))),e.constructorHandlers)for(let t of e.constructorHandlers)i.set(t[0],t[1]);let a=null;return e.proto?c:s;function o(e,o){let s=Object.keys(e),c=Array(s.length);for(let l=0;l<s.length;l++){let u=s[l],d=e[u];if(typeof d!=`object`||!d)c[u]=d;else if(d.constructor!==Object&&(a=i.get(d.constructor)))c[u]=a(d,o);else if(ArrayBuffer.isView(d))c[u]=n(d);else{let e=t.indexOf(d);e===-1?c[u]=o(d):c[u]=r[e]}}return c}function s(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return o(e,s);if(e.constructor!==Object&&(a=i.get(e.constructor)))return a(e,s);let c={};t.push(e),r.push(c);for(let o in e){if(Object.hasOwnProperty.call(e,o)===!1)continue;let l=e[o];if(typeof l!=`object`||!l)c[o]=l;else if(l.constructor!==Object&&(a=i.get(l.constructor)))c[o]=a(l,s);else if(ArrayBuffer.isView(l))c[o]=n(l);else{let e=t.indexOf(l);e===-1?c[o]=s(l):c[o]=r[e]}}return t.pop(),r.pop(),c}function c(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return o(e,c);if(e.constructor!==Object&&(a=i.get(e.constructor)))return a(e,c);let s={};t.push(e),r.push(s);for(let o in e){let l=e[o];if(typeof l!=`object`||!l)s[o]=l;else if(l.constructor!==Object&&(a=i.get(l.constructor)))s[o]=a(l,c);else if(ArrayBuffer.isView(l))s[o]=n(l);else{let e=t.indexOf(l);e===-1?s[o]=c(l):s[o]=r[e]}}return t.pop(),r.pop(),s}}})),fd=o(((e,t)=>{let n=dd()({circles:!1,proto:!0}),{kSchemaVisited:r,kSchemaResponse:i}=bu(),a=Symbol.for(`fluent-schema-object`),{FST_ERR_SCH_MISSING_ID:o,FST_ERR_SCH_ALREADY_PRESENT:s,FST_ERR_SCH_DUPLICATE:c,FST_ERR_SCH_CONTENT_MISSING_SCHEMA:l}=Cu(),u=[`params`,`body`,`querystring`,`query`,`headers`];function d(e){this.store=e||{}}d.prototype.add=function(e){let t=n(e.isFluentSchema||e.isFluentJSONSchema||e[a]?e.valueOf():e),r=t.$id;if(!r)throw new o;if(this.store[r])throw new s(r);this.store[r]=t},d.prototype.getSchemas=function(){return Object.assign({},this.store)},d.prototype.getSchema=function(e){return this.store[e]};function f(e){return typeof e==`object`&&Object.getPrototypeOf(e)!==Object.prototype}function p(e,t){if(e[r])return e;if(e.query){if(e.querystring)throw new c(`querystring`);e.querystring=e.query}m(e);for(let t of u){let n=e[t];if(n&&!f(n)&&t===`body`&&n.content){let e=n.content,t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(!e[r].schema)throw new l(r)}continue}}if(e.response){let t=Object.keys(e.response);for(let n of t){if(f(e.response[n]))continue;let t=e.response[n].content;if(t){let e=Object.keys(t);for(let n=0;n<e.length;n++){let r=e[n];if(!t[r].schema)throw new l(r)}}}}return e[r]=!0,e}function m(e){for(let t of u)e[t]&&(e[t].isFluentSchema||e[t][a])&&(e[t]=e[t].valueOf());if(e.response){let t=Object.keys(e.response);for(let n of t)(e.response[n].isFluentSchema||e.response[n][a])&&(e.response[n]=e.response[n].valueOf())}}function h(e,t,n){let r=e[i];if(!r)return!1;if(r[t]){if(r[t].constructor===Object&&n){let e=n.split(`;`,1)[0];return r[t][e]?r[t][e]:r[t][`*/*`]?r[t][`*/*`]:!1}return r[t]}let a=(t+``)[0]+`xx`;if(r[a]){if(r[a].constructor===Object&&n){let e=n.split(`;`,1)[0];return r[a][e]?r[a][e]:r[a][`*/*`]?r[a][`*/*`]:!1}return r[a]}if(r.default){if(r.default.constructor===Object&&n){let e=n.split(`;`,1)[0];return r.default[e]?r.default[e]:r.default[`*/*`]?r.default[`*/*`]:!1}return r.default}return!1}t.exports={buildSchemas(e){return new d(e)},getSchemaSerializer:h,normalizeSchema:p}})),pd=o(((e,t)=>{let n=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;t.exports=class e{constructor(e){switch(e&&e.rounding){case`floor`:this.parseInteger=Math.floor;break;case`ceil`:this.parseInteger=Math.ceil;break;case`round`:this.parseInteger=Math.round;break;default:this.parseInteger=Math.trunc;break}this._options=e}asInteger(e){if(Number.isInteger(e))return``+e;if(typeof e==`bigint`)return e.toString();let t=this.parseInteger(e);if(t===1/0||t===-1/0||t!==t)throw Error(`The value "${e}" cannot be converted to an integer.`);return``+t}asNumber(e){let t=Number(e);if(t!==t)throw Error(`The value "${e}" cannot be converted to a number.`);return t===1/0||t===-1/0?`null`:``+t}asBoolean(e){return e&&`true`||`false`}asDateTime(e){if(e===null)return`""`;if(e instanceof Date)return`"`+e.toISOString()+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a date-time.`)}asDate(e){if(e===null)return`""`;if(e instanceof Date)return`"`+new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,10)+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a date.`)}asTime(e){if(e===null)return`""`;if(e instanceof Date)return`"`+new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(11,19)+`"`;if(typeof e==`string`)return`"`+e+`"`;throw Error(`The value "${e}" cannot be converted to a time.`)}asString(e){let t=e.length;if(t===0)return`""`;if(t<42){let n=``,r=-1,i=255;for(let a=0;a<t;a++)if(i=e.charCodeAt(a),i===34||i===92)r===-1&&(r=0),n+=e.slice(r,a)+`\\`,r=a;else if(i<32||i>=55296&&i<=57343)return JSON.stringify(e);return r===-1&&`"`+e+`"`||`"`+n+e.slice(r)+`"`}else if(t<5e3&&n.test(e)===!1)return`"`+e+`"`;else return JSON.stringify(e)}asUnsafeString(e){return`"`+e+`"`}getState(){return this._options}static restoreFromState(t){return new e(t)}}})),md=o(((e,t)=>{t.exports=function(e,t){let{asString:n,asNumber:r,asBoolean:i,asDateTime:a,asDate:o,asTime:s,asUnsafeString:c}=t;t.asInteger.bind(t);function l(e){let t=e&&typeof e.toJSON==`function`?e.toJSON():e;if(t===null)return`{}`;let i,a=`{`,o=!1;return i=t.statusCode,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"statusCode":`,a+=r(i)),i=t.code,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"code":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),i=t.error,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"error":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),i=t.message,i!==void 0&&(!o&&(o=!0)||(a+=`,`),a+=`"message":`,typeof i==`string`?a+=n(i):i===null?a+=`""`:i instanceof Date?a+=`"`+i.toISOString()+`"`:i instanceof RegExp?a+=n(i.source):a+=n(i.toString())),a+`}`}return l}(null,pd().restoreFromState({mode:`standalone`}))})),hd=o(((e,t)=>{let n=require(`node:http`).STATUS_CODES,r=Au(),{setErrorStatusCode:i}=ku(),{kReplyHeaders:a,kReplyNextErrorHandler:o,kReplyIsRunningOnErrorHook:s,kRouteContext:c,kDisableRequestLogging:l}=bu(),{FST_ERR_REP_INVALID_PAYLOAD_TYPE:u,FST_ERR_FAILED_ERROR_SERIALIZATION:d}=Cu(),{getSchemaSerializer:f}=fd(),p=md(),m={func:g,toJSON(){return this.func.name.toString()+`()`}};function h(e,t,n){e[s]=!1;let i=e[c];if(e[o]===!1){_(t,e,function(e,t){try{e.raw.writeHead(e.raw.statusCode,e[a])}catch(t){e.log[l]||e.log.warn({req:e.request,res:e,err:t},t?.message),e.raw.writeHead(e.raw.statusCode)}e.raw.end(t)});return}let u=e[o]||i.errorHandler;e[o]=Object.getPrototypeOf(u),delete e[a][`content-type`],delete e[a][`content-length`];let d=u.func;if(!d){e[o]=!1,_(t,e,n);return}try{let n=d(t,e.request,e);n!==void 0&&(n!==null&&typeof n.then==`function`?r(n,e):e.send(n))}catch(t){e.send(t)}}function g(e,t,n){y(e,n),i(n,e),n.statusCode<500?n.log[l]||n.log.info({res:n,err:e},e?.message):n.log[l]||n.log.error({req:t,res:n,err:e},e?.message),n.send(e)}function _(e,t,r){let i=t.raw,o=t.statusCode;t[a][`content-type`]=t[a][`content-type`]??`application/json; charset=utf-8`;let s;try{let r=f(t[c],o,t[a][`content-type`]);s=r===!1?p({error:n[o+``],code:e.code,message:e.message,statusCode:o}):r(Object.create(e,{error:{value:n[o+``]},message:{value:e.message},statusCode:{value:o}}))}catch(n){t.log[l]||t.log.error({err:n,statusCode:i.statusCode},`The serializer for the given status code failed`),t.code(500),s=p(new d(n.message,e.message))}typeof s!=`string`&&!Buffer.isBuffer(s)&&(s=p(new u(typeof s))),t[a][`content-length`]=``+Buffer.byteLength(s),r(t,s)}function v(e=m,t){if(!t)return e;let n=Object.create(e);return n.func=t,n}function y(e,t){let n=t.raw,r=n.statusCode;r=r>=400?r:500,e!=null&&(e.headers!==void 0&&t.headers(e.headers),e.status>=400?r=e.status:e.statusCode>=400&&(r=e.statusCode)),n.statusCode=r}t.exports={buildErrorHandler:v,handleError:h}})),gd=o(((e,t)=>{let{kReply:n,kRequest:r,kState:i,kHasBeenDecorated:a}=bu(),{FST_ERR_DEC_ALREADY_PRESENT:o,FST_ERR_DEC_MISSING_DEPENDENCY:s,FST_ERR_DEC_AFTER_START:c,FST_ERR_DEC_REFERENCE_TYPE:l,FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:u,FST_ERR_DEC_UNDECLARED:d}=Cu();function f(e,t,n,r){if(Object.hasOwn(e,t))throw new o(t);x(e,t,r),n&&(typeof n.getter==`function`||typeof n.setter==`function`)?Object.defineProperty(e,t,{get:n.getter,set:n.setter}):e[t]=n}function p(e){if(!_(this,e))throw new d(e,`instance`);return typeof this[e]==`function`?this[e].bind(this):this[e]}function m(e,t,n,r){let i=e.prototype;if(Object.hasOwn(i,t)||v(e,t))throw new o(t);e[a]=!0,x(e,t,r),n&&(typeof n.getter==`function`||typeof n.setter==`function`)?Object.defineProperty(i,t,{get:n.getter,set:n.setter}):typeof n==`function`?i[t]=n:e.props.push({key:t,value:n})}function h(e,t){if(typeof t==`object`&&t&&!(typeof t.getter==`function`||typeof t.setter==`function`))throw new l(e,typeof t)}function g(e,t,n){return w(this,e),f(this,e,t,n),this}function _(e,t){return t?t in e||e.prototype&&t in e.prototype||v(e,t):e in this}function v(e,t){return e.props?e.props.find(({key:e})=>e===t):!1}function y(e){return e&&v(this[r],e)?!0:_(this[r].prototype,e)}function b(e){return e&&v(this[n],e)?!0:_(this[n].prototype,e)}function x(e,t,n){if(n!=null){if(!Array.isArray(n))throw new u(t);for(let t=0;t!==n.length;++t)if(!_(e,n[t]))throw new s(n[t])}}function S(e,t,r){return w(this,e),h(e,t),m(this[n],e,t,r),this}function C(e,t,n){return w(this,e),h(e,t),m(this[r],e,t,n),this}function w(e,t){if(e[i].started)throw new c(t)}t.exports={add:g,exist:_,existRequest:y,existReply:b,dependencies:x,decorateReply:S,decorateRequest:C,getInstanceDecorator:p,hasKey:v}})),_d=o(((e,t)=>{let n=require(`node:stream`).finished,{kFourOhFourContext:r,kReplyErrorHandlerCalled:i,kReplyHijacked:a,kReplyStartTime:o,kReplyEndTime:s,kReplySerializer:c,kReplySerializerDefault:l,kReplyIsError:u,kReplyHeaders:d,kReplyTrailers:f,kReplyHasStatusCode:p,kReplyIsRunningOnErrorHook:m,kReplyNextErrorHandler:h,kDisableRequestLogging:g,kSchemaResponse:_,kReplyCacheSerializeFns:v,kSchemaController:y,kOptions:b,kRouteContext:x}=bu(),{onSendHookRunner:S,onResponseHookRunner:C,preHandlerHookRunner:w,preSerializationHookRunner:T}=wu(),E=Mu()[Symbol.for(`internals`)],D=ud().now,{handleError:O}=hd(),{getSchemaSerializer:k}=fd(),A={JSON:`application/json; charset=utf-8`,PLAIN:`text/plain; charset=utf-8`,OCTET:`application/octet-stream`},{FST_ERR_REP_INVALID_PAYLOAD_TYPE:j,FST_ERR_REP_RESPONSE_BODY_CONSUMED:M,FST_ERR_REP_READABLE_STREAM_LOCKED:ee,FST_ERR_REP_ALREADY_SENT:N,FST_ERR_SEND_INSIDE_ONERR:te,FST_ERR_BAD_STATUS_CODE:P,FST_ERR_BAD_TRAILER_NAME:ne,FST_ERR_BAD_TRAILER_VALUE:re,FST_ERR_MISSING_SERIALIZATION_FN:F,FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:ie,FST_ERR_DEC_UNDECLARED:I}=Cu(),ae=gd(),oe=Object.prototype.toString;function L(e,t,n){this.raw=e,this[c]=null,this[i]=!1,this[u]=!1,this[m]=!1,this.request=t,this[d]={},this[f]=null,this[p]=!1,this[o]=void 0,this.log=n}L.props=[],Object.defineProperties(L.prototype,{[x]:{get(){return this.request[x]}},elapsedTime:{get(){return this[o]===void 0?0:(this[s]||D())-this[o]}},server:{get(){return this.request[x].server}},sent:{enumerable:!0,get(){return(this[a]||this.raw.writableEnded)===!0}},statusCode:{get(){return this.raw.statusCode},set(e){this.code(e)}},routeOptions:{get(){return this.request.routeOptions}}}),L.prototype.writeEarlyHints=function(e,t){return this.raw.writeEarlyHints(e,t),this},L.prototype.hijack=function(){return this[a]=!0,this},L.prototype.send=function(e){if(this[m])throw new te;if(this.sent===!0)return this.log.warn({err:new N(this.request.url,this.request.method)}),this;if(this[u]||e instanceof Error)return this[u]=!1,be(this,e,de),this;if(e===void 0)return de(this,e),this;let t=this.getHeader(`content-type`),n=t!==void 0;if(e!==null){if(typeof e.pipe==`function`||typeof e.getReader==`function`||oe.call(e)===`[object Response]`)return de(this,e),this;if(e.buffer instanceof ArrayBuffer){n||(this[d][`content-type`]=A.OCTET);let t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength);return de(this,t),this}if(!n&&typeof e==`string`)return this[d][`content-type`]=A.PLAIN,de(this,e),this}if(this[c]!==null){if(typeof e!=`string`)return ce(this,e),this;e=this[c](e)}else if(!n||t.indexOf(`json`)!==-1){if(!n)this[d][`content-type`]=A.JSON;else if(t.indexOf(`charset`)===-1){let e=t.trim();e.endsWith(`;`)?this[d][`content-type`]=`${e} charset=utf-8`:this[d][`content-type`]=`${e}; charset=utf-8`}if(typeof e!=`string`)return ce(this,e),this}return de(this,e),this},L.prototype.getHeader=function(e){e=e.toLowerCase();let t=this[d][e];return t===void 0?this.raw.getHeader(e):t},L.prototype.getHeaders=function(){return{...this.raw.getHeaders(),...this[d]}},L.prototype.hasHeader=function(e){return e=e.toLowerCase(),this[d][e]!==void 0||this.raw.hasHeader(e)},L.prototype.removeHeader=function(e){return delete this[d][e.toLowerCase()],this},L.prototype.header=function(e,t=``){return e=e.toLowerCase(),this[d][e]&&e===`set-cookie`?(typeof this[d][e]==`string`&&(this[d][e]=[this[d][e]]),Array.isArray(t)?Array.prototype.push.apply(this[d][e],t):this[d][e].push(t)):this[d][e]=t,this},L.prototype.headers=function(e){let t=Object.keys(e);for(let n=0;n!==t.length;++n){let r=t[n];this.header(r,e[r])}return this};let se=new Set([`transfer-encoding`,`content-length`,`host`,`cache-control`,`max-forwards`,`te`,`authorization`,`set-cookie`,`content-encoding`,`content-type`,`content-range`,`trailer`]);L.prototype.trailer=function(e,t){if(e=e.toLowerCase(),se.has(e))throw new ne(e);if(typeof t!=`function`)throw new re(e,typeof t);return this[f]===null&&(this[f]={}),this[f][e]=t,this},L.prototype.hasTrailer=function(e){return this[f]?.[e.toLowerCase()]!==void 0},L.prototype.removeTrailer=function(e){return this[f]===null||(this[f][e.toLowerCase()]=void 0),this},L.prototype.code=function(e){let t=+e;if(!(t>=100&&t<=599))throw new P(e||String(e));return this.raw.statusCode=t,this[p]=!0,this},L.prototype.status=L.prototype.code,L.prototype.getSerializationFunction=function(e,t){let n;return typeof e==`string`||typeof e==`number`?n=typeof t==`string`?this[x][_]?.[e]?.[t]:this[x][_]?.[e]:typeof e==`object`&&(n=this[x][v]?.get(e)),n},L.prototype.compileSerializationSchema=function(e,t=null,n=null){let{request:r}=this,{method:i,url:a}=r;if(this[x][v]?.has(e))return this[x][v].get(e);let o=(this[x].serializerCompiler||this.server[y].serializerCompiler||this.server[y].setupSerializer(this.server[b])||this.server[y].serializerCompiler)({schema:e,method:i,url:a,httpStatus:t,contentType:n});return this[x][v]??(this[x][v]=new WeakMap),this[x][v].set(e,o),o},L.prototype.serializeInput=function(e,t,n,r){let i=n,a;if(n=typeof t==`string`||typeof t==`number`?t:n,r=n&&i!==n?i:r,n!=null){if(a=r==null?this[x][_]?.[n]:this[x][_]?.[n]?.[r],a==null)throw r?new ie(n,r):new F(n)}else a=this[x][v]?.has(t)?this[x][v].get(t):this.compileSerializationSchema(t,n,r);return a(e)},L.prototype.serialize=function(e){return this[c]===null?this[x]&&this[x][l]?this[x][l](e,this.raw.statusCode):Te(this[x],e,this.raw.statusCode):this[c](e)},L.prototype.serializer=function(e){return this[c]=e,this},L.prototype.type=function(e){return this[d][`content-type`]=e,this},L.prototype.redirect=function(e,t){return t||=this[p]?this.raw.statusCode:302,this.header(`location`,e).code(t).send()},L.prototype.callNotFound=function(){return we(this),this},L.prototype.then=function(e,t){if(this.sent){e();return}n(this.raw,n=>{n&&n.code!==`ERR_STREAM_PREMATURE_CLOSE`?t?t(n):this.log&&this.log.warn(`unhandled rejection on reply.then`):e()})},L.prototype.getDecorator=function(e){if(!ae.hasKey(this,e)&&!ae.exist(this,e))throw new I(e,`reply`);let t=this[e];return typeof t==`function`?t.bind(this):t};function ce(e,t){e[x].preSerialization===null?le(null,void 0,e,t):T(e[x].preSerialization,e.request,e,t,le)}function le(e,t,n,r){if(e!=null){be(n,e);return}try{r=n[c]===null?n[x]&&n[x][l]?n[x][l](r,n.raw.statusCode):Te(n[x],r,n.raw.statusCode,n[d][`content-type`]):n[c](r)}catch(e){ue(e,n),be(n,e);return}de(n,r)}function ue(e,t){e.serialization=t[x].config}function de(e,t){e[x].onSend===null?me(e,t):S(e[x].onSend,e.request,e,t,fe)}function fe(e,t,n,r){e==null?me(n,r):be(n,e)}function pe(e,t){let n=e.raw;try{n.writeHead(t,e[d])}catch(t){throw t.code===`ERR_HTTP_HEADERS_SENT`&&e.log.warn(`Reply was already sent, did you forget to "return reply" in the "${e.request.raw.url}" (${e.request.raw.method}) route?`),t}}function me(e,t){let n=e.raw,r=e.request;if(e[f]!==null){let t=Object.keys(e[f]),n=``;for(let r of t)typeof e[f][r]==`function`&&(n+=` `,n+=r);e.header(`Transfer-Encoding`,`chunked`),e.header(`Trailer`,n.trim())}if(oe.call(t)===`[object Response]`){if(typeof t.status==`number`&&e.code(t.status),typeof t.headers==`object`&&typeof t.headers.forEach==`function`)for(let[n,r]of t.headers)e.header(n,r);if(t.body!==null&&t.bodyUsed)throw new M;t=t.body}let i=n.statusCode;if(t==null){i>=200&&i!==204&&i!==304&&r.method!==`HEAD`&&e[f]===null&&(e[d][`content-length`]=`0`),pe(e,i),ve(t,n,e);return}if(i>=100&&i<200||i===204){e.removeHeader(`content-type`),e.removeHeader(`content-length`),pe(e,i),ve(void 0,n,e),typeof t.resume==`function`&&(t.on(`error`,Ee),t.resume());return}if(typeof t.pipe==`function`){_e(t,n,e);return}if(typeof t.getReader==`function`){ge(t,n,e);return}if(typeof t!=`string`&&!Buffer.isBuffer(t))throw new j(typeof t);if(e[f]===null){let n=e[d][`content-length`];(!n||r.raw.method!==`HEAD`&&Number(n)!==Buffer.byteLength(t))&&(e[d][`content-length`]=``+Buffer.byteLength(t))}pe(e,i),n.write(t),ve(t,n,e)}function he(e,t,n){t.code===`ERR_STREAM_PREMATURE_CLOSE`?e[g]||e.info({res:n},`stream closed prematurely`):e.warn({err:t},`response terminated with an error with headers already sent`)}function ge(e,t,r){if(e.locked)throw new ee;let i=!0,a=!1,o=!1,s=e.getReader();if(n(t,function(e){i&&(e!=null&&t.headersSent&&!a&&(a=!0,he(r.log,e,t)),s.cancel().catch(Ee))}),t.headersSent)r.log.warn(`response will send, but you shouldn't use res.writeHead in stream mode`);else for(let e in r[d])t.setHeader(e,r[d][e]);function c(e){if(e.done){i=!1,ve(null,t,r);return}if(t.destroyed){i=!1,s.cancel().catch(Ee);return}if(t.write(e.value)===!1){o=!0,t.once(`drain`,l);return}s.read().then(c,u)}function l(){!o||!i||t.destroyed||(o=!1,s.read().then(c,u))}function u(e){i=!1,t.headersSent||r.request.raw.aborted===!0?(a||(a=!0,he(r.log,e,r)),t.destroy()):be(r,e)}s.read().then(c,u)}function _e(e,t,r){let i=!0,a=!1;if(ye(e,t,r),n(e,{readable:!0,writable:!1},function(e){i=!1,e!=null&&(t.headersSent||r.request.raw.aborted===!0?(a||(a=!0,he(r.log,e,r)),t.destroy()):be(r,e))}),n(t,function(n){i&&(n!=null&&t.headersSent&&!a&&(a=!0,he(r.log,n,t)),typeof e.destroy==`function`?e.destroy():typeof e.close==`function`?e.close(Ee):typeof e.abort==`function`?e.abort():r.log.warn(`stream payload does not end properly`))}),t.headersSent)r.log.warn(`response will send, but you shouldn't use res.writeHead in stream mode`);else for(let e in r[d])t.setHeader(e,r[d][e]);e.pipe(t)}function ve(e,t,n){if(n[f]===null){t.end(null,null,null);return}let r=Object.keys(n[f]),i={},a=0,o=!0;function s(){a===0&&(t.addTrailers(i),t.end(null,null,null))}for(let t of r){if(typeof n[f][t]!=`function`)continue;o=!1,a--;function r(e,r){a++,e?n.log.debug(e):i[t]=r,process.nextTick(s)}let c=n[f][t](n,e,r);typeof c==`object`&&typeof c.then==`function`&&c.then(e=>r(null,e),r)}o&&t.end(null,null,null)}function ye(e,t,n){n[f]!==null&&e.on(`end`,()=>ve(null,t,n))}function be(e,t,n){e[x].onError!==null&&!e[h]?(e[m]=!0,S(e[x].onError,e.request,e,t,()=>O(e,t,n))):O(e,t,n)}function xe(e){e[o]=D();let t=n=>{e[s]=D(),e.raw.removeListener(`finish`,t),e.raw.removeListener(`error`,t);let r=e[x];r&&r.onResponse!==null?C(r.onResponse,e.request,e,Se):Se(n,e.request,e)};e.raw.on(`finish`,t),e.raw.on(`error`,t)}function Se(e,t,n){if(n.log[g])return;let r=n.elapsedTime;if(e!=null){n.log.error({res:n,err:e,responseTime:r},`request errored`);return}n.log.info({res:n,responseTime:r},`request completed`)}function Ce(e){let t=e.props.slice();function n(e,n,r){this.raw=e,this[u]=!1,this[i]=!1,this[a]=!1,this[c]=null,this.request=n,this[d]={},this[f]=null,this[o]=void 0,this[s]=void 0,this.log=r;let l;for(let e=0;e<t.length;e++)l=t[e],this[l.key]=l.value}return Object.setPrototypeOf(n.prototype,e.prototype),Object.setPrototypeOf(n,e),n.parent=e,n.props=t,n}function we(e){if(e[x][r]===null){e.log.warn(`Trying to send a NotFound error inside a 404 handler. Sending basic 404 response.`),e.code(404).send(`404 Not Found`);return}e.request[x]=e[x][r],e[x].preHandler===null?E.preHandlerCallback(null,e.request,e):w(e[x].preHandler,e.request,e,E.preHandlerCallback)}function Te(e,t,n,r){let i=k(e,n,r);return i?i(t):JSON.stringify(t)}function Ee(){}t.exports=L,t.exports.buildReply=Ce,t.exports.setupResponseListeners=xe})),vd=o(((e,t)=>{function n(e){if(!e)throw TypeError(`argument req is required`);let t=e.headers[`x-forwarded-for`],n=e.socket.remoteAddress;if(!t||typeof t!=`string`)return[n];if(t.indexOf(`,`)===-1){let e=t.trim();return e.length?[n,e]:[n]}else return r(t,n)}function r(e,t){let n=[t],r=e.length,i=r,a,o;for(o=r-1;o>=0;--o)a=e[o],a===` `?i===r&&(i=r=o):a===`,`?(i!==r&&n.push(e.slice(i,r)),i=r=o):i=o;return i!==r&&n.push(e.substring(i,r)),n}t.exports=n,t.exports.default=n,t.exports.forwarded=n})),yd=o(((e,t)=>{(function(e){"use strict";let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=RegExp(`^0[0-7]+$`,`i`),a=RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:new RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function l(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function u(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function d(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function f(e,t){for(;e.length<t;)e=`0${e}`;return e}let p={};p.IPv4=(function(){function e(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return`ipv4`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return u(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(`.`)},e})(),p.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.isIPv4=function(e){return this.parser(e)!==null},p.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},p.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(e){return!!(p.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!p.IPv4.isValidCIDR(e)||!t?!1:p.IPv4.isValidFourPartDecimal(t[1])},p.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},p.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,`toString`,{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},p.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(d(n));return r})();if(t=e.match(r.longValue)){if(i=d(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}else if(t=e.match(r.twoOctet))return(function(){let e=t.slice(1,4),n=[];if(i=d(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})();else if(t=e.match(r.threeOctet))return(function(){let e=t.slice(1,5),n=[];if(i=d(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(d(e[1])),n.push(i>>8&255),n.push(i&255),n})();else return null},p.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.IPv6=(function(){function e(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecated:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},e.prototype.kind=function(){return`ipv6`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return u(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},e.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(f(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new p.IPv4([t>>8,t&255,n>>8,n&255])},e.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString(),n=0,r=-1,i;for(;i=e.exec(t);)i[0].length>r&&(n=i.index,r=i[0].length);return r<0?t:`${t.substring(0,n)}::${t.substring(n+r)}`},e.prototype.toString=function(){return this.toRFC5952String()},e})(),p.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.isIPv6=function(e){return this.parser(e)!==null},p.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},p.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.parse=function(e){let t=this.parser(e);if(t.parts===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},p.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,`toString`,{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},p.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return l(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=l(t+o,6),t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.fromByteArray=function(e){let t=e.length;if(t===4)return new p.IPv4(e);if(t===16)return new p.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},p.isValid=function(e){return p.IPv6.isValid(e)||p.IPv4.isValid(e)},p.isValidCIDR=function(e){return p.IPv6.isValidCIDR(e)||p.IPv4.isValidCIDR(e)},p.parse=function(e){if(p.IPv6.isValid(e))return p.IPv6.parse(e);if(p.IPv4.isValid(e))return p.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},p.parseCIDR=function(e){try{return p.IPv6.parseCIDR(e)}catch{try{return p.IPv4.parseCIDR(e)}catch{throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`)}}},p.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},p.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=p:e.ipaddr=p})(e)})),bd=o(((e,t)=>{t.exports=m,t.exports.default=m,t.exports.proxyaddr=m,t.exports.all=c,t.exports.compile=l;let n=vd(),r=yd(),i=/^\d+$/u,a=r.isValid,o=r.parse,s={linklocal:[`169.254.0.0/16`,`fe80::/10`],loopback:[`127.0.0.1/8`,`::1/128`],uniquelocal:[`10.0.0.0/8`,`172.16.0.0/12`,`192.168.0.0/16`,`fc00::/7`]};function c(e,t){let r=n(e);if(!t)return r;typeof t!=`function`&&(t=l(t));for(let e=0;e<r.length-1;e++)t(r[e],e)||(r.length=e+1);return r}function l(e){if(!e)throw TypeError(`argument is required`);let t;if(typeof e==`string`)t=[e];else if(Array.isArray(e))t=e.slice();else throw TypeError(`unsupported trust argument`);for(let n=0;n<t.length;n++)e=t[n],Object.hasOwn(s,e)&&(e=s[e],t.splice.apply(t,[n,1].concat(e)),n+=e.length-1);return d(u(t))}function u(e){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=f(e[n]);return t}function d(e){let t=e.length;return t===0?h:t===1?_(e[0]):g(e)}function f(e){let t=e.lastIndexOf(`/`),n=t===-1?e:e.substring(0,t);if(!a(n))throw TypeError(`invalid IP address: `+n);let r=o(n);t===-1&&r.kind()===`ipv6`&&r.isIPv4MappedAddress()&&(r=r.toIPv4Address());let s=r.kind()===`ipv6`?128:32,c=t===-1?null:e.substring(t+1,e.length);if(c=c===null?s:i.test(c)?parseInt(c,10):r.kind()===`ipv4`&&a(c)?p(c):null,c<=0||c>s)throw TypeError(`invalid range on address: `+e);return[r,c]}function p(e){let t=o(e);return t.kind()===`ipv4`?t.prefixLengthFromSubnetMask():null}function m(e,t){if(!e)throw TypeError(`req argument is required`);if(!t)throw TypeError(`trust argument is required`);let n=c(e,t);return n[n.length-1]}function h(){return!1}function g(e){return function(t){if(!a(t))return!1;let n=o(t),r,i=n.kind();for(let t=0;t<e.length;t++){let a=e[t],o=a[0],s=o.kind(),c=a[1],l=n;if(i!==s){let e=s===`ipv4`;if(e&&!n.isIPv4MappedAddress())continue;r||=e?n.toIPv4Address():n.toIPv4MappedAddress(),l=r}if(l.match(o,c))return!0}return!1}}function _(e){let t=e[0],n=t.kind(),r=n===`ipv4`,i=e[1];return function(e){if(!a(e))return!1;let s=o(e);if(s.kind()!==n){if(r&&!s.isIPv4MappedAddress())return!1;s=r?s.toIPv4Address():s.toIPv4MappedAddress()}return s.match(t,i)}}})),xd=o(((e,t)=>{let n=bd(),{kHasBeenDecorated:r,kSchemaBody:i,kSchemaHeaders:a,kSchemaParams:o,kSchemaQuerystring:s,kSchemaController:c,kOptions:l,kRequestCacheValidateFns:u,kRouteContext:d,kRequestOriginalUrl:f}=bu(),{FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:p,FST_ERR_DEC_UNDECLARED:m}=Cu(),h=gd(),g={body:i,headers:a,params:o,querystring:s,query:s};function _(e,t,n,r,i,a){this.id=e,this[d]=a,this.params=t,this.raw=n,this.query=r,this.log=i,this.body=void 0}_.props=[];function v(e){if(typeof e==`function`)return e;if(e===!0)return null;if(typeof e==`number`)return function(t,n){return n<e};if(typeof e==`string`){let t=e.split(`,`).map(e=>e.trim());return n.compile(t)}return n.compile(e)}function y(e,t){return t?S(e,t):b(e)}function b(e){let t=e.props.slice();function n(e,n,r,i,a,o){this.id=e,this[d]=o,this.params=n,this.raw=r,this.query=i,this.log=a,this.body=void 0;let s;for(let e=0;e<t.length;e++)s=t[e],this[s.key]=s.value}return Object.setPrototypeOf(n.prototype,e.prototype),Object.setPrototypeOf(n,e),n.props=t,n.parent=e,n}function x(e){let t=e.lastIndexOf(`,`);return t===-1?e.trim():e.slice(t+1).trim()}function S(e,t){let i=b(e),a=v(t);return i[r]=!0,Object.defineProperties(i.prototype,{ip:{get(){let e=n.all(this.raw,a);return e[e.length-1]}},ips:{get(){return n.all(this.raw,a)}},host:{get(){return this.ip!==void 0&&this.headers[`x-forwarded-host`]?x(this.headers[`x-forwarded-host`]):this.headers.host??this.headers[`:authority`]??``}},protocol:{get(){if(this.headers[`x-forwarded-proto`])return x(this.headers[`x-forwarded-proto`]);if(this.socket)return this.socket.encrypted?`https`:`http`}}}),i}function C(e,t){if(!h.hasKey(e,t)&&!h.exist(e,t))throw new m(t,`request`)}Object.defineProperties(_.prototype,{server:{get(){return this[d].server}},url:{get(){return this.raw.url}},originalUrl:{get(){return this[f]||(this[f]=this.raw.originalUrl||this.raw.url),this[f]}},method:{get(){return this.raw.method}},routeOptions:{get(){let e=this[d],t=e._parserOptions.limit,n=e.server.initialConfig.bodyLimit,r=e.server.hasConstraintStrategy(`version`)?this.raw.headers[`accept-version`]:void 0;return{method:e.config?.method,url:e.config?.url,bodyLimit:t||n,attachValidation:e.attachValidation,logLevel:e.logLevel,exposeHeadRoute:e.exposeHeadRoute,prefixTrailingSlash:e.prefixTrailingSlash,handler:e.handler,config:e.config,schema:e.schema,version:r}}},is404:{get(){return this[d].config?.url===void 0}},socket:{get(){return this.raw.socket}},ip:{get(){if(this.socket)return this.socket.remoteAddress}},host:{get(){return this.raw.headers.host??this.raw.headers[`:authority`]??``}},hostname:{get(){return this.host[0]===`[`?this.host.slice(0,this.host.indexOf(`]`)+1):this.host.split(`:`,1)[0]}},port:{get(){let e=parseInt(this.host.split(`:`).slice(-1)[0]);if(!isNaN(e))return e;let t=this.headers.host??this.headers[`:authority`]??``,n=parseInt(t.split(`:`).slice(-1)[0]);return isNaN(n)?null:n}},protocol:{get(){if(this.socket)return this.socket.encrypted?`https`:`http`}},headers:{get(){return this.additionalHeaders?Object.assign({},this.raw.headers,this.additionalHeaders):this.raw.headers},set(e){this.additionalHeaders=e}},getValidationFunction:{value:function(e){if(typeof e==`string`){let t=g[e];return this[d][t]}else if(typeof e==`object`)return this[d][u]?.get(e)}},compileValidationSchema:{value:function(e,t=null){let{method:n,url:r}=this;if(this[d][u]?.has(e))return this[d][u].get(e);let i=(this[d].validatorCompiler||this.server[c].validatorCompiler||this.server[c].setupValidator(this.server[l])||this.server[c].validatorCompiler)({schema:e,method:n,url:r,httpPart:t});return this[d][u]??(this[d][u]=new WeakMap),this[d][u].set(e,i),i}},validateInput:{value:function(e,t,n){n=typeof t==`string`?t:n;let r=n!=null&&typeof n==`string`&&g[n],i;if(r&&(i=this[d][r]),i==null&&(typeof t!=`object`||!t||Array.isArray(t)))throw new p(n);return i??=this[d][u]?.has(t)?this[d][u].get(t):this.compileValidationSchema(t,n),i(e)}},getDecorator:{value:function(e){C(this,e);let t=this[e];return typeof t==`function`?t.bind(this):t}},setDecorator:{value:function(e,t){C(this,e),this[e]=t}}}),t.exports=_,t.exports.buildRequest=y})),Sd=o(((e,t)=>{let{kFourOhFourContext:n,kReplySerializerDefault:r,kSchemaErrorFormatter:i,kErrorHandler:a,kChildLoggerFactory:o,kOptions:s,kReply:c,kRequest:l,kBodyLimit:u,kLogLevel:d,kContentTypeParser:f,kRouteByFastify:p,kRequestCacheValidateFns:m,kReplyCacheSerializeFns:h}=bu();function g({schema:e,handler:t,config:g,requestIdLogLabel:v,childLoggerFactory:y,errorHandler:b,bodyLimit:x,logLevel:S,logSerializers:C,attachValidation:w,validatorCompiler:T,serializerCompiler:E,replySerializer:D,schemaErrorFormatter:O,exposeHeadRoute:k,prefixTrailingSlash:A,server:j,isFastify:M}){this.schema=e,this.handler=t,this.Reply=j[c],this.Request=j[l],this.contentTypeParser=j[f],this.onRequest=null,this.onSend=null,this.onError=null,this.onTimeout=null,this.preHandler=null,this.onResponse=null,this.preSerialization=null,this.onRequestAbort=null,this.config=g,this.errorHandler=b||j[a],this.requestIdLogLabel=v||j[s].requestIdLogLabel,this.childLoggerFactory=y||j[o],this._middie=null,this._parserOptions={limit:x||j[u]},this.exposeHeadRoute=k,this.prefixTrailingSlash=A,this.logLevel=S||j[d],this.logSerializers=C,this[n]=null,this.attachValidation=w,this[r]=D,this.schemaErrorFormatter=O||j[i]||_,this[p]=M,this[m]=null,this[h]=null,this.validatorCompiler=T||null,this.serializerCompiler=E||null,this.server=j}function _(e,t){let n=``;for(let r=0;r!==e.length;++r){let i=e[r];n+=t+(i.instancePath||``)+` `+i.message+`, `}return Error(n.slice(0,-2))}t.exports=g})),Cd=o((e=>{var t=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=t}get size(){return this.items.size}clear(){this.items=new Map,this.first=null,this.last=null}delete(e){if(this.items.has(e)){let t=this.items.get(e);this.items.delete(e),t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(this.items.has(e))return this.items.get(e).expiry}get(e){if(this.items.has(e)){let t=this.items.get(e);if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return this.items.keys()}set(e,t){if(this.items.has(e)){let n=this.items.get(e);n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items.set(e,n),this.size===1?this.first=n:this.last.next=n,this.last=n}},n=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=t}get size(){return this.items.size}bumpLru(e){if(this.last===e)return;let t=this.last,n=e.next,r=e.prev;this.first===e&&(this.first=n),e.next=null,e.prev=t,t.next=e,r!==null&&(r.next=n),n!==null&&(n.prev=r),this.last=e}clear(){this.items=new Map,this.first=null,this.last=null}delete(e){if(this.items.has(e)){let t=this.items.get(e);this.items.delete(e),t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(this.items.has(e))return this.items.get(e).expiry}get(e){if(this.items.has(e)){let t=this.items.get(e);if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(t),t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return this.items.keys()}set(e,t){if(this.items.has(e)){let n=this.items.get(e);n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.last!==n&&this.bumpLru(n);return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items.set(e,n),this.size===1?this.first=n:this.last.next=n,this.last=n}},r=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=t}bumpLru(e){if(this.last===e)return;let t=this.last,n=e.next,r=e.prev;this.first===e&&(this.first=n),e.next=null,e.prev=t,t.next=e,r!==null&&(r.next=n),n!==null&&(n.prev=r),this.last=e}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(Object.prototype.hasOwnProperty.call(this.items,e))return this.items[e].expiry}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(t),t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return Object.keys(this.items)}set(e,t){if(Object.prototype.hasOwnProperty.call(this.items,e)){let n=this.items[e];n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.last!==n&&this.bumpLru(n);return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items[e]=n,++this.size===1?this.first=n:this.last.next=n,this.last=n}},i=class{constructor(){this.records={}}initForCache(e,t){this.records[e]={[t]:{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}}resetForCache(e){for(let t of Object.keys(this.records[e]))this.records[e][t]={cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}getStatistics(){return this.records}};function a(e){return`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,`0`)}-${e.getDate().toString().padStart(2,`0`)}`}var o=class{constructor(e,t,n){this.cacheId=e,this.statisticTtlInHours=t,this.collectionStart=new Date,this.currentTimeStamp=a(this.collectionStart),this.records=n||new i,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){return this.records.records[this.cacheId][this.currentTimeStamp]||(this.records.records[this.cacheId][this.currentTimeStamp]={cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,sets:0,invalidateOne:0,invalidateAll:0}),this.records.records[this.cacheId][this.currentTimeStamp]}hoursPassed(){return(Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++}setCacheSize(e){this.archiveIfNeeded(),this.currentRecord.cacheSize=e}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){this.hoursPassed()>=this.statisticTtlInHours&&(this.collectionStart=new Date,this.currentTimeStamp=a(this.collectionStart),this.records.initForCache(this.cacheId,this.currentTimeStamp))}},s=class extends r{constructor(e,t,n,r,i){if(super(e||1e3,t||0),!n)throw Error(`Cache id is mandatory`);this.hitStatistics=new o(n,i===void 0?24:i,r)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,t){super.set(e,t),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){super.evict(),this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,t=!1){super.delete(e),t||this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(t),t.value||this.hitStatistics.addFalsyHit(),(t.value===void 0||t.value===null||t.value===``)&&this.hitStatistics.addEmptyHit(),this.hitStatistics.addHit(),t.value}this.hitStatistics.addMiss()}},c=class{constructor(e=1e3,t=0){if(isNaN(e)||e<0)throw Error(`Invalid max value`);if(isNaN(t)||t<0)throw Error(`Invalid ttl value`);this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=t}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){if(Object.prototype.hasOwnProperty.call(this.items,e))return this.items[e].expiry}get(e){if(Object.prototype.hasOwnProperty.call(this.items,e)){let t=this.items[e];if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return t.value}}getMany(e){let t=[];for(var n=0;n<e.length;n++)t.push(this.get(e[n]));return t}keys(){return Object.keys(this.items)}set(e,t){if(Object.prototype.hasOwnProperty.call(this.items,e)){let n=this.items[e];n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size===this.max&&this.evict();let n={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items[e]=n,++this.size===1?this.first=n:this.last.next=n,this.last=n}};e.Fifo=c,e.FifoMap=t,e.FifoObject=c,e.HitStatisticsRecord=i,e.Lru=r,e.LruHitStatistics=s,e.LruMap=n,e.LruObject=r,e.LruObjectHitStatistics=s})),wd=o(((e,t)=>{let n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),Td=o(((e,t)=>{let{AsyncResource:n}=require(`node:async_hooks`),{FifoMap:r}=Cd(),{parse:i}=wd(),a=Ou(),{kDefaultJsonParse:o,kContentTypeParser:s,kBodyLimit:c,kRequestPayloadStream:l,kState:u,kTestInternals:d,kReplyIsError:f,kRouteContext:p}=bu(),{FST_ERR_CTP_INVALID_TYPE:m,FST_ERR_CTP_EMPTY_TYPE:h,FST_ERR_CTP_ALREADY_PRESENT:g,FST_ERR_CTP_INVALID_HANDLER:_,FST_ERR_CTP_INVALID_PARSE_TYPE:v,FST_ERR_CTP_BODY_TOO_LARGE:y,FST_ERR_CTP_INVALID_MEDIA_TYPE:b,FST_ERR_CTP_INVALID_CONTENT_LENGTH:x,FST_ERR_CTP_EMPTY_JSON_BODY:S,FST_ERR_CTP_INSTANCE_ALREADY_STARTED:C,FST_ERR_CTP_INVALID_JSON_BODY:w}=Cu(),{FSTSEC001:T}=Su();function E(e,t,n){this[o]=O(t,n),this.customParsers=new Map,this.customParsers.set(`application/json`,new A(!0,!1,e,this[o])),this.customParsers.set(`text/plain`,new A(!0,!1,e,k)),this.parserList=[`application/json`,`text/plain`],this.parserRegExpList=[],this.cache=new r(100)}E.prototype.add=function(e,t,n){let r=typeof e==`string`;if(r){if(e=e.trim().toLowerCase(),e.length===0)throw new h}else if(!(e instanceof RegExp))throw new m;if(typeof n!=`function`)throw new _;if(this.existingParser(e))throw new g(e);if(t.parseAs!==void 0&&t.parseAs!==`string`&&t.parseAs!==`buffer`)throw new v(t.parseAs);let i=new A(t.parseAs===`string`,t.parseAs===`buffer`,t.bodyLimit,n);if(e===`*`)this.customParsers.set(``,i);else if(r){let t=new a(e);if(t.isValid===!1)throw new m;let n=t.toString();this.parserList.unshift(n),this.customParsers.set(n,i)}else P(e),this.parserRegExpList.unshift(e),this.customParsers.set(e.toString(),i)},E.prototype.hasParser=function(e){if(typeof e==`string`)e=new a(e).toString();else{if(!(e instanceof RegExp))throw new m;e=e.toString()}return this.customParsers.has(e)},E.prototype.existingParser=function(e){if(typeof e==`string`){let t=new a(e).toString();if(e===`application/json`&&this.customParsers.has(e))return this.customParsers.get(t).fn!==this[o];if(e===`text/plain`&&this.customParsers.has(e))return this.customParsers.get(t).fn!==k}return this.hasParser(e)},E.prototype.getParser=function(e){typeof e==`string`&&(e=new a(e));let t=e.toString(),n=this.cache.get(t);if(n!==void 0)return n;if(n=this.customParsers.get(t),n!==void 0)return this.cache.set(t,n),n;if(n=this.customParsers.get(e.mediaType),n!==void 0)return n;for(let e=0;e!==this.parserRegExpList.length;++e){let r=this.parserRegExpList[e];if(r.test(t))return n=this.customParsers.get(r.toString()),this.cache.set(t,n),n}return this.customParsers.get(``)},E.prototype.removeAll=function(){this.customParsers=new Map,this.parserRegExpList=[],this.parserList=[],this.cache=new r(100)},E.prototype.remove=function(e){let t;if(typeof e==`string`)e=new a(e).toString(),t=this.parserList;else{if(!(e instanceof RegExp))throw new m;e=e.toString(),t=this.parserRegExpList}let n=this.customParsers.delete(e),r=t.findIndex(t=>t.toString()===e);return r>-1&&t.splice(r,1),n||r>-1},E.prototype.run=function(e,t,r,i){let a=this.getParser(e);if(a===void 0){if(r.is404===!0){t(r,i);return}i[f]=!0,i.send(new b(e||void 0));return}let o=new n(`content-type-parser:run`,r),s=o.bind(u);if(a.asString===!0||a.asBuffer===!0){D(r,i,i[p]._parserOptions,a,s);return}let c=a.fn(r,r[l],s);c&&typeof c.then==`function`&&c.then(e=>{s(null,e)},s);function u(e,n){if(o.emitDestroy(),e!=null){i.header(`connection`,`close`),i[f]=!0,i.send(e);return}r.body=n,t(r,i)}};function D(e,t,n,r,i){let a=r.asString===!0,o=n.limit===null?r.bodyLimit:n.limit,s=Number(e.headers[`content-length`]);if(s>o){i(new y,void 0);return}let c=0,u=a?``:[],d=e[l]||e.raw;a&&d.setEncoding(`utf8`),d.on(`data`,f),d.on(`end`,p),d.on(`error`,p),d.resume();function f(e){c+=a?Buffer.byteLength(e):e.length;let{receivedEncodedLength:t=0}=d;if(c>o||t>o){d.removeListener(`data`,f),d.removeListener(`end`,p),d.removeListener(`error`,p),i(new y,void 0);return}a?u+=e:u.push(e)}function p(t){if(d.removeListener(`data`,f),d.removeListener(`end`,p),d.removeListener(`error`,p),t!=null){typeof t.statusCode==`number`&&t.statusCode>=400||(t.statusCode=400),i(t,void 0);return}if(!Number.isNaN(s)&&(d.receivedEncodedLength||c)!==s){i(new x,void 0);return}a||(u=Buffer.concat(u));let n=r.fn(e,u,i);n&&typeof n.then==`function`&&n.then(e=>{i(null,e)},i)}}function O(e,t){let n={protoAction:e,constructorAction:t};return r;function r(e,t,r){if(t.length===0){r(new S,void 0);return}try{r(null,i(t,n))}catch{r(new w,void 0)}}}function k(e,t,n){n(null,t)}function A(e,t,n,r){this.asString=e,this.asBuffer=t,this.bodyLimit=n,this.fn=r}function j(e){let t=new E;return t[o]=e[o],t.customParsers=new Map(e.customParsers.entries()),t.parserList=e.parserList.slice(),t.parserRegExpList=e.parserRegExpList.slice(),t}function M(e,t,n){if(this[u].started)throw new C(`addContentTypeParser`);return typeof t==`function`&&(n=t,t={}),t||={},t.bodyLimit||=this[c],Array.isArray(e)?e.forEach(e=>this[s].add(e,t,n)):this[s].add(e,t,n),this}function ee(e){return this[s].hasParser(e)}function N(e){if(this[u].started)throw new C(`removeContentTypeParser`);if(Array.isArray(e))for(let t of e)this[s].remove(t);else this[s].remove(e)}function te(){if(this[u].started)throw new C(`removeAllContentTypeParsers`);this[s].removeAll()}function P(e){e.source[0]!==`^`&&e.source.includes(`;?`)===!1&&T(e.source)}t.exports=E,t.exports.helpers={buildContentTypeParser:j,addContentTypeParser:M,hasContentTypeParser:ee,removeContentTypeParser:N,removeAllContentTypeParsers:te},t.exports.defaultParsers={getDefaultJsonParser:O,defaultTextParser:k},t.exports[d]={rawBody:D}})),Ed=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Dd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Ed();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),X=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Ed(),n=Dd();var r=Ed();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=Dd();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=k(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=k(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=k(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(A(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>D(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(j(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=k(this.condition,e,t),this}get names(){let e=super.names;return O(e,this.condition),this.else&&D(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=k(this.iteration,e,t),this}get names(){return D(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return O(O(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=k(this.iterable,e,t),this}get names(){return D(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&D(e,this.catch.names),this.finally&&D(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
129
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new E,this.code(n)),this._endBlockNode(T,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function D(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function O(e,n){return n instanceof t._CodeOrName?D(e,n.names):e}function k(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function A(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function j(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ne(e)}`}e.not=j;let M=P(e.operators.AND);function ee(...e){return e.reduce(M)}e.and=ee;let N=P(e.operators.OR);function te(...e){return e.reduce(N)}e.or=te;function P(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ne(n)} ${e} ${ne(r)}`}function ne(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Z=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=X(),n=Ed();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Od=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),kd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=X(),n=Z(),r=Od();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Ad=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=kd(),n=X(),r=Od(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),jd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Md=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Nd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=jd(),n=Md(),r=kd(),i=X(),a=Z();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
130
130
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
131
131
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
132
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Nd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=X(),n=Z();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Pd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=X(),n=Z(),r=Dd(),i=Z();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Fd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=X(),n=Dd(),r=Pd(),i=Od();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Id=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=X(),n=Z();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Ld=o(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Rd=o(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),zd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Z(),n=Ld(),r=Rd(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Bd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=kd(),n=Md(),r=jd(),i=Md(),a=Nd(),o=Fd(),s=Id(),c=X(),l=Dd(),u=zd(),d=Z(),f=Od();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&A(e),D(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),j(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&A(e),O(e),k(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return ee(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ee(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function D(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function O(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function k(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function A({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function j(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&M(e),t.return((0,c._)`${l.default.errors} === 0`))}function M({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ee(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>L(e,`$ref`,h.all.$ref.definition));return}p.jtd||te(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),N(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):N(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function N(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&L(e,n.keyword,n.definition,t.type)})}function te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P(e,t),e.opts.allowUnionTypes||ne(e,t),re(e,e.dataTypes))}function P(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{ie(e.dataTypes,t)||ae(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),I(e,t)}}function ne(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ae(e,`use allowUnionTypes to allow union type keyword`)}function re(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>F(t,e))&&ae(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function F(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function ie(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function I(e,t){let n=[];for(let r of e.dataTypes)ie(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ae(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var oe=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,le(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=oe;function L(e,t,n,r){let i=new oe(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let se=/^\/(?:[^~]|~0|~1)*$/,ce=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function le(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!se.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ce.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=le})),Vd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Hd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=zd();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Ud=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=X(),n=Vd(),r=Dd(),i=zd(),a=Z(),o=Bd();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Wd=o(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Gd=o(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(!(s===`[`||s===`]`))if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}else if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),Kd=o(((e,t)=>{let{isUUID:n}=Gd(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=S(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=S(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},b={scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0},x={http:h,https:g,ws:_,wss:v,urn:y,"urn:uuid":b};Object.setPrototypeOf(x,null);function S(e){return e&&(x[e]||x[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:x,isValidSchemeName:a,getSchemeHandler:S}})),qd=o(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Gd(),{SCHEMES:c,getSchemeHandler:l}=Kd();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host)if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Jd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=qd();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Yd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Bd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=X();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=Vd(),i=Hd(),a=Ad(),o=Ud(),s=X(),c=zd(),l=Md(),u=Z(),d=Wd(),f=Jd(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=D(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(k.call(this,n,t),!t)return(0,u.eachItem)(n,e=>A.call(this,e)),this;M.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>A.call(this,e,r):e=>r.type.forEach(t=>A.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=N(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let E={log(){},warn(){},error(){}};function D(e){if(e===!1)return E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let O=/^[a-z_$][a-z0-9_$:-]*$/i;function k(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!O.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function A(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?j.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function j(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function M(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=N(t)),e.validateSchema=this.compile(t,!0))}let ee={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function N(e){return{anyOf:[e,ee]}}})),Xd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Zd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Hd(),n=Pd(),r=X(),i=Dd(),a=Ud(),o=Z(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),Qd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Xd(),n=Zd();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),$d=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=tf();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Pd(),n=Z(),r=X();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),af=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),of=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Pd(),n=X(),r=Z();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ld();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),lf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Md(),n=X(),r=Z(),i=cf();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=cf();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=cf();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$d(),n=ef(),r=nf(),i=rf(),a=af(),o=of(),s=sf(),c=lf(),l=uf(),u=df();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=X(),n=Z(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=X(),n=Z(),r=Pd(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=mf();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=Pd(),i=pf();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),_f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=X(),n=Z(),r=Pd();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
132
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Pd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=X(),n=Z();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Fd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=X(),n=Z(),r=Od(),i=Z();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Id=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=X(),n=Od(),r=Fd(),i=kd();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Ld=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=X(),n=Z();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Rd=o(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),zd=o(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Bd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Z(),n=Rd(),r=zd(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Vd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Ad(),n=Nd(),r=Md(),i=Nd(),a=Pd(),o=Id(),s=Ld(),c=X(),l=Od(),u=Bd(),d=Z(),f=kd();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&A(e),D(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),j(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&A(e),O(e),k(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return ee(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ee(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function D(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function O(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function k(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function A({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function j(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&M(e),t.return((0,c._)`${l.default.errors} === 0`))}function M({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ee(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>L(e,`$ref`,h.all.$ref.definition));return}p.jtd||te(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),N(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):N(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function N(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&L(e,n.keyword,n.definition,t.type)})}function te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P(e,t),e.opts.allowUnionTypes||ne(e,t),re(e,e.dataTypes))}function P(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{ie(e.dataTypes,t)||ae(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),I(e,t)}}function ne(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ae(e,`use allowUnionTypes to allow union type keyword`)}function re(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>F(t,e))&&ae(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function F(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function ie(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function I(e,t){let n=[];for(let r of e.dataTypes)ie(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ae(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var oe=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,le(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=oe;function L(e,t,n,r){let i=new oe(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let se=/^\/(?:[^~]|~0|~1)*$/,ce=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function le(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!se.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ce.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=le})),Hd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Ud=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Bd();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Wd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=X(),n=Hd(),r=Od(),i=Bd(),a=Z(),o=Vd();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Gd=o(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Kd=o(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(!(s===`[`||s===`]`))if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}else if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),qd=o(((e,t)=>{let{isUUID:n}=Kd(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=S(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=S(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},b={scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0},x={http:h,https:g,ws:_,wss:v,urn:y,"urn:uuid":b};Object.setPrototypeOf(x,null);function S(e){return e&&(x[e]||x[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:x,isValidSchemeName:a,getSchemeHandler:S}})),Jd=o(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Kd(),{SCHEMES:c,getSchemeHandler:l}=qd();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host)if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Yd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Jd();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Xd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Vd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=X();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=Hd(),i=Ud(),a=jd(),o=Wd(),s=X(),c=Bd(),l=Nd(),u=Z(),d=Gd(),f=Yd(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=D(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(k.call(this,n,t),!t)return(0,u.eachItem)(n,e=>A.call(this,e)),this;M.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>A.call(this,e,r):e=>r.type.forEach(t=>A.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=N(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let E={log(){},warn(){},error(){}};function D(e){if(e===!1)return E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let O=/^[a-z_$][a-z0-9_$:-]*$/i;function k(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!O.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function A(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?j.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function j(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function M(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=N(t)),e.validateSchema=this.compile(t,!0))}let ee={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function N(e){return{anyOf:[e,ee]}}})),Zd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Qd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Ud(),n=Fd(),r=X(),i=Od(),a=Wd(),o=Z(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),$d=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Zd(),n=Qd();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=nf();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),af=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Fd(),n=Z(),r=X();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),of=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Fd(),n=X(),r=Z();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),lf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Rd();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Nd(),n=X(),r=Z(),i=lf();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=lf();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=lf();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ef(),n=tf(),r=rf(),i=af(),a=of(),o=sf(),s=cf(),c=uf(),l=df(),u=ff();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=X(),n=Z(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=X(),n=Z(),r=Fd(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=hf();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),_f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=Fd(),i=mf();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=X(),n=Z(),r=Fd();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
133
133
  missingProperty: ${i},
134
134
  depsCount: ${n},
135
- deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Pd(),n=X(),r=Dd(),i=Z();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Bd(),n=Pd(),r=Z(),i=bf();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Pd(),n=X(),r=Z(),i=Z();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),Cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Pd().validateUnion,error:{message:`must match a schema in anyOf`}}})),Tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),Ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),Df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Of=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),kf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=pf(),n=hf(),r=mf(),i=gf(),a=_f(),o=vf(),s=yf(),c=bf(),l=xf(),u=Sf(),d=Cf(),f=wf(),p=Tf(),m=Ef(),h=Df(),g=Of();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Af=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Af().default]})),Mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Qd(),n=ff(),r=kf(),i=jf(),a=Mf();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Pf(),r=Ud(),i=Hd(),a=Z();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),If=o(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Lf=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Yd(),r=Nf(),i=Ff(),a=If(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Bd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Vd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Hd();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkMetadata=void 0;let t=Z(),n={keyword:`metadata`,schemaType:`object`,code(e){r(e);let{gen:n,schema:i,it:a}=e;if((0,t.alwaysValidSchema)(a,i))return;let o=n.name(`valid`);e.subschema({keyword:`metadata`,jtdMetadata:!0},o),e.ok(o)}};function r({it:e,keyword:t},n){if(e.jtdMetadata!==n)throw Error(`JTD: "${t}" cannot be used in this schema location`)}e.checkMetadata=r,e.default=n})),zf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hasRef=void 0;let t=Ud(),n=X(),r=Hd(),i=Dd(),a=Zd(),o=Rf(),s={keyword:`ref`,schemaType:`string`,code(e){(0,o.checkMetadata)(e);let{gen:s,data:l,schema:u,parentSchema:d,it:f}=e,{schemaEnv:{root:p}}=f,m=s.name(`valid`);d.nullable?(s.var(m,(0,n._)`${l} === null`),s.if((0,n.not)(m),h)):(s.var(m,!1),h()),e.ok(m);function h(){let e=p.schema.definitions?.[u];if(!e)throw new r.default(f.opts.uriResolver,``,u,`No definition ${u}`);c(e)||!f.opts.inlineRefs?g(e):_(e)}function g(r){let o=t.compileSchema.call(f.self,new t.SchemaEnv({schema:r,root:p,schemaPath:`/definitions/${u}`})),c=(0,a.getValidate)(e,o),l=s.const(`_errs`,i.default.errors);(0,a.callRef)(e,c,o,o.$async),s.assign(m,(0,n._)`${l} === ${i.default.errors}`)}function _(t){let r=s.scopeValue(`schema`,f.opts.code.source===!0?{ref:t,code:(0,n.stringify)(t)}:{ref:t});e.subschema({schema:t,dataTypes:[],schemaPath:n.nil,topSchemaRef:r,errSchemaPath:`/definitions/${u}`},m)}}};function c(e){for(let t in e){let n;if(t===`ref`||typeof(n=e[t])==`object`&&c(n))return!0}return!1}e.hasRef=c,e.default=s})),Bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/t|\s/i,n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e,n){let r=e.split(t);return r.length===2&&o(r[0])&&s(r[1])||n&&r.length===1&&o(r[0])}e.default=a;function o(e){let t=n.exec(e);if(!t)return!1;let r=+t[1],a=+t[2],o=+t[3];return a>=1&&a<=12&&o>=1&&(o<=i[a]||a===2&&o===29&&(r%100==0?r%400==0:r%4==0))}function s(e){let t=r.exec(e);if(!t)return!1;let n=+t[1],i=+t[2],a=+t[3],o=+(t[4]||0),s=+(t[5]||0);return n<=23&&i<=59&&a<=59||n-o===23&&i-s===59&&a===60}a.code=`require("ajv/dist/runtime/timestamp").default`})),Vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.typeErrorParams=e.typeErrorMessage=e.typeError=void 0;let t=X();function n(e){return{message:t=>r(t,e),params:t=>i(t,e)}}e.typeError=n;function r({parentSchema:e},t){return e?.nullable?`must be ${t} or null`:`must be ${t}`}e.typeErrorMessage=r;function i({parentSchema:e},n){return(0,t._)`{type: ${n}, nullable: ${!!e?.nullable}}`}e.typeErrorParams=i})),Hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.intRange=void 0;let t=X(),n=Bf(),r=Z(),i=Rf(),a=Vf();e.intRange={int8:[-128,127,3],uint8:[0,255,3],int16:[-32768,32767,5],uint16:[0,65535,5],int32:[-2147483648,2147483647,10],uint32:[0,4294967295,10]};let o={message:e=>(0,a.typeErrorMessage)(e,e.schema),params:e=>(0,a.typeErrorParams)(e,e.schema)};function s(e){let{gen:i,data:a,it:o}=e,{timestamp:s,allowDate:c}=o.opts;if(s===`date`)return(0,t._)`${a} instanceof Date `;let l=(0,r.useFunc)(i,n.default),u=c?(0,t._)`, true`:t.nil,d=(0,t._)`typeof ${a} == "string" && ${l}(${a}${u})`;return s===`string`?d:(0,t.or)((0,t._)`${a} instanceof Date`,d)}e.default={keyword:`type`,schemaType:`string`,error:o,code(n){(0,i.checkMetadata)(n);let{data:r,schema:a,parentSchema:o,it:c}=n,l;switch(a){case`boolean`:case`string`:l=(0,t._)`typeof ${r} == ${a}`;break;case`timestamp`:l=s(n);break;case`float32`:case`float64`:l=(0,t._)`typeof ${r} == "number"`;break;default:{let n=a;if(l=(0,t._)`typeof ${r} == "number" && isFinite(${r}) && !(${r} % 1)`,!c.opts.int32range&&(n===`int32`||n===`uint32`))n===`uint32`&&(l=(0,t._)`${l} && ${r} >= 0`);else{let[i,a]=e.intRange[n];l=(0,t._)`${l} && ${r} >= ${i} && ${r} <= ${a}`}}}n.pass(o.nullable?(0,t.or)((0,t._)`${r} === null`,l):l)}}})),Uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkNullableObject=e.checkNullable=void 0;let t=X();function n({gen:e,data:n,parentSchema:r},i=t.nil){let a=e.name(`valid`);return r.nullable?(e.let(a,(0,t._)`${n} === null`),i=(0,t.not)(a)):e.let(a,!1),[a,i]}e.checkNullable=n;function r(e,r){let[i,a]=n(e,r);return[i,(0,t._)`${a} && typeof ${e.data} == "object" && !Array.isArray(${e.data})`]}e.checkNullableObject=r})),Wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Rf(),r=Uf();e.default={keyword:`enum`,schemaType:`array`,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){(0,n.checkMetadata)(e);let{gen:i,data:a,schema:o,schemaValue:s,parentSchema:c,it:l}=e;if(o.length===0)throw Error(`enum must have non-empty array`);if(o.length!==new Set(o).size)throw Error(`enum items must be unique`);let u,d=(0,t._)`typeof ${a} == "string"`;if(o.length>=l.opts.loopEnum){let t;[u,t]=(0,r.checkNullable)(e,d),i.if(t,f)}else{if(!Array.isArray(o))throw Error(`ajv implementation error`);u=(0,t.and)(d,(0,t.or)(...o.map(e=>(0,t._)`${a} === ${e}`))),c.nullable&&(u=(0,t.or)((0,t._)`${a} === null`,u))}e.pass(u);function f(){i.forOf(`v`,s,e=>i.if((0,t._)`${u} = ${a} === ${e}`,()=>i.break()))}}}})),Gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Pd(),r=X(),i=Rf(),a=Uf();e.default={keyword:`elements`,schemaType:`object`,error:(0,Vf().typeError)(`array`),code(e){(0,i.checkMetadata)(e);let{gen:o,data:s,schema:c,it:l}=e;if((0,t.alwaysValidSchema)(l,c))return;let[u]=(0,a.checkNullable)(e);o.if((0,r.not)(u),()=>o.if((0,r._)`Array.isArray(${s})`,()=>o.assign(u,(0,n.validateArray)(e)),()=>e.error())),e.ok(u)}}})),Kf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateProperties=e.error=void 0;let t=Pd(),n=Z(),r=X(),i=Rf(),a=Uf(),o=Vf();var s;(function(e){e.Additional=`additional`,e.Missing=`missing`})(s||={}),e.error={message:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?`must NOT have additional properties`:`must have property '${t.missingProperty}'`:(0,o.typeErrorMessage)(e,`object`)},params:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?(0,r._)`{error: ${t.propError}, additionalProperty: ${t.additionalProperty}}`:(0,r._)`{error: ${t.propError}, missingProperty: ${t.missingProperty}}`:(0,o.typeErrorParams)(e,`object`)}};let c={keyword:`properties`,schemaType:`object`,error:e.error,code:l};function l(e){(0,i.checkMetadata)(e);let{gen:o,data:c,parentSchema:l,it:u}=e,{additionalProperties:d,nullable:f}=l;if(u.jtdDiscriminator&&f)throw Error(`JTD: nullable inside discriminator mapping`);if(y())throw Error(`JTD: properties and optionalProperties have common members`);let[p,m]=b(`properties`),[h,g]=b(`optionalProperties`);if(m.length===0&&g.length===0&&d)return;let[_,v]=u.jtdDiscriminator===void 0?(0,a.checkNullableObject)(e,c):[o.let(`valid`,!1),!0];o.if(v,()=>o.assign(_,!0).block(()=>{x(m,`properties`,!0),x(g,`optionalProperties`),d||C()})),e.pass(_);function y(){let e=l.properties,t=l.optionalProperties;if(!(e&&t))return!1;for(let n in e)if(Object.prototype.hasOwnProperty.call(t,n))return!0;return!1}function b(e){let r=l[e],i=r?(0,t.allSchemaProperties)(r):[];if(u.jtdDiscriminator&&i.some(e=>e===u.jtdDiscriminator))throw Error(`JTD: discriminator tag used in ${e}`);return[i,i.filter(e=>!(0,n.alwaysValidSchema)(u,r[e]))]}function x(n,r,i){let a=o.var(`valid`);for(let i of n)o.if((0,t.propertyInData)(o,c,i,u.opts.ownProperties),()=>S(i,r,a),()=>l(i)),e.ok(a);function l(t){i?(o.assign(a,!1),e.error(!1,{propError:s.Missing,missingProperty:t},{schemaPath:t})):o.assign(a,!0)}}function S(t,n,r){e.subschema({keyword:n,schemaProp:t,dataProp:t},r)}function C(){o.forIn(`key`,c,t=>{let n=w(t,p,`properties`,u.jtdDiscriminator),i=w(t,h,`optionalProperties`),a=n===!0?i:i===!0?n:(0,r.and)(n,i);o.if(a,()=>{u.opts.removeAdditional?o.code((0,r._)`delete ${c}[${t}]`):(e.error(!1,{propError:s.Additional,additionalProperty:t},{instancePath:t,parentSchema:!0}),u.opts.allErrors||o.break())})})}function w(e,i,a,s){let c;if(i.length>8){let i=(0,n.schemaRefOrVal)(u,l[a],a);c=(0,r.not)((0,t.isOwnProperty)(o,i,e)),s!==void 0&&(c=(0,r.and)(c,(0,r._)`${e} !== ${s}`))}else if(i.length||s!==void 0){let t=s===void 0?i:[s].concat(i);c=(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`))}else c=!0;return c}}e.validateProperties=l,e.default=c})),qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kf();e.default={keyword:`optionalProperties`,schemaType:`object`,error:t.error,code(e){e.parentSchema.properties||(0,t.validateProperties)(e)}}})),Jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Rf(),r=Uf(),i=Vf(),a=Pf();e.default={keyword:`discriminator`,schemaType:`string`,implements:[`mapping`],error:{message:e=>{let{schema:t,params:n}=e;return n.discrError?n.discrError===a.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in mapping`:(0,i.typeErrorMessage)(e,`object`)},params:e=>{let{schema:n,params:r}=e;return r.discrError?(0,t._)`{error: ${r.discrError}, tag: ${n}, tagValue: ${r.tag}}`:(0,i.typeErrorParams)(e,`object`)}},code(e){(0,n.checkMetadata)(e);let{gen:i,data:o,schema:s,parentSchema:c}=e,[l,u]=(0,r.checkNullableObject)(e,o);i.if(u),d(),i.elseIf((0,t.not)(l)),e.error(),i.endIf(),e.ok(l);function d(){let n=i.const(`tag`,(0,t._)`${o}${(0,t.getProperty)(s)}`);i.if((0,t._)`${n} === undefined`),e.error(!1,{discrError:a.DiscrError.Tag,tag:n}),i.elseIf((0,t._)`typeof ${n} == "string"`),f(n),i.else(),e.error(!1,{discrError:a.DiscrError.Tag,tag:n},{instancePath:s}),i.endIf()}function f(n){i.if(!1);for(let e in c.mapping)i.elseIf((0,t._)`${n} === ${e}`),i.assign(l,p(e));i.else(),e.error(!1,{discrError:a.DiscrError.Mapping,tag:n},{instancePath:s,schemaPath:`mapping`,parentSchema:!0}),i.endIf()}function p(t){let n=i.name(`valid`);return e.subschema({keyword:`mapping`,schemaProp:t,jtdDiscriminator:s},n),n}}}})),Yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=X(),r=Rf(),i=Uf();e.default={keyword:`values`,schemaType:`object`,error:(0,Vf().typeError)(`object`),code(e){(0,r.checkMetadata)(e);let{gen:a,data:o,schema:s,it:c}=e,[l,u]=(0,i.checkNullableObject)(e,o);(0,t.alwaysValidSchema)(c,s)?a.if((0,n.not)((0,n.or)(u,l)),()=>e.error()):(a.if(u),a.assign(l,d()),a.elseIf((0,n.not)(l)),e.error(),a.endIf()),e.ok(l);function d(){let r=a.name(`valid`);if(c.allErrors){let e=a.let(`valid`,!0);return i(()=>a.assign(e,!1)),e}return a.var(r,!0),i(()=>a.break()),r;function i(i){a.forIn(`key`,o,o=>{e.subschema({keyword:`values`,dataProp:o,dataPropType:t.Type.Str},r),a.if((0,n.not)(r),i)})}}}}})),Xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`union`,schemaType:`array`,trackErrors:!0,code:Pd().validateUnion,error:{message:`must match a schema in union`}}})),Zf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=zf(),n=Hf(),r=Wf(),i=Gf(),a=Kf(),o=qf(),s=Jf(),c=Yf(),l=Xf(),u=Rf();e.default=[`definitions`,t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,l.default,u.default,{keyword:`additionalProperties`,schemaType:`boolean`},{keyword:`nullable`,schemaType:`boolean`}]})),Qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=e=>{let t={nullable:{type:`boolean`},metadata:{optionalProperties:{union:{elements:{ref:`schema`}}},additionalProperties:!0}};return e&&(t.definitions={values:{ref:`schema`}}),t},n=e=>({optionalProperties:t(e)}),r=e=>({properties:{ref:{type:`string`}},optionalProperties:t(e)}),i=e=>({properties:{type:{enum:[`boolean`,`timestamp`,`string`,`float32`,`float64`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`]}},optionalProperties:t(e)}),a=e=>({properties:{enum:{elements:{type:`string`}}},optionalProperties:t(e)}),o=e=>({properties:{elements:{ref:`schema`}},optionalProperties:t(e)}),s=e=>({properties:{properties:{values:{ref:`schema`}}},optionalProperties:{optionalProperties:{values:{ref:`schema`}},additionalProperties:{type:`boolean`},...t(e)}}),c=e=>({properties:{optionalProperties:{values:{ref:`schema`}}},optionalProperties:{additionalProperties:{type:`boolean`},...t(e)}}),l=e=>({properties:{discriminator:{type:`string`},mapping:{values:{metadata:{union:[s(!1),c(!1)]}}}},optionalProperties:t(e)}),u=e=>({properties:{values:{ref:`schema`}},optionalProperties:t(e)}),d=e=>({metadata:{union:[n,r,i,a,o,s,c,l,u].map(t=>t(e))}});e.default={definitions:{schema:d(!1)},...d(!0)}})),$f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.jtdForms=void 0,e.jtdForms=[`elements`,`values`,`discriminator`,`properties`,`optionalProperties`,`enum`,`type`,`ref`]})),ep=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n={"\b":`\\b`," ":`\\t`,"\n":`\\n`,"\f":`\\f`,"\r":`\\r`,'"':`\\"`,"\\":`\\\\`};function r(e){return t.lastIndex=0,`"`+(t.test(e)?e.replace(t,e=>{let t=n[e];return typeof t==`string`?t:`\\u`+(`0000`+e.charCodeAt(0).toString(16)).slice(-4)}):e)+`"`}e.default=r,r.code=`require("ajv/dist/runtime/quote").default`})),tp=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$f(),n=Ud(),r=X(),i=Hd(),a=Dd(),o=Pd(),s=zf(),c=Z(),l=ep(),u={elements:m,values:h,discriminator:_,properties:v,optionalProperties:v,enum:x,type:b,ref:C};function d(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`serialize`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data},p;try{this._compilations.add(e),e.serializeName=u,l.func(u,a.default.data,!1,()=>{l.let(a.default.json,(0,r.str)``),f(d),l.return(a.default.json)}),l.optimize(this.opts.code.optimize);let t=l.toString();p=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,p)(this.scope.get());this.scope.value(u,{ref:n}),e.serialize=n}catch(t){throw p&&this.logger.error(`Error compiling serializer, function code:`,p),delete e.serialize,delete e.serializeName,t}finally{this._compilations.delete(e)}return e}e.default=d;function f(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}p(e,n?u[n]:T)}function p(e,t){let{gen:n,schema:i,data:o}=e;if(!i.nullable)return t(e);n.if((0,r._)`${o} === undefined || ${o} === null`,()=>n.add(a.default.json,(0,r._)`"null"`),()=>t(e))}function m(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`[`);let o=t.let(`first`,!0);t.forOf(`el`,i,t=>{E(e,o),f({...e,schema:n.elements,data:t})}),t.add(a.default.json,(0,r.str)`]`)}function h(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`{`);let o=t.let(`first`,!0);t.forIn(`key`,i,t=>g(e,t,n.values,o)),t.add(a.default.json,(0,r.str)`}`)}function g(e,t,n,i){let{gen:o,data:s}=e;E(e,i),x({...e,data:t}),o.add(a.default.json,(0,r.str)`:`);let c=o.const(`value`,(0,r._)`${s}${(0,r.getProperty)(t)}`);f({...e,schema:n,data:c})}function _(e){let{gen:t,schema:n,data:i}=e,{discriminator:o}=n;t.add(a.default.json,(0,r.str)`{${JSON.stringify(o)}:`);let s=t.const(`tag`,(0,r._)`${i}${(0,r.getProperty)(o)}`);x({...e,data:s}),t.if(!1);for(let i in n.mapping){t.elseIf((0,r._)`${s} === ${i}`);let a=n.mapping[i];y({...e,schema:a},o)}t.endIf(),t.add(a.default.json,(0,r.str)`}`)}function v(e){let{gen:t}=e;t.add(a.default.json,(0,r.str)`{`),y(e),t.add(a.default.json,(0,r.str)`}`)}function y(e,t){let{gen:n,schema:i,data:s}=e,{properties:c,optionalProperties:l}=i,u=_(c),d=_(l),p=v(u.concat(d)),m=!t,h;for(let e of u)m?m=!1:n.add(a.default.json,(0,r.str)`,`),b(e,c[e],y(e));m&&(h=n.let(`first`,!0));for(let t of d){let i=y(t);n.if((0,r.and)((0,r._)`${i} !== undefined`,(0,o.isOwnProperty)(n,s,t)),()=>{E(e,h),b(t,l[t],i)})}i.additionalProperties&&n.forIn(`key`,s,t=>n.if(x(t,p),()=>g(e,t,{},h)));function _(e){return e?Object.keys(e):[]}function v(e){if(t&&e.push(t),new Set(e).size!==e.length)throw Error(`JTD: properties/optionalProperties/disciminator overlap`);return e}function y(e){return n.const(`value`,(0,r._)`${s}${(0,r.getProperty)(e)}`)}function b(t,i,o){n.add(a.default.json,(0,r.str)`${JSON.stringify(t)}:`),f({...e,schema:i,data:o})}function x(e,t){return t.length?(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`)):!0}}function b(e){let{gen:t,schema:n,data:i}=e;switch(n.type){case`boolean`:t.add(a.default.json,(0,r._)`${i} ? "true" : "false"`);break;case`string`:x(e);break;case`timestamp`:t.if((0,r._)`${i} instanceof Date`,()=>t.add(a.default.json,(0,r._)`'"' + ${i}.toISOString() + '"'`),()=>x(e));break;default:S(e)}}function x({gen:e,data:t}){e.add(a.default.json,(0,r._)`${(0,c.useFunc)(e,l.default)}(${t})`)}function S({gen:e,data:t,self:n}){let i=(0,r._)`${t} === Infinity || ${t} === -Infinity || ${t} !== ${t}`;n.opts.specialNumbers===void 0||n.opts.specialNumbers===`fast`?e.add(a.default.json,(0,r._)`"" + ${t}`):e.if(i,()=>e.add(a.default.json,(0,r._)`null`),()=>e.add(a.default.json,(0,r._)`"" + ${t}`))}function C(e){let{gen:t,self:o,data:c,definitions:l,schema:u,schemaEnv:p}=e,{ref:m}=u,h=l[m];if(!h)throw new i.default(o.opts.uriResolver,``,m,`No definition ${m}`);if(!(0,s.hasRef)(h))return f({...e,schema:h});let{root:g}=p,_=d.call(o,new n.SchemaEnv({schema:h,root:g}),l);t.add(a.default.json,(0,r._)`${w(t,_)}(${c})`)}function w(e,t){return t.serialize?e.scopeValue(`serialize`,{ref:t.serialize}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.serialize`}function T({gen:e,data:t}){e.add(a.default.json,(0,r._)`JSON.stringify(${t})`)}function E({gen:e},t){t?e.if(t,()=>e.assign(t,!1),()=>e.add(a.default.json,(0,r.str)`,`)):e.add(a.default.json,(0,r.str)`,`)}})),np=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseJsonString=e.parseJsonNumber=e.parseJson=void 0;let t=/position\s(\d+)(?: \(line \d+ column \d+\))?$/;function n(e,r){let i;n.message=void 0;let a;r&&(e=e.slice(r));try{return n.position=r+e.length,JSON.parse(e)}catch(o){if(a=t.exec(o.message),!a){n.message=`unexpected end`;return}i=+a[1];let s=e[i];e=e.slice(0,i),n.position=r+i;try{return JSON.parse(e)}catch{n.message=`unexpected token ${s}`;return}}}e.parseJson=n,n.message=void 0,n.position=0,n.code=`require("ajv/dist/runtime/parseJson").parseJson`;function r(e,t,n){let i=``,a;if(r.message=void 0,e[t]===`-`&&(i+=`-`,t++),e[t]===`0`)i+=`0`,t++;else if(!o(n)){s();return}if(n)return r.position=t,+i;if(e[t]===`.`&&(i+=`.`,t++,!o())){s();return}if(a=e[t],(a===`e`||a===`E`)&&(i+=`e`,t++,a=e[t],(a===`+`||a===`-`)&&(i+=a,t++),!o())){s();return}return r.position=t,+i;function o(n){let r=!1;for(;a=e[t],a>=`0`&&a<=`9`&&(n===void 0||n-- >0);)r=!0,i+=a,t++;return r}function s(){r.position=t,r.message=t<e.length?`unexpected token ${e[t]}`:`unexpected end`}}e.parseJsonNumber=r,r.message=void 0,r.position=0,r.code=`require("ajv/dist/runtime/parseJson").parseJsonNumber`;let i={b:`\b`,f:`\f`,n:`
136
- `,r:`\r`,t:` `,'"':`"`,"/":`/`,"\\":`\\`};function a(e,t){let n=``,r;for(a.message=void 0;r=e[t++],r!==`"`;)if(r===`\\`)if(r=e[t],r in i)n+=i[r],t++;else if(r===`u`){t++;let i=4,a=0;for(;i--;){if(a<<=4,r=e[t],r===void 0){o(`unexpected end`);return}if(r=r.toLowerCase(),r>=`a`&&r<=`f`)a+=r.charCodeAt(0)-97+10;else if(r>=`0`&&r<=`9`)a+=r.charCodeAt(0)-48;else{o(`unexpected token ${r}`);return}t++}n+=String.fromCharCode(a)}else{o(`unexpected token ${r}`);return}else if(r===void 0){o(`unexpected end`);return}else if(r.charCodeAt(0)>=32)n+=r;else{o(`unexpected token ${r}`);return}return a.position=t,n;function o(e){a.position=t,a.message=e}}e.parseJsonString=a,a.message=void 0,a.position=0,a.code=`require("ajv/dist/runtime/parseJson").parseJsonString`})),rp=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$f(),n=Ud(),r=X(),i=Hd(),a=Dd(),o=Pd(),s=zf(),c=Hf(),l=np(),u=Z(),d=Bf(),f={elements:y,values:b,discriminator:w,properties:T,optionalProperties:T,enum:j,type:k,ref:N};function p(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`parse`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data,parseName:u,char:l.name(`c`)},f;try{this._compilations.add(e),e.parseName=u,h(d),l.optimize(this.opts.code.optimize);let t=l.toString();f=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,f)(this.scope.get());this.scope.value(u,{ref:n}),e.parse=n}catch(t){throw f&&this.logger.error(`Error compiling parser, function code:`,f),delete e.parse,delete e.parseName,t}finally{this._compilations.delete(e)}return e}e.default=p;let m=(0,r._)`undefined`;function h(e){let{gen:t,parseName:n,char:i}=e;t.func(n,(0,r._)`${a.default.json}, ${a.default.jsonPos}, ${a.default.jsonPart}`,!1,()=>{t.let(a.default.data),t.let(i),t.assign((0,r._)`${n}.message`,m),t.assign((0,r._)`${n}.position`,m),t.assign(a.default.jsonPos,(0,r._)`${a.default.jsonPos} || 0`),t.const(a.default.jsonLen,(0,r._)`${a.default.json}.length`),g(e),I(e),t.if(a.default.jsonPart,()=>{t.assign((0,r._)`${n}.position`,a.default.jsonPos),t.return(a.default.data)}),t.if((0,r._)`${a.default.jsonPos} === ${a.default.jsonLen}`,()=>t.return(a.default.data)),oe(e)})}function g(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}n?v(e,f[n]):P(e)}let _=ee(!0,ee(!1,oe));function v(e,t){let{gen:n,schema:r,data:i}=e;if(!r.nullable)return t(e);ie(e,`null`,t,()=>n.assign(i,null))}function y(e){let{gen:t,schema:n,data:i}=e;F(e,`[`);let a=t.let(`i`,0);t.assign(i,(0,r._)`[]`),x(e,`]`,()=>{let o=t.let(`el`);g({...e,schema:n.elements,data:o}),t.assign((0,r._)`${i}[${a}++]`,o)})}function b(e){let{gen:t,schema:n,data:i}=e;F(e,`{`),t.assign(i,(0,r._)`{}`),x(e,`}`,()=>C(e,n.values))}function x(e,t,n){S(e,t,n),F(e,t)}function S(e,t,n){let{gen:i}=e;i.for((0,r._)`;${a.default.jsonPos}<${a.default.jsonLen} && ${ae(1)}!==${t};`,()=>{n(),ie(e,`,`,()=>i.break(),o)});function o(){ie(e,t,()=>{},oe)}}function C(e,t){let{gen:n}=e,r=n.let(`key`);A({...e,data:r}),F(e,`:`),O(e,r,t)}function w(e){let{gen:t,data:n,schema:i}=e,{discriminator:o,mapping:s}=i;F(e,`{`),t.assign(n,(0,r._)`{}`);let c=t.const(`pos`,a.default.jsonPos),l=t.let(`value`),u=t.let(`tag`);S(e,`}`,()=>{let i=t.let(`key`);A({...e,data:i}),F(e,`:`),t.if((0,r._)`${i} === ${o}`,()=>{A({...e,data:u}),t.assign((0,r._)`${n}[${i}]`,u),t.break()},()=>P({...e,data:l}))}),t.assign(a.default.jsonPos,c),t.if((0,r._)`${u} === undefined`),L(e,(0,r.str)`discriminator tag not found`);for(let n in s)t.elseIf((0,r._)`${u} === ${n}`),E({...e,schema:s[n]},o);t.else(),L(e,(0,r.str)`discriminator value not in schema`),t.endIf()}function T(e){let{gen:t,data:n}=e;F(e,`{`),t.assign(n,(0,r._)`{}`),E(e)}function E(e,t){let{gen:n,schema:i,data:a}=e,{properties:s,optionalProperties:c,additionalProperties:l}=i;if(x(e,`}`,()=>{let i=n.let(`key`);if(A({...e,data:i}),F(e,`:`),n.if(!1),D(e,i,s),D(e,i,c),t){n.elseIf((0,r._)`${i} === ${t}`);let a=n.let(`tag`);A({...e,data:a})}n.else(),l?P({...e,data:(0,r._)`${a}[${i}]`}):L(e,(0,r.str)`property ${i} not allowed`),n.endIf()}),s){let t=(0,o.hasPropFunc)(n),i=(0,r.and)(...Object.keys(s).map(e=>(0,r._)`${t}.call(${a}, ${e})`));n.if((0,r.not)(i),()=>L(e,(0,r.str)`missing required properties`))}}function D(e,t,n={}){let{gen:i}=e;for(let a in n)i.elseIf((0,r._)`${t} === ${a}`),O(e,t,n[a])}function O(e,t,n){g({...e,schema:n,data:(0,r._)`${e.data}[${t}]`})}function k(e){let{gen:t,schema:n,data:i,self:a}=e;switch(n.type){case`boolean`:_(e);break;case`string`:A(e);break;case`timestamp`:{A(e);let n=(0,u.useFunc)(t,d.default),{allowDate:o,parseDate:s}=a.opts,c=o?(0,r._)`!${n}(${i}, true)`:(0,r._)`!${n}(${i})`,l=s?(0,r.or)(c,(0,r._)`(${i} = new Date(${i}), false)`,(0,r._)`isNaN(${i}.valueOf())`):c;t.if(l,()=>L(e,(0,r.str)`invalid timestamp`));break}case`float32`:case`float64`:M(e);break;default:{let o=n.type;if(!a.opts.int32range&&(o===`int32`||o===`uint32`))M(e,16),o===`uint32`&&t.if((0,r._)`${i} < 0`,()=>L(e,(0,r.str)`integer out of range`));else{let[n,a,s]=c.intRange[o];M(e,s),t.if((0,r._)`${i} < ${n} || ${i} > ${a}`,()=>L(e,(0,r.str)`integer out of range`))}}}}function A(e){F(e,`"`),ne(e,l.parseJsonString)}function j(e){let{gen:t,data:n,schema:i}=e,o=i.enum;F(e,`"`),t.if(!1);for(let e of o){let i=JSON.stringify(e).slice(1);t.elseIf((0,r._)`${ae(i.length)} === ${i}`),t.assign(n,(0,r.str)`${e}`),t.add(a.default.jsonPos,i.length)}t.else(),oe(e),t.endIf()}function M(e,t){let{gen:n}=e;I(e),n.if((0,r._)`"-0123456789".indexOf(${ae(1)}) < 0`,()=>oe(e),()=>ne(e,l.parseJsonNumber,t))}function ee(e,t){return n=>{let{gen:r,data:i}=n;ie(n,`${e}`,()=>t(n),()=>r.assign(i,e))}}function N(e){let{gen:t,self:r,definitions:a,schema:o,schemaEnv:c}=e,{ref:l}=o,u=a[l];if(!u)throw new i.default(r.opts.uriResolver,``,l,`No definition ${l}`);if(!(0,s.hasRef)(u))return g({...e,schema:u});let{root:d}=c;re(e,te(t,p.call(r,new n.SchemaEnv({schema:u,root:d}),a)),!0)}function te(e,t){return t.parse?e.scopeValue(`parse`,{ref:t.parse}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.parse`}function P(e){ne(e,l.parseJson)}function ne(e,t,n){re(e,(0,u.useFunc)(e.gen,t),n)}function re(e,t,n){let{gen:i,data:o}=e;i.assign(o,(0,r._)`${t}(${a.default.json}, ${a.default.jsonPos}${n?(0,r._)`, ${n}`:r.nil})`),i.assign(a.default.jsonPos,(0,r._)`${t}.position`),i.if((0,r._)`${o} === undefined`,()=>L(e,(0,r._)`${t}.message`))}function F(e,t){ie(e,t,oe)}function ie(e,t,n,i){let{gen:o}=e,s=t.length;I(e),o.if((0,r._)`${ae(s)} === ${t}`,()=>{o.add(a.default.jsonPos,s),i?.(e)},()=>n(e))}function I({gen:e,char:t}){e.code((0,r._)`while((${t}=${a.default.json}[${a.default.jsonPos}],${t}===" "||${t}==="\\n"||${t}==="\\r"||${t}==="\\t"))${a.default.jsonPos}++;`)}function ae(e){return e===1?(0,r._)`${a.default.json}[${a.default.jsonPos}]`:(0,r._)`${a.default.json}.slice(${a.default.jsonPos}, ${a.default.jsonPos}+${e})`}function oe(e){L(e,(0,r._)`"unexpected token " + ${a.default.json}[${a.default.jsonPos}]`)}function L({gen:e,parseName:t},n){e.assign((0,r._)`${t}.message`,n),e.assign((0,r._)`${t}.position`,a.default.jsonPos),e.return(m)}})),ip=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Yd(),r=Zf(),i=Qf(),a=tp(),o=rp(),s=`JTD-meta-schema`;var c=class extends n.default{constructor(e={}){super({...e,jtd:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(r.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema(),this.opts.meta&&this.addMetaSchema(i.default,s,!1)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}compileSerializer(e){let t=this._addSchema(e);return t.serialize||this._compileSerializer(t)}compileParser(e){let t=this._addSchema(e);return t.parse||this._compileParser(t)}_compileSerializer(e){if(a.default.call(this,e,e.schema.definitions||{}),!e.serialize)throw Error(`ajv implementation error`);return e.serialize}_compileParser(e){if(o.default.call(this,e,e.schema.definitions||{}),!e.parse)throw Error(`ajv implementation error`);return e.parse}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Bd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Vd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Hd();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),ap=o(((e,t)=>{let n=qd();t.exports=Object.freeze({coerceTypes:`array`,useDefaults:!0,removeAdditional:!0,uriResolver:n,addUsedSchema:!1,allErrors:!1})})),op=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),sp=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Lf(),n=X(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),cp=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=op(),r=sp(),i=X(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=s})),lp=o(((e,t)=>{let n=Lf().default,r=ip(),i=ap();t.exports=class{constructor(e,t){t.mode===`JTD`?this.ajv=new r(Object.assign({},i,t.customOptions)):this.ajv=new n(Object.assign({},i,t.customOptions));let a=!0;if(t.plugins&&t.plugins.length>0)for(let e of t.plugins)Array.isArray(e)?(a&&=e[0].name!==`formatsPlugin`,e[0](this.ajv,e[1])):(a&&=e.name!==`formatsPlugin`,e(this.ajv));a&&cp()(this.ajv),t.onCreate?.(this.ajv);let o=Object.values(e);for(let e of o)this.ajv.addSchema(e)}buildValidatorFunction({schema:e}){if(e.$id){let t=this.ajv.getSchema(e.$id);if(t)return t}return this.ajv.compile(e)}}})),up=o(((e,t)=>{let n=ip(),r=ap();t.exports=class{constructor(e,t){this.ajv=new n(Object.assign({},r,t))}buildSerializerFunction({schema:e}){return this.ajv.compileSerializer(e)}}})),dp=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Ed(),r=Td();function i(e,t){if(!e.opts.code.source)throw Error(`moduleCode: ajv instance must have code.source option`);let{_n:i}=e.scope.opts;return typeof t==`function`?o(t.source):t===void 0?s(e.schemas,t=>t.meta?void 0:e.compile(t.schema)):s(t,a);function a(t){let n=e.getSchema(t);if(!n)throw Error(`moduleCode: no schema with id ${t}`);return n}function o(t){let n={},r=t?.validateName,a=c(n,t);return e.opts.code.esm?`"use strict";${i}export const validate = ${r};${i}export default ${r};${i}${a}`:`"use strict";${i}module.exports = ${r};${i}module.exports.default = ${r};${i}${a}`}function s(t,n){let a={},o=(0,r._)`"use strict";`;for(let s in t){let l=n(t[s]);if(l){let t=c(a,l.source),n=e.opts.code.esm?(0,r._)`export const ${(0,r.getEsmExportName)(s)}`:(0,r._)`exports${(0,r.getProperty)(s)}`;o=(0,r._)`${o}${i}${n} = ${l.source?.validateName};${i}${t}`}}return`${o}`}function c(t,a){if(!a)throw Error(`moduleCode: function does not have "source" property`);if(u(a.validateName)===n.UsedValueState.Completed)return r.nil;d(a.validateName,n.UsedValueState.Started);let o=e.scope.scopeCode(a.scopeValues,t,l),s=new r._Code(`${o}${i}${a.validateCode}`);return a.evaluated?(0,r._)`${s}${a.validateName}.evaluated = ${a.evaluated};${i}`:s;function l(a){let o=a.value?.ref;if(a.prefix===`validate`&&typeof o==`function`)return c(t,o.source);if((a.prefix===`root`||a.prefix===`wrapper`)&&typeof o==`object`){let{validate:s,validateName:l}=o;if(!l)throw Error(`ajv internal error`);let d=e.opts.code.es5?n.varKinds.var:n.varKinds.const,f=(0,r._)`${d} ${a} = {validate: ${l}};`;if(u(l)===n.UsedValueState.Started)return f;let p=c(t,s?.source);return(0,r._)`${f}${i}${p}`}}function u(e){return t[e.prefix]?.get(e)}function d(e,n){let{prefix:r}=e;(t[r]=t[r]||new Map).set(e,n)}}}t.exports=e=i,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=i})),fp=o(((e,t)=>{let n=pp(),r=dp().default;function i(e={readMode:!0}){if(e.readMode===!0&&!e.restoreFunction)throw Error(`You must provide a restoreFunction options when readMode ON`);if(e.readMode!==!0&&!e.storeFunction)throw Error(`You must provide a storeFunction options when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=n();return function(i,a={}){(!a.customOptions||!a.customOptions.code)&&(a.customOptions=Object.assign({},a.customOptions,{code:{source:!0}}));let o=t(i,a);return function(t){let i=o(t),a=r(o[n.AjvReference].ajv,i);return e.storeFunction(t,a),i}}}t.exports=i})),pp=o(((e,t)=>{let n=Symbol.for(`fastify.ajv-compiler.reference`),r=lp(),i=up();function a(e){let t=new Map,a=new Map;return e&&e.jtdSerializer===!0?function(e,t){let n=o({},t);if(a.has(n))return a.get(n);let r=new i(e,t),s=r.buildSerializerFunction.bind(r);return a.set(n,s),s}:function(e,i){let a=o(e,i.customOptions);if(t.has(a))return t.get(a);let s=new r(e,i),c=s.buildValidatorFunction.bind(s);return t.set(a,c),i.customOptions.code!==void 0&&(c[n]=s),c}}function o(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}t.exports=a,t.exports.default=a,t.exports.AjvCompiler=a,t.exports.AjvReference=n,t.exports.StandaloneValidator=fp()})),mp=o((e=>{var t=Object.prototype.hasOwnProperty;function n(e,t,n){for(n of e.keys())if(r(n,t))return n}function r(e,i){var a,o,s;if(e===i)return!0;if(e&&i&&(a=e.constructor)===i.constructor){if(a===Date)return e.getTime()===i.getTime();if(a===RegExp)return e.toString()===i.toString();if(a===Array){if((o=e.length)===i.length)for(;o--&&r(e[o],i[o]););return o===-1}if(a===Set){if(e.size!==i.size)return!1;for(o of e)if(s=o,s&&typeof s==`object`&&(s=n(i,s),!s)||!i.has(s))return!1;return!0}if(a===Map){if(e.size!==i.size)return!1;for(o of e)if(s=o[0],s&&typeof s==`object`&&(s=n(i,s),!s)||!r(o[1],i.get(s)))return!1;return!0}if(a===ArrayBuffer)e=new Uint8Array(e),i=new Uint8Array(i);else if(a===DataView){if((o=e.byteLength)===i.byteLength)for(;o--&&e.getInt8(o)===i.getInt8(o););return o===-1}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===i.byteLength)for(;o--&&e[o]===i[o];);return o===-1}if(!a||typeof e==`object`){for(a in o=0,e)if(t.call(e,a)&&++o&&!t.call(i,a)||!(a in i)||!r(e[a],i[a]))return!1;return Object.keys(i).length===o}}return e!==e&&i!==i}e.dequal=r})),hp=o(((e,t)=>{let{dequal:n}=mp(),r=Symbol.for(`json-schema-ref`);var i=class{#e;#t;#n;#r;#i;constructor(e={}){this.#e={},this.#t={},this.#n=e.insertRefSymbol??!1,this.#r=e.allowEqualDuplicates??!0,this.#i=e.cloneSchemaWithoutRefs??!1}addSchema(e,t,n=!0){n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#c(e,t));let r=e.$id;r!==void 0&&typeof r==`string`&&(r.charAt(0)===`#`?this.#l(e,t,r):(this.#c(e,r),t=r));let i=e.$ref;if(i!==void 0&&typeof i==`string`){let{refSchemaId:e,refJsonPointer:n}=this.#a(i,t);this.#e[t].refs.push({schemaId:e,jsonPointer:n})}for(let n in e)typeof e[n]==`object`&&e[n]!==null&&this.addSchema(e[n],t,!1)}getSchema(e,t=`#`){let n=this.#e[e];if(n===void 0)throw Error(`Cannot resolve ref "${e}${t}". Schema with id "${e}" is not found.`);return n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}hasSchema(e){return this.#e[e]!==void 0}getSchemaRefs(e){let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);return t.refs}getSchemaDependencies(e,t={}){let n=this.#e[e];for(let r of n.refs){let n=r.schemaId;n===e||t[n]!==void 0||(t[n]=this.getSchema(n),this.getSchemaDependencies(n,t))}return t}derefSchema(e){if(this.#t[e]!==void 0)return;let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);!this.#i&&t.refs.length===0&&(this.#t[e]={schema:t.schema,anchors:t.anchors});let n=[];this.#o(t.schema,e,!0,n);let r=this.getSchemaDependencies(e);for(let e in r){let t=r[e];this.#o(t,e,!0,n)}for(let e of n){let{refSchemaId:t,refJsonPointer:n}=this.#a(e.ref,e.sourceSchemaId),r=this.getDerefSchema(t,n);if(r===null)throw Error(`Cannot resolve ref "${e.ref}". Ref "${n}" is not found in schema "${t}".`);e.targetSchema=r,e.targetSchemaId=t}for(let e of n)this.#s(e,n)}getDerefSchema(e,t=`#`){let n=this.#t[e];return n===void 0&&(this.derefSchema(e),n=this.#t[e]),n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}#a(e,t){let n=e.indexOf(`#`);return n===-1?{refSchemaId:e,refJsonPointer:`#`}:n===0?{refSchemaId:t,refJsonPointer:e}:{refSchemaId:e.slice(0,n),refJsonPointer:e.slice(n)}}#o(e,t,n,r=[]){let i=Array.isArray(e)?[...e]:{...e};n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#u(i,t));let a=i.$id;a!==void 0&&typeof a==`string`&&(a.charAt(0)===`#`?this.#d(i,t,a):(this.#u(i,a),t=a)),i.$ref!==void 0&&r.push({ref:i.$ref,sourceSchemaId:t,sourceSchema:i});for(let e in i){let n=i[e];typeof n==`object`&&n&&(i[e]=this.#o(n,t,!1,r))}return i}#s(e,t){let{sourceSchema:i,targetSchema:a}=e;if(i.$ref){if(this.#n&&(i[r]=i.$ref),delete i.$ref,a.$ref){let e=t.find(e=>e.sourceSchema===a);this.#s(e,t)}for(let t in a)if(t!==`$id`){if(i[t]!==void 0){if(n(i[t],a[t]))continue;throw Error(`Cannot resolve ref "${e.ref}". Property "${t}" already exists in schema "${e.sourceSchemaId}".`)}i[t]=a[t]}e.isResolved=!0}}#c(e,t){let r=this.#e[t];if(r!==void 0){if(this.#r&&n(e,r.schema))return;throw Error(`There is already another schema with id "${t}".`)}this.#e[t]={schema:e,anchors:{},refs:[]}}#l(e,t,n){let{anchors:r}=this.#e[t];if(r[n]!==void 0)throw Error(`There is already another anchor "${n}" in schema "${t}".`);r[n]=e}#u(e,t){this.#t[t]===void 0&&(this.#t[t]={schema:e,anchors:{}})}#d(e,t,n){let{anchors:r}=this.#t[t];r[n]=e}};function a(e,t){let n=t.split(`/`),r=e;for(let e of n)if(!(e===``||e===`#`)){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}t.exports={RefResolver:i}})),gp=o(((e,t)=>{let n=Lf(),r=qd(),i=cp(),a=ud()({proto:!0});t.exports=class e{constructor(e){this.ajv=new n({...e,strictSchema:!1,validateSchema:!1,allowUnionTypes:!0,uriResolver:r}),i(this.ajv),this.ajv.addKeyword({keyword:`fjs_type`,type:`object`,errors:!1,validate:(e,t)=>t&&typeof t.toJSON==`function`}),this._ajvSchemas={},this._ajvOptions=e||{}}addSchema(e,t){let n=e.$id||t;if(e.$id!==void 0&&e.$id[0]===`#`&&(n=t+e.$id),this.ajv.refs[n]===void 0&&this.ajv.schemas[n]===void 0){let t=a(e);this.convertSchemaToAjvFormat(t),this.ajv.addSchema(t,n),this._ajvSchemas[n]=e}}validate(e,t){return this.ajv.validate(e,t)}convertSchemaToAjvFormat(e){if(e!==null){e.type===`string`?(e.fjs_type=`string`,e.type=[`string`,`object`]):Array.isArray(e.type)&&e.type.includes(`string`)&&!e.type.includes(`object`)&&(e.fjs_type=`string`,e.type.push(`object`));for(let t in e)typeof e[t]==`object`&&this.convertSchemaToAjvFormat(e[t])}}getState(){return{ajvOptions:this._ajvOptions,ajvSchemas:this._ajvSchemas}}static restoreFromState(t){let n=new e(t.ajvOptions);for(let[e,r]of Object.entries(t.ajvSchemas))n.ajv.addSchema(r,e);return n}}})),_p=o(((e,t)=>{t.exports=class e{constructor(e,t,n=`#`){this.schema=e,this.schemaId=t,this.jsonPointer=n}getPropertyLocation(t){return new e(this.schema[t],this.schemaId,this.jsonPointer+`/`+t)}getSchemaRef(){return this.schemaId+this.jsonPointer}}})),vp=o(((e,t)=>{t.exports=d,t.exports.default=d;let n={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0},r={enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},i=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,a=op().fullFormats.uri,o=op().fullFormats.regex;function s(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){return typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e==`number`&&isFinite(e)&&(e<0||isNaN(e))?(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1):(s.errors=null,!0):(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1)}let c={validate:d};function l(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){let a=null,o=0;if(o===0)if(Array.isArray(e)){if(e.length<1)return l.errors=[{instancePath:t,schemaPath:`#/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let n=e.length;for(let r=0;r<n;r++){let n=o;if(c.validate(e[r],{instancePath:t+`/`+r,parentData:e,parentDataProperty:r,rootData:i})||(a=a===null?c.validate.errors:a.concat(c.validate.errors),o=a.length),n!==o)break}}}else return l.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;return l.errors=a,o===0}let u=cf().default;function d(e,{instancePath:t=``,parentData:c,parentDataProperty:f,rootData:p=e}={}){let m=null,h=0;if(!(e&&typeof e==`object`&&!Array.isArray(e))&&typeof e!=`boolean`)return d.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:n.type},message:`must be object,boolean`}],!1;if(h===0&&e&&typeof e==`object`&&!Array.isArray(e)){if(e.$id!==void 0){let n=e.$id,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$schema!==void 0){let n=e.$schema,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!a(n))return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/format`,keyword:`format`,params:{format:`uri`},message:`must match format "uri"`}],!1}else return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$ref!==void 0){let n=e.$ref,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$comment!==void 0){let n=h;if(typeof e.$comment!=`string`)return d.errors=[{instancePath:t+`/$comment`,schemaPath:`#/properties/%24comment/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.title!==void 0){let n=h;if(typeof e.title!=`string`)return d.errors=[{instancePath:t+`/title`,schemaPath:`#/properties/title/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.description!==void 0){let n=h;if(typeof e.description!=`string`)return d.errors=[{instancePath:t+`/description`,schemaPath:`#/properties/description/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.readOnly!==void 0){let n=h;if(typeof e.readOnly!=`boolean`)return d.errors=[{instancePath:t+`/readOnly`,schemaPath:`#/properties/readOnly/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.examples!==void 0){let n=h;if(h===n&&!Array.isArray(e.examples))return d.errors=[{instancePath:t+`/examples`,schemaPath:`#/properties/examples/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=n===h}else var g=!0;if(g){if(e.multipleOf!==void 0){let n=e.multipleOf,r=h;if(h===r)if(typeof n==`number`&&isFinite(n)){if(n<=0||isNaN(n))return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/exclusiveMinimum`,keyword:`exclusiveMinimum`,params:{comparison:`>`,limit:0},message:`must be > 0`}],!1}else return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maximum!==void 0){let n=e.maximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/maximum`,schemaPath:`#/properties/maximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMaximum!==void 0){let n=e.exclusiveMaximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMaximum`,schemaPath:`#/properties/exclusiveMaximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.minimum!==void 0){let n=e.minimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/minimum`,schemaPath:`#/properties/minimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMinimum!==void 0){let n=e.exclusiveMinimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMinimum`,schemaPath:`#/properties/exclusiveMinimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maxLength!==void 0){let n=e.maxLength,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minLength!==void 0){let n=h;s(e.minLength,{instancePath:t+`/minLength`,parentData:e,parentDataProperty:`minLength`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.pattern!==void 0){let n=e.pattern,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!o(n))return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`}],!1}else return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalItems!==void 0){let n=h;d(e.additionalItems,{instancePath:t+`/additionalItems`,parentData:e,parentDataProperty:`additionalItems`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.items!==void 0){let n=e.items,r=h,i=h,a=!1,o=h;d(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var _=o===h;if(a||=_,!a){let r=h;l(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var _=r===h;a||=_}if(a)h=i,m!==null&&(i?m.length=i:m=null);else{let e={instancePath:t+`/items`,schemaPath:`#/properties/items/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=r===h}else var g=!0;if(g){if(e.maxItems!==void 0){let n=e.maxItems,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minItems!==void 0){let n=h;s(e.minItems,{instancePath:t+`/minItems`,parentData:e,parentDataProperty:`minItems`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.uniqueItems!==void 0){let n=h;if(typeof e.uniqueItems!=`boolean`)return d.errors=[{instancePath:t+`/uniqueItems`,schemaPath:`#/properties/uniqueItems/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.contains!==void 0){let n=h;d(e.contains,{instancePath:t+`/contains`,parentData:e,parentDataProperty:`contains`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.maxProperties!==void 0){let n=e.maxProperties,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minProperties!==void 0){let n=h;s(e.minProperties,{instancePath:t+`/minProperties`,parentData:e,parentDataProperty:`minProperties`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.required!==void 0){let n=e.required,r=h;if(h===h)if(Array.isArray(n)){var v=!0;let e=n.length;for(let r=0;r<e;r++){let e=h;if(typeof n[r]!=`string`)return d.errors=[{instancePath:t+`/required/`+r,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var v=e===h;if(!v)break}if(v){let e=n.length,r;if(e>1){let i={};for(;e--;){let a=n[e];if(typeof a==`string`){if(typeof i[a]==`number`)return r=i[a],d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1;i[a]=e}}}}}else return d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalProperties!==void 0){let n=h;d(e.additionalProperties,{instancePath:t+`/additionalProperties`,parentData:e,parentDataProperty:`additionalProperties`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.definitions!==void 0){let n=e.definitions,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/definitions/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/definitions`,schemaPath:`#/properties/definitions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.properties!==void 0){let n=e.properties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/properties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/properties`,schemaPath:`#/properties/properties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.patternProperties!==void 0){let n=e.patternProperties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n)){for(let e in n){let n=h;if(h===n&&typeof e==`string`&&!o(e)){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`,propertyName:e};m===null?m=[n]:m.push(n),h++}var y=n===h;if(!y){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames`,keyword:`propertyNames`,params:{propertyName:e},message:`property name must be valid`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}}if(y)for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/patternProperties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}}else return d.errors=[{instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.dependencies!==void 0){let n=e.dependencies,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=h,a=h,o=!1,s=h;d(r,{instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var b=s===h;if(o||=b,!o){let n=h;if(h===h)if(Array.isArray(r)){var x=!0;let n=r.length;for(let i=0;i<n;i++){let n=h;if(typeof r[i]!=`string`){let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/`+i,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`};m===null?m=[n]:m.push(n),h++}var x=n===h;if(!x)break}if(x){let n=r.length,i;if(n>1){let a={};for(;n--;){let o=r[n];if(typeof o==`string`){if(typeof a[o]==`number`){i=a[o];let r={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:n,j:i},message:`must NOT have duplicate items (items ## `+i+` and `+n+` are identical)`};m===null?m=[r]:m.push(r),h++;break}a[o]=n}}}}}else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[n]:m.push(n),h++}var b=n===h;o||=b}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/dependencies/additionalProperties/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}if(i!==h)break}else return d.errors=[{instancePath:t+`/dependencies`,schemaPath:`#/properties/dependencies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.propertyNames!==void 0){let n=h;d(e.propertyNames,{instancePath:t+`/propertyNames`,parentData:e,parentDataProperty:`propertyNames`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.enum!==void 0){let n=e.enum,r=h;if(h===r)if(Array.isArray(n)){if(n.length<1)return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let e=n.length,r;if(e>1){outer0:for(;e--;)for(r=e;r--;)if(u(n[e],n[r]))return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1}}}else return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.type!==void 0){let n=e.type,i=h,a=h,o=!1,s=h;if(!(n===`array`||n===`boolean`||n===`integer`||n===`null`||n===`number`||n===`object`||n===`string`)){let e={instancePath:t+`/type`,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var S=s===h;if(o||=S,!o){let e=h;if(h===e)if(Array.isArray(n))if(n.length<1){let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`};m===null?m=[e]:m.push(e),h++}else{var C=!0;let e=n.length;for(let i=0;i<e;i++){let e=n[i],a=h;if(!(e===`array`||e===`boolean`||e===`integer`||e===`null`||e===`number`||e===`object`||e===`string`)){let e={instancePath:t+`/type/`+i,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var C=a===h;if(!C)break}if(C){let e=n.length,r;if(e>1){outer1:for(;e--;)for(r=e;r--;)if(u(n[e],n[r])){let n={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`};m===null?m=[n]:m.push(n),h++;break outer1}}}}else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[e]:m.push(e),h++}var S=e===h;o||=S}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=i===h}else var g=!0;if(g){if(e.format!==void 0){let n=h;if(typeof e.format!=`string`)return d.errors=[{instancePath:t+`/format`,schemaPath:`#/properties/format/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentMediaType!==void 0){let n=h;if(typeof e.contentMediaType!=`string`)return d.errors=[{instancePath:t+`/contentMediaType`,schemaPath:`#/properties/contentMediaType/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentEncoding!==void 0){let n=h;if(typeof e.contentEncoding!=`string`)return d.errors=[{instancePath:t+`/contentEncoding`,schemaPath:`#/properties/contentEncoding/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.if!==void 0){let n=h;d(e.if,{instancePath:t+`/if`,parentData:e,parentDataProperty:`if`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.then!==void 0){let n=h;d(e.then,{instancePath:t+`/then`,parentData:e,parentDataProperty:`then`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.else!==void 0){let n=h;d(e.else,{instancePath:t+`/else`,parentData:e,parentDataProperty:`else`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.allOf!==void 0){let n=h;l(e.allOf,{instancePath:t+`/allOf`,parentData:e,parentDataProperty:`allOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.anyOf!==void 0){let n=h;l(e.anyOf,{instancePath:t+`/anyOf`,parentData:e,parentDataProperty:`anyOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.oneOf!==void 0){let n=h;l(e.oneOf,{instancePath:t+`/oneOf`,parentData:e,parentDataProperty:`oneOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g)if(e.not!==void 0){let n=h;d(e.not,{instancePath:t+`/not`,parentData:e,parentDataProperty:`not`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return d.errors=m,h===0}})),yp=o(((e,t)=>{t.exports={MergeError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Failed to merge "${e}" keyword schemas.`,this.schemas=t}},ResolverNotFoundError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Resolver for "${e}" keyword not found.`,this.schemas=t}},InvalidOnConflictOptionError:class extends Error{constructor(e){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Invalid "onConflict" option: "${e}".`}}}})),bp=o(((e,t)=>{let{dequal:n}=mp(),{MergeError:r}=yp();function i(e){let t=e[0];for(let n=1;n<e.length;n++)t=t.filter(t=>e[n].includes(t));return t}function a(e,t,n){let a=i(t);if(a.length===0)throw new r(e,t);n[e]=a}function o(e,t,n){for(let e=0;e<t.length;e++)Array.isArray(t[e])||(t[e]=[t[e]]);let a=i(t);if(a.length===0)throw new r(e,t);a.length===1?n[e]=a[0]:n[e]=a}function s(e,t,n){let r=[];for(let e of t)for(let t of e)r.includes(t)||r.push(t);n[e]=r}function c(e,t,n){n[e]=Math.min(...t)}function l(e,t,n){n[e]=Math.max(...t)}function u(e,t,n){let r=(e,t)=>t?r(t,e%t):e,i=(e,t)=>e*t/r(e,t),a=1;for(let e of t)for(;e*a%1!=0;)a*=10;let o=t[0]*a;for(let e of t)o=i(o,e*a);n[e]=o/a}function d(e,t,i){let a=t[0];for(let i=1;i<t.length;i++)if(!n(t[i],a))throw new r(e,t);i[e]=a}function f(){}function p(e,t,n){for(let r of t)if(r===!1){n[e]=!1;return}n[e]=!0}function m(e,t,n){for(let r of t)if(r===!0){n[e]=!0;return}n[e]=!1}t.exports={arraysIntersection:a,hybridArraysIntersection:o,arraysUnion:s,minNumber:c,maxNumber:l,commonMultiple:u,allEqual:d,booleanAnd:p,booleanOr:m,skip:f}})),xp=o(((e,t)=>{let{dequal:n}=mp(),r=bp(),i=yp(),a={$id:r.skip,type:r.hybridArraysIntersection,enum:r.arraysIntersection,minLength:r.maxNumber,maxLength:r.minNumber,minimum:r.maxNumber,maximum:r.minNumber,multipleOf:r.commonMultiple,exclusiveMinimum:r.maxNumber,exclusiveMaximum:r.minNumber,minItems:r.maxNumber,maxItems:r.minNumber,maxProperties:r.minNumber,minProperties:r.maxNumber,const:r.allEqual,default:r.allEqual,format:r.allEqual,required:r.arraysUnion,properties:p,patternProperties:m,additionalProperties:o,items:u,additionalItems:d,definitions:m,$defs:m,nullable:r.booleanAnd,oneOf:c,anyOf:c,allOf:r.arraysUnion,not:o,if:h,then:r.skip,else:r.skip,dependencies:g,dependentRequired:g,dependentSchemas:m,propertyNames:o,uniqueItems:r.booleanOr,contains:o};function o(e,t,n,r,i){n[e]=_(t,i)}function s(e){let t=[[]];for(let n of e){let e=[];for(let r of t)for(let t of n)e.push([...r,t]);t=e}return t}function c(e,t,n,r,a){if(t.length===1){n[e]=t[0];return}let o=s(t),c=[];for(let e of o)try{let t=_(e,a);t!==void 0&&c.push(t)}catch(e){if(e instanceof i.MergeError)continue;throw e}n[e]=c}function l(e,t){let{items:n,additionalItems:r}=e;return Array.isArray(n)?t<n.length?n[t]:r:n===void 0?r:n}function u(e,t,n,r,i){let a=0;for(let e of t)Array.isArray(e)&&(a=Math.max(a,e.length));if(a===0){n[e]=_(t,i);return}let o=[];for(let e=0;e<a;e++){let t=[];for(let n of r){let r=l(n,e);r!==void 0&&t.push(r)}o[e]=_(t,i)}n[e]=o}function d(e,t,n,r,i){let a=!1;for(let e of r)if(Array.isArray(e.items)){a=!0;break}if(!a){n[e]=_(t,i);return}let o=[];for(let e of r){let t=e.additionalItems;t===void 0&&!Array.isArray(e.items)&&(t=e.items),t!==void 0&&o.push(t)}n[e]=_(o,i)}function f(e,t){let{properties:n,patternProperties:r,additionalProperties:i}=e;if(n?.[t]!==void 0)return n[t];for(let e of Object.keys(r??{}))if(new RegExp(e).test(t))return r[e];return i}function p(e,t,n,r,i){let a={};for(let e of r){let t=e.properties??{};for(let n of Object.keys(t))if(a[n]===void 0){a[n]=[t[n]];for(let t of r){if(e===t)continue;let r=f(t,n);r!==void 0&&a[n].push(r)}}}let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function m(e,t,n,r,i){let a={};for(let e of t)for(let t of Object.keys(e))a[t]===void 0&&(a[t]=[]),a[t].push(e[t]);let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function h(e,t,n,r,i){for(let e=0;e<r.length;e++){let t={if:r[e].if,then:r[e].then,else:r[e].else};if(t.if!==void 0){if(n.if===void 0){n.if=t.if,t.then!==void 0&&(n.then=t.then),t.else!==void 0&&(n.else=t.else);continue}n.then!==void 0&&(n.then=_([n.then,t],i)),n.else!==void 0&&(n.else=_([n.else,t],i))}}}function g(e,t,n){let r={};for(let e of t)for(let t of Object.keys(e)){r[t]===void 0&&(r[t]=[]);let n=r[t];for(let r of e[t])n.includes(r)||n.push(r)}n[e]=r}function _(e,t){if(e.length===0)return{};if(e.length===1)return e[0];let n={},r={},i=!0;for(let t of e){if(t===!1)return!1;if(t!==!0){i=!1;for(let e of Object.keys(t))r[e]===void 0&&(r[e]=[]),r[e].push(t[e])}}if(i)return!0;for(let i of Object.keys(r)){let a=r[i];(t.resolvers[i]??t.defaultResolver)(i,a,n,e,t)}return n}function v(e,t,r,a,o){let s=o.onConflict??`throw`;if(t.length===1||s===`first`){r[e]=t[0];return}let c=!0;for(let e=1;e<t.length;e++)if(!n(t[e],t[0])){c=!1;break}if(c){r[e]=t[0];return}if(s===`throw`)throw new i.ResolverNotFoundError(e,t);if(s!==`skip`)throw new i.InvalidOnConflictOptionError(s)}function y(e,t={}){return t.defaultResolver===void 0&&(t.defaultResolver=v),t.resolvers={...a,...t.resolvers},_(e,t)}t.exports={mergeSchemas:y,keywordsResolvers:a,defaultResolver:v,...i}})),Sp=o(((e,t)=>{let{mergeSchemas:n}=xp();function r(e){return n(e,{onConflict:`skip`})}t.exports=r})),Cp=o(((e,t)=>{function n(e,t,n,r){let i=``;t.validatorSchemasIds.size>0?(i+=`const Validator = require('fast-json-stringify/lib/validator')
135
+ deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Fd(),n=X(),r=Od(),i=Z();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Sf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Vd(),n=Fd(),r=Z(),i=xf();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Cf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Fd(),n=X(),r=Z(),i=Z();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),Tf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Fd().validateUnion,error:{message:`must match a schema in anyOf`}}})),Ef=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),Df=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),Of=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),kf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Af=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=mf(),n=gf(),r=hf(),i=_f(),a=vf(),o=yf(),s=bf(),c=xf(),l=Sf(),u=Cf(),d=wf(),f=Tf(),p=Ef(),m=Df(),h=Of(),g=kf();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Mf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[jf().default]})),Nf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Pf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$d(),n=pf(),r=Af(),i=Mf(),a=Nf();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Ff=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),If=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Ff(),r=Wd(),i=Ud(),a=Z();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Lf=o(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Rf=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Xd(),r=Pf(),i=If(),a=Lf(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Vd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Hd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Ud();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),zf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkMetadata=void 0;let t=Z(),n={keyword:`metadata`,schemaType:`object`,code(e){r(e);let{gen:n,schema:i,it:a}=e;if((0,t.alwaysValidSchema)(a,i))return;let o=n.name(`valid`);e.subschema({keyword:`metadata`,jtdMetadata:!0},o),e.ok(o)}};function r({it:e,keyword:t},n){if(e.jtdMetadata!==n)throw Error(`JTD: "${t}" cannot be used in this schema location`)}e.checkMetadata=r,e.default=n})),Bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hasRef=void 0;let t=Wd(),n=X(),r=Ud(),i=Od(),a=Qd(),o=zf(),s={keyword:`ref`,schemaType:`string`,code(e){(0,o.checkMetadata)(e);let{gen:s,data:l,schema:u,parentSchema:d,it:f}=e,{schemaEnv:{root:p}}=f,m=s.name(`valid`);d.nullable?(s.var(m,(0,n._)`${l} === null`),s.if((0,n.not)(m),h)):(s.var(m,!1),h()),e.ok(m);function h(){let e=p.schema.definitions?.[u];if(!e)throw new r.default(f.opts.uriResolver,``,u,`No definition ${u}`);c(e)||!f.opts.inlineRefs?g(e):_(e)}function g(r){let o=t.compileSchema.call(f.self,new t.SchemaEnv({schema:r,root:p,schemaPath:`/definitions/${u}`})),c=(0,a.getValidate)(e,o),l=s.const(`_errs`,i.default.errors);(0,a.callRef)(e,c,o,o.$async),s.assign(m,(0,n._)`${l} === ${i.default.errors}`)}function _(t){let r=s.scopeValue(`schema`,f.opts.code.source===!0?{ref:t,code:(0,n.stringify)(t)}:{ref:t});e.subschema({schema:t,dataTypes:[],schemaPath:n.nil,topSchemaRef:r,errSchemaPath:`/definitions/${u}`},m)}}};function c(e){for(let t in e){let n;if(t===`ref`||typeof(n=e[t])==`object`&&c(n))return!0}return!1}e.hasRef=c,e.default=s})),Vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/t|\s/i,n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e,n){let r=e.split(t);return r.length===2&&o(r[0])&&s(r[1])||n&&r.length===1&&o(r[0])}e.default=a;function o(e){let t=n.exec(e);if(!t)return!1;let r=+t[1],a=+t[2],o=+t[3];return a>=1&&a<=12&&o>=1&&(o<=i[a]||a===2&&o===29&&(r%100==0?r%400==0:r%4==0))}function s(e){let t=r.exec(e);if(!t)return!1;let n=+t[1],i=+t[2],a=+t[3],o=+(t[4]||0),s=+(t[5]||0);return n<=23&&i<=59&&a<=59||n-o===23&&i-s===59&&a===60}a.code=`require("ajv/dist/runtime/timestamp").default`})),Hf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.typeErrorParams=e.typeErrorMessage=e.typeError=void 0;let t=X();function n(e){return{message:t=>r(t,e),params:t=>i(t,e)}}e.typeError=n;function r({parentSchema:e},t){return e?.nullable?`must be ${t} or null`:`must be ${t}`}e.typeErrorMessage=r;function i({parentSchema:e},n){return(0,t._)`{type: ${n}, nullable: ${!!e?.nullable}}`}e.typeErrorParams=i})),Uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.intRange=void 0;let t=X(),n=Vf(),r=Z(),i=zf(),a=Hf();e.intRange={int8:[-128,127,3],uint8:[0,255,3],int16:[-32768,32767,5],uint16:[0,65535,5],int32:[-2147483648,2147483647,10],uint32:[0,4294967295,10]};let o={message:e=>(0,a.typeErrorMessage)(e,e.schema),params:e=>(0,a.typeErrorParams)(e,e.schema)};function s(e){let{gen:i,data:a,it:o}=e,{timestamp:s,allowDate:c}=o.opts;if(s===`date`)return(0,t._)`${a} instanceof Date `;let l=(0,r.useFunc)(i,n.default),u=c?(0,t._)`, true`:t.nil,d=(0,t._)`typeof ${a} == "string" && ${l}(${a}${u})`;return s===`string`?d:(0,t.or)((0,t._)`${a} instanceof Date`,d)}e.default={keyword:`type`,schemaType:`string`,error:o,code(n){(0,i.checkMetadata)(n);let{data:r,schema:a,parentSchema:o,it:c}=n,l;switch(a){case`boolean`:case`string`:l=(0,t._)`typeof ${r} == ${a}`;break;case`timestamp`:l=s(n);break;case`float32`:case`float64`:l=(0,t._)`typeof ${r} == "number"`;break;default:{let n=a;if(l=(0,t._)`typeof ${r} == "number" && isFinite(${r}) && !(${r} % 1)`,!c.opts.int32range&&(n===`int32`||n===`uint32`))n===`uint32`&&(l=(0,t._)`${l} && ${r} >= 0`);else{let[i,a]=e.intRange[n];l=(0,t._)`${l} && ${r} >= ${i} && ${r} <= ${a}`}}}n.pass(o.nullable?(0,t.or)((0,t._)`${r} === null`,l):l)}}})),Wf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkNullableObject=e.checkNullable=void 0;let t=X();function n({gen:e,data:n,parentSchema:r},i=t.nil){let a=e.name(`valid`);return r.nullable?(e.let(a,(0,t._)`${n} === null`),i=(0,t.not)(a)):e.let(a,!1),[a,i]}e.checkNullable=n;function r(e,r){let[i,a]=n(e,r);return[i,(0,t._)`${a} && typeof ${e.data} == "object" && !Array.isArray(${e.data})`]}e.checkNullableObject=r})),Gf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=zf(),r=Wf();e.default={keyword:`enum`,schemaType:`array`,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){(0,n.checkMetadata)(e);let{gen:i,data:a,schema:o,schemaValue:s,parentSchema:c,it:l}=e;if(o.length===0)throw Error(`enum must have non-empty array`);if(o.length!==new Set(o).size)throw Error(`enum items must be unique`);let u,d=(0,t._)`typeof ${a} == "string"`;if(o.length>=l.opts.loopEnum){let t;[u,t]=(0,r.checkNullable)(e,d),i.if(t,f)}else{if(!Array.isArray(o))throw Error(`ajv implementation error`);u=(0,t.and)(d,(0,t.or)(...o.map(e=>(0,t._)`${a} === ${e}`))),c.nullable&&(u=(0,t.or)((0,t._)`${a} === null`,u))}e.pass(u);function f(){i.forOf(`v`,s,e=>i.if((0,t._)`${u} = ${a} === ${e}`,()=>i.break()))}}}})),Kf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=Fd(),r=X(),i=zf(),a=Wf();e.default={keyword:`elements`,schemaType:`object`,error:(0,Hf().typeError)(`array`),code(e){(0,i.checkMetadata)(e);let{gen:o,data:s,schema:c,it:l}=e;if((0,t.alwaysValidSchema)(l,c))return;let[u]=(0,a.checkNullable)(e);o.if((0,r.not)(u),()=>o.if((0,r._)`Array.isArray(${s})`,()=>o.assign(u,(0,n.validateArray)(e)),()=>e.error())),e.ok(u)}}})),qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateProperties=e.error=void 0;let t=Fd(),n=Z(),r=X(),i=zf(),a=Wf(),o=Hf();var s;(function(e){e.Additional=`additional`,e.Missing=`missing`})(s||={}),e.error={message:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?`must NOT have additional properties`:`must have property '${t.missingProperty}'`:(0,o.typeErrorMessage)(e,`object`)},params:e=>{let{params:t}=e;return t.propError?t.propError===s.Additional?(0,r._)`{error: ${t.propError}, additionalProperty: ${t.additionalProperty}}`:(0,r._)`{error: ${t.propError}, missingProperty: ${t.missingProperty}}`:(0,o.typeErrorParams)(e,`object`)}};let c={keyword:`properties`,schemaType:`object`,error:e.error,code:l};function l(e){(0,i.checkMetadata)(e);let{gen:o,data:c,parentSchema:l,it:u}=e,{additionalProperties:d,nullable:f}=l;if(u.jtdDiscriminator&&f)throw Error(`JTD: nullable inside discriminator mapping`);if(y())throw Error(`JTD: properties and optionalProperties have common members`);let[p,m]=b(`properties`),[h,g]=b(`optionalProperties`);if(m.length===0&&g.length===0&&d)return;let[_,v]=u.jtdDiscriminator===void 0?(0,a.checkNullableObject)(e,c):[o.let(`valid`,!1),!0];o.if(v,()=>o.assign(_,!0).block(()=>{x(m,`properties`,!0),x(g,`optionalProperties`),d||C()})),e.pass(_);function y(){let e=l.properties,t=l.optionalProperties;if(!(e&&t))return!1;for(let n in e)if(Object.prototype.hasOwnProperty.call(t,n))return!0;return!1}function b(e){let r=l[e],i=r?(0,t.allSchemaProperties)(r):[];if(u.jtdDiscriminator&&i.some(e=>e===u.jtdDiscriminator))throw Error(`JTD: discriminator tag used in ${e}`);return[i,i.filter(e=>!(0,n.alwaysValidSchema)(u,r[e]))]}function x(n,r,i){let a=o.var(`valid`);for(let i of n)o.if((0,t.propertyInData)(o,c,i,u.opts.ownProperties),()=>S(i,r,a),()=>l(i)),e.ok(a);function l(t){i?(o.assign(a,!1),e.error(!1,{propError:s.Missing,missingProperty:t},{schemaPath:t})):o.assign(a,!0)}}function S(t,n,r){e.subschema({keyword:n,schemaProp:t,dataProp:t},r)}function C(){o.forIn(`key`,c,t=>{let n=w(t,p,`properties`,u.jtdDiscriminator),i=w(t,h,`optionalProperties`),a=n===!0?i:i===!0?n:(0,r.and)(n,i);o.if(a,()=>{u.opts.removeAdditional?o.code((0,r._)`delete ${c}[${t}]`):(e.error(!1,{propError:s.Additional,additionalProperty:t},{instancePath:t,parentSchema:!0}),u.opts.allErrors||o.break())})})}function w(e,i,a,s){let c;if(i.length>8){let i=(0,n.schemaRefOrVal)(u,l[a],a);c=(0,r.not)((0,t.isOwnProperty)(o,i,e)),s!==void 0&&(c=(0,r.and)(c,(0,r._)`${e} !== ${s}`))}else if(i.length||s!==void 0){let t=s===void 0?i:[s].concat(i);c=(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`))}else c=!0;return c}}e.validateProperties=l,e.default=c})),Jf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=qf();e.default={keyword:`optionalProperties`,schemaType:`object`,error:t.error,code(e){e.parentSchema.properties||(0,t.validateProperties)(e)}}})),Yf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=zf(),r=Wf(),i=Hf(),a=Ff();e.default={keyword:`discriminator`,schemaType:`string`,implements:[`mapping`],error:{message:e=>{let{schema:t,params:n}=e;return n.discrError?n.discrError===a.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in mapping`:(0,i.typeErrorMessage)(e,`object`)},params:e=>{let{schema:n,params:r}=e;return r.discrError?(0,t._)`{error: ${r.discrError}, tag: ${n}, tagValue: ${r.tag}}`:(0,i.typeErrorParams)(e,`object`)}},code(e){(0,n.checkMetadata)(e);let{gen:i,data:o,schema:s,parentSchema:c}=e,[l,u]=(0,r.checkNullableObject)(e,o);i.if(u),d(),i.elseIf((0,t.not)(l)),e.error(),i.endIf(),e.ok(l);function d(){let n=i.const(`tag`,(0,t._)`${o}${(0,t.getProperty)(s)}`);i.if((0,t._)`${n} === undefined`),e.error(!1,{discrError:a.DiscrError.Tag,tag:n}),i.elseIf((0,t._)`typeof ${n} == "string"`),f(n),i.else(),e.error(!1,{discrError:a.DiscrError.Tag,tag:n},{instancePath:s}),i.endIf()}function f(n){i.if(!1);for(let e in c.mapping)i.elseIf((0,t._)`${n} === ${e}`),i.assign(l,p(e));i.else(),e.error(!1,{discrError:a.DiscrError.Mapping,tag:n},{instancePath:s,schemaPath:`mapping`,parentSchema:!0}),i.endIf()}function p(t){let n=i.name(`valid`);return e.subschema({keyword:`mapping`,schemaProp:t,jtdDiscriminator:s},n),n}}}})),Xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z(),n=X(),r=zf(),i=Wf();e.default={keyword:`values`,schemaType:`object`,error:(0,Hf().typeError)(`object`),code(e){(0,r.checkMetadata)(e);let{gen:a,data:o,schema:s,it:c}=e,[l,u]=(0,i.checkNullableObject)(e,o);(0,t.alwaysValidSchema)(c,s)?a.if((0,n.not)((0,n.or)(u,l)),()=>e.error()):(a.if(u),a.assign(l,d()),a.elseIf((0,n.not)(l)),e.error(),a.endIf()),e.ok(l);function d(){let r=a.name(`valid`);if(c.allErrors){let e=a.let(`valid`,!0);return i(()=>a.assign(e,!1)),e}return a.var(r,!0),i(()=>a.break()),r;function i(i){a.forIn(`key`,o,o=>{e.subschema({keyword:`values`,dataProp:o,dataPropType:t.Type.Str},r),a.if((0,n.not)(r),i)})}}}}})),Zf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`union`,schemaType:`array`,trackErrors:!0,code:Fd().validateUnion,error:{message:`must match a schema in union`}}})),Qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Bf(),n=Uf(),r=Gf(),i=Kf(),a=qf(),o=Jf(),s=Yf(),c=Xf(),l=Zf(),u=zf();e.default=[`definitions`,t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,l.default,u.default,{keyword:`additionalProperties`,schemaType:`boolean`},{keyword:`nullable`,schemaType:`boolean`}]})),$f=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=e=>{let t={nullable:{type:`boolean`},metadata:{optionalProperties:{union:{elements:{ref:`schema`}}},additionalProperties:!0}};return e&&(t.definitions={values:{ref:`schema`}}),t},n=e=>({optionalProperties:t(e)}),r=e=>({properties:{ref:{type:`string`}},optionalProperties:t(e)}),i=e=>({properties:{type:{enum:[`boolean`,`timestamp`,`string`,`float32`,`float64`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`]}},optionalProperties:t(e)}),a=e=>({properties:{enum:{elements:{type:`string`}}},optionalProperties:t(e)}),o=e=>({properties:{elements:{ref:`schema`}},optionalProperties:t(e)}),s=e=>({properties:{properties:{values:{ref:`schema`}}},optionalProperties:{optionalProperties:{values:{ref:`schema`}},additionalProperties:{type:`boolean`},...t(e)}}),c=e=>({properties:{optionalProperties:{values:{ref:`schema`}}},optionalProperties:{additionalProperties:{type:`boolean`},...t(e)}}),l=e=>({properties:{discriminator:{type:`string`},mapping:{values:{metadata:{union:[s(!1),c(!1)]}}}},optionalProperties:t(e)}),u=e=>({properties:{values:{ref:`schema`}},optionalProperties:t(e)}),d=e=>({metadata:{union:[n,r,i,a,o,s,c,l,u].map(t=>t(e))}});e.default={definitions:{schema:d(!1)},...d(!0)}})),ep=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.jtdForms=void 0,e.jtdForms=[`elements`,`values`,`discriminator`,`properties`,`optionalProperties`,`enum`,`type`,`ref`]})),tp=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n={"\b":`\\b`," ":`\\t`,"\n":`\\n`,"\f":`\\f`,"\r":`\\r`,'"':`\\"`,"\\":`\\\\`};function r(e){return t.lastIndex=0,`"`+(t.test(e)?e.replace(t,e=>{let t=n[e];return typeof t==`string`?t:`\\u`+(`0000`+e.charCodeAt(0).toString(16)).slice(-4)}):e)+`"`}e.default=r,r.code=`require("ajv/dist/runtime/quote").default`})),np=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ep(),n=Wd(),r=X(),i=Ud(),a=Od(),o=Fd(),s=Bf(),c=Z(),l=tp(),u={elements:m,values:h,discriminator:_,properties:v,optionalProperties:v,enum:x,type:b,ref:C};function d(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`serialize`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data},p;try{this._compilations.add(e),e.serializeName=u,l.func(u,a.default.data,!1,()=>{l.let(a.default.json,(0,r.str)``),f(d),l.return(a.default.json)}),l.optimize(this.opts.code.optimize);let t=l.toString();p=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,p)(this.scope.get());this.scope.value(u,{ref:n}),e.serialize=n}catch(t){throw p&&this.logger.error(`Error compiling serializer, function code:`,p),delete e.serialize,delete e.serializeName,t}finally{this._compilations.delete(e)}return e}e.default=d;function f(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}p(e,n?u[n]:T)}function p(e,t){let{gen:n,schema:i,data:o}=e;if(!i.nullable)return t(e);n.if((0,r._)`${o} === undefined || ${o} === null`,()=>n.add(a.default.json,(0,r._)`"null"`),()=>t(e))}function m(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`[`);let o=t.let(`first`,!0);t.forOf(`el`,i,t=>{E(e,o),f({...e,schema:n.elements,data:t})}),t.add(a.default.json,(0,r.str)`]`)}function h(e){let{gen:t,schema:n,data:i}=e;t.add(a.default.json,(0,r.str)`{`);let o=t.let(`first`,!0);t.forIn(`key`,i,t=>g(e,t,n.values,o)),t.add(a.default.json,(0,r.str)`}`)}function g(e,t,n,i){let{gen:o,data:s}=e;E(e,i),x({...e,data:t}),o.add(a.default.json,(0,r.str)`:`);let c=o.const(`value`,(0,r._)`${s}${(0,r.getProperty)(t)}`);f({...e,schema:n,data:c})}function _(e){let{gen:t,schema:n,data:i}=e,{discriminator:o}=n;t.add(a.default.json,(0,r.str)`{${JSON.stringify(o)}:`);let s=t.const(`tag`,(0,r._)`${i}${(0,r.getProperty)(o)}`);x({...e,data:s}),t.if(!1);for(let i in n.mapping){t.elseIf((0,r._)`${s} === ${i}`);let a=n.mapping[i];y({...e,schema:a},o)}t.endIf(),t.add(a.default.json,(0,r.str)`}`)}function v(e){let{gen:t}=e;t.add(a.default.json,(0,r.str)`{`),y(e),t.add(a.default.json,(0,r.str)`}`)}function y(e,t){let{gen:n,schema:i,data:s}=e,{properties:c,optionalProperties:l}=i,u=_(c),d=_(l),p=v(u.concat(d)),m=!t,h;for(let e of u)m?m=!1:n.add(a.default.json,(0,r.str)`,`),b(e,c[e],y(e));m&&(h=n.let(`first`,!0));for(let t of d){let i=y(t);n.if((0,r.and)((0,r._)`${i} !== undefined`,(0,o.isOwnProperty)(n,s,t)),()=>{E(e,h),b(t,l[t],i)})}i.additionalProperties&&n.forIn(`key`,s,t=>n.if(x(t,p),()=>g(e,t,{},h)));function _(e){return e?Object.keys(e):[]}function v(e){if(t&&e.push(t),new Set(e).size!==e.length)throw Error(`JTD: properties/optionalProperties/disciminator overlap`);return e}function y(e){return n.const(`value`,(0,r._)`${s}${(0,r.getProperty)(e)}`)}function b(t,i,o){n.add(a.default.json,(0,r.str)`${JSON.stringify(t)}:`),f({...e,schema:i,data:o})}function x(e,t){return t.length?(0,r.and)(...t.map(t=>(0,r._)`${e} !== ${t}`)):!0}}function b(e){let{gen:t,schema:n,data:i}=e;switch(n.type){case`boolean`:t.add(a.default.json,(0,r._)`${i} ? "true" : "false"`);break;case`string`:x(e);break;case`timestamp`:t.if((0,r._)`${i} instanceof Date`,()=>t.add(a.default.json,(0,r._)`'"' + ${i}.toISOString() + '"'`),()=>x(e));break;default:S(e)}}function x({gen:e,data:t}){e.add(a.default.json,(0,r._)`${(0,c.useFunc)(e,l.default)}(${t})`)}function S({gen:e,data:t,self:n}){let i=(0,r._)`${t} === Infinity || ${t} === -Infinity || ${t} !== ${t}`;n.opts.specialNumbers===void 0||n.opts.specialNumbers===`fast`?e.add(a.default.json,(0,r._)`"" + ${t}`):e.if(i,()=>e.add(a.default.json,(0,r._)`null`),()=>e.add(a.default.json,(0,r._)`"" + ${t}`))}function C(e){let{gen:t,self:o,data:c,definitions:l,schema:u,schemaEnv:p}=e,{ref:m}=u,h=l[m];if(!h)throw new i.default(o.opts.uriResolver,``,m,`No definition ${m}`);if(!(0,s.hasRef)(h))return f({...e,schema:h});let{root:g}=p,_=d.call(o,new n.SchemaEnv({schema:h,root:g}),l);t.add(a.default.json,(0,r._)`${w(t,_)}(${c})`)}function w(e,t){return t.serialize?e.scopeValue(`serialize`,{ref:t.serialize}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.serialize`}function T({gen:e,data:t}){e.add(a.default.json,(0,r._)`JSON.stringify(${t})`)}function E({gen:e},t){t?e.if(t,()=>e.assign(t,!1),()=>e.add(a.default.json,(0,r.str)`,`)):e.add(a.default.json,(0,r.str)`,`)}})),rp=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseJsonString=e.parseJsonNumber=e.parseJson=void 0;let t=/position\s(\d+)(?: \(line \d+ column \d+\))?$/;function n(e,r){let i;n.message=void 0;let a;r&&(e=e.slice(r));try{return n.position=r+e.length,JSON.parse(e)}catch(o){if(a=t.exec(o.message),!a){n.message=`unexpected end`;return}i=+a[1];let s=e[i];e=e.slice(0,i),n.position=r+i;try{return JSON.parse(e)}catch{n.message=`unexpected token ${s}`;return}}}e.parseJson=n,n.message=void 0,n.position=0,n.code=`require("ajv/dist/runtime/parseJson").parseJson`;function r(e,t,n){let i=``,a;if(r.message=void 0,e[t]===`-`&&(i+=`-`,t++),e[t]===`0`)i+=`0`,t++;else if(!o(n)){s();return}if(n)return r.position=t,+i;if(e[t]===`.`&&(i+=`.`,t++,!o())){s();return}if(a=e[t],(a===`e`||a===`E`)&&(i+=`e`,t++,a=e[t],(a===`+`||a===`-`)&&(i+=a,t++),!o())){s();return}return r.position=t,+i;function o(n){let r=!1;for(;a=e[t],a>=`0`&&a<=`9`&&(n===void 0||n-- >0);)r=!0,i+=a,t++;return r}function s(){r.position=t,r.message=t<e.length?`unexpected token ${e[t]}`:`unexpected end`}}e.parseJsonNumber=r,r.message=void 0,r.position=0,r.code=`require("ajv/dist/runtime/parseJson").parseJsonNumber`;let i={b:`\b`,f:`\f`,n:`
136
+ `,r:`\r`,t:` `,'"':`"`,"/":`/`,"\\":`\\`};function a(e,t){let n=``,r;for(a.message=void 0;r=e[t++],r!==`"`;)if(r===`\\`)if(r=e[t],r in i)n+=i[r],t++;else if(r===`u`){t++;let i=4,a=0;for(;i--;){if(a<<=4,r=e[t],r===void 0){o(`unexpected end`);return}if(r=r.toLowerCase(),r>=`a`&&r<=`f`)a+=r.charCodeAt(0)-97+10;else if(r>=`0`&&r<=`9`)a+=r.charCodeAt(0)-48;else{o(`unexpected token ${r}`);return}t++}n+=String.fromCharCode(a)}else{o(`unexpected token ${r}`);return}else if(r===void 0){o(`unexpected end`);return}else if(r.charCodeAt(0)>=32)n+=r;else{o(`unexpected token ${r}`);return}return a.position=t,n;function o(e){a.position=t,a.message=e}}e.parseJsonString=a,a.message=void 0,a.position=0,a.code=`require("ajv/dist/runtime/parseJson").parseJsonString`})),ip=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ep(),n=Wd(),r=X(),i=Ud(),a=Od(),o=Fd(),s=Bf(),c=Uf(),l=rp(),u=Z(),d=Vf(),f={elements:y,values:b,discriminator:w,properties:T,optionalProperties:T,enum:j,type:k,ref:N};function p(e,t){let i=n.getCompilingSchema.call(this,e);if(i)return i;let{es5:o,lines:s}=this.opts.code,{ownProperties:c}=this.opts,l=new r.CodeGen(this.scope,{es5:o,lines:s,ownProperties:c}),u=l.scopeName(`parse`),d={self:this,gen:l,schema:e.schema,schemaEnv:e,definitions:t,data:a.default.data,parseName:u,char:l.name(`c`)},f;try{this._compilations.add(e),e.parseName=u,h(d),l.optimize(this.opts.code.optimize);let t=l.toString();f=`${l.scopeRefs(a.default.scope)}return ${t}`;let n=Function(`${a.default.scope}`,f)(this.scope.get());this.scope.value(u,{ref:n}),e.parse=n}catch(t){throw f&&this.logger.error(`Error compiling parser, function code:`,f),delete e.parse,delete e.parseName,t}finally{this._compilations.delete(e)}return e}e.default=p;let m=(0,r._)`undefined`;function h(e){let{gen:t,parseName:n,char:i}=e;t.func(n,(0,r._)`${a.default.json}, ${a.default.jsonPos}, ${a.default.jsonPart}`,!1,()=>{t.let(a.default.data),t.let(i),t.assign((0,r._)`${n}.message`,m),t.assign((0,r._)`${n}.position`,m),t.assign(a.default.jsonPos,(0,r._)`${a.default.jsonPos} || 0`),t.const(a.default.jsonLen,(0,r._)`${a.default.json}.length`),g(e),I(e),t.if(a.default.jsonPart,()=>{t.assign((0,r._)`${n}.position`,a.default.jsonPos),t.return(a.default.data)}),t.if((0,r._)`${a.default.jsonPos} === ${a.default.jsonLen}`,()=>t.return(a.default.data)),oe(e)})}function g(e){let n;for(let r of t.jtdForms)if(r in e.schema){n=r;break}n?v(e,f[n]):P(e)}let _=ee(!0,ee(!1,oe));function v(e,t){let{gen:n,schema:r,data:i}=e;if(!r.nullable)return t(e);ie(e,`null`,t,()=>n.assign(i,null))}function y(e){let{gen:t,schema:n,data:i}=e;F(e,`[`);let a=t.let(`i`,0);t.assign(i,(0,r._)`[]`),x(e,`]`,()=>{let o=t.let(`el`);g({...e,schema:n.elements,data:o}),t.assign((0,r._)`${i}[${a}++]`,o)})}function b(e){let{gen:t,schema:n,data:i}=e;F(e,`{`),t.assign(i,(0,r._)`{}`),x(e,`}`,()=>C(e,n.values))}function x(e,t,n){S(e,t,n),F(e,t)}function S(e,t,n){let{gen:i}=e;i.for((0,r._)`;${a.default.jsonPos}<${a.default.jsonLen} && ${ae(1)}!==${t};`,()=>{n(),ie(e,`,`,()=>i.break(),o)});function o(){ie(e,t,()=>{},oe)}}function C(e,t){let{gen:n}=e,r=n.let(`key`);A({...e,data:r}),F(e,`:`),O(e,r,t)}function w(e){let{gen:t,data:n,schema:i}=e,{discriminator:o,mapping:s}=i;F(e,`{`),t.assign(n,(0,r._)`{}`);let c=t.const(`pos`,a.default.jsonPos),l=t.let(`value`),u=t.let(`tag`);S(e,`}`,()=>{let i=t.let(`key`);A({...e,data:i}),F(e,`:`),t.if((0,r._)`${i} === ${o}`,()=>{A({...e,data:u}),t.assign((0,r._)`${n}[${i}]`,u),t.break()},()=>P({...e,data:l}))}),t.assign(a.default.jsonPos,c),t.if((0,r._)`${u} === undefined`),L(e,(0,r.str)`discriminator tag not found`);for(let n in s)t.elseIf((0,r._)`${u} === ${n}`),E({...e,schema:s[n]},o);t.else(),L(e,(0,r.str)`discriminator value not in schema`),t.endIf()}function T(e){let{gen:t,data:n}=e;F(e,`{`),t.assign(n,(0,r._)`{}`),E(e)}function E(e,t){let{gen:n,schema:i,data:a}=e,{properties:s,optionalProperties:c,additionalProperties:l}=i;if(x(e,`}`,()=>{let i=n.let(`key`);if(A({...e,data:i}),F(e,`:`),n.if(!1),D(e,i,s),D(e,i,c),t){n.elseIf((0,r._)`${i} === ${t}`);let a=n.let(`tag`);A({...e,data:a})}n.else(),l?P({...e,data:(0,r._)`${a}[${i}]`}):L(e,(0,r.str)`property ${i} not allowed`),n.endIf()}),s){let t=(0,o.hasPropFunc)(n),i=(0,r.and)(...Object.keys(s).map(e=>(0,r._)`${t}.call(${a}, ${e})`));n.if((0,r.not)(i),()=>L(e,(0,r.str)`missing required properties`))}}function D(e,t,n={}){let{gen:i}=e;for(let a in n)i.elseIf((0,r._)`${t} === ${a}`),O(e,t,n[a])}function O(e,t,n){g({...e,schema:n,data:(0,r._)`${e.data}[${t}]`})}function k(e){let{gen:t,schema:n,data:i,self:a}=e;switch(n.type){case`boolean`:_(e);break;case`string`:A(e);break;case`timestamp`:{A(e);let n=(0,u.useFunc)(t,d.default),{allowDate:o,parseDate:s}=a.opts,c=o?(0,r._)`!${n}(${i}, true)`:(0,r._)`!${n}(${i})`,l=s?(0,r.or)(c,(0,r._)`(${i} = new Date(${i}), false)`,(0,r._)`isNaN(${i}.valueOf())`):c;t.if(l,()=>L(e,(0,r.str)`invalid timestamp`));break}case`float32`:case`float64`:M(e);break;default:{let o=n.type;if(!a.opts.int32range&&(o===`int32`||o===`uint32`))M(e,16),o===`uint32`&&t.if((0,r._)`${i} < 0`,()=>L(e,(0,r.str)`integer out of range`));else{let[n,a,s]=c.intRange[o];M(e,s),t.if((0,r._)`${i} < ${n} || ${i} > ${a}`,()=>L(e,(0,r.str)`integer out of range`))}}}}function A(e){F(e,`"`),ne(e,l.parseJsonString)}function j(e){let{gen:t,data:n,schema:i}=e,o=i.enum;F(e,`"`),t.if(!1);for(let e of o){let i=JSON.stringify(e).slice(1);t.elseIf((0,r._)`${ae(i.length)} === ${i}`),t.assign(n,(0,r.str)`${e}`),t.add(a.default.jsonPos,i.length)}t.else(),oe(e),t.endIf()}function M(e,t){let{gen:n}=e;I(e),n.if((0,r._)`"-0123456789".indexOf(${ae(1)}) < 0`,()=>oe(e),()=>ne(e,l.parseJsonNumber,t))}function ee(e,t){return n=>{let{gen:r,data:i}=n;ie(n,`${e}`,()=>t(n),()=>r.assign(i,e))}}function N(e){let{gen:t,self:r,definitions:a,schema:o,schemaEnv:c}=e,{ref:l}=o,u=a[l];if(!u)throw new i.default(r.opts.uriResolver,``,l,`No definition ${l}`);if(!(0,s.hasRef)(u))return g({...e,schema:u});let{root:d}=c;re(e,te(t,p.call(r,new n.SchemaEnv({schema:u,root:d}),a)),!0)}function te(e,t){return t.parse?e.scopeValue(`parse`,{ref:t.parse}):(0,r._)`${e.scopeValue(`wrapper`,{ref:t})}.parse`}function P(e){ne(e,l.parseJson)}function ne(e,t,n){re(e,(0,u.useFunc)(e.gen,t),n)}function re(e,t,n){let{gen:i,data:o}=e;i.assign(o,(0,r._)`${t}(${a.default.json}, ${a.default.jsonPos}${n?(0,r._)`, ${n}`:r.nil})`),i.assign(a.default.jsonPos,(0,r._)`${t}.position`),i.if((0,r._)`${o} === undefined`,()=>L(e,(0,r._)`${t}.message`))}function F(e,t){ie(e,t,oe)}function ie(e,t,n,i){let{gen:o}=e,s=t.length;I(e),o.if((0,r._)`${ae(s)} === ${t}`,()=>{o.add(a.default.jsonPos,s),i?.(e)},()=>n(e))}function I({gen:e,char:t}){e.code((0,r._)`while((${t}=${a.default.json}[${a.default.jsonPos}],${t}===" "||${t}==="\\n"||${t}==="\\r"||${t}==="\\t"))${a.default.jsonPos}++;`)}function ae(e){return e===1?(0,r._)`${a.default.json}[${a.default.jsonPos}]`:(0,r._)`${a.default.json}.slice(${a.default.jsonPos}, ${a.default.jsonPos}+${e})`}function oe(e){L(e,(0,r._)`"unexpected token " + ${a.default.json}[${a.default.jsonPos}]`)}function L({gen:e,parseName:t},n){e.assign((0,r._)`${t}.message`,n),e.assign((0,r._)`${t}.position`,a.default.jsonPos),e.return(m)}})),ap=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Xd(),r=Qf(),i=$f(),a=np(),o=ip(),s=`JTD-meta-schema`;var c=class extends n.default{constructor(e={}){super({...e,jtd:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(r.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema(),this.opts.meta&&this.addMetaSchema(i.default,s,!1)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}compileSerializer(e){let t=this._addSchema(e);return t.serialize||this._compileSerializer(t)}compileParser(e){let t=this._addSchema(e);return t.parse||this._compileParser(t)}_compileSerializer(e){if(a.default.call(this,e,e.schema.definitions||{}),!e.serialize)throw Error(`ajv implementation error`);return e.serialize}_compileParser(e){if(o.default.call(this,e,e.schema.definitions||{}),!e.parse)throw Error(`ajv implementation error`);return e.parse}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Vd();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Hd();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Ud();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),op=o(((e,t)=>{let n=Jd();t.exports=Object.freeze({coerceTypes:`array`,useDefaults:!0,removeAdditional:!0,uriResolver:n,addUsedSchema:!1,allErrors:!1})})),sp=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),cp=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Rf(),n=X(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),lp=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=sp(),r=cp(),i=X(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=s})),up=o(((e,t)=>{let n=Rf().default,r=ap(),i=op();t.exports=class{constructor(e,t){t.mode===`JTD`?this.ajv=new r(Object.assign({},i,t.customOptions)):this.ajv=new n(Object.assign({},i,t.customOptions));let a=!0;if(t.plugins&&t.plugins.length>0)for(let e of t.plugins)Array.isArray(e)?(a&&=e[0].name!==`formatsPlugin`,e[0](this.ajv,e[1])):(a&&=e.name!==`formatsPlugin`,e(this.ajv));a&&lp()(this.ajv),t.onCreate?.(this.ajv);let o=Object.values(e);for(let e of o)this.ajv.addSchema(e)}buildValidatorFunction({schema:e}){if(e.$id){let t=this.ajv.getSchema(e.$id);if(t)return t}return this.ajv.compile(e)}}})),dp=o(((e,t)=>{let n=ap(),r=op();t.exports=class{constructor(e,t){this.ajv=new n(Object.assign({},r,t))}buildSerializerFunction({schema:e}){return this.ajv.compileSerializer(e)}}})),fp=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Dd(),r=Ed();function i(e,t){if(!e.opts.code.source)throw Error(`moduleCode: ajv instance must have code.source option`);let{_n:i}=e.scope.opts;return typeof t==`function`?o(t.source):t===void 0?s(e.schemas,t=>t.meta?void 0:e.compile(t.schema)):s(t,a);function a(t){let n=e.getSchema(t);if(!n)throw Error(`moduleCode: no schema with id ${t}`);return n}function o(t){let n={},r=t?.validateName,a=c(n,t);return e.opts.code.esm?`"use strict";${i}export const validate = ${r};${i}export default ${r};${i}${a}`:`"use strict";${i}module.exports = ${r};${i}module.exports.default = ${r};${i}${a}`}function s(t,n){let a={},o=(0,r._)`"use strict";`;for(let s in t){let l=n(t[s]);if(l){let t=c(a,l.source),n=e.opts.code.esm?(0,r._)`export const ${(0,r.getEsmExportName)(s)}`:(0,r._)`exports${(0,r.getProperty)(s)}`;o=(0,r._)`${o}${i}${n} = ${l.source?.validateName};${i}${t}`}}return`${o}`}function c(t,a){if(!a)throw Error(`moduleCode: function does not have "source" property`);if(u(a.validateName)===n.UsedValueState.Completed)return r.nil;d(a.validateName,n.UsedValueState.Started);let o=e.scope.scopeCode(a.scopeValues,t,l),s=new r._Code(`${o}${i}${a.validateCode}`);return a.evaluated?(0,r._)`${s}${a.validateName}.evaluated = ${a.evaluated};${i}`:s;function l(a){let o=a.value?.ref;if(a.prefix===`validate`&&typeof o==`function`)return c(t,o.source);if((a.prefix===`root`||a.prefix===`wrapper`)&&typeof o==`object`){let{validate:s,validateName:l}=o;if(!l)throw Error(`ajv internal error`);let d=e.opts.code.es5?n.varKinds.var:n.varKinds.const,f=(0,r._)`${d} ${a} = {validate: ${l}};`;if(u(l)===n.UsedValueState.Started)return f;let p=c(t,s?.source);return(0,r._)`${f}${i}${p}`}}function u(e){return t[e.prefix]?.get(e)}function d(e,n){let{prefix:r}=e;(t[r]=t[r]||new Map).set(e,n)}}}t.exports=e=i,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=i})),pp=o(((e,t)=>{let n=mp(),r=fp().default;function i(e={readMode:!0}){if(e.readMode===!0&&!e.restoreFunction)throw Error(`You must provide a restoreFunction options when readMode ON`);if(e.readMode!==!0&&!e.storeFunction)throw Error(`You must provide a storeFunction options when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=n();return function(i,a={}){(!a.customOptions||!a.customOptions.code)&&(a.customOptions=Object.assign({},a.customOptions,{code:{source:!0}}));let o=t(i,a);return function(t){let i=o(t),a=r(o[n.AjvReference].ajv,i);return e.storeFunction(t,a),i}}}t.exports=i})),mp=o(((e,t)=>{let n=Symbol.for(`fastify.ajv-compiler.reference`),r=up(),i=dp();function a(e){let t=new Map,a=new Map;return e&&e.jtdSerializer===!0?function(e,t){let n=o({},t);if(a.has(n))return a.get(n);let r=new i(e,t),s=r.buildSerializerFunction.bind(r);return a.set(n,s),s}:function(e,i){let a=o(e,i.customOptions);if(t.has(a))return t.get(a);let s=new r(e,i),c=s.buildValidatorFunction.bind(s);return t.set(a,c),i.customOptions.code!==void 0&&(c[n]=s),c}}function o(e,t){return`${JSON.stringify(e)}${JSON.stringify(t)}`}t.exports=a,t.exports.default=a,t.exports.AjvCompiler=a,t.exports.AjvReference=n,t.exports.StandaloneValidator=pp()})),hp=o((e=>{var t=Object.prototype.hasOwnProperty;function n(e,t,n){for(n of e.keys())if(r(n,t))return n}function r(e,i){var a,o,s;if(e===i)return!0;if(e&&i&&(a=e.constructor)===i.constructor){if(a===Date)return e.getTime()===i.getTime();if(a===RegExp)return e.toString()===i.toString();if(a===Array){if((o=e.length)===i.length)for(;o--&&r(e[o],i[o]););return o===-1}if(a===Set){if(e.size!==i.size)return!1;for(o of e)if(s=o,s&&typeof s==`object`&&(s=n(i,s),!s)||!i.has(s))return!1;return!0}if(a===Map){if(e.size!==i.size)return!1;for(o of e)if(s=o[0],s&&typeof s==`object`&&(s=n(i,s),!s)||!r(o[1],i.get(s)))return!1;return!0}if(a===ArrayBuffer)e=new Uint8Array(e),i=new Uint8Array(i);else if(a===DataView){if((o=e.byteLength)===i.byteLength)for(;o--&&e.getInt8(o)===i.getInt8(o););return o===-1}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===i.byteLength)for(;o--&&e[o]===i[o];);return o===-1}if(!a||typeof e==`object`){for(a in o=0,e)if(t.call(e,a)&&++o&&!t.call(i,a)||!(a in i)||!r(e[a],i[a]))return!1;return Object.keys(i).length===o}}return e!==e&&i!==i}e.dequal=r})),gp=o(((e,t)=>{let{dequal:n}=hp(),r=Symbol.for(`json-schema-ref`);var i=class{#e;#t;#n;#r;#i;constructor(e={}){this.#e={},this.#t={},this.#n=e.insertRefSymbol??!1,this.#r=e.allowEqualDuplicates??!0,this.#i=e.cloneSchemaWithoutRefs??!1}addSchema(e,t,n=!0){n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#c(e,t));let r=e.$id;r!==void 0&&typeof r==`string`&&(r.charAt(0)===`#`?this.#l(e,t,r):(this.#c(e,r),t=r));let i=e.$ref;if(i!==void 0&&typeof i==`string`){let{refSchemaId:e,refJsonPointer:n}=this.#a(i,t);this.#e[t].refs.push({schemaId:e,jsonPointer:n})}for(let n in e)typeof e[n]==`object`&&e[n]!==null&&this.addSchema(e[n],t,!1)}getSchema(e,t=`#`){let n=this.#e[e];if(n===void 0)throw Error(`Cannot resolve ref "${e}${t}". Schema with id "${e}" is not found.`);return n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}hasSchema(e){return this.#e[e]!==void 0}getSchemaRefs(e){let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);return t.refs}getSchemaDependencies(e,t={}){let n=this.#e[e];for(let r of n.refs){let n=r.schemaId;n===e||t[n]!==void 0||(t[n]=this.getSchema(n),this.getSchemaDependencies(n,t))}return t}derefSchema(e){if(this.#t[e]!==void 0)return;let t=this.#e[e];if(t===void 0)throw Error(`Schema with id "${e}" is not found.`);!this.#i&&t.refs.length===0&&(this.#t[e]={schema:t.schema,anchors:t.anchors});let n=[];this.#o(t.schema,e,!0,n);let r=this.getSchemaDependencies(e);for(let e in r){let t=r[e];this.#o(t,e,!0,n)}for(let e of n){let{refSchemaId:t,refJsonPointer:n}=this.#a(e.ref,e.sourceSchemaId),r=this.getDerefSchema(t,n);if(r===null)throw Error(`Cannot resolve ref "${e.ref}". Ref "${n}" is not found in schema "${t}".`);e.targetSchema=r,e.targetSchemaId=t}for(let e of n)this.#s(e,n)}getDerefSchema(e,t=`#`){let n=this.#t[e];return n===void 0&&(this.derefSchema(e),n=this.#t[e]),n.anchors[t]===void 0?a(n.schema,t):n.anchors[t]}#a(e,t){let n=e.indexOf(`#`);return n===-1?{refSchemaId:e,refJsonPointer:`#`}:n===0?{refSchemaId:t,refJsonPointer:e}:{refSchemaId:e.slice(0,n),refJsonPointer:e.slice(n)}}#o(e,t,n,r=[]){let i=Array.isArray(e)?[...e]:{...e};n&&(e.$id!==void 0&&e.$id.charAt(0)!==`#`?t=e.$id:this.#u(i,t));let a=i.$id;a!==void 0&&typeof a==`string`&&(a.charAt(0)===`#`?this.#d(i,t,a):(this.#u(i,a),t=a)),i.$ref!==void 0&&r.push({ref:i.$ref,sourceSchemaId:t,sourceSchema:i});for(let e in i){let n=i[e];typeof n==`object`&&n&&(i[e]=this.#o(n,t,!1,r))}return i}#s(e,t){let{sourceSchema:i,targetSchema:a}=e;if(i.$ref){if(this.#n&&(i[r]=i.$ref),delete i.$ref,a.$ref){let e=t.find(e=>e.sourceSchema===a);this.#s(e,t)}for(let t in a)if(t!==`$id`){if(i[t]!==void 0){if(n(i[t],a[t]))continue;throw Error(`Cannot resolve ref "${e.ref}". Property "${t}" already exists in schema "${e.sourceSchemaId}".`)}i[t]=a[t]}e.isResolved=!0}}#c(e,t){let r=this.#e[t];if(r!==void 0){if(this.#r&&n(e,r.schema))return;throw Error(`There is already another schema with id "${t}".`)}this.#e[t]={schema:e,anchors:{},refs:[]}}#l(e,t,n){let{anchors:r}=this.#e[t];if(r[n]!==void 0)throw Error(`There is already another anchor "${n}" in schema "${t}".`);r[n]=e}#u(e,t){this.#t[t]===void 0&&(this.#t[t]={schema:e,anchors:{}})}#d(e,t,n){let{anchors:r}=this.#t[t];r[n]=e}};function a(e,t){let n=t.split(`/`),r=e;for(let e of n)if(!(e===``||e===`#`)){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}t.exports={RefResolver:i}})),_p=o(((e,t)=>{let n=Rf(),r=Jd(),i=lp(),a=dd()({proto:!0});t.exports=class e{constructor(e){this.ajv=new n({...e,strictSchema:!1,validateSchema:!1,allowUnionTypes:!0,uriResolver:r}),i(this.ajv),this.ajv.addKeyword({keyword:`fjs_type`,type:`object`,errors:!1,validate:(e,t)=>t&&typeof t.toJSON==`function`}),this._ajvSchemas={},this._ajvOptions=e||{}}addSchema(e,t){let n=e.$id||t;if(e.$id!==void 0&&e.$id[0]===`#`&&(n=t+e.$id),this.ajv.refs[n]===void 0&&this.ajv.schemas[n]===void 0){let t=a(e);this.convertSchemaToAjvFormat(t),this.ajv.addSchema(t,n),this._ajvSchemas[n]=e}}validate(e,t){return this.ajv.validate(e,t)}convertSchemaToAjvFormat(e){if(e!==null){e.type===`string`?(e.fjs_type=`string`,e.type=[`string`,`object`]):Array.isArray(e.type)&&e.type.includes(`string`)&&!e.type.includes(`object`)&&(e.fjs_type=`string`,e.type.push(`object`));for(let t in e)typeof e[t]==`object`&&this.convertSchemaToAjvFormat(e[t])}}getState(){return{ajvOptions:this._ajvOptions,ajvSchemas:this._ajvSchemas}}static restoreFromState(t){let n=new e(t.ajvOptions);for(let[e,r]of Object.entries(t.ajvSchemas))n.ajv.addSchema(r,e);return n}}})),vp=o(((e,t)=>{t.exports=class e{constructor(e,t,n=`#`){this.schema=e,this.schemaId=t,this.jsonPointer=n}getPropertyLocation(t){return new e(this.schema[t],this.schemaId,this.jsonPointer+`/`+t)}getSchemaRef(){return this.schemaId+this.jsonPointer}}})),yp=o(((e,t)=>{t.exports=d,t.exports.default=d;let n={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0},r={enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},i=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,a=sp().fullFormats.uri,o=sp().fullFormats.regex;function s(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){return typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e==`number`&&isFinite(e)&&(e<0||isNaN(e))?(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1):(s.errors=null,!0):(s.errors=[{instancePath:t,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1)}let c={validate:d};function l(e,{instancePath:t=``,parentData:n,parentDataProperty:r,rootData:i=e}={}){let a=null,o=0;if(o===0)if(Array.isArray(e)){if(e.length<1)return l.errors=[{instancePath:t,schemaPath:`#/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let n=e.length;for(let r=0;r<n;r++){let n=o;if(c.validate(e[r],{instancePath:t+`/`+r,parentData:e,parentDataProperty:r,rootData:i})||(a=a===null?c.validate.errors:a.concat(c.validate.errors),o=a.length),n!==o)break}}}else return l.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;return l.errors=a,o===0}let u=lf().default;function d(e,{instancePath:t=``,parentData:c,parentDataProperty:f,rootData:p=e}={}){let m=null,h=0;if(!(e&&typeof e==`object`&&!Array.isArray(e))&&typeof e!=`boolean`)return d.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:n.type},message:`must be object,boolean`}],!1;if(h===0&&e&&typeof e==`object`&&!Array.isArray(e)){if(e.$id!==void 0){let n=e.$id,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$id`,schemaPath:`#/properties/%24id/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$schema!==void 0){let n=e.$schema,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!a(n))return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/format`,keyword:`format`,params:{format:`uri`},message:`must match format "uri"`}],!1}else return d.errors=[{instancePath:t+`/$schema`,schemaPath:`#/properties/%24schema/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$ref!==void 0){let n=e.$ref,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!i.test(n))return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/format`,keyword:`format`,params:{format:`uri-reference`},message:`must match format "uri-reference"`}],!1}else return d.errors=[{instancePath:t+`/$ref`,schemaPath:`#/properties/%24ref/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.$comment!==void 0){let n=h;if(typeof e.$comment!=`string`)return d.errors=[{instancePath:t+`/$comment`,schemaPath:`#/properties/%24comment/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.title!==void 0){let n=h;if(typeof e.title!=`string`)return d.errors=[{instancePath:t+`/title`,schemaPath:`#/properties/title/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.description!==void 0){let n=h;if(typeof e.description!=`string`)return d.errors=[{instancePath:t+`/description`,schemaPath:`#/properties/description/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.readOnly!==void 0){let n=h;if(typeof e.readOnly!=`boolean`)return d.errors=[{instancePath:t+`/readOnly`,schemaPath:`#/properties/readOnly/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.examples!==void 0){let n=h;if(h===n&&!Array.isArray(e.examples))return d.errors=[{instancePath:t+`/examples`,schemaPath:`#/properties/examples/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=n===h}else var g=!0;if(g){if(e.multipleOf!==void 0){let n=e.multipleOf,r=h;if(h===r)if(typeof n==`number`&&isFinite(n)){if(n<=0||isNaN(n))return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/exclusiveMinimum`,keyword:`exclusiveMinimum`,params:{comparison:`>`,limit:0},message:`must be > 0`}],!1}else return d.errors=[{instancePath:t+`/multipleOf`,schemaPath:`#/properties/multipleOf/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maximum!==void 0){let n=e.maximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/maximum`,schemaPath:`#/properties/maximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMaximum!==void 0){let n=e.exclusiveMaximum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMaximum`,schemaPath:`#/properties/exclusiveMaximum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.minimum!==void 0){let n=e.minimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/minimum`,schemaPath:`#/properties/minimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.exclusiveMinimum!==void 0){let n=e.exclusiveMinimum,r=h;if(!(typeof n==`number`&&isFinite(n)))return d.errors=[{instancePath:t+`/exclusiveMinimum`,schemaPath:`#/properties/exclusiveMinimum/type`,keyword:`type`,params:{type:`number`},message:`must be number`}],!1;var g=r===h}else var g=!0;if(g){if(e.maxLength!==void 0){let n=e.maxLength,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxLength`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minLength!==void 0){let n=h;s(e.minLength,{instancePath:t+`/minLength`,parentData:e,parentDataProperty:`minLength`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.pattern!==void 0){let n=e.pattern,r=h;if(h===r&&h===r)if(typeof n==`string`){if(!o(n))return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`}],!1}else return d.errors=[{instancePath:t+`/pattern`,schemaPath:`#/properties/pattern/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalItems!==void 0){let n=h;d(e.additionalItems,{instancePath:t+`/additionalItems`,parentData:e,parentDataProperty:`additionalItems`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.items!==void 0){let n=e.items,r=h,i=h,a=!1,o=h;d(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var _=o===h;if(a||=_,!a){let r=h;l(n,{instancePath:t+`/items`,parentData:e,parentDataProperty:`items`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var _=r===h;a||=_}if(a)h=i,m!==null&&(i?m.length=i:m=null);else{let e={instancePath:t+`/items`,schemaPath:`#/properties/items/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=r===h}else var g=!0;if(g){if(e.maxItems!==void 0){let n=e.maxItems,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxItems`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minItems!==void 0){let n=h;s(e.minItems,{instancePath:t+`/minItems`,parentData:e,parentDataProperty:`minItems`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.uniqueItems!==void 0){let n=h;if(typeof e.uniqueItems!=`boolean`)return d.errors=[{instancePath:t+`/uniqueItems`,schemaPath:`#/properties/uniqueItems/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;var g=n===h}else var g=!0;if(g){if(e.contains!==void 0){let n=h;d(e.contains,{instancePath:t+`/contains`,parentData:e,parentDataProperty:`contains`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.maxProperties!==void 0){let n=e.maxProperties,r=h,i=h;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;if(h===i&&typeof n==`number`&&isFinite(n)&&(n<0||isNaN(n)))return d.errors=[{instancePath:t+`/maxProperties`,schemaPath:`#/definitions/nonNegativeInteger/minimum`,keyword:`minimum`,params:{comparison:`>=`,limit:0},message:`must be >= 0`}],!1;var g=r===h}else var g=!0;if(g){if(e.minProperties!==void 0){let n=h;s(e.minProperties,{instancePath:t+`/minProperties`,parentData:e,parentDataProperty:`minProperties`,rootData:p})||(m=m===null?s.errors:m.concat(s.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.required!==void 0){let n=e.required,r=h;if(h===h)if(Array.isArray(n)){var v=!0;let e=n.length;for(let r=0;r<e;r++){let e=h;if(typeof n[r]!=`string`)return d.errors=[{instancePath:t+`/required/`+r,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var v=e===h;if(!v)break}if(v){let e=n.length,r;if(e>1){let i={};for(;e--;){let a=n[e];if(typeof a==`string`){if(typeof i[a]==`number`)return r=i[a],d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1;i[a]=e}}}}}else return d.errors=[{instancePath:t+`/required`,schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.additionalProperties!==void 0){let n=h;d(e.additionalProperties,{instancePath:t+`/additionalProperties`,parentData:e,parentDataProperty:`additionalProperties`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.definitions!==void 0){let n=e.definitions,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/definitions/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/definitions`,schemaPath:`#/properties/definitions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.properties!==void 0){let n=e.properties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/properties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}else return d.errors=[{instancePath:t+`/properties`,schemaPath:`#/properties/properties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.patternProperties!==void 0){let n=e.patternProperties,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n)){for(let e in n){let n=h;if(h===n&&typeof e==`string`&&!o(e)){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames/format`,keyword:`format`,params:{format:`regex`},message:`must match format "regex"`,propertyName:e};m===null?m=[n]:m.push(n),h++}var y=n===h;if(!y){let n={instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/propertyNames`,keyword:`propertyNames`,params:{propertyName:e},message:`property name must be valid`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}}if(y)for(let e in n){let r=h;if(d(n[e],{instancePath:t+`/patternProperties/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length),r!==h)break}}else return d.errors=[{instancePath:t+`/patternProperties`,schemaPath:`#/properties/patternProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.dependencies!==void 0){let n=e.dependencies,r=h;if(h===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=h,a=h,o=!1,s=h;d(r,{instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),parentData:n,parentDataProperty:e,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var b=s===h;if(o||=b,!o){let n=h;if(h===h)if(Array.isArray(r)){var x=!0;let n=r.length;for(let i=0;i<n;i++){let n=h;if(typeof r[i]!=`string`){let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/`+i,schemaPath:`#/definitions/stringArray/items/type`,keyword:`type`,params:{type:`string`},message:`must be string`};m===null?m=[n]:m.push(n),h++}var x=n===h;if(!x)break}if(x){let n=r.length,i;if(n>1){let a={};for(;n--;){let o=r[n];if(typeof o==`string`){if(typeof a[o]==`number`){i=a[o];let r={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/uniqueItems`,keyword:`uniqueItems`,params:{i:n,j:i},message:`must NOT have duplicate items (items ## `+i+` and `+n+` are identical)`};m===null?m=[r]:m.push(r),h++;break}a[o]=n}}}}}else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/definitions/stringArray/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[n]:m.push(n),h++}var b=n===h;o||=b}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let n={instancePath:t+`/dependencies/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/dependencies/additionalProperties/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[n]:m.push(n),h++,d.errors=m,!1}if(i!==h)break}else return d.errors=[{instancePath:t+`/dependencies`,schemaPath:`#/properties/dependencies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var g=r===h}else var g=!0;if(g){if(e.propertyNames!==void 0){let n=h;d(e.propertyNames,{instancePath:t+`/propertyNames`,parentData:e,parentDataProperty:`propertyNames`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.enum!==void 0){let n=e.enum,r=h;if(h===r)if(Array.isArray(n)){if(n.length<1)return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`}],!1;{let e=n.length,r;if(e>1){outer0:for(;e--;)for(r=e;r--;)if(u(n[e],n[r]))return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`}],!1}}}else return d.errors=[{instancePath:t+`/enum`,schemaPath:`#/properties/enum/type`,keyword:`type`,params:{type:`array`},message:`must be array`}],!1;var g=r===h}else var g=!0;if(g){if(e.type!==void 0){let n=e.type,i=h,a=h,o=!1,s=h;if(!(n===`array`||n===`boolean`||n===`integer`||n===`null`||n===`number`||n===`object`||n===`string`)){let e={instancePath:t+`/type`,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var S=s===h;if(o||=S,!o){let e=h;if(h===e)if(Array.isArray(n))if(n.length<1){let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/minItems`,keyword:`minItems`,params:{limit:1},message:`must NOT have fewer than 1 items`};m===null?m=[e]:m.push(e),h++}else{var C=!0;let e=n.length;for(let i=0;i<e;i++){let e=n[i],a=h;if(!(e===`array`||e===`boolean`||e===`integer`||e===`null`||e===`number`||e===`object`||e===`string`)){let e={instancePath:t+`/type/`+i,schemaPath:`#/definitions/simpleTypes/enum`,keyword:`enum`,params:{allowedValues:r.enum},message:`must be equal to one of the allowed values`};m===null?m=[e]:m.push(e),h++}var C=a===h;if(!C)break}if(C){let e=n.length,r;if(e>1){outer1:for(;e--;)for(r=e;r--;)if(u(n[e],n[r])){let n={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/uniqueItems`,keyword:`uniqueItems`,params:{i:e,j:r},message:`must NOT have duplicate items (items ## `+r+` and `+e+` are identical)`};m===null?m=[n]:m.push(n),h++;break outer1}}}}else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf/1/type`,keyword:`type`,params:{type:`array`},message:`must be array`};m===null?m=[e]:m.push(e),h++}var S=e===h;o||=S}if(o)h=a,m!==null&&(a?m.length=a:m=null);else{let e={instancePath:t+`/type`,schemaPath:`#/properties/type/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return m===null?m=[e]:m.push(e),h++,d.errors=m,!1}var g=i===h}else var g=!0;if(g){if(e.format!==void 0){let n=h;if(typeof e.format!=`string`)return d.errors=[{instancePath:t+`/format`,schemaPath:`#/properties/format/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentMediaType!==void 0){let n=h;if(typeof e.contentMediaType!=`string`)return d.errors=[{instancePath:t+`/contentMediaType`,schemaPath:`#/properties/contentMediaType/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.contentEncoding!==void 0){let n=h;if(typeof e.contentEncoding!=`string`)return d.errors=[{instancePath:t+`/contentEncoding`,schemaPath:`#/properties/contentEncoding/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;var g=n===h}else var g=!0;if(g){if(e.if!==void 0){let n=h;d(e.if,{instancePath:t+`/if`,parentData:e,parentDataProperty:`if`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.then!==void 0){let n=h;d(e.then,{instancePath:t+`/then`,parentData:e,parentDataProperty:`then`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.else!==void 0){let n=h;d(e.else,{instancePath:t+`/else`,parentData:e,parentDataProperty:`else`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.allOf!==void 0){let n=h;l(e.allOf,{instancePath:t+`/allOf`,parentData:e,parentDataProperty:`allOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.anyOf!==void 0){let n=h;l(e.anyOf,{instancePath:t+`/anyOf`,parentData:e,parentDataProperty:`anyOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g){if(e.oneOf!==void 0){let n=h;l(e.oneOf,{instancePath:t+`/oneOf`,parentData:e,parentDataProperty:`oneOf`,rootData:p})||(m=m===null?l.errors:m.concat(l.errors),h=m.length);var g=n===h}else var g=!0;if(g)if(e.not!==void 0){let n=h;d(e.not,{instancePath:t+`/not`,parentData:e,parentDataProperty:`not`,rootData:p})||(m=m===null?d.errors:m.concat(d.errors),h=m.length);var g=n===h}else var g=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return d.errors=m,h===0}})),bp=o(((e,t)=>{t.exports={MergeError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Failed to merge "${e}" keyword schemas.`,this.schemas=t}},ResolverNotFoundError:class extends Error{constructor(e,t){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Resolver for "${e}" keyword not found.`,this.schemas=t}},InvalidOnConflictOptionError:class extends Error{constructor(e){super(),this.name=`JsonSchemaMergeError`,this.code=`JSON_SCHEMA_MERGE_ERROR`,this.message=`Invalid "onConflict" option: "${e}".`}}}})),xp=o(((e,t)=>{let{dequal:n}=hp(),{MergeError:r}=bp();function i(e){let t=e[0];for(let n=1;n<e.length;n++)t=t.filter(t=>e[n].includes(t));return t}function a(e,t,n){let a=i(t);if(a.length===0)throw new r(e,t);n[e]=a}function o(e,t,n){for(let e=0;e<t.length;e++)Array.isArray(t[e])||(t[e]=[t[e]]);let a=i(t);if(a.length===0)throw new r(e,t);a.length===1?n[e]=a[0]:n[e]=a}function s(e,t,n){let r=[];for(let e of t)for(let t of e)r.includes(t)||r.push(t);n[e]=r}function c(e,t,n){n[e]=Math.min(...t)}function l(e,t,n){n[e]=Math.max(...t)}function u(e,t,n){let r=(e,t)=>t?r(t,e%t):e,i=(e,t)=>e*t/r(e,t),a=1;for(let e of t)for(;e*a%1!=0;)a*=10;let o=t[0]*a;for(let e of t)o=i(o,e*a);n[e]=o/a}function d(e,t,i){let a=t[0];for(let i=1;i<t.length;i++)if(!n(t[i],a))throw new r(e,t);i[e]=a}function f(){}function p(e,t,n){for(let r of t)if(r===!1){n[e]=!1;return}n[e]=!0}function m(e,t,n){for(let r of t)if(r===!0){n[e]=!0;return}n[e]=!1}t.exports={arraysIntersection:a,hybridArraysIntersection:o,arraysUnion:s,minNumber:c,maxNumber:l,commonMultiple:u,allEqual:d,booleanAnd:p,booleanOr:m,skip:f}})),Sp=o(((e,t)=>{let{dequal:n}=hp(),r=xp(),i=bp(),a={$id:r.skip,type:r.hybridArraysIntersection,enum:r.arraysIntersection,minLength:r.maxNumber,maxLength:r.minNumber,minimum:r.maxNumber,maximum:r.minNumber,multipleOf:r.commonMultiple,exclusiveMinimum:r.maxNumber,exclusiveMaximum:r.minNumber,minItems:r.maxNumber,maxItems:r.minNumber,maxProperties:r.minNumber,minProperties:r.maxNumber,const:r.allEqual,default:r.allEqual,format:r.allEqual,required:r.arraysUnion,properties:p,patternProperties:m,additionalProperties:o,items:u,additionalItems:d,definitions:m,$defs:m,nullable:r.booleanAnd,oneOf:c,anyOf:c,allOf:r.arraysUnion,not:o,if:h,then:r.skip,else:r.skip,dependencies:g,dependentRequired:g,dependentSchemas:m,propertyNames:o,uniqueItems:r.booleanOr,contains:o};function o(e,t,n,r,i){n[e]=_(t,i)}function s(e){let t=[[]];for(let n of e){let e=[];for(let r of t)for(let t of n)e.push([...r,t]);t=e}return t}function c(e,t,n,r,a){if(t.length===1){n[e]=t[0];return}let o=s(t),c=[];for(let e of o)try{let t=_(e,a);t!==void 0&&c.push(t)}catch(e){if(e instanceof i.MergeError)continue;throw e}n[e]=c}function l(e,t){let{items:n,additionalItems:r}=e;return Array.isArray(n)?t<n.length?n[t]:r:n===void 0?r:n}function u(e,t,n,r,i){let a=0;for(let e of t)Array.isArray(e)&&(a=Math.max(a,e.length));if(a===0){n[e]=_(t,i);return}let o=[];for(let e=0;e<a;e++){let t=[];for(let n of r){let r=l(n,e);r!==void 0&&t.push(r)}o[e]=_(t,i)}n[e]=o}function d(e,t,n,r,i){let a=!1;for(let e of r)if(Array.isArray(e.items)){a=!0;break}if(!a){n[e]=_(t,i);return}let o=[];for(let e of r){let t=e.additionalItems;t===void 0&&!Array.isArray(e.items)&&(t=e.items),t!==void 0&&o.push(t)}n[e]=_(o,i)}function f(e,t){let{properties:n,patternProperties:r,additionalProperties:i}=e;if(n?.[t]!==void 0)return n[t];for(let e of Object.keys(r??{}))if(new RegExp(e).test(t))return r[e];return i}function p(e,t,n,r,i){let a={};for(let e of r){let t=e.properties??{};for(let n of Object.keys(t))if(a[n]===void 0){a[n]=[t[n]];for(let t of r){if(e===t)continue;let r=f(t,n);r!==void 0&&a[n].push(r)}}}let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function m(e,t,n,r,i){let a={};for(let e of t)for(let t of Object.keys(e))a[t]===void 0&&(a[t]=[]),a[t].push(e[t]);let o={};for(let e of Object.keys(a)){let t=a[e];o[e]=_(t,i)}n[e]=o}function h(e,t,n,r,i){for(let e=0;e<r.length;e++){let t={if:r[e].if,then:r[e].then,else:r[e].else};if(t.if!==void 0){if(n.if===void 0){n.if=t.if,t.then!==void 0&&(n.then=t.then),t.else!==void 0&&(n.else=t.else);continue}n.then!==void 0&&(n.then=_([n.then,t],i)),n.else!==void 0&&(n.else=_([n.else,t],i))}}}function g(e,t,n){let r={};for(let e of t)for(let t of Object.keys(e)){r[t]===void 0&&(r[t]=[]);let n=r[t];for(let r of e[t])n.includes(r)||n.push(r)}n[e]=r}function _(e,t){if(e.length===0)return{};if(e.length===1)return e[0];let n={},r={},i=!0;for(let t of e){if(t===!1)return!1;if(t!==!0){i=!1;for(let e of Object.keys(t))r[e]===void 0&&(r[e]=[]),r[e].push(t[e])}}if(i)return!0;for(let i of Object.keys(r)){let a=r[i];(t.resolvers[i]??t.defaultResolver)(i,a,n,e,t)}return n}function v(e,t,r,a,o){let s=o.onConflict??`throw`;if(t.length===1||s===`first`){r[e]=t[0];return}let c=!0;for(let e=1;e<t.length;e++)if(!n(t[e],t[0])){c=!1;break}if(c){r[e]=t[0];return}if(s===`throw`)throw new i.ResolverNotFoundError(e,t);if(s!==`skip`)throw new i.InvalidOnConflictOptionError(s)}function y(e,t={}){return t.defaultResolver===void 0&&(t.defaultResolver=v),t.resolvers={...a,...t.resolvers},_(e,t)}t.exports={mergeSchemas:y,keywordsResolvers:a,defaultResolver:v,...i}})),Cp=o(((e,t)=>{let{mergeSchemas:n}=Sp();function r(e){return n(e,{onConflict:`skip`})}t.exports=r})),wp=o(((e,t)=>{function n(e,t,n,r){let i=``;t.validatorSchemasIds.size>0?(i+=`const Validator = require('fast-json-stringify/lib/validator')
137
137
  `,i+=`const validatorState = ${JSON.stringify(r.getState())}\n`,i+=`const validator = Validator.restoreFromState(validatorState)
138
138
  `):i+=`const validator = null
139
139
  `;let{schema:a,...o}=n.getState();return`
@@ -145,7 +145,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
145
145
 
146
146
  ${i}
147
147
 
148
- module.exports = ${e.toString()}(validator, serializer)`}t.exports=n,t.exports.dependencies={Serializer:fd(),Validator:gp()}})),wp=o(((e,t)=>{let{RefResolver:n}=hp(),r=fd(),i=gp(),a=_p(),o=vp(),s=Sp(),c=/'/g,l=2e4,u=`default`,d=new Set([`floor`,`ceil`,`round`,`trunc`]),f=new Set([`default`,`json-stringify`]),p=0;function m(e,t){if(!o(e)){t=t?`"${t}" `:``;let e=o.errors[0],n=Error(`${t}schema is invalid: data${e.instancePath} ${e.message}`);throw n.errors=m.errors,n}}function h(e,t){let n=t.schema.$ref,r=n.indexOf(`#`);r===-1&&(r=n.length);let i=n.slice(0,r)||t.schemaId,o=n.slice(r)||`#`,s=e.refResolver.getSchema(i,o);if(s===null)throw Error(`Cannot find reference "${n}"`);let c=new a(s,i,o);return s.$ref===void 0?c:h(e,c)}function g(e,t){return new a(e.refResolver.getSchema(t,`#`),t,`#`)}function _(e,t){return e.$id&&e.$id.charAt(0)!==`#`?e.$id:t}function v(e,t){let n=t.getSchemaRef()||``;return n.startsWith(e.rootSchemaId)&&(n=n.replace(e.rootSchemaId,``)||`#`),n}function y(e,t){m(e),t||={};let o={functions:[],functionsCounter:0,functionsNamesBySchema:new Map,options:t,refResolver:new n,rootSchemaId:e.$id||`__fjs_root_${p++}`,validatorSchemasIds:new Set,mergedSchemasIds:new Map,recursiveSchemas:new Set,recursivePaths:new Set,buildingSet:new Set,uid:0},s=_(e,o.rootSchemaId);if(o.refResolver.hasSchema(s)||o.refResolver.addSchema(e,o.rootSchemaId),t.schema)for(let e in t.schema){let n=t.schema[e],r=_(n,e);o.refResolver.hasSchema(r)||(m(n,e),o.refResolver.addSchema(n,e))}if(t.rounding&&!d.has(t.rounding))throw Error(`Unsupported integer rounding method ${t.rounding}`);if(t.largeArrayMechanism)if(f.has(t.largeArrayMechanism))u=t.largeArrayMechanism;else throw Error(`Unsupported large array mechanism ${t.largeArrayMechanism}`);if(t.largeArraySize){let e=typeof t.largeArraySize,n;if(e===`string`&&Number.isFinite(n=Number.parseInt(t.largeArraySize,10)))l=n;else if(e===`number`&&Number.isInteger(t.largeArraySize))l=t.largeArraySize;else if(e===`bigint`)l=Number(t.largeArraySize);else throw Error(`Unsupported large array size. Expected integer-like, got ${typeof t.largeArraySize} with value ${t.largeArraySize}`)}let c=new a(e,o.rootSchemaId);P(o,c);let h=I(o,c,`input`),g=`
148
+ module.exports = ${e.toString()}(validator, serializer)`}t.exports=n,t.exports.dependencies={Serializer:pd(),Validator:_p()}})),Tp=o(((e,t)=>{let{RefResolver:n}=gp(),r=pd(),i=_p(),a=vp(),o=yp(),s=Cp(),c=/'/g,l=2e4,u=`default`,d=new Set([`floor`,`ceil`,`round`,`trunc`]),f=new Set([`default`,`json-stringify`]),p=0;function m(e,t){if(!o(e)){t=t?`"${t}" `:``;let e=o.errors[0],n=Error(`${t}schema is invalid: data${e.instancePath} ${e.message}`);throw n.errors=m.errors,n}}function h(e,t){let n=t.schema.$ref,r=n.indexOf(`#`);r===-1&&(r=n.length);let i=n.slice(0,r)||t.schemaId,o=n.slice(r)||`#`,s=e.refResolver.getSchema(i,o);if(s===null)throw Error(`Cannot find reference "${n}"`);let c=new a(s,i,o);return s.$ref===void 0?c:h(e,c)}function g(e,t){return new a(e.refResolver.getSchema(t,`#`),t,`#`)}function _(e,t){return e.$id&&e.$id.charAt(0)!==`#`?e.$id:t}function v(e,t){let n=t.getSchemaRef()||``;return n.startsWith(e.rootSchemaId)&&(n=n.replace(e.rootSchemaId,``)||`#`),n}function y(e,t){m(e),t||={};let o={functions:[],functionsCounter:0,functionsNamesBySchema:new Map,options:t,refResolver:new n,rootSchemaId:e.$id||`__fjs_root_${p++}`,validatorSchemasIds:new Set,mergedSchemasIds:new Map,recursiveSchemas:new Set,recursivePaths:new Set,buildingSet:new Set,uid:0},s=_(e,o.rootSchemaId);if(o.refResolver.hasSchema(s)||o.refResolver.addSchema(e,o.rootSchemaId),t.schema)for(let e in t.schema){let n=t.schema[e],r=_(n,e);o.refResolver.hasSchema(r)||(m(n,e),o.refResolver.addSchema(n,e))}if(t.rounding&&!d.has(t.rounding))throw Error(`Unsupported integer rounding method ${t.rounding}`);if(t.largeArrayMechanism)if(f.has(t.largeArrayMechanism))u=t.largeArrayMechanism;else throw Error(`Unsupported large array mechanism ${t.largeArrayMechanism}`);if(t.largeArraySize){let e=typeof t.largeArraySize,n;if(e===`string`&&Number.isFinite(n=Number.parseInt(t.largeArraySize,10)))l=n;else if(e===`number`&&Number.isInteger(t.largeArraySize))l=t.largeArraySize;else if(e===`bigint`)l=Number(t.largeArraySize);else throw Error(`Unsupported large array size. Expected integer-like, got ${typeof t.largeArraySize} with value ${t.largeArraySize}`)}let c=new a(e,o.rootSchemaId);P(o,c);let h=I(o,c,`input`),g=`
149
149
 
150
150
  const {
151
151
  asString,
@@ -185,7 +185,7 @@ const asInteger = serializer.asInteger.bind(serializer)
185
185
  ${o.functions.join(`
186
186
  `)}
187
187
  return main
188
- `;let v=new r(t),y=new i(t.ajv);for(let e of o.validatorSchemasIds){let t=o.refResolver.getSchema(e);y.addSchema(t,e);let n=o.refResolver.getSchemaDependencies(e);for(let[e,t]of Object.entries(n))y.addSchema(t,e)}if(t.debugMode&&(t.mode=`debug`),t.mode===`debug`)return{validator:y,serializer:v,code:`validator\nserializer\n${g}`,ajv:y.ajv};let b=Function(`validator`,`serializer`,g);return t.mode===`standalone`?Cp()(b,o,v,y):b(y,v)}let b=[`properties`,`required`,`additionalProperties`,`patternProperties`,`maxProperties`,`minProperties`,`dependencies`],x=[`items`,`additionalItems`,`maxItems`,`minItems`,`uniqueItems`,`contains`],S=[`maxLength`,`minLength`,`pattern`],C=[`multipleOf`,`maximum`,`exclusiveMaximum`,`minimum`,`exclusiveMinimum`];function w(e){for(let t of b)if(t in e)return`object`;for(let t of x)if(t in e)return`array`;for(let t of S)if(t in e)return`string`;for(let t of C)if(t in e)return`number`;return e.type}function T(e,t,n,r){let i=t.schema,a=Object.keys(i.properties||{}),o=`
188
+ `;let v=new r(t),y=new i(t.ajv);for(let e of o.validatorSchemasIds){let t=o.refResolver.getSchema(e);y.addSchema(t,e);let n=o.refResolver.getSchemaDependencies(e);for(let[e,t]of Object.entries(n))y.addSchema(t,e)}if(t.debugMode&&(t.mode=`debug`),t.mode===`debug`)return{validator:y,serializer:v,code:`validator\nserializer\n${g}`,ajv:y.ajv};let b=Function(`validator`,`serializer`,g);return t.mode===`standalone`?wp()(b,o,v,y):b(y,v)}let b=[`properties`,`required`,`additionalProperties`,`patternProperties`,`maxProperties`,`minProperties`,`dependencies`],x=[`items`,`additionalItems`,`maxItems`,`minItems`,`uniqueItems`,`contains`],S=[`maxLength`,`minLength`,`pattern`],C=[`multipleOf`,`maximum`,`exclusiveMaximum`,`minimum`,`exclusiveMinimum`];function w(e){for(let t of b)if(t in e)return`object`;for(let t of x)if(t in e)return`array`;for(let t of S)if(t in e)return`string`;for(let t of C)if(t in e)return`number`;return e.type}function T(e,t,n,r){let i=t.schema,a=Object.keys(i.properties||{}),o=`
189
189
  for (const key of Object.keys(${r})) {
190
190
  if (
191
191
  ${a.length>0?a.map(e=>`key === ${JSON.stringify(e)}`).join(` || `)+` ||`:``}
@@ -427,11 +427,11 @@ const asInteger = serializer.asInteger.bind(serializer)
427
427
  } else {
428
428
  `),r.const===void 0?Array.isArray(a)?i+=N(e,t,n):i+=te(e,t,n):i+=ne(t,n),o&&(i+=`
429
429
  }
430
- `),i}t.exports=y,t.exports.default=y,t.exports.build=y,t.exports.validLargeArrayMechanisms=f,t.exports.restore=function({code:e,validator:t,serializer:n}){return Function.apply(null,[`validator`,`serializer`,e]).apply(null,[t,n])}})),Tp=o(((e,t)=>{let n=wp();function r(){return function(e,t){let n=Object.assign({},t,{schema:e});return i.bind(null,n)}}function i(e,{schema:t}){return e.schema&&t.$id&&e.schema[t.$id]&&(e.schema={...e.schema},delete e.schema[t.$id]),n(t,e)}function a(e={readMode:!0}){if(e.readMode===!0&&typeof e.restoreFunction!=`function`)throw Error(`You must provide a function for the restoreFunction-option when readMode ON`);if(e.readMode!==!0&&typeof e.storeFunction!=`function`)throw Error(`You must provide a function for the storeFunction-option when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=r();return function(n,r={}){r.mode=`standalone`;let i=t(n,r);return function(t){let n=i(t);return e.storeFunction(t,n),Function(n)}}}t.exports.SerializerSelector=r,t.exports.StandaloneSerializer=a,t.exports.default=a})),Ep=o(((e,t)=>{let{SerializerSelector:n,StandaloneSerializer:r}=Tp();t.exports=n,t.exports.default=n,t.exports.SerializerSelector=n,t.exports.StandaloneSerializer=r})),Dp=o(((e,t)=>{let{buildSchemas:n}=dd();function r(e,t){if(e)return new i(e,t);let r=Object.assign({buildValidator:null,buildSerializer:null},t?.compilersFactory);return r.buildValidator||=pp()(),r.buildSerializer||=Ep()(),new i(void 0,{bucket:t&&t.bucket||n,compilersFactory:r,isCustomValidatorCompiler:typeof t?.compilersFactory?.buildValidator==`function`,isCustomSerializerCompiler:typeof t?.compilersFactory?.buildValidator==`function`})}var i=class{constructor(e,t){this.opts=t||e?.opts,this.addedSchemas=!1,this.compilersFactory=this.opts.compilersFactory,e?(this.schemaBucket=this.opts.bucket(e.getSchemas()),this.validatorCompiler=e.getValidatorCompiler(),this.serializerCompiler=e.getSerializerCompiler(),this.isCustomValidatorCompiler=e.isCustomValidatorCompiler,this.isCustomSerializerCompiler=e.isCustomSerializerCompiler,this.parent=e):(this.schemaBucket=this.opts.bucket(),this.isCustomValidatorCompiler=this.opts.isCustomValidatorCompiler||!1,this.isCustomSerializerCompiler=this.opts.isCustomSerializerCompiler||!1)}add(e){return this.addedSchemas=!0,this.schemaBucket.add(e)}getSchema(e){return this.schemaBucket.getSchema(e)}getSchemas(){return this.schemaBucket.getSchemas()}setValidatorCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildValidator:()=>e}),this.validatorCompiler=e,this.isCustomValidatorCompiler=!0}setSerializerCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildSerializer:()=>e}),this.serializerCompiler=e,this.isCustomSerializerCompiler=!0}getValidatorCompiler(){return this.validatorCompiler||this.parent&&this.parent.getValidatorCompiler()}getSerializerCompiler(){return this.serializerCompiler||this.parent&&this.parent.getSerializerCompiler()}getSerializerBuilder(){return this.compilersFactory.buildSerializer||this.parent&&this.parent.getSerializerBuilder()}getValidatorBuilder(){return this.compilersFactory.buildValidator||this.parent&&this.parent.getValidatorBuilder()}setupValidator(e){this.validatorCompiler!==void 0&&!this.addedSchemas||(this.validatorCompiler=this.getValidatorBuilder()(this.schemaBucket.getSchemas(),e.ajv))}setupSerializer(e){this.serializerCompiler!==void 0&&!this.addedSchemas||(this.serializerCompiler=this.getSerializerBuilder()(this.schemaBucket.getSchemas(),e.serializerOpts))}};i.buildSchemaController=r,t.exports=i})),Op=o(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),kp=o(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),Ap=o(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=Op(),a=kp();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),jp=o(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),Mp=o(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),Np=o(((e,t)=>{let n=kp(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=Op(),{safeRe:a,t:o}=Ap(),s=jp(),{compareIdentifiers:c}=Mp();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Pp=o(((e,t)=>{let n=Np();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),Fp=o(((e,t)=>{let n=Pp();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),Ip=o(((e,t)=>{let n=Pp();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),Lp=o(((e,t)=>{let n=Np();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),Rp=o(((e,t)=>{let n=Pp();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),zp=o(((e,t)=>{let n=Np();t.exports=(e,t)=>new n(e,t).major})),Bp=o(((e,t)=>{let n=Np();t.exports=(e,t)=>new n(e,t).minor})),Vp=o(((e,t)=>{let n=Np();t.exports=(e,t)=>new n(e,t).patch})),Hp=o(((e,t)=>{let n=Pp();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),Up=o(((e,t)=>{let n=Np();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),Wp=o(((e,t)=>{let n=Up();t.exports=(e,t,r)=>n(t,e,r)})),Gp=o(((e,t)=>{let n=Up();t.exports=(e,t)=>n(e,t,!0)})),Kp=o(((e,t)=>{let n=Np();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),qp=o(((e,t)=>{let n=Kp();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),Jp=o(((e,t)=>{let n=Kp();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),Yp=o(((e,t)=>{let n=Up();t.exports=(e,t,r)=>n(e,t,r)>0})),Xp=o(((e,t)=>{let n=Up();t.exports=(e,t,r)=>n(e,t,r)<0})),Zp=o(((e,t)=>{let n=Up();t.exports=(e,t,r)=>n(e,t,r)===0})),Qp=o(((e,t)=>{let n=Up();t.exports=(e,t,r)=>n(e,t,r)!==0})),$p=o(((e,t)=>{let n=Up();t.exports=(e,t,r)=>n(e,t,r)>=0})),em=o(((e,t)=>{let n=Up();t.exports=(e,t,r)=>n(e,t,r)<=0})),tm=o(((e,t)=>{let n=Zp(),r=Qp(),i=Yp(),a=$p(),o=Xp(),s=em();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),nm=o(((e,t)=>{let n=Np(),r=Pp(),{safeRe:i,t:a}=Ap();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),rm=o(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),im=o(((e,t)=>{let n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,O(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k(this.set[t],e,this.options))return!0;return!1}};let r=new(rm()),i=jp(),a=am(),o=kp(),s=Np(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=Ap(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=Op(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=S(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=w(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(` `),x=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},S=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(` `),C=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},w=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>T(e,t)).join(` `)),T=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),O=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),k=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),am=o(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=jp(),{safeRe:i,t:a}=Ap(),o=tm(),s=kp(),c=Np(),l=im()})),om=o(((e,t)=>{let n=im();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),sm=o(((e,t)=>{let n=im();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),cm=o(((e,t)=>{let n=Np(),r=im();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),lm=o(((e,t)=>{let n=Np(),r=im();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),um=o(((e,t)=>{let n=Np(),r=im(),i=Yp();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),dm=o(((e,t)=>{let n=im();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),fm=o(((e,t)=>{let n=Np(),r=am(),{ANY:i}=r,a=im(),o=om(),s=Yp(),c=Xp(),l=em(),u=$p();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),pm=o(((e,t)=>{let n=fm();t.exports=(e,t,r)=>n(e,t,`>`,r)})),mm=o(((e,t)=>{let n=fm();t.exports=(e,t,r)=>n(e,t,`<`,r)})),hm=o(((e,t)=>{let n=im();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),gm=o(((e,t)=>{let n=om(),r=Up();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),_m=o(((e,t)=>{let n=im(),r=am(),{ANY:i}=r,a=om(),o=Up(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),vm=o(((e,t)=>{let n=Ap(),r=Op(),i=Np(),a=Mp();t.exports={parse:Pp(),valid:Fp(),clean:Ip(),inc:Lp(),diff:Rp(),major:zp(),minor:Bp(),patch:Vp(),prerelease:Hp(),compare:Up(),rcompare:Wp(),compareLoose:Gp(),compareBuild:Kp(),sort:qp(),rsort:Jp(),gt:Yp(),lt:Xp(),eq:Zp(),neq:Qp(),gte:$p(),lte:em(),cmp:tm(),coerce:nm(),Comparator:am(),Range:im(),satisfies:om(),toComparators:sm(),maxSatisfying:cm(),minSatisfying:lm(),minVersion:um(),validRange:dm(),outside:fm(),gtr:pm(),ltr:mm(),intersects:hm(),simplifyRange:gm(),subset:_m(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}})),ym=o(((e,t)=>{let n=vm(),r=require(`node:assert`),i=Symbol.for(`registered-plugin`),{kTestInternals:a}=yu(),{exist:o,existReply:s,existRequest:c}=hd(),{FST_ERR_PLUGIN_VERSION_MISMATCH:l,FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:u,FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:d}=Su(),f=/-(?:rc|pre|alpha).+$/u;function p(e){return e[Symbol.for(`plugin-meta`)]}function m(e){let t=g(e);if(t)return t;let n=require.cache;if(n){let t=Object.keys(n);for(let r=0;r<t.length;r++){let i=t[r];if(n[i].exports===e)return i}}return e.name?e.name:null}function h(e){return e.toString().split(`
431
- `,2).map(e=>e.trim()).join(` -- `)}function g(e){return e[Symbol.for(`fastify.display-name`)]}function _(e){return!!e[Symbol.for(`skip-override`)]}function v(e){let t=p(e);if(!t)return;let n=t.dependencies;n&&(r(Array.isArray(n),`The dependencies should be an array of strings`),n.forEach(e=>{r(this[i].indexOf(e)>-1,`The dependency '${e}' of plugin '${t.name}' is not registered`)}))}function y(e){let t=p(e);if(!t)return;let{decorators:n,name:r}=t;n&&(n.fastify&&x(this,`Fastify`,n.fastify,r),n.reply&&x(this,`Reply`,n.reply,r),n.request&&x(this,`Request`,n.request,r))}let b={Fastify:o,Request:c,Reply:s};function x(e,t,n,i){r(Array.isArray(n),`The decorators should be an array of strings`),n.forEach(n=>{let r=typeof i==`string`?` required by '${i}'`:``;if(!b[t].call(e,n))throw new u(n,r,t)})}function S(e){let t=p(e);if(t?.fastify==null)return;let r=t.fastify,i=f.test(this.version);if(!(i===!0&&n.gt(this.version,n.coerce(r))===!0)&&r&&n.satisfies(this.version,r,{includePrerelease:i})===!1)throw new l(t.name,r,this.version)}function C(e){let t=p(e);if(!t)return;let n=t.name;if(n)return this[i].push(n),n}function w(e,t){if(e.constructor.name===`AsyncFunction`&&e.length===3)throw new d(t)}function T(e){let t=C.call(this,e)||m(e);return w.call(this,e,t),S.call(this,e),y.call(this,e),v.call(this,e),_(e)}t.exports={getPluginName:m,getFuncPreview:h,kRegisteredPlugins:i,getDisplayName:g,registerPlugin:T},t.exports[a]={shouldSkipOverride:_,getMeta:p,checkDecorators:y,checkDependencies:v}})),bm=o(((e,t)=>{function n(e,t){let n=t||i();return e?a(e,n):n}function r(e,t){return e.genReqId(t)}function i(){let e=0;return function(){return e=e+1&2147483647,`req-${e.toString(36)}`}}function a(e,t){return function(n){return n.headers[e]||t(n)}}t.exports={getGenReqId:r,reqIdGenFactory:n}})),xm=o(((e,t)=>{var n=12,r=0,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function a(e){var t=e.indexOf(`%`);if(t===-1)return e;for(var a=e.length,o=``,c=0,l=0,u=t,d=n;t>-1&&t<a;){var f=s(e[t+1],4)|s(e[t+2],0),p=i[f];if(d=i[256+d+p],l=l<<6|f&i[364+p],d===n)o+=e.slice(c,u),o+=l<=65535?String.fromCharCode(l):String.fromCharCode(55232+(l>>10),56320+(l&1023)),l=0,c=t+3,t=u=e.indexOf(`%`,c);else if(d===r)return null;else{if(t+=3,t<a&&e.charCodeAt(t)===37)continue;return null}}return o+e.slice(c)}var o={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function s(e,t){var n=o[e];return n===void 0?255:n<<t}t.exports=a})),Sm=o(((e,t)=>{let n=xm(),r=/\+/g,i=function(){};i.prototype=Object.create(null);function a(e){let t=new i;if(typeof e!=`string`)return t;let a=e.length,o=``,s=``,c=-1,l=-1,u=!1,d=!1,f=!1,p=!1,m=!1,h=0;for(let i=0;i<a+1;i++)if(h=i===a?38:e.charCodeAt(i),h===38){if(m=l>c,m||(l=i),o=e.slice(c+1,l),m||o.length>0){f&&(o=o.replace(r,` `)),u&&(o=n(o)||o),m&&(s=e.slice(l+1,i),p&&(s=s.replace(r,` `)),d&&(s=n(s)||s));let a=t[o];a===void 0?t[o]=s:a.pop?a.push(s):t[o]=[a,s]}s=``,c=i,l=i,u=!1,d=!1,f=!1,p=!1}else h===61?l<=c?l=i:d=!0:h===43?l>c?p=!0:f=!0:h===37&&(l>c?d=!0:u=!0);return t}t.exports=a})),Cm=o(((e,t)=>{let n=Array.from({length:256},(e,t)=>`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase()),r=new Int8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0]);function i(e){let t=e.length;if(t===0)return``;let i=``,a=0,o=0;outer:for(;o<t;o++){let s=e.charCodeAt(o);for(;s<128;){if(r[s]!==1&&(a<o&&(i+=e.slice(a,o)),a=o+1,i+=n[s]),++o===t)break outer;s=e.charCodeAt(o)}if(a<o&&(i+=e.slice(a,o)),s<2048){a=o+1,i+=n[192|s>>6]+n[128|s&63];continue}if(s<55296||s>=57344){a=o+1,i+=n[224|s>>12]+n[128|s>>6&63]+n[128|s&63];continue}if(++o,o>=t)throw Error(`URI malformed`);let c=e.charCodeAt(o)&1023;a=o+1,s=65536+((s&1023)<<10|c),i+=n[240|s>>18]+n[128|s>>12&63]+n[128|s>>6&63]+n[128|s&63]}return a===0?e:a<t?i+e.slice(a):i}t.exports={encodeString:i}})),wm=o(((e,t)=>{let{encodeString:n}=Cm();function r(e){let t=typeof e;return t===`string`?n(e):t===`bigint`?e.toString():t===`boolean`?e?`true`:`false`:t===`number`&&Number.isFinite(e)?e<1e21?``+e:n(``+e):``}function i(e){let t=``;if(typeof e!=`object`||!e)return t;let i=Object.keys(e),a=i.length,o=0;for(let s=0;s<a;s++){let a=i[s],c=e[a],l=n(a)+`=`;if(s&&(t+=`&`),Array.isArray(c)){o=c.length;for(let e=0;e<o;e++)e&&(t+=`&`),t+=l,t+=r(c[e])}else t+=l,t+=r(c)}return t}t.exports=i})),Tm=o(((e,t)=>{let n=Sm(),r=wm(),i={parse:n,stringify:r};t.exports=i,t.exports.default=i,t.exports.parse=n,t.exports.stringify=r})),Em=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),Dm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0,(function(e){e[e.ROOT=0]=`ROOT`,e[e.GROUP=1]=`GROUP`,e[e.POSITION=2]=`POSITION`,e[e.SET=3]=`SET`,e[e.RANGE=4]=`RANGE`,e[e.REPETITION=5]=`REPETITION`,e[e.REFERENCE=6]=`REFERENCE`,e[e.CHAR=7]=`CHAR`})(e.types||={})})),Om=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),km=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),n(Em(),e),n(Dm(),e),n(Om(),e)})),Am=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.anyChar=e.notWhitespace=e.whitespace=e.notInts=e.ints=e.notWords=e.words=void 0;let t=km(),n=()=>[{type:t.types.RANGE,from:48,to:57}],r=()=>[{type:t.types.CHAR,value:95},{type:t.types.RANGE,from:97,to:122},{type:t.types.RANGE,from:65,to:90},{type:t.types.RANGE,from:48,to:57}],i=()=>[{type:t.types.CHAR,value:9},{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:11},{type:t.types.CHAR,value:12},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:32},{type:t.types.CHAR,value:160},{type:t.types.CHAR,value:5760},{type:t.types.RANGE,from:8192,to:8202},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233},{type:t.types.CHAR,value:8239},{type:t.types.CHAR,value:8287},{type:t.types.CHAR,value:12288},{type:t.types.CHAR,value:65279}],a=()=>[{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233}];e.words=()=>({type:t.types.SET,set:r(),not:!1}),e.notWords=()=>({type:t.types.SET,set:r(),not:!0}),e.ints=()=>({type:t.types.SET,set:n(),not:!1}),e.notInts=()=>({type:t.types.SET,set:n(),not:!0}),e.whitespace=()=>({type:t.types.SET,set:i(),not:!1}),e.notWhitespace=()=>({type:t.types.SET,set:i(),not:!0}),e.anyChar=()=>({type:t.types.SET,set:a(),not:!0})})),jm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizeClass=e.strToChars=void 0;let i=km(),a=r(Am());e.strToChars=e=>e.replace(/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g,(e,t,n,r,i,a,o)=>{if(n)return e;let s=t?8:r?parseInt(r,16):i?parseInt(i,16):a?`@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?`.indexOf(a):{0:0,t:9,n:10,v:11,f:12,r:13}[o],c=String.fromCharCode(s);return/[[\]{}^$.|?*+()]/.test(c)?`\\${c}`:c}),e.tokenizeClass=(e,t)=>{let n=[],r,o,s=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;for(;(r=s.exec(e))!==null;){let e=(r[1]&&a.words())??(r[2]&&a.ints())??(r[3]&&a.whitespace())??(r[4]&&a.notWords())??(r[5]&&a.notInts())??(r[6]&&a.notWhitespace())??(r[7]&&{type:i.types.RANGE,from:(r[8]||r[9]).charCodeAt(0),to:(o=r[10]).charCodeAt(o.length-1)})??((o=r[16])&&{type:i.types.CHAR,value:o.charCodeAt(0)});if(e)n.push(e);else return[n,s.lastIndex]}throw SyntaxError(`Invalid regular expression: /${t}/: Unterminated character class`)}})),Mm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizer=void 0;let i=r(jm()),a=km(),o=r(Am()),s=/^[a-zA-Z_$]$/i,c=/^[a-zA-Z0-9_$]$/i,l=/\d/;e.tokenizer=e=>{let t=0,n,r={type:a.types.ROOT,stack:[]},d=r,f=r.stack,p=[],m=[],h=0,g=t=>{throw SyntaxError(`Invalid regular expression: /${e}/: Nothing to repeat at column ${t-1}`)},_=i.strToChars(e);for(;t<_.length;)switch(n=_[t++]){case`\\`:if(t===_.length)throw SyntaxError(`Invalid regular expression: /${e}/: \\ at end of pattern`);switch(n=_[t++]){case`b`:f.push({type:a.types.POSITION,value:`b`});break;case`B`:f.push({type:a.types.POSITION,value:`B`});break;case`w`:f.push(o.words());break;case`W`:f.push(o.notWords());break;case`d`:f.push(o.ints());break;case`D`:f.push(o.notInts());break;case`s`:f.push(o.whitespace());break;case`S`:f.push(o.notWhitespace());break;default:if(l.test(n)){let e=n;for(;t<_.length&&l.test(_[t]);)e+=_[t++];let r=parseInt(e,10),i={type:a.types.REFERENCE,value:r};f.push(i),m.push({reference:i,stack:f,index:f.length-1})}else f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}break;case`^`:f.push({type:a.types.POSITION,value:`^`});break;case`$`:f.push({type:a.types.POSITION,value:`$`});break;case`[`:{let n;_[t]===`^`?(n=!0,t++):n=!1;let r=i.tokenizeClass(_.slice(t),e);t+=r[1],f.push({type:a.types.SET,set:r[0],not:n});break}case`.`:f.push(o.anyChar());break;case`(`:{let r={type:a.types.GROUP,stack:[],remember:!0};if(_[t]===`?`)if(n=_[t+1],t+=2,n===`=`)r.followedBy=!0,r.remember=!1;else if(n===`!`)r.notFollowedBy=!0,r.remember=!1;else if(n===`<`){let n=``;if(s.test(_[t]))n+=_[t],t++;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);for(;t<_.length&&c.test(_[t]);)n+=_[t],t++;if(!n)throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);if(_[t]!==`>`)throw SyntaxError(`Invalid regular expression: /${e}/: Unclosed capture group name, expected '>', found '${_[t]}' at column ${t+1}`);r.name=n,t++}else if(n===`:`)r.remember=!1;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid group, character '${n}' after '?' at column ${t-1}`);else h+=1;f.push(r),p.push(d),d=r,f=r.stack;break}case`)`:if(p.length===0)throw SyntaxError(`Invalid regular expression: /${e}/: Unmatched ) at column ${t-1}`);d=p.pop(),f=d.options?d.options[d.options.length-1]:d.stack;break;case`|`:{d.options||(d.options=[d.stack],delete d.stack);let e=[];d.options.push(e),f=e;break}case`{`:{let e=/^(\d+)(,(\d+)?)?\}/.exec(_.slice(t)),n,r;e===null?f.push({type:a.types.CHAR,value:123}):(f.length===0&&g(t),n=parseInt(e[1],10),r=e[2]?e[3]?parseInt(e[3],10):1/0:n,t+=e[0].length,f.push({type:a.types.REPETITION,min:n,max:r,value:f.pop()}));break}case`?`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1,value:f.pop()});break;case`+`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:1,max:1/0,value:f.pop()});break;case`*`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1/0,value:f.pop()});break;default:f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}if(p.length!==0)throw SyntaxError(`Invalid regular expression: /${e}/: Unterminated group`);return u(m,h),r};function u(e,t){for(let n of e.reverse())if(t<n.reference.value){n.reference.type=a.types.CHAR;let e=n.reference.value.toString();if(n.reference.value=parseInt(e,8),!/^[0-7]+$/.test(e)){let t=0;for(;e[t]!==`8`&&e[t]!==`9`;)t+=1;if(t===0?(n.reference.value=e.charCodeAt(0),t+=1):n.reference.value=parseInt(e.slice(0,t),8),e.length>t){let r=n.stack.splice(n.index+1);for(let r of e.slice(t))n.stack.push({type:a.types.CHAR,value:r.charCodeAt(0)});n.stack.push(...r)}}}}})),Nm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.NOTANYCHAR=e.WHITESPACE=e.WORDS=e.INTS=void 0;let i=r(Am()),a=km();function o(e){let t={},n=0;for(let r of e)r.type===a.types.CHAR&&(t[r.value]=!0),r.type===a.types.RANGE&&(t[`${r.from}-${r.to}`]=!0),n+=1;return{lookup:()=>Object.assign({},t),len:n}}e.INTS=o(i.ints().set),e.WORDS=o(i.words().set),e.WHITESPACE=o(i.whitespace().set),e.NOTANYCHAR=o(i.anyChar().set)})),Pm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.writeSetTokens=e.setChar=void 0;let i=km(),a=r(Nm());function o(e){return e===94?`\\^`:e===92?`\\\\`:e===93?`\\]`:e===45?`\\-`:String.fromCharCode(e)}e.setChar=o;function s(e,{lookup:t,len:n}){if(n!==e.length)return!1;let r=t();for(let t of e){if(t.type===i.types.SET)return!1;let e=t.type===i.types.CHAR?t.value:`${t.from}-${t.to}`;if(r[e])r[e]=!1;else return!1}return!0}function c(e,t=!1){if(s(e.set,a.INTS))return e.not?`\\D`:`\\d`;if(s(e.set,a.WORDS))return e.not?`\\W`:`\\w`;if(e.not&&s(e.set,a.NOTANYCHAR))return`.`;if(s(e.set,a.WHITESPACE))return e.not?`\\S`:`\\s`;let n=``;for(let t=0;t<e.set.length;t++){let r=e.set[t];n+=l(r)}let r=`${e.not?`^`:``}${n}`;return t?r:`[${r}]`}e.writeSetTokens=c;function l(e){return e.type===i.types.CHAR?o(e.value):e.type===i.types.RANGE?`${o(e.from)}-${o(e.to)}`:c(e,!0)}})),Fm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconstruct=void 0;let t=km(),n=Pm(),r=t=>t.map(e.reconstruct).join(``),i=e=>{if(`options`in e)return e.options.map(r).join(`|`);if(`stack`in e)return r(e.stack);throw Error(`options or stack must be Root or Group token`)};e.reconstruct=r=>{switch(r.type){case t.types.ROOT:return i(r);case t.types.CHAR:{let e=String.fromCharCode(r.value);return(/[[\\{}$^.|?*+()]/.test(e)?`\\`:``)+e}case t.types.POSITION:return r.value===`^`||r.value===`$`?r.value:`\\${r.value}`;case t.types.REFERENCE:return`\\${r.value}`;case t.types.SET:return n.writeSetTokens(r);case t.types.GROUP:return`(${r.name?`?<${r.name}>`:r.remember?``:r.followedBy?`?=`:r.notFollowedBy?`?!`:`?:`}${i(r)})`;case t.types.REPETITION:{let{min:t,max:n}=r,i;return i=t===0&&n===1?`?`:t===1&&n===1/0?`+`:t===0&&n===1/0?`*`:n===1/0?`{${t},}`:t===n?`{${t}}`:`{${t},${n}}`,`${e.reconstruct(r.value)}${i}`}case t.types.RANGE:return`${n.setChar(r.from)}-${n.setChar(r.to)}`;default:throw Error(`Invalid token type ${r}`)}}})),Im=o(((e,t)=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__exportStar||function(e,t){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0;let i=km();Object.defineProperty(e,`types`,{enumerable:!0,get:function(){return i.types}}),r(Mm(),e),r(Fm(),e);let a=Mm(),o=Fm();r(km(),e),e.default=a.tokenizer,t.exports=a.tokenizer,t.exports.types=i.types,t.exports.reconstruct=o.reconstruct})),Lm=o(((e,t)=>{let n=Im(),r=n.types;function i(e,t){t||={};let i=t.limit===void 0?25:t.limit;a(e)?e=e.source:typeof e!=`string`&&(e=String(e));try{e=n(e)}catch{return!1}let o=0;return(function e(t,n){let a,s,c;if(t.type===r.REPETITION&&(n++,o++,n>1||o>i))return!1;if(t.options){for(a=0,c=t.options.length;a<c;a++)if(s=e({stack:t.options[a]},n),!s)return!1}let l=t.stack||t.value?.stack;if(!l)return!0;for(a=0;a<l.length;a++)if(s=e(l[a],n),!s)return!1;return!0})(e,0)}function a(e){return{}.toString.call(e)===`[object RegExp]`}t.exports=i,t.exports.default=i,t.exports.safeRegex=i})),Rm=o(((e,t)=>{t.exports={name:`__fmw_internal_strategy_merged_tree_http_method__`,storage:function(){let e=new Map;return{get:t=>e.get(t)||null,set:(t,n)=>{e.set(t,n)}}},deriveConstraint:e=>e.method,mustMatchWhenDerived:!0}})),zm=o(((e,t)=>{let n=Ld(),r=Rm(),i=Symbol(`treeData`);function a(e,t=``){let n=``,r=Object.keys(e);for(let o=0;o<r.length;o++){let s=r[o],c=e[s],l=o===r.length-1,u=l?`└── `:`├── `,d=l?` `:`│ `,f=(c[i]||``).replaceAll(`
430
+ `),i}t.exports=y,t.exports.default=y,t.exports.build=y,t.exports.validLargeArrayMechanisms=f,t.exports.restore=function({code:e,validator:t,serializer:n}){return Function.apply(null,[`validator`,`serializer`,e]).apply(null,[t,n])}})),Ep=o(((e,t)=>{let n=Tp();function r(){return function(e,t){let n=Object.assign({},t,{schema:e});return i.bind(null,n)}}function i(e,{schema:t}){return e.schema&&t.$id&&e.schema[t.$id]&&(e.schema={...e.schema},delete e.schema[t.$id]),n(t,e)}function a(e={readMode:!0}){if(e.readMode===!0&&typeof e.restoreFunction!=`function`)throw Error(`You must provide a function for the restoreFunction-option when readMode ON`);if(e.readMode!==!0&&typeof e.storeFunction!=`function`)throw Error(`You must provide a function for the storeFunction-option when readMode OFF`);if(e.readMode===!0)return function(){return function(t){return e.restoreFunction(t)}};let t=r();return function(n,r={}){r.mode=`standalone`;let i=t(n,r);return function(t){let n=i(t);return e.storeFunction(t,n),Function(n)}}}t.exports.SerializerSelector=r,t.exports.StandaloneSerializer=a,t.exports.default=a})),Dp=o(((e,t)=>{let{SerializerSelector:n,StandaloneSerializer:r}=Ep();t.exports=n,t.exports.default=n,t.exports.SerializerSelector=n,t.exports.StandaloneSerializer=r})),Op=o(((e,t)=>{let{buildSchemas:n}=fd();function r(e,t){if(e)return new i(e,t);let r=Object.assign({buildValidator:null,buildSerializer:null},t?.compilersFactory);return r.buildValidator||=mp()(),r.buildSerializer||=Dp()(),new i(void 0,{bucket:t&&t.bucket||n,compilersFactory:r,isCustomValidatorCompiler:typeof t?.compilersFactory?.buildValidator==`function`,isCustomSerializerCompiler:typeof t?.compilersFactory?.buildValidator==`function`})}var i=class{constructor(e,t){this.opts=t||e?.opts,this.addedSchemas=!1,this.compilersFactory=this.opts.compilersFactory,e?(this.schemaBucket=this.opts.bucket(e.getSchemas()),this.validatorCompiler=e.getValidatorCompiler(),this.serializerCompiler=e.getSerializerCompiler(),this.isCustomValidatorCompiler=e.isCustomValidatorCompiler,this.isCustomSerializerCompiler=e.isCustomSerializerCompiler,this.parent=e):(this.schemaBucket=this.opts.bucket(),this.isCustomValidatorCompiler=this.opts.isCustomValidatorCompiler||!1,this.isCustomSerializerCompiler=this.opts.isCustomSerializerCompiler||!1)}add(e){return this.addedSchemas=!0,this.schemaBucket.add(e)}getSchema(e){return this.schemaBucket.getSchema(e)}getSchemas(){return this.schemaBucket.getSchemas()}setValidatorCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildValidator:()=>e}),this.validatorCompiler=e,this.isCustomValidatorCompiler=!0}setSerializerCompiler(e){this.compilersFactory=Object.assign({},this.compilersFactory,{buildSerializer:()=>e}),this.serializerCompiler=e,this.isCustomSerializerCompiler=!0}getValidatorCompiler(){return this.validatorCompiler||this.parent&&this.parent.getValidatorCompiler()}getSerializerCompiler(){return this.serializerCompiler||this.parent&&this.parent.getSerializerCompiler()}getSerializerBuilder(){return this.compilersFactory.buildSerializer||this.parent&&this.parent.getSerializerBuilder()}getValidatorBuilder(){return this.compilersFactory.buildValidator||this.parent&&this.parent.getValidatorBuilder()}setupValidator(e){this.validatorCompiler!==void 0&&!this.addedSchemas||(this.validatorCompiler=this.getValidatorBuilder()(this.schemaBucket.getSchemas(),e.ajv))}setupSerializer(e){this.serializerCompiler!==void 0&&!this.addedSchemas||(this.serializerCompiler=this.getSerializerBuilder()(this.schemaBucket.getSchemas(),e.serializerOpts))}};i.buildSchemaController=r,t.exports=i})),kp=o(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),Ap=o(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),jp=o(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=kp(),a=Ap();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),Mp=o(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),Np=o(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),Pp=o(((e,t)=>{let n=Ap(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=kp(),{safeRe:a,t:o}=jp(),s=Mp(),{compareIdentifiers:c}=Np();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Fp=o(((e,t)=>{let n=Pp();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),Ip=o(((e,t)=>{let n=Fp();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),Lp=o(((e,t)=>{let n=Fp();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),Rp=o(((e,t)=>{let n=Pp();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),zp=o(((e,t)=>{let n=Fp();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),Bp=o(((e,t)=>{let n=Pp();t.exports=(e,t)=>new n(e,t).major})),Vp=o(((e,t)=>{let n=Pp();t.exports=(e,t)=>new n(e,t).minor})),Hp=o(((e,t)=>{let n=Pp();t.exports=(e,t)=>new n(e,t).patch})),Up=o(((e,t)=>{let n=Fp();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),Wp=o(((e,t)=>{let n=Pp();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),Gp=o(((e,t)=>{let n=Wp();t.exports=(e,t,r)=>n(t,e,r)})),Kp=o(((e,t)=>{let n=Wp();t.exports=(e,t)=>n(e,t,!0)})),qp=o(((e,t)=>{let n=Pp();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),Jp=o(((e,t)=>{let n=qp();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),Yp=o(((e,t)=>{let n=qp();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),Xp=o(((e,t)=>{let n=Wp();t.exports=(e,t,r)=>n(e,t,r)>0})),Zp=o(((e,t)=>{let n=Wp();t.exports=(e,t,r)=>n(e,t,r)<0})),Qp=o(((e,t)=>{let n=Wp();t.exports=(e,t,r)=>n(e,t,r)===0})),$p=o(((e,t)=>{let n=Wp();t.exports=(e,t,r)=>n(e,t,r)!==0})),em=o(((e,t)=>{let n=Wp();t.exports=(e,t,r)=>n(e,t,r)>=0})),tm=o(((e,t)=>{let n=Wp();t.exports=(e,t,r)=>n(e,t,r)<=0})),nm=o(((e,t)=>{let n=Qp(),r=$p(),i=Xp(),a=em(),o=Zp(),s=tm();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),rm=o(((e,t)=>{let n=Pp(),r=Fp(),{safeRe:i,t:a}=jp();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),im=o(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),am=o(((e,t)=>{let n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,O(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k(this.set[t],e,this.options))return!0;return!1}};let r=new(im()),i=Mp(),a=om(),o=Ap(),s=Pp(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=jp(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=kp(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=S(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=w(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(` `),x=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},S=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(` `),C=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},w=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>T(e,t)).join(` `)),T=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),O=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),k=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),om=o(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=Mp(),{safeRe:i,t:a}=jp(),o=nm(),s=Ap(),c=Pp(),l=am()})),sm=o(((e,t)=>{let n=am();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),cm=o(((e,t)=>{let n=am();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),lm=o(((e,t)=>{let n=Pp(),r=am();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),um=o(((e,t)=>{let n=Pp(),r=am();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),dm=o(((e,t)=>{let n=Pp(),r=am(),i=Xp();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),fm=o(((e,t)=>{let n=am();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),pm=o(((e,t)=>{let n=Pp(),r=om(),{ANY:i}=r,a=am(),o=sm(),s=Xp(),c=Zp(),l=tm(),u=em();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),mm=o(((e,t)=>{let n=pm();t.exports=(e,t,r)=>n(e,t,`>`,r)})),hm=o(((e,t)=>{let n=pm();t.exports=(e,t,r)=>n(e,t,`<`,r)})),gm=o(((e,t)=>{let n=am();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),_m=o(((e,t)=>{let n=sm(),r=Wp();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),vm=o(((e,t)=>{let n=am(),r=om(),{ANY:i}=r,a=sm(),o=Wp(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),ym=o(((e,t)=>{let n=jp(),r=kp(),i=Pp(),a=Np();t.exports={parse:Fp(),valid:Ip(),clean:Lp(),inc:Rp(),diff:zp(),major:Bp(),minor:Vp(),patch:Hp(),prerelease:Up(),compare:Wp(),rcompare:Gp(),compareLoose:Kp(),compareBuild:qp(),sort:Jp(),rsort:Yp(),gt:Xp(),lt:Zp(),eq:Qp(),neq:$p(),gte:em(),lte:tm(),cmp:nm(),coerce:rm(),Comparator:om(),Range:am(),satisfies:sm(),toComparators:cm(),maxSatisfying:lm(),minSatisfying:um(),minVersion:dm(),validRange:fm(),outside:pm(),gtr:mm(),ltr:hm(),intersects:gm(),simplifyRange:_m(),subset:vm(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}})),bm=o(((e,t)=>{let n=ym(),r=require(`node:assert`),i=Symbol.for(`registered-plugin`),{kTestInternals:a}=bu(),{exist:o,existReply:s,existRequest:c}=gd(),{FST_ERR_PLUGIN_VERSION_MISMATCH:l,FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:u,FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:d}=Cu(),f=/-(?:rc|pre|alpha).+$/u;function p(e){return e[Symbol.for(`plugin-meta`)]}function m(e){let t=g(e);if(t)return t;let n=require.cache;if(n){let t=Object.keys(n);for(let r=0;r<t.length;r++){let i=t[r];if(n[i].exports===e)return i}}return e.name?e.name:null}function h(e){return e.toString().split(`
431
+ `,2).map(e=>e.trim()).join(` -- `)}function g(e){return e[Symbol.for(`fastify.display-name`)]}function _(e){return!!e[Symbol.for(`skip-override`)]}function v(e){let t=p(e);if(!t)return;let n=t.dependencies;n&&(r(Array.isArray(n),`The dependencies should be an array of strings`),n.forEach(e=>{r(this[i].indexOf(e)>-1,`The dependency '${e}' of plugin '${t.name}' is not registered`)}))}function y(e){let t=p(e);if(!t)return;let{decorators:n,name:r}=t;n&&(n.fastify&&x(this,`Fastify`,n.fastify,r),n.reply&&x(this,`Reply`,n.reply,r),n.request&&x(this,`Request`,n.request,r))}let b={Fastify:o,Request:c,Reply:s};function x(e,t,n,i){r(Array.isArray(n),`The decorators should be an array of strings`),n.forEach(n=>{let r=typeof i==`string`?` required by '${i}'`:``;if(!b[t].call(e,n))throw new u(n,r,t)})}function S(e){let t=p(e);if(t?.fastify==null)return;let r=t.fastify,i=f.test(this.version);if(!(i===!0&&n.gt(this.version,n.coerce(r))===!0)&&r&&n.satisfies(this.version,r,{includePrerelease:i})===!1)throw new l(t.name,r,this.version)}function C(e){let t=p(e);if(!t)return;let n=t.name;if(n)return this[i].push(n),n}function w(e,t){if(e.constructor.name===`AsyncFunction`&&e.length===3)throw new d(t)}function T(e){let t=C.call(this,e)||m(e);return w.call(this,e,t),S.call(this,e),y.call(this,e),v.call(this,e),_(e)}t.exports={getPluginName:m,getFuncPreview:h,kRegisteredPlugins:i,getDisplayName:g,registerPlugin:T},t.exports[a]={shouldSkipOverride:_,getMeta:p,checkDecorators:y,checkDependencies:v}})),xm=o(((e,t)=>{function n(e,t){let n=t||i();return e?a(e,n):n}function r(e,t){return e.genReqId(t)}function i(){let e=0;return function(){return e=e+1&2147483647,`req-${e.toString(36)}`}}function a(e,t){return function(n){return n.headers[e]||t(n)}}t.exports={getGenReqId:r,reqIdGenFactory:n}})),Sm=o(((e,t)=>{var n=12,r=0,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function a(e){var t=e.indexOf(`%`);if(t===-1)return e;for(var a=e.length,o=``,c=0,l=0,u=t,d=n;t>-1&&t<a;){var f=s(e[t+1],4)|s(e[t+2],0),p=i[f];if(d=i[256+d+p],l=l<<6|f&i[364+p],d===n)o+=e.slice(c,u),o+=l<=65535?String.fromCharCode(l):String.fromCharCode(55232+(l>>10),56320+(l&1023)),l=0,c=t+3,t=u=e.indexOf(`%`,c);else if(d===r)return null;else{if(t+=3,t<a&&e.charCodeAt(t)===37)continue;return null}}return o+e.slice(c)}var o={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function s(e,t){var n=o[e];return n===void 0?255:n<<t}t.exports=a})),Cm=o(((e,t)=>{let n=Sm(),r=/\+/g,i=function(){};i.prototype=Object.create(null);function a(e){let t=new i;if(typeof e!=`string`)return t;let a=e.length,o=``,s=``,c=-1,l=-1,u=!1,d=!1,f=!1,p=!1,m=!1,h=0;for(let i=0;i<a+1;i++)if(h=i===a?38:e.charCodeAt(i),h===38){if(m=l>c,m||(l=i),o=e.slice(c+1,l),m||o.length>0){f&&(o=o.replace(r,` `)),u&&(o=n(o)||o),m&&(s=e.slice(l+1,i),p&&(s=s.replace(r,` `)),d&&(s=n(s)||s));let a=t[o];a===void 0?t[o]=s:a.pop?a.push(s):t[o]=[a,s]}s=``,c=i,l=i,u=!1,d=!1,f=!1,p=!1}else h===61?l<=c?l=i:d=!0:h===43?l>c?p=!0:f=!0:h===37&&(l>c?d=!0:u=!0);return t}t.exports=a})),wm=o(((e,t)=>{let n=Array.from({length:256},(e,t)=>`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase()),r=new Int8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0]);function i(e){let t=e.length;if(t===0)return``;let i=``,a=0,o=0;outer:for(;o<t;o++){let s=e.charCodeAt(o);for(;s<128;){if(r[s]!==1&&(a<o&&(i+=e.slice(a,o)),a=o+1,i+=n[s]),++o===t)break outer;s=e.charCodeAt(o)}if(a<o&&(i+=e.slice(a,o)),s<2048){a=o+1,i+=n[192|s>>6]+n[128|s&63];continue}if(s<55296||s>=57344){a=o+1,i+=n[224|s>>12]+n[128|s>>6&63]+n[128|s&63];continue}if(++o,o>=t)throw Error(`URI malformed`);let c=e.charCodeAt(o)&1023;a=o+1,s=65536+((s&1023)<<10|c),i+=n[240|s>>18]+n[128|s>>12&63]+n[128|s>>6&63]+n[128|s&63]}return a===0?e:a<t?i+e.slice(a):i}t.exports={encodeString:i}})),Tm=o(((e,t)=>{let{encodeString:n}=wm();function r(e){let t=typeof e;return t===`string`?n(e):t===`bigint`?e.toString():t===`boolean`?e?`true`:`false`:t===`number`&&Number.isFinite(e)?e<1e21?``+e:n(``+e):``}function i(e){let t=``;if(typeof e!=`object`||!e)return t;let i=Object.keys(e),a=i.length,o=0;for(let s=0;s<a;s++){let a=i[s],c=e[a],l=n(a)+`=`;if(s&&(t+=`&`),Array.isArray(c)){o=c.length;for(let e=0;e<o;e++)e&&(t+=`&`),t+=l,t+=r(c[e])}else t+=l,t+=r(c)}return t}t.exports=i})),Em=o(((e,t)=>{let n=Cm(),r=Tm(),i={parse:n,stringify:r};t.exports=i,t.exports.default=i,t.exports.parse=n,t.exports.stringify=r})),Dm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),Om=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0,(function(e){e[e.ROOT=0]=`ROOT`,e[e.GROUP=1]=`GROUP`,e[e.POSITION=2]=`POSITION`,e[e.SET=3]=`SET`,e[e.RANGE=4]=`RANGE`,e[e.REPETITION=5]=`REPETITION`,e[e.REFERENCE=6]=`REFERENCE`,e[e.CHAR=7]=`CHAR`})(e.types||={})})),km=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),Am=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),n(Dm(),e),n(Om(),e),n(km(),e)})),jm=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.anyChar=e.notWhitespace=e.whitespace=e.notInts=e.ints=e.notWords=e.words=void 0;let t=Am(),n=()=>[{type:t.types.RANGE,from:48,to:57}],r=()=>[{type:t.types.CHAR,value:95},{type:t.types.RANGE,from:97,to:122},{type:t.types.RANGE,from:65,to:90},{type:t.types.RANGE,from:48,to:57}],i=()=>[{type:t.types.CHAR,value:9},{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:11},{type:t.types.CHAR,value:12},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:32},{type:t.types.CHAR,value:160},{type:t.types.CHAR,value:5760},{type:t.types.RANGE,from:8192,to:8202},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233},{type:t.types.CHAR,value:8239},{type:t.types.CHAR,value:8287},{type:t.types.CHAR,value:12288},{type:t.types.CHAR,value:65279}],a=()=>[{type:t.types.CHAR,value:10},{type:t.types.CHAR,value:13},{type:t.types.CHAR,value:8232},{type:t.types.CHAR,value:8233}];e.words=()=>({type:t.types.SET,set:r(),not:!1}),e.notWords=()=>({type:t.types.SET,set:r(),not:!0}),e.ints=()=>({type:t.types.SET,set:n(),not:!1}),e.notInts=()=>({type:t.types.SET,set:n(),not:!0}),e.whitespace=()=>({type:t.types.SET,set:i(),not:!1}),e.notWhitespace=()=>({type:t.types.SET,set:i(),not:!0}),e.anyChar=()=>({type:t.types.SET,set:a(),not:!0})})),Mm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizeClass=e.strToChars=void 0;let i=Am(),a=r(jm());e.strToChars=e=>e.replace(/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g,(e,t,n,r,i,a,o)=>{if(n)return e;let s=t?8:r?parseInt(r,16):i?parseInt(i,16):a?`@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?`.indexOf(a):{0:0,t:9,n:10,v:11,f:12,r:13}[o],c=String.fromCharCode(s);return/[[\]{}^$.|?*+()]/.test(c)?`\\${c}`:c}),e.tokenizeClass=(e,t)=>{let n=[],r,o,s=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;for(;(r=s.exec(e))!==null;){let e=(r[1]&&a.words())??(r[2]&&a.ints())??(r[3]&&a.whitespace())??(r[4]&&a.notWords())??(r[5]&&a.notInts())??(r[6]&&a.notWhitespace())??(r[7]&&{type:i.types.RANGE,from:(r[8]||r[9]).charCodeAt(0),to:(o=r[10]).charCodeAt(o.length-1)})??((o=r[16])&&{type:i.types.CHAR,value:o.charCodeAt(0)});if(e)n.push(e);else return[n,s.lastIndex]}throw SyntaxError(`Invalid regular expression: /${t}/: Unterminated character class`)}})),Nm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.tokenizer=void 0;let i=r(Mm()),a=Am(),o=r(jm()),s=/^[a-zA-Z_$]$/i,c=/^[a-zA-Z0-9_$]$/i,l=/\d/;e.tokenizer=e=>{let t=0,n,r={type:a.types.ROOT,stack:[]},d=r,f=r.stack,p=[],m=[],h=0,g=t=>{throw SyntaxError(`Invalid regular expression: /${e}/: Nothing to repeat at column ${t-1}`)},_=i.strToChars(e);for(;t<_.length;)switch(n=_[t++]){case`\\`:if(t===_.length)throw SyntaxError(`Invalid regular expression: /${e}/: \\ at end of pattern`);switch(n=_[t++]){case`b`:f.push({type:a.types.POSITION,value:`b`});break;case`B`:f.push({type:a.types.POSITION,value:`B`});break;case`w`:f.push(o.words());break;case`W`:f.push(o.notWords());break;case`d`:f.push(o.ints());break;case`D`:f.push(o.notInts());break;case`s`:f.push(o.whitespace());break;case`S`:f.push(o.notWhitespace());break;default:if(l.test(n)){let e=n;for(;t<_.length&&l.test(_[t]);)e+=_[t++];let r=parseInt(e,10),i={type:a.types.REFERENCE,value:r};f.push(i),m.push({reference:i,stack:f,index:f.length-1})}else f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}break;case`^`:f.push({type:a.types.POSITION,value:`^`});break;case`$`:f.push({type:a.types.POSITION,value:`$`});break;case`[`:{let n;_[t]===`^`?(n=!0,t++):n=!1;let r=i.tokenizeClass(_.slice(t),e);t+=r[1],f.push({type:a.types.SET,set:r[0],not:n});break}case`.`:f.push(o.anyChar());break;case`(`:{let r={type:a.types.GROUP,stack:[],remember:!0};if(_[t]===`?`)if(n=_[t+1],t+=2,n===`=`)r.followedBy=!0,r.remember=!1;else if(n===`!`)r.notFollowedBy=!0,r.remember=!1;else if(n===`<`){let n=``;if(s.test(_[t]))n+=_[t],t++;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);for(;t<_.length&&c.test(_[t]);)n+=_[t],t++;if(!n)throw SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${_[t]}' after '<' at column ${t+1}`);if(_[t]!==`>`)throw SyntaxError(`Invalid regular expression: /${e}/: Unclosed capture group name, expected '>', found '${_[t]}' at column ${t+1}`);r.name=n,t++}else if(n===`:`)r.remember=!1;else throw SyntaxError(`Invalid regular expression: /${e}/: Invalid group, character '${n}' after '?' at column ${t-1}`);else h+=1;f.push(r),p.push(d),d=r,f=r.stack;break}case`)`:if(p.length===0)throw SyntaxError(`Invalid regular expression: /${e}/: Unmatched ) at column ${t-1}`);d=p.pop(),f=d.options?d.options[d.options.length-1]:d.stack;break;case`|`:{d.options||(d.options=[d.stack],delete d.stack);let e=[];d.options.push(e),f=e;break}case`{`:{let e=/^(\d+)(,(\d+)?)?\}/.exec(_.slice(t)),n,r;e===null?f.push({type:a.types.CHAR,value:123}):(f.length===0&&g(t),n=parseInt(e[1],10),r=e[2]?e[3]?parseInt(e[3],10):1/0:n,t+=e[0].length,f.push({type:a.types.REPETITION,min:n,max:r,value:f.pop()}));break}case`?`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1,value:f.pop()});break;case`+`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:1,max:1/0,value:f.pop()});break;case`*`:f.length===0&&g(t),f.push({type:a.types.REPETITION,min:0,max:1/0,value:f.pop()});break;default:f.push({type:a.types.CHAR,value:n.charCodeAt(0)})}if(p.length!==0)throw SyntaxError(`Invalid regular expression: /${e}/: Unterminated group`);return u(m,h),r};function u(e,t){for(let n of e.reverse())if(t<n.reference.value){n.reference.type=a.types.CHAR;let e=n.reference.value.toString();if(n.reference.value=parseInt(e,8),!/^[0-7]+$/.test(e)){let t=0;for(;e[t]!==`8`&&e[t]!==`9`;)t+=1;if(t===0?(n.reference.value=e.charCodeAt(0),t+=1):n.reference.value=parseInt(e.slice(0,t),8),e.length>t){let r=n.stack.splice(n.index+1);for(let r of e.slice(t))n.stack.push({type:a.types.CHAR,value:r.charCodeAt(0)});n.stack.push(...r)}}}}})),Pm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.NOTANYCHAR=e.WHITESPACE=e.WORDS=e.INTS=void 0;let i=r(jm()),a=Am();function o(e){let t={},n=0;for(let r of e)r.type===a.types.CHAR&&(t[r.value]=!0),r.type===a.types.RANGE&&(t[`${r.from}-${r.to}`]=!0),n+=1;return{lookup:()=>Object.assign({},t),len:n}}e.INTS=o(i.ints().set),e.WORDS=o(i.words().set),e.WHITESPACE=o(i.whitespace().set),e.NOTANYCHAR=o(i.anyChar().set)})),Fm=o((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,`__esModule`,{value:!0}),e.writeSetTokens=e.setChar=void 0;let i=Am(),a=r(Pm());function o(e){return e===94?`\\^`:e===92?`\\\\`:e===93?`\\]`:e===45?`\\-`:String.fromCharCode(e)}e.setChar=o;function s(e,{lookup:t,len:n}){if(n!==e.length)return!1;let r=t();for(let t of e){if(t.type===i.types.SET)return!1;let e=t.type===i.types.CHAR?t.value:`${t.from}-${t.to}`;if(r[e])r[e]=!1;else return!1}return!0}function c(e,t=!1){if(s(e.set,a.INTS))return e.not?`\\D`:`\\d`;if(s(e.set,a.WORDS))return e.not?`\\W`:`\\w`;if(e.not&&s(e.set,a.NOTANYCHAR))return`.`;if(s(e.set,a.WHITESPACE))return e.not?`\\S`:`\\s`;let n=``;for(let t=0;t<e.set.length;t++){let r=e.set[t];n+=l(r)}let r=`${e.not?`^`:``}${n}`;return t?r:`[${r}]`}e.writeSetTokens=c;function l(e){return e.type===i.types.CHAR?o(e.value):e.type===i.types.RANGE?`${o(e.from)}-${o(e.to)}`:c(e,!0)}})),Im=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconstruct=void 0;let t=Am(),n=Fm(),r=t=>t.map(e.reconstruct).join(``),i=e=>{if(`options`in e)return e.options.map(r).join(`|`);if(`stack`in e)return r(e.stack);throw Error(`options or stack must be Root or Group token`)};e.reconstruct=r=>{switch(r.type){case t.types.ROOT:return i(r);case t.types.CHAR:{let e=String.fromCharCode(r.value);return(/[[\\{}$^.|?*+()]/.test(e)?`\\`:``)+e}case t.types.POSITION:return r.value===`^`||r.value===`$`?r.value:`\\${r.value}`;case t.types.REFERENCE:return`\\${r.value}`;case t.types.SET:return n.writeSetTokens(r);case t.types.GROUP:return`(${r.name?`?<${r.name}>`:r.remember?``:r.followedBy?`?=`:r.notFollowedBy?`?!`:`?:`}${i(r)})`;case t.types.REPETITION:{let{min:t,max:n}=r,i;return i=t===0&&n===1?`?`:t===1&&n===1/0?`+`:t===0&&n===1/0?`*`:n===1/0?`{${t},}`:t===n?`{${t}}`:`{${t},${n}}`,`${e.reconstruct(r.value)}${i}`}case t.types.RANGE:return`${n.setChar(r.from)}-${n.setChar(r.to)}`;default:throw Error(`Invalid token type ${r}`)}}})),Lm=o(((e,t)=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__exportStar||function(e,t){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,`__esModule`,{value:!0}),e.types=void 0;let i=Am();Object.defineProperty(e,`types`,{enumerable:!0,get:function(){return i.types}}),r(Nm(),e),r(Im(),e);let a=Nm(),o=Im();r(Am(),e),e.default=a.tokenizer,t.exports=a.tokenizer,t.exports.types=i.types,t.exports.reconstruct=o.reconstruct})),Rm=o(((e,t)=>{let n=Lm(),r=n.types;function i(e,t){t||={};let i=t.limit===void 0?25:t.limit;a(e)?e=e.source:typeof e!=`string`&&(e=String(e));try{e=n(e)}catch{return!1}let o=0;return(function e(t,n){let a,s,c;if(t.type===r.REPETITION&&(n++,o++,n>1||o>i))return!1;if(t.options){for(a=0,c=t.options.length;a<c;a++)if(s=e({stack:t.options[a]},n),!s)return!1}let l=t.stack||t.value?.stack;if(!l)return!0;for(a=0;a<l.length;a++)if(s=e(l[a],n),!s)return!1;return!0})(e,0)}function a(e){return{}.toString.call(e)===`[object RegExp]`}t.exports=i,t.exports.default=i,t.exports.safeRegex=i})),zm=o(((e,t)=>{t.exports={name:`__fmw_internal_strategy_merged_tree_http_method__`,storage:function(){let e=new Map;return{get:t=>e.get(t)||null,set:(t,n)=>{e.set(t,n)}}},deriveConstraint:e=>e.method,mustMatchWhenDerived:!0}})),Bm=o(((e,t)=>{let n=Rd(),r=zm(),i=Symbol(`treeData`);function a(e,t=``){let n=``,r=Object.keys(e);for(let o=0;o<r.length;o++){let s=r[o],c=e[s],l=o===r.length-1,u=l?`└── `:`├── `,d=l?` `:`│ `,f=(c[i]||``).replaceAll(`
432
432
  `,`
433
433
  `+t+d);n+=t+u+s+f+`
434
- `,n+=a(c,t+d)}return n}function o(e){let t=e.name||``;return t=t.replace(`bound`,``).trim(),t=(t||`anonymous`)+`()`,t}function s(e){return Array.isArray(e)?e.map(e=>s(e)):typeof e==`symbol`?e.toString():typeof e==`function`?o(e):e}function c(e,t){if(!t.includeMeta)return{};let n=t.buildPrettyMeta(e),r={},i=t.includeMeta;Array.isArray(i)||(i=Reflect.ownKeys(n));for(let e of i){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let t=e.toString(),i=n[e];i!=null&&(r[t]=JSON.stringify(s(i)))}return r}function l(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\n• (${n}) ${r}`;return t}function u(e){let t={...e.opts.constraints},n=t[r.name];return delete t[r.name],{...e,method:n,opts:{constraints:t}}}function d(e){let t=` (${e.method})`,n=e.opts.constraints||{};return Object.keys(n).length!==0&&(t+=` `+JSON.stringify(n)),t+=l(e.metaData),t}function f(e){return e.reduce((e,t)=>{for(let r of e)if(n(t.opts.constraints,r.opts.constraints)&&n(t.metaData,r.metaData))return r.method+=`, `+t.method,e;return e.push(t),e},[])}function p(e,t,n){let r=e.routes;return n.method===void 0&&(r=r.map(u)),r=r.map(e=>(e.metaData=c(e,n),e)),n.method===void 0&&(r=f(r)),r.map(d).join(`\n${t}`)}function m(e,t,n,r){if((e.isLeafNode||r.commonPrefix!==!1)&&(n||=`(empty root node)`,t=t[n]={},e.isLeafNode&&(t[i]=p(e,n,r)),n=``),e.staticChildren)for(let i of Object.values(e.staticChildren))m(i,t,n+i.prefix,r);if(e.parametricChildren)for(let i of Object.values(e.parametricChildren)){let e=Array.from(i.nodePaths).join(`|`);m(i,t,n+e,r)}e.wildcardChild&&m(e.wildcardChild,t,`*`,r)}function h(e,t){let n={};return m(e,n,e.prefix,t),a(n)}t.exports={prettyPrintTree:h}})),Bm=o(((e,t)=>{let n=function(){};n.prototype=Object.create(null),t.exports={NullObject:n}})),Vm=o(((e,t)=>{let{NullObject:n}=Bm(),r=Rm();t.exports=class{constructor(){this.unconstrainedHandler=null,this.constraints=[],this.handlers=[],this.constrainedHandlerStores=null}getMatchingHandler(e){return e===void 0?this.unconstrainedHandler:this._getHandlerMatchingConstraints(e)}addHandler(e,t){let n=t.params,i=t.opts.constraints||{},a={params:n,constraints:i,handler:t.handler,store:t.store||null,_createParamsObject:this._compileCreateParamsObject(n)},o=Object.keys(i);o.length===0&&(this.unconstrainedHandler=a);for(let e of o)this.constraints.includes(e)||(e===`version`?this.constraints.unshift(e):this.constraints.push(e));let s=o.includes(r.name);if(!s&&this.handlers.length>=31)throw Error(`find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached`);this.handlers.push(a),this.handlers.sort((e,t)=>Object.keys(e.constraints).length-Object.keys(t.constraints).length),s||this._compileGetHandlerMatchingConstraints(e,i)}_compileCreateParamsObject(e){let t=[];t.push(`const fn = function _createParamsObject (paramsArray) {`),t.push(`const params = new NullObject()`);for(let n=0;n<e.length;n++)t.push(`params['${e[n]}'] = paramsArray[${n}]`);return t.push(`return params`),t.push(`}`),t.push(`return fn`),Function(`NullObject`,t.join(`
434
+ `,n+=a(c,t+d)}return n}function o(e){let t=e.name||``;return t=t.replace(`bound`,``).trim(),t=(t||`anonymous`)+`()`,t}function s(e){return Array.isArray(e)?e.map(e=>s(e)):typeof e==`symbol`?e.toString():typeof e==`function`?o(e):e}function c(e,t){if(!t.includeMeta)return{};let n=t.buildPrettyMeta(e),r={},i=t.includeMeta;Array.isArray(i)||(i=Reflect.ownKeys(n));for(let e of i){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let t=e.toString(),i=n[e];i!=null&&(r[t]=JSON.stringify(s(i)))}return r}function l(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\n• (${n}) ${r}`;return t}function u(e){let t={...e.opts.constraints},n=t[r.name];return delete t[r.name],{...e,method:n,opts:{constraints:t}}}function d(e){let t=` (${e.method})`,n=e.opts.constraints||{};return Object.keys(n).length!==0&&(t+=` `+JSON.stringify(n)),t+=l(e.metaData),t}function f(e){return e.reduce((e,t)=>{for(let r of e)if(n(t.opts.constraints,r.opts.constraints)&&n(t.metaData,r.metaData))return r.method+=`, `+t.method,e;return e.push(t),e},[])}function p(e,t,n){let r=e.routes;return n.method===void 0&&(r=r.map(u)),r=r.map(e=>(e.metaData=c(e,n),e)),n.method===void 0&&(r=f(r)),r.map(d).join(`\n${t}`)}function m(e,t,n,r){if((e.isLeafNode||r.commonPrefix!==!1)&&(n||=`(empty root node)`,t=t[n]={},e.isLeafNode&&(t[i]=p(e,n,r)),n=``),e.staticChildren)for(let i of Object.values(e.staticChildren))m(i,t,n+i.prefix,r);if(e.parametricChildren)for(let i of Object.values(e.parametricChildren)){let e=Array.from(i.nodePaths).join(`|`);m(i,t,n+e,r)}e.wildcardChild&&m(e.wildcardChild,t,`*`,r)}function h(e,t){let n={};return m(e,n,e.prefix,t),a(n)}t.exports={prettyPrintTree:h}})),Vm=o(((e,t)=>{let n=function(){};n.prototype=Object.create(null),t.exports={NullObject:n}})),Hm=o(((e,t)=>{let{NullObject:n}=Vm(),r=zm();t.exports=class{constructor(){this.unconstrainedHandler=null,this.constraints=[],this.handlers=[],this.constrainedHandlerStores=null}getMatchingHandler(e){return e===void 0?this.unconstrainedHandler:this._getHandlerMatchingConstraints(e)}addHandler(e,t){let n=t.params,i=t.opts.constraints||{},a={params:n,constraints:i,handler:t.handler,store:t.store||null,_createParamsObject:this._compileCreateParamsObject(n)},o=Object.keys(i);o.length===0&&(this.unconstrainedHandler=a);for(let e of o)this.constraints.includes(e)||(e===`version`?this.constraints.unshift(e):this.constraints.push(e));let s=o.includes(r.name);if(!s&&this.handlers.length>=31)throw Error(`find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached`);this.handlers.push(a),this.handlers.sort((e,t)=>Object.keys(e.constraints).length-Object.keys(t.constraints).length),s||this._compileGetHandlerMatchingConstraints(e,i)}_compileCreateParamsObject(e){let t=[];t.push(`const fn = function _createParamsObject (paramsArray) {`),t.push(`const params = new NullObject()`);for(let n=0;n<e.length;n++)t.push(`params['${e[n]}'] = paramsArray[${n}]`);return t.push(`return params`),t.push(`}`),t.push(`return fn`),Function(`NullObject`,t.join(`
435
435
  `))(n)}_getHandlerMatchingConstraints(){return null}_buildConstraintStore(e,t){for(let n=0;n<this.handlers.length;n++){let r=this.handlers[n].constraints[t];if(r!==void 0){let t=e.get(r)||0;t|=1<<n,e.set(r,t)}}}_constrainedIndexBitmask(e){let t=0;for(let n=0;n<this.handlers.length;n++)this.handlers[n].constraints[e]!==void 0&&(t|=1<<n);return~t}_compileGetHandlerMatchingConstraints(e){this.constrainedHandlerStores={};for(let t of this.constraints){let n=e.newStoreForConstraint(t);this.constrainedHandlerStores[t]=n,this._buildConstraintStore(n,t)}let t=[];t.push(`
436
436
  let candidates = ${(1<<this.handlers.length)-1}
437
437
  let mask, matches
@@ -447,41 +447,41 @@ const asInteger = serializer.asInteger.bind(serializer)
447
447
  }
448
448
  if (candidates === 0) return null;
449
449
  `)}for(let n in e.strategies)e.strategies[n].mustMatchWhenDerived&&!this.constraints.includes(n)&&t.push(`if (derivedConstraints.${n} !== undefined) return null`);t.push(`return this.handlers[Math.floor(Math.log2(candidates))]`),this._getHandlerMatchingConstraints=Function(`derivedConstraints`,t.join(`
450
- `))}}})),Hm=o(((e,t)=>{let n=Vm(),r={STATIC:0,PARAMETRIC:1,WILDCARD:2};var i=class{constructor(){this.isLeafNode=!1,this.routes=null,this.handlerStorage=null}addRoute(e,t){this.routes===null&&(this.routes=[]),this.handlerStorage===null&&(this.handlerStorage=new n),this.isLeafNode=!0,this.routes.push(e),this.handlerStorage.addHandler(t,e)}},a=class extends i{constructor(){super(),this.staticChildren={}}findStaticMatchingChild(e,t){let n=this.staticChildren[e.charAt(t)];return n===void 0||!n.matchPrefix(e,t)?null:n}getStaticChild(e,t=0){if(e.length===t)return this;let n=this.findStaticMatchingChild(e,t);return n?n.getStaticChild(e,t+n.prefix.length):null}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let n=e.charAt(0);return this.staticChildren[n]=new o(e),this.staticChildren[n]}},o=class e extends a{constructor(e){super(),this.prefix=e,this.wildcardChild=null,this.parametricChildren=[],this.kind=r.STATIC,this._compilePrefixMatch()}getParametricChild(e){let t=e&&e.source;return this.parametricChildren.find(e=>(e.regex&&e.regex.source)===t)||null}createParametricChild(e,t,n){let r=this.getParametricChild(e);return r?(r.nodePaths.add(n),r):(r=new s(e,t,n),this.parametricChildren.push(r),this.parametricChildren.sort((e,t)=>e.isRegex?t.isRegex?e.staticSuffix===null?1:t.staticSuffix===null?-1:t.staticSuffix.endsWith(e.staticSuffix)?1:e.staticSuffix.endsWith(t.staticSuffix)?-1:0:-1:1),r)}getWildcardChild(){return this.wildcardChild}createWildcardChild(){return this.wildcardChild=this.getWildcardChild()||new c,this.wildcardChild}split(t,n){let r=this.prefix.slice(0,n),i=this.prefix.slice(n);this.prefix=i,this._compilePrefixMatch();let a=new e(r);return a.staticChildren[i.charAt(0)]=this,t.staticChildren[r.charAt(0)]=a,a}getNextNode(e,t,n,r){let i=this.findStaticMatchingChild(e,t),a=0;if(i===null){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],a=1}this.wildcardChild!==null&&n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let e=this.parametricChildren.length-1;e>=a;e--)n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.parametricChildren[e]});return i}_compilePrefixMatch(){if(this.prefix.length===1){this.matchPrefix=()=>!0;return}let e=[];for(let t=1;t<this.prefix.length;t++){let n=this.prefix.charCodeAt(t);e.push(`path.charCodeAt(i + ${t}) === ${n}`)}this.matchPrefix=Function(`path`,`i`,`return ${e.join(` && `)}`)}},s=class extends a{constructor(e,t,n){super(),this.isRegex=!!e,this.regex=e||null,this.staticSuffix=t||null,this.kind=r.PARAMETRIC,this.nodePaths=new Set([n])}getNextNode(e,t){return this.findStaticMatchingChild(e,t)}},c=class extends i{constructor(){super(),this.kind=r.WILDCARD}getNextNode(){return null}};t.exports={StaticNode:o,ParametricNode:s,WildcardNode:c,NODE_TYPES:r}})),Um=o(((e,t)=>{let n=require(`node:assert`);function r(){if(!(this instanceof r))return new r;this.store=new Map,this.maxMajor=0,this.maxMinors={},this.maxPatches={}}r.prototype.set=function(e,t){if(typeof e!=`string`)throw TypeError(`Version should be a string`);let[n,r,i]=e.split(`.`,3);if(isNaN(n))throw TypeError(`Major version must be a numeric value`);return n=Number(n),r=Number(r)||0,i=Number(i)||0,n>=this.maxMajor&&(this.maxMajor=n,this.store.set(`x`,t),this.store.set(`*`,t),this.store.set(`x.x`,t),this.store.set(`x.x.x`,t)),r>=(this.maxMinors[n]||0)&&(this.maxMinors[n]=r,this.store.set(`${n}.x`,t),this.store.set(`${n}.x.x`,t)),i>=(this.maxPatches[`${n}.${r}`]||0)&&(this.maxPatches[`${n}.${r}`]=i,this.store.set(`${n}.${r}.x`,t)),this.store.set(`${n}.${r}.${i}`,t),this},r.prototype.get=function(e){return this.store.get(e)},t.exports={name:`version`,mustMatchWhenDerived:!0,storage:r,validate(e){n(typeof e==`string`,`Version should be a string`)}}})),Wm=o(((e,t)=>{let n=require(`node:assert`);function r(){let e=new Map,t=[];return{get:n=>{let r=e.get(n);if(r)return r;for(let e of t)if(e.host.test(n))return e.value},set:(n,r)=>{n instanceof RegExp?t.push({host:n,value:r}):e.set(n,r)}}}t.exports={name:`host`,mustMatchWhenDerived:!1,storage:r,validate(e){n(typeof e==`string`||Object.prototype.toString.call(e)===`[object RegExp]`,`Host should be a string or a RegExp`)}}})),Gm=o(((e,t)=>{let n=Um(),r=Wm(),i=require(`node:assert`);t.exports=class{constructor(e){if(this.strategies={version:n,host:r},this.strategiesInUse=new Set,this.asyncStrategiesInUse=new Set,e)for(let t of Object.values(e))this.addConstraintStrategy(t)}isStrategyUsed(e){return this.strategiesInUse.has(e)||this.asyncStrategiesInUse.has(e)}hasConstraintStrategy(e){let t=this.strategies[e];return t===void 0?!1:t.isCustom||this.isStrategyUsed(e)}addConstraintStrategy(e){if(i(typeof e.name==`string`&&e.name!==``,`strategy.name is required.`),i(e.storage&&typeof e.storage==`function`,`strategy.storage function is required.`),i(e.deriveConstraint&&typeof e.deriveConstraint==`function`,`strategy.deriveConstraint function is required.`),this.strategies[e.name]&&this.strategies[e.name].isCustom)throw Error(`There already exists a custom constraint with the name ${e.name}.`);if(this.isStrategyUsed(e.name))throw Error(`There already exists a route with ${e.name} constraint.`);e.isCustom=!0,e.isAsync=e.deriveConstraint.length===3,this.strategies[e.name]=e,e.mustMatchWhenDerived&&this.noteUsage({[e.name]:e})}deriveConstraints(e,t,n){let r=this.deriveSyncConstraints(e,t);if(n===void 0)return r;this.deriveAsyncConstraints(r,e,t,n)}deriveSyncConstraints(e,t){}noteUsage(e){if(e){let t=this.strategiesInUse.size;for(let t in e)this.strategies[t].isAsync?this.asyncStrategiesInUse.add(t):this.strategiesInUse.add(t);t!==this.strategiesInUse.size&&this._buildDeriveConstraints()}}newStoreForConstraint(e){if(!this.strategies[e])throw Error(`No strategy registered for constraint key ${e}`);return this.strategies[e].storage()}validateConstraints(e){for(let t in e){let n=e[t];if(n===void 0)throw Error(`Can't pass an undefined constraint value, must pass null or no key at all`);let r=this.strategies[t];if(!r)throw Error(`No strategy registered for constraint key ${t}`);r.validate&&r.validate(n)}}deriveAsyncConstraints(e,t,n,r){let i=this.asyncStrategiesInUse.size;if(i===0){r(null,e);return}e||={};for(let a of this.asyncStrategiesInUse)this.strategies[a].deriveConstraint(t,n,(t,n)=>{if(t!==null){r(t);return}e[a]=n,--i===0&&r(null,e)})}_buildDeriveConstraints(){if(this.strategiesInUse.size===0)return;let e=[`return {`];for(let t of this.strategiesInUse){let n=this.strategies[t];n.isCustom?e.push(` ${n.name}: this.strategies.${t}.deriveConstraint(req, ctx),`):t===`version`?e.push(` version: req.headers['accept-version'],`):e.push(` host: req.headers.host || req.headers[':authority'],`)}e.push(`}`),this.deriveSyncConstraints=Function(`req`,`ctx`,e.join(`
451
- `)).bind(this)}}})),Km=o(((e,t)=>{t.exports=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`)})),qm=o(((e,t)=>{function n(e,t){return e===50?t===53?`%`:t===51?`#`:t===52?`$`:t===54?`&`:t===66||t===98?`+`:t===67||t===99?`,`:t===70||t===102?`/`:null:e===51?t===65||t===97?`:`:t===66||t===98?`;`:t===68||t===100?`=`:t===70||t===102?`?`:null:e===52&&t===48?`@`:null}function r(e,t){let r=!1,i=!1,a=``;for(let o=1;o<e.length;o++){let s=e.charCodeAt(o);if(s===37){let t=e.charCodeAt(o+1),a=e.charCodeAt(o+2);n(t,a)===null?r=!0:(i=!0,t===50&&a===53&&(r=!0,e=e.slice(0,o+1)+`25`+e.slice(o+1),o+=2),o+=2)}else if(s===63||s===35||s===59&&t){a=e.slice(o+1),e=e.slice(0,o);break}}return{path:r?decodeURI(e):e,querystring:a,shouldDecodeParam:i}}function i(e){let t=e.indexOf(`%`);if(t===-1)return e;let r=``,i=t;for(let a=t;a<e.length;a++)if(e.charCodeAt(a)===37){let t=n(e.charCodeAt(a+1),e.charCodeAt(a+2));r+=e.slice(i,a)+t,i=a+3}return e.slice(0,t)+r+e.slice(i)}t.exports={safeDecodeURI:r,safeDecodeURIComponent:i}})),Jm=o(((e,t)=>{let n=require(`node:assert`),r=Tm(),i=Lm(),a=Ld(),{prettyPrintTree:o}=zm(),{StaticNode:s,NODE_TYPES:c}=Hm(),l=Gm(),u=Km(),d=Rm(),{safeDecodeURI:f,safeDecodeURIComponent:p}=qm(),m=/^https?:\/\/.*?\//,h=/(\/:[^/()]*?)\?(\/?)/,g=/[.*+?^${}()|[\]\\]/g,_=/\/\/+/g;if(!i(m))throw Error(`the FULL_PATH_REGEXP is not safe, update this module`);if(!i(h))throw Error(`the OPTIONAL_PARAM_REGEXP is not safe, update this module`);if(!i(g))throw Error(`the ESCAPE_REGEXP is not safe, update this module`);if(!i(_))throw Error(`the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module`);function v(e){if(!(this instanceof v))return new v(e);e||={},this._opts=e,e.defaultRoute?(n(typeof e.defaultRoute==`function`,`The default route must be a function`),this.defaultRoute=e.defaultRoute):this.defaultRoute=null,e.onBadUrl?(n(typeof e.onBadUrl==`function`,`The bad url handler must be a function`),this.onBadUrl=e.onBadUrl):this.onBadUrl=null,e.buildPrettyMeta?(n(typeof e.buildPrettyMeta==`function`,`buildPrettyMeta must be a function`),this.buildPrettyMeta=e.buildPrettyMeta):this.buildPrettyMeta=w,e.querystringParser?(n(typeof e.querystringParser==`function`,`querystringParser must be a function`),this.querystringParser=e.querystringParser):this.querystringParser=e=>e.length===0?{}:r.parse(e),this.caseSensitive=e.caseSensitive===void 0?!0:e.caseSensitive,this.ignoreTrailingSlash=e.ignoreTrailingSlash||!1,this.ignoreDuplicateSlashes=e.ignoreDuplicateSlashes||!1,this.maxParamLength=e.maxParamLength||100,this.allowUnsafeRegex=e.allowUnsafeRegex||!1,this.constrainer=new l(e.constraints),this.useSemicolonDelimiter=e.useSemicolonDelimiter||!1,this.routes=[],this.trees={}}v.prototype.on=function(e,t,r,i,a){typeof r==`function`&&(i!==void 0&&(a=i),i=r,r={}),n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(typeof i==`function`,`Handler should be a function`);let o=t.match(h);if(o){n(t.length===o.index+o[0].length,`Optional Parameter needs to be the last parameter of the path`);let s=t.replace(h,`$1$2`),c=t.replace(h,`$2`)||`/`;this.on(e,s,r,i,a),this.on(e,c,r,i,a);return}let s=t;this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let c=Array.isArray(e)?e:[e];for(let e of c)n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`),this._on(e,t,r,i,a,s)},v.prototype._on=function(e,t,r,o,c){let l={};r.constraints!==void 0&&(n(typeof r.constraints==`object`&&r.constraints!==null,`Constraints should be an object`),Object.keys(r.constraints).length!==0&&(l=r.constraints)),this.constrainer.validateConstraints(l),this.constrainer.noteUsage(l),this.trees[e]===void 0&&(this.trees[e]=new s(`/`));let u=t;if(u===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new s(``),this.trees[e].staticChildren[`/`]=t}let d=this.trees[e],f=d.prefix.length,p=[];for(let e=0;e<=u.length;e++){if(u.charCodeAt(e)===58&&u.charCodeAt(e+1)===58){e++;continue}let t=u.charCodeAt(e)===58&&u.charCodeAt(e+1)!==58,r=u.charCodeAt(e)===42;if(t||r||e===u.length&&e!==f){let t=u.slice(f,e);this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),d=d.createStaticChild(t)}if(t){let t=!1,r=!0,a=``,o=[],s=e+1;for(let c=s;;c++){let l=u.charCodeAt(c),m=l===40,h=l===45||l===46,g=l===47||c===u.length;if(m||h||g){let l=u.slice(s,c);if(p.push(l),t=t||m||h,m){let e=C(u,c),t=u.slice(c,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),o.push(S(t)),c=e+1,r=!0}else o.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=c;for(;c<u.length;c++){let e=u.charCodeAt(c);if(e===47)break;if(e===58)if(u.charCodeAt(c+1)===58)c++;else break}let v=u.slice(_,c);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),o.push(a=y(v))),s=c+1,g||u.charCodeAt(c)===47||c===u.length){let n=t?`()`+v:v,r=u.slice(e,c);u=u.slice(0,e+1)+n+u.slice(c),e+=n.length;let i=t?RegExp(`^`+o.join(``)+`$`):null;d=d.createParametricChild(i,v||null,r),f=e+1;break}}}}else if(r&&(p.push(`*`),d=d.createWildcardChild(),f=e+1,e!==u.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(u=u.toLowerCase()),u===`*`&&(u=`/*`);for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===u&&a(n,l))throw Error(`Method '${e}' already declared for route '${u}' with constraints '${JSON.stringify(l)}'`)}let m={method:e,path:t,pattern:u,params:p,opts:r,handler:o,store:c};this.routes.push(m),d.addRoute(m,this.constrainer)},v.prototype.hasRoute=function(e,t,n){return this.findRoute(e,t,n)!==null},v.prototype.findRoute=function(e,t,r={}){if(this.trees[e]===void 0)return null;let o=t,s=this.trees[e],c=s.prefix.length,l=[];for(let e=0;e<=o.length;e++){if(o.charCodeAt(e)===58&&o.charCodeAt(e+1)===58){e++;continue}let t=o.charCodeAt(e)===58&&o.charCodeAt(e+1)!==58,r=o.charCodeAt(e)===42;if(t||r||e===o.length&&e!==c){let t=o.slice(c,e);if(this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),s=s.getStaticChild(t),s===null)return null}if(t){let t=!1,r=!0,a=``,u=[],d=e+1;for(let f=d;;f++){let p=o.charCodeAt(f),m=p===40,h=p===45||p===46,g=p===47||f===o.length;if(m||h||g){let p=o.slice(d,f);if(l.push(p),t=t||m||h,m){let e=C(o,f),t=o.slice(f,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),u.push(S(t)),f=e+1,r=!1}else u.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=f;for(;f<o.length;f++){let e=o.charCodeAt(f);if(e===47)break;if(e===58)if(o.charCodeAt(f+1)===58)f++;else break}let v=o.slice(_,f);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),u.push(a=y(v))),d=f+1,g||o.charCodeAt(f)===47||f===o.length){let n=t?`()`+v:v,r=o.slice(e,f);o=o.slice(0,e+1)+n+o.slice(f),e+=n.length;let i=t?RegExp(`^`+u.join(``)+`$`):null;if(s=s.getParametricChild(i,v||null,r),s===null)return null;c=e+1;break}}}}else if(r&&(l.push(`*`),s=s.getWildcardChild(),c=e+1,e!==o.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(o=o.toLowerCase());for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===o&&a(n,r))return{handler:t.handler,store:t.store,params:t.params}}return null},v.prototype.hasConstraintStrategy=function(e){return this.constrainer.hasConstraintStrategy(e)},v.prototype.addConstraintStrategy=function(e){this.constrainer.addConstraintStrategy(e),this._rebuild(this.routes)},v.prototype.reset=function(){this.trees={},this.routes=[]},v.prototype.off=function(e,t,r){n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(r===void 0||typeof r==`object`&&!Array.isArray(r)&&r!==null,`Constraints should be an object or undefined.`);let i=t.match(h);if(i){n(t.length===i.index+i[0].length,`Optional Parameter needs to be the last parameter of the path`);let a=t.replace(h,`$1$2`),o=t.replace(h,`$2`);this.off(e,a,r),this.off(e,o,r);return}this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let a=Array.isArray(e)?e:[e];for(let e of a)this._off(e,t,r)},v.prototype._off=function(e,t,r){n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`);function i(n){return e!==n.method||t!==n.path}function o(e){return i(e)||!a(r,e.opts.constraints||{})}let s=r?o:i,c=this.routes.filter(s);this._rebuild(c)},v.prototype.lookup=function(e,t,n,r){if(typeof n==`function`&&(r=n,n=void 0),r===void 0){let r=this.constrainer.deriveConstraints(e,n),i=this.find(e.method,e.url,r);return this.callHandler(i,e,t,n)}this.constrainer.deriveConstraints(e,n,(i,a)=>{if(i!==null){r(i);return}try{let i=this.find(e.method,e.url,a),o=this.callHandler(i,e,t,n);r(null,o)}catch(e){r(e)}})},v.prototype.callHandler=function(e,t,n,r){return e===null?this._defaultRoute(t,n,r):r===void 0?e.handler(t,n,e.params,e.store,e.searchParams):e.handler.call(r,t,n,e.params,e.store,e.searchParams)},v.prototype.find=function(e,t,n){let r=this.trees[e];if(r===void 0)return null;t.charCodeAt(0)!==47&&(t=t.replace(m,`/`)),this.ignoreDuplicateSlashes&&(t=b(t));let i,a,o;try{i=f(t,this.useSemicolonDelimiter),t=i.path,a=i.querystring,o=i.shouldDecodeParam}catch{return this._onBadUrl(t)}this.ignoreTrailingSlash&&(t=x(t));let s=t;this.caseSensitive===!1&&(t=t.toLowerCase());let l=this.maxParamLength,u=r.prefix.length,d=[],h=t.length,g=[];for(;;){if(u===h&&r.isLeafNode){let e=r.handlerStorage.getMatchingHandler(n);if(e!==null)return{handler:e.handler,store:e.store,params:e._createParamsObject(d),searchParams:this.querystringParser(a)}}let e=r.getNextNode(t,u,g,d.length);if(e===null){if(g.length===0)return null;let t=g.pop();u=t.brotherPathIndex,d.splice(t.paramsCount),e=t.brotherNode}if(r=e,r.kind===c.STATIC){u+=r.prefix.length;continue}if(r.kind===c.WILDCARD){let e=s.slice(u);o&&(e=p(e)),d.push(e),u=h;continue}let i=s.indexOf(`/`,u);i===-1&&(i=h);let f=s.slice(u,i);if(o&&(f=p(f)),r.isRegex){let e=r.regex.exec(f);if(e===null)continue;for(let t=1;t<e.length;t++){let n=e[t];if(n.length>l)return null;d.push(n)}}else{if(f.length>l)return null;d.push(f)}u=i}},v.prototype._rebuild=function(e){this.reset();for(let t of e){let{method:e,path:n,opts:r,handler:i,store:a}=t;this._on(e,n,r,i,a)}},v.prototype._defaultRoute=function(e,t,n){if(this.defaultRoute!==null)return n===void 0?this.defaultRoute(e,t):this.defaultRoute.call(n,e,t);t.statusCode=404,t.end()},v.prototype._onBadUrl=function(e){if(this.onBadUrl===null)return null;let t=this.onBadUrl;return{handler:(n,r,i)=>t(e,n,r),params:{},store:null}},v.prototype.prettyPrint=function(e={}){let t=e.method;e.buildPrettyMeta=this.buildPrettyMeta.bind(this);let n=null;if(t===void 0){let{version:e,host:t,...r}=this.constrainer.strategies;r[d.name]=d;let i=new v({...this._opts,constraints:r}),a=this.routes.map(e=>{let t={...e.opts.constraints,[d.name]:e.method};return{...e,method:`MERGED`,opts:{constraints:t}}});i._rebuild(a),n=i.trees.MERGED}else n=this.trees[t];return n==null?`(empty tree)`:o(n,e)};for(let e in u){if(!u.hasOwnProperty(e))continue;let t=u[e],n=t.toLowerCase();v.prototype[n]=function(e,n,r){return this.on(t,e,n,r)}}v.prototype.all=function(e,t,n){this.on(u,e,t,n)},v.sanitizeUrlPath=function(e,t){let n=f(e,t);return n.shouldDecodeParam?p(n.path):n.path},t.exports=v;function y(e){return e.replace(g,`\\$&`)}function b(e){return e.indexOf(`//`)===-1?e:e.replace(_,`/`)}function x(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function S(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function C(e,t){let n=1;for(;t<e.length;){if(t++,e.charCodeAt(t)===92){t++;continue}if(e.charCodeAt(t)===41?n--:e.charCodeAt(t)===40&&n++,!n)return t}throw TypeError(`Invalid regexp expression in "`+e+`"`)}function w(e){return!e||!e.store?{}:Object.assign({},e.store)}})),Ym=o(((e,t)=>{function n(e,t,n,r){if(n===void 0){t.header(`content-length`,`0`),r(null,null);return}if(typeof n.resume==`function`){n.on(`error`,e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),n.resume(),r(null,null);return}if(typeof n.getReader==`function`){n.cancel(`Stream cancelled by HEAD route`).catch(e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),r(null,null);return}let i=``+Buffer.byteLength(n);t.header(`content-length`,i),r(null,null)}function r(e){return e==null?n:Array.isArray(e)?[...e,n]:[e,n]}t.exports={parseHeadOnSendHandlers:r}})),Xm=o(((e,t)=>{let n=Jm(),r=xd(),i=ju(),{onRequestAbortHookRunner:a,lifecycleHooks:o,preParsingHookRunner:s,onTimeoutHookRunner:c,onRequestHookRunner:l}=Cu(),{normalizeSchema:u}=dd(),{parseHeadOnSendHandlers:d}=Ym(),{compileSchemasForValidation:f,compileSchemasForSerialization:p}=Au(),{FST_ERR_SCH_VALIDATION_BUILD:m,FST_ERR_SCH_SERIALIZATION_BUILD:h,FST_ERR_DUPLICATED_ROUTE:g,FST_ERR_INVALID_URL:_,FST_ERR_HOOK_INVALID_HANDLER:v,FST_ERR_ROUTE_OPTIONS_NOT_OBJ:y,FST_ERR_ROUTE_DUPLICATED_HANDLER:b,FST_ERR_ROUTE_HANDLER_NOT_FN:x,FST_ERR_ROUTE_MISSING_HANDLER:S,FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:C,FST_ERR_ROUTE_METHOD_INVALID:w,FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:T,FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:E,FST_ERR_HOOK_INVALID_ASYNC_HANDLER:D}=Su(),{kRoutePrefix:O,kSupportedHTTPMethods:k,kLogLevel:A,kLogSerializers:j,kHooks:M,kSchemaController:ee,kOptions:N,kReplySerializerDefault:te,kReplyIsError:P,kRequestPayloadStream:ne,kDisableRequestLogging:re,kSchemaErrorFormatter:F,kErrorHandler:ie,kHasBeenDecorated:I,kRequestAcceptVersion:ae,kRouteByFastify:oe,kRouteContext:L}=yu(),{buildErrorHandler:se}=md(),{createChildLogger:ce}=ld(),{getGenReqId:le}=bm(),{FSTDEP022:ue}=xu(),de=[`allowUnsafeRegex`,`buildPrettyMeta`,`caseSensitive`,`constraints`,`defaultRoute`,`ignoreDuplicateSlashes`,`ignoreTrailingSlash`,`maxParamLength`,`onBadUrl`,`querystringParser`,`useSemicolonDelimiter`];function fe(e){let t=n(e),i,s,c,C,w,T,E,k,P,ne,L,ue,de,fe=!1;return{setup(e,t){i=t.avvio,s=t.fourOhFour,c=e.logger,C=t.hasLogger,w=t.setupResponseListeners,T=t.throwIfAlreadyStarted,ue=e.exposeHeadRoutes,E=e.disableRequestLogging,typeof E==`function`&&(k=e.disableRequestLogging),P=e.routerOptions.ignoreTrailingSlash,ne=e.routerOptions.ignoreDuplicateSlashes,L=Object.hasOwn(e,`return503OnClosing`)?e.return503OnClosing:!0,de=t.keepAliveConnections},routing:t.lookup.bind(t),route:Ee,hasRoute:we,prepareRoute:Ce,routeHandler:De,closeRoutes:()=>{fe=!0},printRoutes:t.prettyPrint.bind(t),addConstraintStrategy:ye,hasConstraintStrategy:xe,isAsyncConstraint:Se,findRoute:Te};function ye(e){return T(`Cannot add constraint strategy!`),t.addConstraintStrategy(e)}function xe(e){return t.hasConstraintStrategy(e)}function Se(){return t.constrainer.asyncStrategiesInUse.size>0}function Ce({method:e,url:t,options:n,handler:r,isFastify:i}){if(typeof t!=`string`)throw new _(typeof t);if(!r&&typeof n==`function`)r=n,n={};else if(r&&typeof r==`function`){if(Object.prototype.toString.call(n)!==`[object Object]`)throw new y(e,t);if(n.handler)throw typeof n.handler==`function`?new b(e,t):new x(e,t)}return n=Object.assign({},n,{method:e,url:t,path:t,handler:r||n&&n.handler}),Ee.call(this,{options:n,isFastify:i})}function we({options:e}){let n=e.method?.toUpperCase()??``;return t.hasRoute(n,e.url||``,e.constraints)}function Te(e){let n=t.find(e.method,e.url||``,e.constraints);return n?{handler:n.handler,params:n.params,searchParams:n.searchParams}:null}function Ee({options:e,isFastify:n}){T(`Cannot add route!`);let a={...e},c=a.url||a.path||``;if(!a.handler)throw new S(a.method,c);if(a.errorHandler!==void 0&&typeof a.errorHandler!=`function`)throw new x(a.method,c);_e(a.bodyLimit);let l=a.exposeHeadRoute??ue,_=!1,y=!1;if(Array.isArray(a.method))for(let e=0;e<a.method.length;++e)a.method[e]=he.call(this,a.method[e]),ge.call(this,a.method[e],c,a.schema),_=a.method.includes(`GET`),y=a.method.includes(`HEAD`);else a.method=he.call(this,a.method),ge.call(this,a.method,c,a.schema),_=a.method===`GET`,y=a.method===`HEAD`;let b=l&&_?{...e}:null,C=this[O];if(c===`/`&&C.length>0&&a.method!==`HEAD`)switch(a.prefixTrailingSlash){case`slash`:w.call(this,{path:c,isFastify:n});break;case`no-slash`:w.call(this,{path:``,isFastify:n});break;default:w.call(this,{path:``,isFastify:n}),P!==!0&&(ne!==!0||!C.endsWith(`/`))&&w.call(this,{path:c,prefixing:!0,isFastify:n})}else c[0]===`/`&&C.endsWith(`/`)?w.call(this,{path:c.slice(1),isFastify:n}):w.call(this,{path:c,isFastify:n});return this;function w({path:e,prefixing:n=!1,isFastify:c=!1}){let x=C+e;if(a.url=x,a.path=x,a.routePath=e,a.prefix=C,a.logLevel=a.logLevel||this[A],(this[j]||a.logSerializers)&&(a.logSerializers=Object.assign(Object.create(this[j]),a.logSerializers)),a.attachValidation??=!1,n===!1)for(let e of this[M].onRoute)e.call(this,a);for(let e of o)if(a&&e in a){if(Array.isArray(a[e]))for(let t of a[e]){if(typeof t!=`function`)throw new v(e,Object.prototype.toString.call(t));if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new D}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new D}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new D}else if(a[e]!==void 0&&typeof a[e]!=`function`)throw new v(e,Object.prototype.toString.call(a[e]))}let S=a.constraints||{},w={...a.config,url:x,method:a.method},T=new r({schema:a.schema,handler:a.handler.bind(this),config:w,errorHandler:a.errorHandler,childLoggerFactory:a.childLoggerFactory,bodyLimit:a.bodyLimit,logLevel:a.logLevel,logSerializers:a.logSerializers,attachValidation:a.attachValidation,schemaErrorFormatter:a.schemaErrorFormatter,replySerializer:this[te],validatorCompiler:a.validatorCompiler,serializerCompiler:a.serializerCompiler,exposeHeadRoute:l,prefixTrailingSlash:a.prefixTrailingSlash||`both`,server:this,isFastify:c}),E=t.findRoute(`HEAD`,a.url,S)!==null;try{t.on(a.method,a.url,{constraints:S},De,T)}catch(e){if(!T[oe])throw e.message.includes(`Method '${a.method}' already declared for route`)?new g(a.method,a.url):e}if(this.after((e,t)=>{T.errorHandler=a.errorHandler?se(this[ie],a.errorHandler):this[ie],T._parserOptions.limit=a.bodyLimit||null,T.logLevel=a.logLevel,T.logSerializers=a.logSerializers,T.attachValidation=a.attachValidation,T[te]=this[te],T.schemaErrorFormatter=a.schemaErrorFormatter||this[F]||T.schemaErrorFormatter,i.once(`preReady`,()=>{for(let e of o){let t=this[M][e].concat(a[e]||[]).map(e=>e.bind(this));T[e]=t.length?t:null}for(;!T.Request[I]&&T.Request.parent;)T.Request=T.Request.parent;for(;!T.Reply[I]&&T.Reply.parent;)T.Reply=T.Reply.parent;if(s.setContext(this,T),a.schema){T.schema=u(T.schema,this.initialConfig);let e=this[ee],t=a.schema.body||a.schema.headers||a.schema.querystring||a.schema.params;!a.validatorCompiler&&t&&e.setupValidator(this[N]);try{let t=typeof a?.validatorCompiler==`function`||e.isCustomValidatorCompiler;f(T,a.validatorCompiler||e.validatorCompiler,t)}catch(e){throw new m(a.method,x,e.message)}a.schema.response&&!a.serializerCompiler&&e.setupSerializer(this[N]);try{p(T,a.serializerCompiler||e.serializerCompiler)}catch(e){throw new h(a.method,x,e.message)}}}),t(e)}),l&&_&&!y&&!E){let t=d(b.onSend);Ce.call(this,{method:`HEAD`,url:e,options:{...b,onSend:t},isFastify:!0})}}}function De(e,t,n,r,i){let o=le(r.server,e),s={level:r.logLevel};r.logSerializers&&(s.serializers=r.logSerializers);let u=ce(r,c,e,o,s);if(u[re]=k?!1:E,fe===!0&&(e.httpVersionMajor!==2&&t.setHeader(`Connection`,`close`),L)){t.writeHead(503,{"Content-Type":`application/json`,"Content-Length":`80`}),t.end(`{"error":"Service Unavailable","message":"Service Unavailable","statusCode":503}`),u.info({res:{statusCode:503}},`request aborted - refusing to accept new requests as server is closing`);return}String.prototype.toLowerCase.call(e.headers.connection||``)===`keep-alive`&&de.has(e.socket)===!1&&(de.add(e.socket),e.socket.on(`close`,be.bind({keepAliveConnections:de,socket:e.socket}))),e.headers[ae]!==void 0&&(e.headers[`accept-version`]=e.headers[ae],e.headers[ae]=void 0);let d=new r.Request(o,n,e,i,u,r),f=new r.Reply(t,d,u),p=k?k(d):E;u[re]=p,p===!1&&u.info({req:d},`incoming request`),(C===!0||r.onResponse!==null)&&w(f),r.onRequest===null?ve(null,d,f):l(r.onRequest,d,f,ve),r.onRequestAbort!==null&&e.on(`close`,()=>{e.aborted&&a(r.onRequestAbort,d,pe.bind(null,f))}),r.onTimeout!==null&&(d.raw.socket._meta||d.raw.socket.on(`timeout`,me),d.raw.socket._meta={context:r,request:d,reply:f})}}function pe(e,t){t&&e.log.error({err:t},`onRequestAborted hook failed`)}function me(){let{context:e,request:t,reply:n}=this._meta;c(e.onTimeout,t,n,xe)}function he(e){if(typeof e!=`string`)throw new w;if(e=e.toUpperCase(),!this[k].bodyless.has(e)&&!this[k].bodywith.has(e))throw new C(e);return e}function ge(e,t,n){if(this[k].bodyless.has(e)&&n?.body)throw new T(e,t)}function _e(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw new E(e)}function ve(e,t,n){if(n.sent!==!0){if(e!=null){n[P]=!0,n.send(e);return}t[ne]=t.raw,t[L].preParsing===null?i.call(t.server,null,t,n):s(t[L].preParsing,t,n,i.bind(t.server))}}function ye(e,t){let n=e.routerOptions||Object.create(null),r=de.filter(t=>Object.hasOwn(e,t));r.length>0&&ue(r.join(`, `));for(let r of de)Object.hasOwn(n,r)||(n[r]=e[r]??t[r]);return n}function be(){this.keepAliveConnections.delete(this.socket)}function xe(){}t.exports={buildRouting:fe,validateBodyLimitOption:_e,buildRouterOptions:ye}})),Zm=o(((e,t)=>{let n=Jm(),r=gd(),i=bd(),a=xd(),{kRoutePrefix:o,kCanSetNotFoundHandler:s,kFourOhFourLevelInstance:c,kFourOhFourContext:l,kHooks:u,kErrorHandler:d}=yu(),{lifecycleHooks:f}=Cu(),{buildErrorHandler:p}=md(),{FST_ERR_NOT_FOUND:m}=Su(),{createChildLogger:h}=ld(),{getGenReqId:g}=bm();function _(e){let{logger:t,disableRequestLogging:_}=e,v=n({onBadUrl:S(),defaultRoute:E}),y=null;return{router:v,setNotFoundHandler:w,setContext:C,arrange404:b};function b(e){e[c]=e,e[s]=!0,v.onBadUrl=v.onBadUrl.bind(e),v.defaultRoute=v.defaultRoute.bind(e)}function x(e,t){let{url:n,method:r}=e.raw,i=`Route ${r}:${n} not found`;(typeof _==`function`?_(e.raw):_)||e.log.info(i),t.code(404).send({message:i,error:`Not Found`,statusCode:404})}function S(){return function(e,n,a){let o=this[c][l],s=g(o.server,n),u=h(o,t,n,s),d=new i(s,null,n,null,u,o),f=new r(a,d,u);y(d,f)}}function C(e,t){let n=Object.assign({},e[l]);n.onSend=t.onSend,t[l]=n}function w(e,t,n,r){this[s]===void 0&&(this[s]=!0),this[l]===void 0&&(this[l]=null);let i=this,a=this[o]||`/`;if(this[s]===!1)throw Error(`Not found handler already set for Fastify instance with prefix: '${a}'`);typeof e==`object`&&(e.preHandler&&(Array.isArray(e.preHandler)?e.preHandler=e.preHandler.map(e=>e.bind(i)):e.preHandler=e.preHandler.bind(i)),e.preValidation&&(Array.isArray(e.preValidation)?e.preValidation=e.preValidation.map(e=>e.bind(i)):e.preValidation=e.preValidation.bind(i))),typeof e==`function`&&(t=e,e=void 0),e||={},t?(this[c][s]=!1,t=t.bind(this),y=t):(t=x,y=x),this.after((i,o)=>{T.call(this,a,e,t,n,r),o(i)})}function T(e,t,n,r,i){let o=new a({schema:t.schema,handler:n,config:t.config||{},server:this});if(r.once(`preReady`,()=>{let e=this[l];for(let n of f){let r=this[u][n].concat(t[n]||[]).map(e=>e.bind(this));e[n]=r.length?r:null}e.errorHandler=t.errorHandler?p(this[d],t.errorHandler):this[d]}),this[l]!==null&&e===`/`){Object.assign(this[l],o);return}this[c][l]=o,v.all(e+(e.endsWith(`/`)?`*`:`/*`),i,o),v.all(e,i,o)}function E(e,n){let a=this[c][l],o=g(a.server,e),s=h(a,t,e,o);s.info({req:e},`incoming request`);let u=new i(o,null,e,null,s,a),d=new r(n,u,s);u.log.warn(`the default handler for 404 did not catch this, this is likely a fastify bug, please report it`),u.log.warn(v.prettyPrint()),d.code(404).send(new m)}}t.exports=_})),Qm=o(((e,t)=>{t.exports=a,t.exports.default=a;let n={type:`object`,additionalProperties:!1,properties:{connectionTimeout:{type:`integer`,default:0},keepAliveTimeout:{type:`integer`,default:72e3},forceCloseConnections:{oneOf:[{type:`string`,pattern:`idle`},{type:`boolean`}]},maxRequestsPerSocket:{type:`integer`,default:0,nullable:!0},requestTimeout:{type:`integer`,default:0},bodyLimit:{type:`integer`,default:1048576},caseSensitive:{type:`boolean`,default:!0},allowUnsafeRegex:{type:`boolean`,default:!1},http2:{type:`boolean`},https:{if:{not:{oneOf:[{type:`boolean`},{type:`null`},{type:`object`,additionalProperties:!1,required:[`allowHTTP1`],properties:{allowHTTP1:{type:`boolean`}}}]}},then:{setDefaultValue:!0}},ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},disableRequestLogging:{default:!1},maxParamLength:{type:`integer`,default:100},onProtoPoisoning:{type:`string`,default:`error`},onConstructorPoisoning:{type:`string`,default:`error`},pluginTimeout:{type:`integer`,default:1e4},requestIdHeader:{anyOf:[{type:`boolean`},{type:`string`}],default:!1},requestIdLogLabel:{type:`string`,default:`reqId`},http2SessionTimeout:{type:`integer`,default:72e3},exposeHeadRoutes:{type:`boolean`,default:!0},useSemicolonDelimiter:{type:`boolean`,default:!1},routerOptions:{type:`object`,additionalProperties:!0,properties:{ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},maxParamLength:{type:`integer`,default:100},allowUnsafeRegex:{type:`boolean`,default:!1},useSemicolonDelimiter:{type:`boolean`,default:!1}}},constraints:{type:`object`,additionalProperties:{type:`object`,required:[`name`,`storage`,`validate`,`deriveConstraint`],additionalProperties:!0,properties:{name:{type:`string`},storage:{},validate:{},deriveConstraint:{}}}}}},r=Object.prototype.hasOwnProperty,i=RegExp(`idle`,`u`);function a(e,{instancePath:t=``,parentData:o,parentDataProperty:s,rootData:c=e}={}){let l=null,u=0;if(u===0)if(e&&typeof e==`object`&&!Array.isArray(e)){e.connectionTimeout===void 0&&(e.connectionTimeout=0),e.keepAliveTimeout===void 0&&(e.keepAliveTimeout=72e3),e.maxRequestsPerSocket===void 0&&(e.maxRequestsPerSocket=0),e.requestTimeout===void 0&&(e.requestTimeout=0),e.bodyLimit===void 0&&(e.bodyLimit=1048576),e.caseSensitive===void 0&&(e.caseSensitive=!0),e.allowUnsafeRegex===void 0&&(e.allowUnsafeRegex=!1),e.ignoreTrailingSlash===void 0&&(e.ignoreTrailingSlash=!1),e.ignoreDuplicateSlashes===void 0&&(e.ignoreDuplicateSlashes=!1),e.disableRequestLogging===void 0&&(e.disableRequestLogging=!1),e.maxParamLength===void 0&&(e.maxParamLength=100),e.onProtoPoisoning===void 0&&(e.onProtoPoisoning=`error`),e.onConstructorPoisoning===void 0&&(e.onConstructorPoisoning=`error`),e.pluginTimeout===void 0&&(e.pluginTimeout=1e4),e.requestIdHeader===void 0&&(e.requestIdHeader=!1),e.requestIdLogLabel===void 0&&(e.requestIdLogLabel=`reqId`),e.http2SessionTimeout===void 0&&(e.http2SessionTimeout=72e3),e.exposeHeadRoutes===void 0&&(e.exposeHeadRoutes=!0),e.useSemicolonDelimiter===void 0&&(e.useSemicolonDelimiter=!1);let o=u;for(let t in e)r.call(n.properties,t)||delete e[t];if(o===u){let n=e.connectionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/connectionTimeout`,schemaPath:`#/properties/connectionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.connectionTimeout=i))}var d=r===u;if(d){let n=e.keepAliveTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/keepAliveTimeout`,schemaPath:`#/properties/keepAliveTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.keepAliveTimeout=i))}var d=r===u;if(d){if(e.forceCloseConnections!==void 0){let n=e.forceCloseConnections,r=u,o=u,s=!1,c=null,p=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.forceCloseConnections=i))}if(u===p&&typeof n==`string`&&!i.test(n)){let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/pattern`,keyword:`pattern`,params:{pattern:`idle`},message:`must match pattern "idle"`};l===null?l=[e]:l.push(e),u++}var f=p===u;f&&(s=!0,c=0);let m=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/1/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.forceCloseConnections=r))}var f=m===u;if(f&&s?(s=!1,c=[c,1]):f&&(s=!0,c=1),s)u=o,l!==null&&(o?l.length=o:l=null);else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf`,keyword:`oneOf`,params:{passingSchemas:c},message:`must match exactly one schema in oneOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.maxRequestsPerSocket,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))&&n!==null){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else if(n===``||n===0||n===!1)i=null;else return a.errors=[{instancePath:t+`/maxRequestsPerSocket`,schemaPath:`#/properties/maxRequestsPerSocket/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxRequestsPerSocket=i))}var d=r===u;if(d){let n=e.requestTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/requestTimeout`,schemaPath:`#/properties/requestTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestTimeout=i))}var d=r===u;if(d){let n=e.bodyLimit,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/bodyLimit`,schemaPath:`#/properties/bodyLimit/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.bodyLimit=i))}var d=r===u;if(d){let n=e.caseSensitive,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/caseSensitive`,schemaPath:`#/properties/caseSensitive/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.caseSensitive=r))}var d=r===u;if(d){let n=e.allowUnsafeRegex,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/allowUnsafeRegex`,schemaPath:`#/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.allowUnsafeRegex=r))}var d=r===u;if(d){if(e.http2!==void 0){let n=e.http2,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/http2`,schemaPath:`#/properties/http2/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.http2=r))}var d=r===u}else var d=!0;if(d){if(e.https!==void 0){let n=e.https,r=u,i=u,o=!0,s=u,c=u,f=u,h=u,g=!1,_=null,v=u;if(typeof n!=`boolean`){let t;if(t===void 0)if(n===`false`||n===0||n===null)t=!1;else if(n===`true`||n===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=v===u;p&&(g=!0,_=0);let y=u;if(n!==null){let t;if(t===void 0)if(n===``||n===0||n===!1)t=null;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=y===u;if(p&&g)g=!1,_=[_,1];else{p&&(g=!0,_=1);let e=u;if(u===e)if(n&&typeof n==`object`&&!Array.isArray(n))if(n.allowHTTP1===void 0){let e={};l===null?l=[e]:l.push(e),u++}else{let e=u;for(let e in n)e!==`allowHTTP1`&&delete n[e];if(e===u&&n.allowHTTP1!==void 0){let e=n.allowHTTP1;if(typeof e!=`boolean`){let t;if(t===void 0)if(e===`false`||e===0||e===null)t=!1;else if(e===`true`||e===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(e=t,n!==void 0&&(n.allowHTTP1=t))}}}else{let e={};l===null?l=[e]:l.push(e),u++}var p=e===u;p&&g?(g=!1,_=[_,2]):p&&(g=!0,_=2)}if(g)u=h,l!==null&&(h?l.length=h:l=null);else{let e={};l===null?l=[e]:l.push(e),u++}if(f===u){let e={};l===null?l=[e]:l.push(e),u++}else u=c,l!==null&&(c?l.length=c:l=null);var m=s===u;if(u=i,l!==null&&(i?l.length=i:l=null),m){let t=u;e.https=!0;var m=t===u;o=m}if(!o){let e={instancePath:t+`/https`,schemaPath:`#/properties/https/if`,keyword:`if`,params:{failingKeyword:`then`},message:`must match "then" schema`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.ignoreTrailingSlash,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreTrailingSlash`,schemaPath:`#/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreTrailingSlash=r))}var d=r===u;if(d){let n=e.ignoreDuplicateSlashes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreDuplicateSlashes`,schemaPath:`#/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreDuplicateSlashes=r))}var d=r===u;if(d){let n=e.maxParamLength,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/maxParamLength`,schemaPath:`#/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxParamLength=i))}var d=r===u;if(d){let n=e.onProtoPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onProtoPoisoning`,schemaPath:`#/properties/onProtoPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onProtoPoisoning=i))}var d=r===u;if(d){let n=e.onConstructorPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onConstructorPoisoning`,schemaPath:`#/properties/onConstructorPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onConstructorPoisoning=i))}var d=r===u;if(d){let n=e.pluginTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/pluginTimeout`,schemaPath:`#/properties/pluginTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.pluginTimeout=i))}var d=r===u;if(d){let n=e.requestIdHeader,r=u,i=u,o=!1,s=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/0/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.requestIdHeader=r))}var h=s===u;if(o||=h,!o){let r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.requestIdHeader=i))}var h=r===u;o||=h}if(o)u=i,l!==null&&(i?l.length=i:l=null);else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u;if(d){let n=e.requestIdLogLabel,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/requestIdLogLabel`,schemaPath:`#/properties/requestIdLogLabel/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestIdLogLabel=i))}var d=r===u;if(d){let n=e.http2SessionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/http2SessionTimeout`,schemaPath:`#/properties/http2SessionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.http2SessionTimeout=i))}var d=r===u;if(d){let n=e.exposeHeadRoutes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/exposeHeadRoutes`,schemaPath:`#/properties/exposeHeadRoutes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.exposeHeadRoutes=r))}var d=r===u;if(d){let n=e.useSemicolonDelimiter,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/useSemicolonDelimiter`,schemaPath:`#/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.useSemicolonDelimiter=r))}var d=r===u;if(d){if(e.routerOptions!==void 0){let n=e.routerOptions,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n)){n.ignoreTrailingSlash===void 0&&(n.ignoreTrailingSlash=!1),n.ignoreDuplicateSlashes===void 0&&(n.ignoreDuplicateSlashes=!1),n.maxParamLength===void 0&&(n.maxParamLength=100),n.allowUnsafeRegex===void 0&&(n.allowUnsafeRegex=!1),n.useSemicolonDelimiter===void 0&&(n.useSemicolonDelimiter=!1);let e=n.ignoreTrailingSlash,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreTrailingSlash`,schemaPath:`#/properties/routerOptions/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreTrailingSlash=r))}var g=r===u;if(g){let e=n.ignoreDuplicateSlashes,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreDuplicateSlashes`,schemaPath:`#/properties/routerOptions/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreDuplicateSlashes=r))}var g=r===u;if(g){let e=n.maxParamLength,r=u;if(!(typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e))){let r=typeof e,i;if(i===void 0)if(r===`boolean`||e===null||r===`string`&&e&&e==+e&&!(e%1))i=+e;else return a.errors=[{instancePath:t+`/routerOptions/maxParamLength`,schemaPath:`#/properties/routerOptions/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.maxParamLength=i))}var g=r===u;if(g){let e=n.allowUnsafeRegex,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/allowUnsafeRegex`,schemaPath:`#/properties/routerOptions/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.allowUnsafeRegex=r))}var g=r===u;if(g){let e=n.useSemicolonDelimiter,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/useSemicolonDelimiter`,schemaPath:`#/properties/routerOptions/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.useSemicolonDelimiter=r))}var g=r===u}}}}}else return a.errors=[{instancePath:t+`/routerOptions`,schemaPath:`#/properties/routerOptions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0;if(d)if(e.constraints!==void 0){let n=e.constraints,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=u;if(u===i)if(r&&typeof r==`object`&&!Array.isArray(r)){let n;if(r.name===void 0&&(n=`name`)||r.storage===void 0&&(n=`storage`)||r.validate===void 0&&(n=`validate`)||r.deriveConstraint===void 0&&(n=`deriveConstraint`))return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`}],!1;if(r.name!==void 0){let n=r.name;if(typeof n!=`string`){let i=typeof n,o;if(o===void 0)if(i==`number`||i==`boolean`)o=``+n;else if(n===null)o=``;else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/name`,schemaPath:`#/properties/constraints/additionalProperties/properties/name/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;o!==void 0&&(n=o,r!==void 0&&(r.name=o))}}}else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;if(i!==u)break}else return a.errors=[{instancePath:t+`/constraints`,schemaPath:`#/properties/constraints/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}else return a.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return a.errors=l,u===0}t.exports.defaultInitOptions={connectionTimeout:0,keepAliveTimeout:72e3,maxRequestsPerSocket:0,requestTimeout:0,bodyLimit:1048576,caseSensitive:!0,allowUnsafeRegex:!1,disableRequestLogging:!1,ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,onProtoPoisoning:`error`,onConstructorPoisoning:`error`,pluginTimeout:1e4,requestIdHeader:!1,requestIdLogLabel:`reqId`,http2SessionTimeout:72e3,exposeHeadRoutes:!0,useSemicolonDelimiter:!1,allowErrorHandlerOverride:!0,routerOptions:{ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,allowUnsafeRegex:!1,useSemicolonDelimiter:!1}}})),$m=o(((e,t)=>{let n=Qm(),r=ud()({circles:!0,proto:!1}),{FST_ERR_INIT_OPTS_INVALID:i}=Su();function a(e){let t=r(e);if(!n(t)){let e=new i(JSON.stringify(n.errors.map(e=>e.message)));throw e.errors=n.errors,e}return o(t)}function o(e){let t=Object.getOwnPropertyNames(e);for(let n of t){let t=e[n];ArrayBuffer.isView(t)&&!(t instanceof DataView)||(e[n]=t&&typeof t==`object`?o(t):t)}return Object.freeze(e)}t.exports=a,t.exports.defaultInitOptions=n.defaultInitOptions,t.exports.utils={deepFreezeObject:o}})),eh=o(((e,t)=>{let{kAvvioBoot:n,kChildren:r,kRoutePrefix:i,kLogLevel:a,kLogSerializers:o,kHooks:s,kSchemaController:c,kContentTypeParser:l,kReply:u,kRequest:d,kFourOhFour:f,kPluginNameChain:p,kErrorHandlerAlreadySet:m}=yu(),h=gd(),g=bd(),_=Dp(),v=wd(),{buildHooks:y}=Cu(),b=ym();t.exports=function(e,t,S){let C=b.registerPlugin.call(e,t),w=b.getPluginName(t)||b.getFuncPreview(t);if(C)return e[p].push(w),e;let T=Object.create(e);e[r].push(T),T.ready=e[n].bind(T),T[r]=[],T[u]=h.buildReply(T[u]),T[d]=g.buildRequest(T[d]),T[l]=v.helpers.buildContentTypeParser(T[l]),T[s]=y(T[s]),T[i]=x(T[i],S.prefix),T[a]=S.logLevel||T[a],T[c]=_.buildSchemaController(e[c]),T.getSchema=T[c].getSchema.bind(T[c]),T.getSchemas=T[c].getSchemas.bind(T[c]),T[b.kRegisteredPlugins]=Object.create(T[b.kRegisteredPlugins]),T[p]=[w],T[m]=!1,(T[o]||S.logSerializers)&&(T[o]=Object.assign(Object.create(T[o]),S.logSerializers)),S.prefix&&T[f].arrange404(T);for(let t of T[s].onRegister)t.call(e,T,S);return T};function x(e,t){return t?(e.endsWith(`/`)&&t[0]===`/`?t=t.slice(1):t[0]!==`/`&&(t=`/`+t),e+t):e}})),th=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseCookie=c,e.parse=c,e.stringifyCookie=l,e.stringifySetCookie=u,e.serialize=u,e.parseSetCookie=d,e.stringifySetCookie=u,e.serialize=u;let t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,r=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,i=/^[\u0020-\u003A\u003D-\u007E]*$/,a=/^-?\d+$/,o=Object.prototype.toString,s=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function c(e,t){let n=new s,r=e.length;if(r<2)return n;let i=t?.decode||h,a=0;do{let t=p(e,a,r);if(t===-1)break;let o=f(e,a,r);if(t>o){a=e.lastIndexOf(`;`,t-1)+1;continue}let s=m(e,a,t);n[s]===void 0&&(n[s]=i(m(e,t+1,o))),a=o+1}while(a<r);return n}function l(e,r){let i=r?.encode||encodeURIComponent,a=[];for(let r of Object.keys(e)){let o=e[r];if(o===void 0)continue;if(!t.test(r))throw TypeError(`cookie name is invalid: ${r}`);let s=i(o);if(!n.test(s))throw TypeError(`cookie val is invalid: ${o}`);a.push(`${r}=${s}`)}return a.join(`; `)}function u(e,a,o){let s=typeof e==`object`?e:{...o,name:e,value:String(a)},c=(typeof a==`object`?a:o)?.encode||encodeURIComponent;if(!t.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let l=s.value?c(s.value):``;if(!n.test(l))throw TypeError(`argument val is invalid: ${s.value}`);let u=s.name+`=`+l;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);u+=`; Max-Age=`+s.maxAge}if(s.domain){if(!r.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);u+=`; Domain=`+s.domain}if(s.path){if(!i.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);u+=`; Path=`+s.path}if(s.expires){if(!g(s.expires)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invalid: ${s.expires}`);u+=`; Expires=`+s.expires.toUTCString()}if(s.httpOnly&&(u+=`; HttpOnly`),s.secure&&(u+=`; Secure`),s.partitioned&&(u+=`; Partitioned`),s.priority)switch(typeof s.priority==`string`?s.priority.toLowerCase():void 0){case`low`:u+=`; Priority=Low`;break;case`medium`:u+=`; Priority=Medium`;break;case`high`:u+=`; Priority=High`;break;default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite==`string`?s.sameSite.toLowerCase():s.sameSite){case!0:case`strict`:u+=`; SameSite=Strict`;break;case`lax`:u+=`; SameSite=Lax`;break;case`none`:u+=`; SameSite=None`;break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return u}function d(e,t){let n=t?.decode||h,r=e.length,i=f(e,0,r),o=p(e,0,i),s=o===-1?{name:``,value:n(m(e,0,i))}:{name:m(e,0,o),value:n(m(e,o+1,i))},c=i+1;for(;c<r;){let t=f(e,c,r),n=p(e,c,t),i=n===-1?m(e,c,t):m(e,c,n),o=n===-1?void 0:m(e,n+1,t);switch(i.toLowerCase()){case`httponly`:s.httpOnly=!0;break;case`secure`:s.secure=!0;break;case`partitioned`:s.partitioned=!0;break;case`domain`:s.domain=o;break;case`path`:s.path=o;break;case`max-age`:o&&a.test(o)&&(s.maxAge=Number(o));break;case`expires`:if(!o)break;let e=new Date(o);Number.isFinite(e.valueOf())&&(s.expires=e);break;case`priority`:if(!o)break;let t=o.toLowerCase();(t===`low`||t===`medium`||t===`high`)&&(s.priority=t);break;case`samesite`:if(!o)break;let n=o.toLowerCase();(n===`lax`||n===`strict`||n===`none`)&&(s.sameSite=n);break}c=t+1}return s}function f(e,t,n){let r=e.indexOf(`;`,t);return r===-1?n:r}function p(e,t,n){let r=e.indexOf(`=`,t);return r<n?r:-1}function m(e,t,n){let r=t,i=n;do{let t=e.charCodeAt(r);if(t!==32&&t!==9)break}while(++r<i);for(;i>r;){let t=e.charCodeAt(i-1);if(t!==32&&t!==9)break;i--}return e.slice(r,i)}function h(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function g(e){return o.call(e)===`[object Date]`}})),nh=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),rh=o(((e,t)=>{let{URL:n}=require(`node:url`),r=`http://localhost`;t.exports=function(e,t){(typeof e==`string`||Object.prototype.toString.call(e)===`[object String]`)&&e.startsWith(`//`)&&(e=r+e);let i=typeof e==`object`?Object.assign(new n(r),e):new n(e,r);if(typeof t==`string`){t=new URLSearchParams(t);for(let e of t.keys()){i.searchParams.delete(e);for(let n of t.getAll(e))i.searchParams.append(e,n)}}else{let n=Object.assign({},e.query,t);for(let e in n){let t=n[e];if(Array.isArray(t)){i.searchParams.delete(e);for(let n of t)i.searchParams.append(e,n)}else i.searchParams.set(e,t)}}return i}})),ih=o(((e,t)=>{let{randomUUID:n}=require(`node:crypto`),{Readable:r}=require(`node:stream`),i;function a(e){return e&&typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&e[Symbol.toStringTag]===`FormData`}function o(e){i??=new TextEncoder;let t=`----formdata-${n()}`,a=`--${t}\r\nContent-Disposition: form-data`,o=e=>e.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`),s=e=>e.replace(/\r?\n|\r/g,`\r
452
- `),c=new Uint8Array([13,10]);async function*l(){for(let[t,n]of e)if(typeof n==`string`)yield i.encode(`${a}; name="${o(s(t))}"\r\n\r\n`),yield i.encode(`${s(n)}\r\n`);else{let e=`${a}; name="${o(s(t))}"`;n.name&&(e+=`; filename="${o(n.name)}"`),e+=`\r\nContent-Type: ${n.type||`application/octet-stream`}\r\n\r\n`,yield i.encode(e),n.stream?yield*n.stream():yield n,yield c}yield i.encode(`--${t}--`)}return{stream:r.from(l()),contentType:`multipart/form-data; boundary=${t}`}}t.exports.isFormDataLike=a,t.exports.formDataToStream=o})),ah=o(((e,t)=>{let{Readable:n,addAbortSignal:r}=require(`node:stream`),i=require(`node:util`),a=th(),o=require(`node:assert`),{createDeprecation:s}=nh(),c=rh(),{isFormDataLike:l,formDataToStream:u}=ih(),{EventEmitter:d}=require(`node:events`),f=s({name:`FastifyDeprecationLightMyRequest`,code:`FST_LIGHTMYREQUEST_DEP01`,message:`You are accessing "request.connection", use "request.socket" instead.`});function p(e){return e.port?e.host:e.hostname+(e.protocol===`https:`?`:443`:`:80`)}var m=class extends d{constructor(e){super(),this.remoteAddress=e}};function h(e){return new t(this);function t(t){g.call(t,{...e,Request:void 0}),Object.assign(this,t);for(let e of Object.keys(g.prototype))this.constructor.prototype[e]=g.prototype[e];return i.inherits(this.constructor,e.Request),this}}function g(e){n.call(this,{autoDestroy:!1});let t=c(e.url||e.path,e.query);this.url=t.pathname+t.search,this.aborted=!1,this.httpVersionMajor=1,this.httpVersionMinor=1,this.httpVersion=`1.1`,this.method=e.method?e.method.toUpperCase():`GET`,this.headers={},this.rawHeaders=[];let i=e.headers||{};for(let e in i){let t=e.toLowerCase();if((t===`user-agent`||t===`content-type`)&&i[e]===void 0){this.headers[t]=void 0;continue}let n=i[e];o(n!==void 0,`invalid value "undefined" for header `+e),this.headers[t]=``+n}if(`user-agent`in this.headers||(this.headers[`user-agent`]=`lightMyRequest`),this.headers.host=this.headers.host||e.authority||p(t),e.cookies){let{cookies:t}=e,n=Object.keys(t).map(e=>a.serialize(e,t[e]));this.headers.cookie&&n.unshift(this.headers.cookie),this.headers.cookie=n.join(`; `)}this.socket=new m(e.remoteAddress||`127.0.0.1`),Object.defineProperty(this,`connection`,{get(){return f(),this.socket},configurable:!0});let s=e.payload||e.body||null,d=s&&typeof s.resume==`function`;if(l(s)){let e=u(s);s=e.stream,d=!0,this.headers[`content-type`]=e.contentType,this.headers[`transfer-encoding`]=`chunked`}s&&typeof s!=`string`&&!d&&!Buffer.isBuffer(s)&&(s=JSON.stringify(s),`content-type`in this.headers||(this.headers[`content-type`]=`application/json`)),s&&!d&&!Object.hasOwn(this.headers,`content-length`)&&(this.headers[`content-length`]=(Buffer.isBuffer(s)?s.length:Buffer.byteLength(s)).toString());for(let e of Object.keys(this.headers))this.rawHeaders.push(e,this.headers[e]);this._lightMyRequest={payload:s,isDone:!1,simulate:e.simulate||{},payloadAsStream:e.payloadAsStream,signal:e.signal};let h=e.signal;h&&r(h,this);{let e=this._lightMyRequest.payload;e?._readableState?(this._read=_,e.on(`error`,e=>{this.destroy(e)}),e.on(`end`,()=>{this.push(null)})):this._read=v}return this}function _(){let e=this._lightMyRequest.payload,t=!0,n=!1,r;for(;t&&(r=e.read());)n=!0,t=this.push(r);t&&!n&&this._lightMyRequest.payload.once(`readable`,this._read.bind(this))}function v(){setImmediate(()=>{if(this._lightMyRequest.isDone){this._lightMyRequest.simulate.end!==!1&&this.push(null);return}this._lightMyRequest.isDone=!0,this._lightMyRequest.payload&&(this._lightMyRequest.simulate.split?(this.push(this._lightMyRequest.payload.slice(0,1)),this.push(this._lightMyRequest.payload.slice(1))):this.push(this._lightMyRequest.payload)),this._lightMyRequest.simulate.error&&this.emit(`error`,Error(`Simulated`)),this._lightMyRequest.simulate.close&&this.emit(`close`),this._lightMyRequest.simulate.end!==!1&&this.push(null)})}i.inherits(g,n),i.inherits(h,g),g.prototype.destroy=function(e){this.destroyed||this._lightMyRequest.isDone||(this.destroyed=!0,e&&(this._error=!0,process.nextTick(()=>this.emit(`error`,e))),process.nextTick(()=>this.emit(`close`)))},t.exports=g,t.exports.Request=g,t.exports.CustomRequest=h})),oh=o(((e,t)=>{var n={decodeValues:!0,map:!1,silent:!1};function r(e){return typeof e!=`string`||e in{}}function i(){return Object.create(null)}function a(e){return typeof e==`string`&&!!e.trim()}function o(e,t){var o=e.split(`;`).filter(a),c=s(o.shift()),l=c.name,u=c.value;if(t=t?Object.assign({},n,t):n,r(l))return null;try{u=t.decodeValues?decodeURIComponent(u):u}catch(e){console.error(`set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.`,e)}var d=i();return d.name=l,d.value=u,o.forEach(function(e){var t=e.split(`=`),n=t.shift().trimLeft().toLowerCase();if(!r(n)){var i=t.join(`=`);if(n===`expires`)d.expires=new Date(i);else if(n===`max-age`){var a=parseInt(i,10);Number.isNaN(a)||(d.maxAge=a)}else n===`secure`?d.secure=!0:n===`httponly`?d.httpOnly=!0:n===`samesite`?d.sameSite=i:n===`partitioned`?d.partitioned=!0:n&&(d[n]=i)}}),d}function s(e){var t=``,n=``,r=e.split(`=`);return r.length>1?(t=r.shift(),n=r.join(`=`)):n=e,{name:t,value:n}}function c(e,t){if(t=t?Object.assign({},n,t):n,!e)return t.map?i():[];if(e.headers)if(typeof e.headers.getSetCookie==`function`)e=e.headers.getSetCookie();else if(e.headers[`set-cookie`])e=e.headers[`set-cookie`];else{var s=e.headers[Object.keys(e.headers).find(function(e){return e.toLowerCase()===`set-cookie`})];!s&&e.headers.cookie&&!t.silent&&console.warn(`Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.`),e=s}if(Array.isArray(e)||(e=[e]),t.map){var c=i();return e.filter(a).reduce(function(e,n){var i=o(n,t);return i&&!r(i.name)&&(e[i.name]=i),e},c)}else return e.filter(a).map(function(e){return o(e,t)}).filter(Boolean)}function l(e){if(Array.isArray(e))return e;if(typeof e!=`string`)return[];var t=[],n=0,r,i,a,o,s;function c(){for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n<e.length}function l(){return i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`}for(;n<e.length;){for(r=n,s=!1;c();)if(i=e.charAt(n),i===`,`){for(a=n,n+=1,c(),o=n;n<e.length&&l();)n+=1;n<e.length&&e.charAt(n)===`=`?(s=!0,n=o,t.push(e.substring(r,a)),r=n):n=a+1}else n+=1;(!s||n>=e.length)&&t.push(e.substring(r,e.length))}return t}t.exports=c,t.exports.parse=c,t.exports.parseString=o,t.exports.splitCookiesString=l})),sh=o(((e,t)=>{let n=require(`node:http`),{Writable:r,Readable:i,addAbortSignal:a}=require(`node:stream`),o=require(`node:util`),s=oh();function c(e,t,r){if(n.ServerResponse.call(this,e),e._lightMyRequest?.payloadAsStream){this._lightMyRequest={headers:null,trailers:{},stream:new i({read:this.emit.bind(this,`drain`)})};let t=e._lightMyRequest.signal;t&&a(t,this._lightMyRequest.stream)}else this._lightMyRequest={headers:null,trailers:{},payloadChunks:[]};this.setHeader(`foo`,`bar`),this.removeHeader(`foo`),this.assignSocket(u()),this._promiseCallback=typeof r==`function`;let o=!1,s=e=>{if(!o){if(o=!0,this._promiseCallback)return process.nextTick(()=>t(e));process.nextTick(()=>t(null,e))}};this._lightMyRequest.onEndSuccess=s;let c=!1,d=e=>{if(o){this._lightMyRequest.stream&&!c&&(e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._lightMyRequest.stream.destroy(e),this._lightMyRequest.stream.on(`error`,()=>{}));return}if(o=!0,e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._promiseCallback)return process.nextTick(()=>r(e));process.nextTick(()=>t(e,null))};this._lightMyRequest.stream?this.once(`finish`,()=>{c=!0,this._lightMyRequest.stream.push(null)}):this.once(`finish`,()=>{let t=l(this);t.raw.req=e,s(t)}),this.connection.once(`error`,d),this.once(`error`,d),this.once(`close`,d)}o.inherits(c,n.ServerResponse),c.prototype.setTimeout=function(e,t){return this.timeoutHandle=setTimeout(()=>{this.emit(`timeout`)},e),this.on(`timeout`,t),this},c.prototype.writeHead=function(){let e=n.ServerResponse.prototype.writeHead.apply(this,arguments);return f(this),this._lightMyRequest.stream&&this._lightMyRequest.onEndSuccess(l(this)),e},c.prototype.write=function(e,t,r){return this.timeoutHandle&&clearTimeout(this.timeoutHandle),n.ServerResponse.prototype.write.call(this,e,t,r),this._lightMyRequest.stream?this._lightMyRequest.stream.push(Buffer.from(e,t)):(this._lightMyRequest.payloadChunks.push(Buffer.from(e,t)),!0)},c.prototype.end=function(e,t,r){e&&this.write(e,t),n.ServerResponse.prototype.end.call(this,r),this.emit(`finish`),this.destroy()},c.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,e&&process.nextTick(()=>this.emit(`error`,e)),process.nextTick(()=>this.emit(`close`)))},c.prototype.addTrailers=function(e){for(let t in e)this._lightMyRequest.trailers[t.toLowerCase().trim()]=e[t].toString().trim()};function l(e){e._lightMyRequest.headers===null&&f(e),d(e);let t={raw:{res:e},headers:e._lightMyRequest.headers,statusCode:e.statusCode,statusMessage:e.statusMessage,trailers:{},get cookies(){return s.parse(this)}};if(t.trailers=e._lightMyRequest.trailers,e._lightMyRequest.payloadChunks){let n=Buffer.concat(e._lightMyRequest.payloadChunks);t.rawPayload=n,t.payload=n.toString(),t.body=t.payload,t.json=function(){return JSON.parse(t.payload)}}else t.json=function(){throw Error(`Response payload is not available with payloadAsStream: true`)};return t.stream=function(){return e._lightMyRequest.stream?e._lightMyRequest.stream:i.from(e._lightMyRequest.payloadChunks)},t}function u(){return new r({write(e,t,n){setImmediate(n)}})}function d(e){let t=e._lightMyRequest.headers;for(let e of Object.keys(t)){let n=t[e];Array.isArray(n)?t[e]=n.map(e=>``+e):t[e]=``+n}}function f(e){e._lightMyRequest.headers=Object.assign({},e.getHeaders()),[`Date`,`Connection`,`Transfer-Encoding`].forEach(t=>{let n=RegExp(`\\r\\n`+t+`: ([^\\r]*)\\r\\n`),r=e._header?.match(n);r&&(e._lightMyRequest.headers[t.toLowerCase()]=r[1])})}t.exports=c})),ch=o(((e,t)=>{t.exports=r,t.exports.default=r;let n={type:`object`,properties:{url:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},path:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},cookies:{type:`object`,additionalProperties:!0},headers:{type:`object`,additionalProperties:!0},query:{anyOf:[{type:`object`,additionalProperties:!0},{type:`string`}]},simulate:{type:`object`,properties:{end:{type:`boolean`},split:{type:`boolean`},error:{type:`boolean`},close:{type:`boolean`}}},authority:{type:`string`},remoteAddress:{type:`string`},method:{type:`string`,enum:`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE.acl.bind.checkout.connect.copy.delete.get.head.link.lock.m-search.merge.mkactivity.mkcalendar.mkcol.move.notify.options.patch.post.propfind.proppatch.purge.put.query.rebind.report.search.source.subscribe.trace.unbind.unlink.unlock.unsubscribe`.split(`.`)},validate:{type:`boolean`}},additionalProperties:!0,oneOf:[{required:[`url`]},{required:[`path`]}]};function r(e,{instancePath:t=``,parentData:i,parentDataProperty:a,rootData:o=e}={}){let s=null,c=0,l=c,u=!1,d=null,f=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.url===void 0&&(n=`url`)){let e={instancePath:t,schemaPath:`#/oneOf/0/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=f===c;p&&(u=!0,d=0);let m=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.path===void 0&&(n=`path`)){let e={instancePath:t,schemaPath:`#/oneOf/1/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=m===c;if(p&&u?(u=!1,d=[d,1]):p&&(u=!0,d=1),u)c=l,s!==null&&(l?s.length=l:s=null);else{let e={instancePath:t,schemaPath:`#/oneOf`,keyword:`oneOf`,params:{passingSchemas:d},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}if(c===0)if(e&&typeof e==`object`&&!Array.isArray(e)){if(e.url!==void 0){let n=e.url,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.url=i))}var h=u===c;h&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/protocol`,schemaPath:`#/properties/url/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var g=r===c}else var g=!0;if(g){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/hostname`,schemaPath:`#/properties/url/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var g=r===c}else var g=!0;if(g)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/pathname`,schemaPath:`#/properties/url/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var g=r===c}else var g=!0}}}else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var h=d===c;if(h&&o?(o=!1,l=[l,1]):h&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.path!==void 0){let n=e.path,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.path=i))}var v=u===c;v&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/protocol`,schemaPath:`#/properties/path/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var y=r===c}else var y=!0;if(y){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/hostname`,schemaPath:`#/properties/path/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var y=r===c}else var y=!0;if(y)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/pathname`,schemaPath:`#/properties/path/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var y=r===c}else var y=!0}}}else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var v=d===c;if(v&&o?(o=!1,l=[l,1]):v&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.cookies!==void 0){let n=e.cookies,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/cookies`,schemaPath:`#/properties/cookies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.headers!==void 0){let n=e.headers,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/headers`,schemaPath:`#/properties/headers/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.query!==void 0){let n=e.query,i=c,a=c,o=!1,l=c;if(c===l&&!(n&&typeof n==`object`&&!Array.isArray(n))){let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/0/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var b=l===c;if(o||=b,!o){let r=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.query=i))}var b=r===c;o||=b}if(o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.simulate!==void 0){let n=e.simulate,i=c;if(c===i)if(n&&typeof n==`object`&&!Array.isArray(n)){if(n.end!==void 0){let e=n.end,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/end`,schemaPath:`#/properties/simulate/properties/end/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.end=i))}var x=i===c}else var x=!0;if(x){if(n.split!==void 0){let e=n.split,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/split`,schemaPath:`#/properties/simulate/properties/split/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.split=i))}var x=i===c}else var x=!0;if(x){if(n.error!==void 0){let e=n.error,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/error`,schemaPath:`#/properties/simulate/properties/error/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.error=i))}var x=i===c}else var x=!0;if(x)if(n.close!==void 0){let e=n.close,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/close`,schemaPath:`#/properties/simulate/properties/close/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.close=i))}var x=i===c}else var x=!0}}}else return r.errors=[{instancePath:t+`/simulate`,schemaPath:`#/properties/simulate/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.authority!==void 0){let n=e.authority,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/authority`,schemaPath:`#/properties/authority/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.authority=a))}var _=i===c}else var _=!0;if(_){if(e.remoteAddress!==void 0){let n=e.remoteAddress,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/remoteAddress`,schemaPath:`#/properties/remoteAddress/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.remoteAddress=a))}var _=i===c}else var _=!0;if(_){if(e.method!==void 0){let i=e.method,a=c;if(typeof i!=`string`){let n=typeof i,a;if(a===void 0)if(n==`number`||n==`boolean`)a=``+i;else if(i===null)a=``;else return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(i=a,e!==void 0&&(e.method=a))}if(!(i===`ACL`||i===`BIND`||i===`CHECKOUT`||i===`CONNECT`||i===`COPY`||i===`DELETE`||i===`GET`||i===`HEAD`||i===`LINK`||i===`LOCK`||i===`M-SEARCH`||i===`MERGE`||i===`MKACTIVITY`||i===`MKCALENDAR`||i===`MKCOL`||i===`MOVE`||i===`NOTIFY`||i===`OPTIONS`||i===`PATCH`||i===`POST`||i===`PROPFIND`||i===`PROPPATCH`||i===`PURGE`||i===`PUT`||i===`QUERY`||i===`REBIND`||i===`REPORT`||i===`SEARCH`||i===`SOURCE`||i===`SUBSCRIBE`||i===`TRACE`||i===`UNBIND`||i===`UNLINK`||i===`UNLOCK`||i===`UNSUBSCRIBE`||i===`acl`||i===`bind`||i===`checkout`||i===`connect`||i===`copy`||i===`delete`||i===`get`||i===`head`||i===`link`||i===`lock`||i===`m-search`||i===`merge`||i===`mkactivity`||i===`mkcalendar`||i===`mkcol`||i===`move`||i===`notify`||i===`options`||i===`patch`||i===`post`||i===`propfind`||i===`proppatch`||i===`purge`||i===`put`||i===`query`||i===`rebind`||i===`report`||i===`search`||i===`source`||i===`subscribe`||i===`trace`||i===`unbind`||i===`unlink`||i===`unlock`||i===`unsubscribe`))return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/enum`,keyword:`enum`,params:{allowedValues:n.properties.method.enum},message:`must be equal to one of the allowed values`}],!1;var _=a===c}else var _=!0;if(_)if(e.validate!==void 0){let n=e.validate,i=c;if(typeof n!=`boolean`){let i;if(i===void 0)if(n===`false`||n===0||n===null)i=!1;else if(n===`true`||n===1)i=!0;else return r.errors=[{instancePath:t+`/validate`,schemaPath:`#/properties/validate/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.validate=i))}var _=i===c}else var _=!0}}}}}}}}}else return r.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return r.errors=s,c===0}})),lh=o(((e,t)=>{let n=require(`node:assert`),r=ah(),i=sh(),a=`The dispatch function has already been invoked`,o=ch();function s(e,t,n){return n===void 0?new d(e,t):u(e,t,n)}function c(e,t){let n=e._lightMyRequest.payload;if(!n||n._readableState||typeof n.resume!=`function`)return t();let r=[];n.on(`data`,e=>r.push(Buffer.from(e))),n.on(`end`,()=>{let n=Buffer.concat(r);return e.headers[`content-length`]=e.headers[`content-length`]||``+n.length,delete e.headers[`transfer-encoding`],e._lightMyRequest.payload=n,t()}),n.resume()}function l(e,t,n,r){return n.once(`error`,function(e){this.destroyed&&r.destroy(e)}),n.once(`close`,function(){this.destroyed&&!this._error&&r.destroy()}),c(n,()=>e.call(t,n,r))}function u(e,t,a){if(t=typeof t==`string`?{url:t}:t,t.validate!==!1&&(n(typeof e==`function`,`dispatchFunc should be a function`),!o(t)))throw Error(o.errors.map(e=>e.message));let s=t.server||{},c=t.Request?r.CustomRequest:r;if(e.request&&e.request.app===e&&(Object.setPrototypeOf(Object.getPrototypeOf(e.request),c.prototype),Object.setPrototypeOf(Object.getPrototypeOf(e.response),i.prototype)),typeof a==`function`){let n=new c(t);return l(e,s,n,new i(n,a))}else return new Promise((n,r)=>{let a=new c(t);l(e,s,a,new i(a,n,r))})}function d(e,t){typeof t==`string`?this.option={url:t}:this.option=Object.assign({},t),this.dispatch=e,this._hasInvoked=!1,this._promise=null,this.option.autoStart!==!1&&process.nextTick(()=>{this._hasInvoked||this.end()})}[`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option.url=t,this.option.method=e.toUpperCase(),this}}),[`body`,`cookies`,`headers`,`payload`,`query`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option[e]=t,this}}),d.prototype.end=function(e){if(this._hasInvoked===!0||this._promise)throw Error(a);if(this._hasInvoked=!0,typeof e==`function`)u(this.dispatch,this.option,e);else return this._promise=u(this.dispatch,this.option),this._promise},Object.getOwnPropertyNames(Promise.prototype).forEach(e=>{e!==`constructor`&&(d.prototype[e]=function(...t){if(!this._promise){if(this._hasInvoked===!0)throw Error(a);this._hasInvoked=!0,this._promise=u(this.dispatch,this.option)}return this._promise[e](...t)})});function f(e){return e instanceof r||e instanceof i||e?.constructor?.name===`_CustomLMRRequest`}t.exports=s,t.exports.default=s,t.exports.inject=s,t.exports.isInjection=f})),uh=o(((e,t)=>{let n=vu(),r=require(`node:http`),i=require(`node:diagnostics_channel`),a,{kAvvioBoot:o,kChildren:s,kServerBindings:c,kBodyLimit:l,kSupportedHTTPMethods:u,kRoutePrefix:d,kLogLevel:f,kLogSerializers:p,kHooks:m,kSchemaController:h,kRequestAcceptVersion:g,kReplySerializerDefault:_,kContentTypeParser:v,kReply:y,kRequest:b,kFourOhFour:x,kState:S,kOptions:C,kPluginNameChain:w,kSchemaErrorFormatter:T,kErrorHandler:E,kKeepAliveConnections:D,kChildLoggerFactory:O,kGenReqId:k,kErrorHandlerAlreadySet:A}=yu(),{createServer:j}=Eu(),M=gd(),ee=bd(),N=xd(),te=hd(),P=wd(),ne=Dp(),{Hooks:re,hookRunnerApplication:F,supportedHooks:ie}=Cu(),{createChildLogger:I,defaultChildLoggerFactory:ae,createLogger:oe}=ld(),L=ym(),{getGenReqId:se,reqIdGenFactory:ce}=bm(),{buildRouting:le,validateBodyLimitOption:ue,buildRouterOptions:de}=Xm(),fe=Zm(),pe=$m(),me=eh(),{appendStackTrace:he,AVVIO_ERRORS_MAP:ge,..._e}=Su(),ve=Tu(),{defaultInitOptions:ye}=pe,{FST_ERR_ASYNC_CONSTRAINT:be,FST_ERR_BAD_URL:xe,FST_ERR_OPTIONS_NOT_OBJ:Se,FST_ERR_QSP_NOT_FN:Ce,FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:we,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:Te,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:Ee,FST_ERR_INSTANCE_ALREADY_LISTENING:De,FST_ERR_REOPENED_CLOSE_SERVER:Oe,FST_ERR_ROUTE_REWRITE_NOT_STR:ke,FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:Ae,FST_ERR_ERROR_HANDLER_NOT_FN:je,FST_ERR_ERROR_HANDLER_ALREADY_SET:Me,FST_ERR_ROUTE_METHOD_INVALID:Ne}=_e,{buildErrorHandler:Pe}=md(),{FSTWRN004:Fe}=xu(),Ie=i.channel(`fastify.initialization`);function Le(e){let{options:t,genReqId:i,disableRequestLogging:oe,hasLogger:ue,initialConfig:de}=Re(e,Qe,$e),pe=le(t.routerOptions),Se=fe(t),Ce=ut(pe,t),{server:we,listen:Te,forceCloseConnections:Ee,serverHasCloseAllConnections:Ae,serverHasCloseHttp2Sessions:Le,keepAliveConnections:ze}=j(t,Ce),Be=M.setupResponseListeners,He=ne.buildSchemaController(null,t.schemaController),R={[S]:{listening:!1,closing:!1,started:!1,ready:!1,booting:!1,aborted:!1,readyResolver:null},[D]:ze,[u]:{bodyless:new Set([`GET`,`HEAD`,`TRACE`]),bodywith:new Set([`DELETE`,`OPTIONS`,`PATCH`,`PUT`,`POST`])},[C]:t,[s]:[],[c]:[],[l]:t.bodyLimit,[d]:``,[f]:``,[p]:null,[m]:new re,[h]:He,[T]:null,[E]:Pe(),[A]:!1,[O]:t.childLoggerFactory||ae,[_]:null,[v]:new P(t.bodyLimit,t.onProtoPoisoning||ye.onProtoPoisoning,t.onConstructorPoisoning||ye.onConstructorPoisoning),[y]:M.buildReply(M),[b]:ee.buildRequest(ee,t.trustProxy),[x]:Se,[L.kRegisteredPlugins]:[],[w]:[`fastify`],[o]:null,[k]:i,routing:Ce,delete:function(e,t,n){return pe.prepareRoute.call(this,{method:`DELETE`,url:e,options:t,handler:n})},get:function(e,t,n){return pe.prepareRoute.call(this,{method:`GET`,url:e,options:t,handler:n})},head:function(e,t,n){return pe.prepareRoute.call(this,{method:`HEAD`,url:e,options:t,handler:n})},trace:function(e,t,n){return pe.prepareRoute.call(this,{method:`TRACE`,url:e,options:t,handler:n})},patch:function(e,t,n){return pe.prepareRoute.call(this,{method:`PATCH`,url:e,options:t,handler:n})},post:function(e,t,n){return pe.prepareRoute.call(this,{method:`POST`,url:e,options:t,handler:n})},put:function(e,t,n){return pe.prepareRoute.call(this,{method:`PUT`,url:e,options:t,handler:n})},options:function(e,t,n){return pe.prepareRoute.call(this,{method:`OPTIONS`,url:e,options:t,handler:n})},all:function(e,t,n){return pe.prepareRoute.call(this,{method:this.supportedMethods,url:e,options:t,handler:n})},route:function(e){return pe.route.call(this,{options:e})},hasRoute:function(e){return pe.hasRoute.call(this,{options:e})},findRoute:function(e){return pe.findRoute(e)},log:t.logger,withTypeProvider:Ye,addHook:Xe,addSchema:Ze,getSchema:He.getSchema.bind(He),getSchemas:He.getSchemas.bind(He),setValidatorCompiler:nt,setSerializerCompiler:it,setSchemaController:at,setReplySerializer:ot,setSchemaErrorFormatter:rt,setGenReqId:dt,addContentTypeParser:P.helpers.addContentTypeParser,hasContentTypeParser:P.helpers.hasContentTypeParser,getDefaultJsonParser:P.defaultParsers.getDefaultJsonParser,defaultTextParser:P.defaultParsers.defaultTextParser,removeContentTypeParser:P.helpers.removeContentTypeParser,removeAllContentTypeParsers:P.helpers.removeAllContentTypeParsers,register:null,after:null,ready:null,onClose:null,close:null,printPlugins:null,hasPlugin:function(e){return this[L.kRegisteredPlugins].includes(e)||this[w].includes(e)},listen:Te,server:we,addresses:function(){let e=this[c].map(e=>e.address());return e.push(this.server.address()),e.filter(e=>e)},decorate:te.add,hasDecorator:te.exist,decorateReply:te.decorateReply,decorateRequest:te.decorateRequest,hasRequestDecorator:te.existRequest,hasReplyDecorator:te.existReply,getDecorator:te.getInstanceDecorator,addHttpMethod:ft,inject:qe,printRoutes:lt,setNotFoundHandler:tt,setErrorHandler:st,setChildLoggerFactory:ct,initialConfig:de,addConstraintStrategy:pe.addConstraintStrategy.bind(pe),hasConstraintStrategy:pe.hasConstraintStrategy.bind(pe)};Object.defineProperties(R,{listeningOrigin:{get(){let e=this.addresses().slice(-1).pop();if(typeof e==`string`)return e;let t=e.family===`IPv6`?`[${e.address}]`:e.address;return`${this[C].https?`https`:`http`}://${t}:${e.port}`}},pluginName:{configurable:!0,get(){return this[w].length>1?this[w].join(` -> `):this[w][0]}},prefix:{configurable:!0,get(){return this[d]}},validatorCompiler:{configurable:!0,get(){return this[h].getValidatorCompiler()}},serializerCompiler:{configurable:!0,get(){return this[h].getSerializerCompiler()}},childLoggerFactory:{configurable:!0,get(){return this[O]}},version:{configurable:!0,get(){return`5.7.4`}},errorHandler:{configurable:!0,get(){return this[E].func}},genReqId:{configurable:!0,get(){return this[k]}},supportedMethods:{configurable:!1,get(){return[...this[u].bodyless,...this[u].bodywith]}}}),t.schemaErrorFormatter&&(Ve(t.schemaErrorFormatter),R[T]=t.schemaErrorFormatter.bind(R));let Ue=Number(t.pluginTimeout),We=n(R,{autostart:!1,timeout:isNaN(Ue)===!1?Ue:ye.pluginTimeout,expose:{use:`register`}});We.override=me,We.on(`start`,()=>R[S].started=!0),R[o]=R.ready,R.ready=Je,R.printPlugins=We.prettyPrint.bind(We),We.once(`preReady`,()=>{R.onClose((e,n)=>{R[S].closing=!0,pe.closeRoutes(),F(`preClose`,R[o],R,function(){if(R[S].listening){if(Ee===`idle`)e.server.closeIdleConnections();else if(Ae&&Ee)e.server.closeAllConnections();else if(Ee===!0)for(let e of R[D])e.destroy(),R[D].delete(e)}Le&&e.server.closeHttp2Sessions(),!t.serverFactory||R[S].listening?e.server.close(function(e){e&&e.code!==`ERR_SERVER_NOT_RUNNING`?n(null):n()}):process.nextTick(n,null)})})});let Ge=new N({server:R,config:{}});return R.setNotFoundHandler(),Se.arrange404(R),pe.setup(t,{avvio:We,fourOhFour:Se,hasLogger:ue,setupResponseListeners:Be,throwIfAlreadyStarted:Ke,keepAliveConnections:ze}),we.on(`clientError`,t.clientErrorHandler.bind(R)),Ie.hasSubscribers&&Ie.publish({fastify:R}),`asyncDispose`in Symbol&&(R[Symbol.asyncDispose]=function(){return R.close()}),R;function Ke(e){if(R[S].started)throw new De(e)}function qe(e,t){if(a===void 0&&(a=lh()),R[S].started){if(R[S].closing){let e=new Oe;if(t){t(e);return}else return Promise.reject(e)}return a(Ce,e,t)}if(t)this.ready(n=>{n?t(n,null):a(Ce,e,t)});else return a((e,t)=>{this.ready(function(n){if(n){t.emit(`error`,n);return}Ce(e,t)})},e)}function Je(e){if(this[S].readyResolver!==null){if(e!=null){this[S].readyResolver.promise.then(()=>e(null,R),e);return}return this[S].readyResolver.promise}if(process.nextTick(t),this[S].readyResolver=ve.withResolvers(),e)this[S].readyResolver.promise.then(()=>e(null,R),e);else return this[S].readyResolver.promise;function t(){R[o]((e,t)=>{e||R[S].started||R[S].ready||R[S].booting?n(e):(R[S].booting=!0,F(`onReady`,R[o],R,n)),t()})}function n(e){if(e=e!=null&&ge[e.code]!=null?he(e,new ge[e.code](e.message)):e,e)return R[S].readyResolver.reject(e);R[S].readyResolver.resolve(R),R[S].booting=!1,R[S].ready=!0,R[S].readyResolver=null}}function Ye(){return this}function Xe(e,t){if(Ke(`Cannot call "addHook"!`),t==null)throw new _e.FST_ERR_HOOK_INVALID_HANDLER(e,t);if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onReady`||e===`onListen`){if(t.constructor.name===`AsyncFunction`&&t.length!==0)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER;return e===`onClose`?this.onClose(t.bind(this)):e===`onReady`||e===`onListen`||e===`onRoute`?this[m].add(e,t):this.after((r,i)=>{try{n.call(this,e,t),i(r)}catch(e){i(e)}}),this;function n(e,t){this[m].add(e,t),this[s].forEach(r=>n.call(r,e,t))}}function Ze(e){return Ke(`Cannot call "addSchema"!`),this[h].add(e),this[s].forEach(t=>t.addSchema(e)),this}function Qe(e,t){e.headers[`accept-version`]!==void 0&&(e.headers[g]=e.headers[`accept-version`],e.headers[`accept-version`]=void 0),Se.router.lookup(e,t)}function $e(e,n,r){if(t.frameworkErrors){let i=se(Ge.server,n),a=I(Ge,t.logger,n,i),o=new ee(i,null,n,null,a,Ge),s=new M(r,o,a);return(typeof oe==`function`?oe(n):oe)===!1&&a.info({req:o},`incoming request`),t.frameworkErrors(new xe(e),o,s)}let i=JSON.stringify({error:`Bad Request`,code:`FST_ERR_BAD_URL`,message:`'${e}' is not a valid url component`,statusCode:400});r.writeHead(400,{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(i)}),r.end(i)}function et(e,n,r){if(e!==!1)return function(e){if(e){if(t.frameworkErrors){let e=se(Ge.server,n),i=I(Ge,t.logger,n,e),a=new ee(e,null,n,null,i,Ge),o=new M(r,a,i);return(typeof oe==`function`?oe(n):oe)===!1&&i.info({req:a},`incoming request`),t.frameworkErrors(new be,a,o)}r.writeHead(500,{"Content-Type":`application/json`,"Content-Length":101}),r.end(`{"error":"Internal Server Error","message":"Unexpected error from async constraint","statusCode":500}`)}}}function tt(e,t){return Ke(`Cannot call "setNotFoundHandler"!`),Se.setNotFoundHandler.call(this,e,t,We,pe.routeHandler),this}function nt(e){return Ke(`Cannot call "setValidatorCompiler"!`),this[h].setValidatorCompiler(e),this}function rt(e){return Ke(`Cannot call "setSchemaErrorFormatter"!`),Ve(e),this[T]=e.bind(this),this}function it(e){return Ke(`Cannot call "setSerializerCompiler"!`),this[h].setSerializerCompiler(e),this}function at(e){Ke(`Cannot call "setSchemaController"!`);let t=this[h],n=ne.buildSchemaController(t,Object.assign({},t.opts,e));return this[h]=n,this.getSchema=n.getSchema.bind(n),this.getSchemas=n.getSchemas.bind(n),this}function ot(e){return Ke(`Cannot call "setReplySerializer"!`),this[_]=e,this}function st(e){if(Ke(`Cannot call "setErrorHandler"!`),typeof e!=`function`)throw new je;if(!t.allowErrorHandlerOverride&&this[A])throw new Me;return this[A]&&Fe(`To disable this behavior, set 'allowErrorHandlerOverride' to false or ignore this message. For more information, visit: https://fastify.dev/docs/latest/Reference/Server/#allowerrorhandleroverride`),this[A]=!0,this[E]=Pe(this[E],e.bind(this)),this}function ct(e){return Ke(`Cannot call "setChildLoggerFactory"!`),this[O]=e,this}function lt(e={}){return e.includeMeta=e.includeHooks?e.includeMeta?ie.concat(e.includeMeta):ie:e.includeMeta,pe.printRoutes(e)}function ut(e,{rewriteUrl:t,logger:n}){let r;return function(n,i){if(r===void 0&&(r=e.isAsyncConstraint()),t){n.originalUrl=n.url;let e=t.call(R,n);if(typeof e==`string`)n.url=e;else{let t=new ke(n.url,typeof e);n.destroy(t)}}e.routing(n,i,et(r,n,i))}}function dt(e){return Ke(`Cannot call "setGenReqId"!`),this[k]=ce(this[C].requestIdHeader,e),this}function ft(e,{hasBody:t=!1}={}){if(typeof e!=`string`||r.METHODS.indexOf(e)===-1)throw new Ne;t===!0?(this[u].bodywith.add(e),this[u].bodyless.delete(e)):(this[u].bodywith.delete(e),this[u].bodyless.add(e));let n=e.toLowerCase();return this.hasDecorator(n)||this.decorate(n,function(t,n,r){return pe.prepareRoute.call(this,{method:e,url:t,options:n,handler:r})}),this}}function Re(e,t,n){if(e&&typeof e!=`object`)throw new Se;if(e=Object.assign({},e),e.querystringParser&&typeof e.querystringParser!=`function`||e.routerOptions?.querystringParser&&typeof e.routerOptions.querystringParser!=`function`)throw new Ce(typeof(e.querystringParser??e.routerOptions.querystringParser));if(e.schemaController&&e.schemaController.bucket&&typeof e.schemaController.bucket!=`function`)throw new we(typeof e.schemaController.bucket);ue(e.bodyLimit);let r=typeof e.requestIdHeader==`string`&&e.requestIdHeader.length!==0?e.requestIdHeader.toLowerCase():e.requestIdHeader===!0&&`request-id`,i=ce(r,e.genReqId),a=e.requestIdLogLabel||`reqId`;e.bodyLimit=e.bodyLimit||ye.bodyLimit;let o=e.disableRequestLogging||!1,s=Object.assign({customOptions:{},plugins:[]},e.ajv);if(!s.customOptions||Object.prototype.toString.call(s.customOptions)!==`[object Object]`)throw new Te(typeof s.customOptions);if(!s.plugins||!Array.isArray(s.plugins))throw new Ee(typeof s.plugins);let{logger:c,hasLogger:l}=oe(e);e.connectionTimeout=e.connectionTimeout||ye.connectionTimeout,e.keepAliveTimeout=e.keepAliveTimeout||ye.keepAliveTimeout,e.maxRequestsPerSocket=e.maxRequestsPerSocket||ye.maxRequestsPerSocket,e.requestTimeout=e.requestTimeout||ye.requestTimeout,e.logger=c,e.requestIdHeader=r,e.requestIdLogLabel=a,e.disableRequestLogging=o,e.ajv=s,e.clientErrorHandler=e.clientErrorHandler||Be,e.allowErrorHandlerOverride=e.allowErrorHandlerOverride??ye.allowErrorHandlerOverride;let u=pe(e);return e.exposeHeadRoutes=u.exposeHeadRoutes,e.http2SessionTimeout=u.http2SessionTimeout,e.routerOptions=de(e,{defaultRoute:t,onBadUrl:n,ignoreTrailingSlash:ye.ignoreTrailingSlash,ignoreDuplicateSlashes:ye.ignoreDuplicateSlashes,maxParamLength:ye.maxParamLength,allowUnsafeRegex:ye.allowUnsafeRegex,buildPrettyMeta:ze,useSemicolonDelimiter:ye.useSemicolonDelimiter}),{options:e,genReqId:i,disableRequestLogging:o,hasLogger:l,initialConfig:u}}function ze(e){let t={};return[`errorHandler`,`logLevel`,`logSerializers`].concat(ie).forEach(n=>{t[n]=e.store[n]}),Object.assign({},t)}function Be(e,t){if(e.code===`ECONNRESET`||t.destroyed)return;let n,i,a,o;e.code===`ERR_HTTP_REQUEST_TIMEOUT`?(i=`408`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Timeout","statusCode":408}`,o=`timeout`):e.code===`HPE_HEADER_OVERFLOW`?(i=`431`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`,o=`header_overflow`):(i=`400`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Error","statusCode":400}`,o=`error`),this.log.trace({err:e},`client ${o}`),t.writable&&t.write(`HTTP/1.1 ${i} ${a}\r\nContent-Length: ${n.length}\r\nContent-Type: application/json\r\n\r\n${n}`),t.destroy(e)}function Ve(e){if(typeof e!=`function`)throw new Ae(typeof e);if(e.constructor.name===`AsyncFunction`)throw new Ae(`AsyncFunction`)}t.exports=Le,t.exports.errorCodes=_e,t.exports.fastify=Le,t.exports.default=Le})),dh=o(((e,t)=>{let n=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,r=/(\w*(\.\w*)*)\..*/;t.exports=function(e){if(e.name.length>0)return e.name;let t=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw Error(`anonymous function`)}catch(e){return Error.stackTraceLimit=t,i(e.stack)}};function i(e){let t=e.match(n);return t?t[1].split(/[/\\]/).slice(-1)[0].match(r)[1]:`anonymous`}t.exports.extractPluginName=i})),fh=o(((e,t)=>{t.exports=function(e){return e[0]===`@`&&(e=e.slice(1).replace(`/`,`-`)),e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}})),ph=o(((e,t)=>{let n=dh(),r=fh(),i=0;function a(e,t={}){let a=!1;if(e.default!==void 0&&(e=e.default),typeof e!=`function`)throw TypeError(`fastify-plugin expects a function, instead got a '${typeof e}'`);if(typeof t==`string`&&(t={fastify:t}),typeof t!=`object`||Array.isArray(t)||t===null)throw TypeError(`The options object should be an object`);if(t.fastify!==void 0&&typeof t.fastify!=`string`)throw TypeError(`fastify-plugin expects a version string, instead got '${typeof t.fastify}'`);t.name||(a=!0,t.name=n(e)+`-auto-`+ i++),e[Symbol.for(`skip-override`)]=t.encapsulate!==!0,e[Symbol.for(`fastify.display-name`)]=t.name,e[Symbol.for(`plugin-meta`)]=t,e.default||=e;let o=r(t.name);return!a&&!e[o]&&(e[o]=e),e}t.exports=a,t.exports.default=a,t.exports.fastifyPlugin=a})),mh=o(((e,t)=>{function n(e){if(typeof e!=`function`)throw Error(`obliterator/iterator: expecting a function!`);this.next=e}typeof Symbol<`u`&&(n.prototype[Symbol.iterator]=function(){return this}),n.of=function(){var e=arguments,t=e.length,r=0;return new n(function(){return r>=t?{done:!0}:{done:!1,value:e[r++]}})},n.empty=function(){return new n(function(){return{done:!0}})},n.fromSequence=function(e){var t=0,r=e.length;return new n(function(){return t>=r?{done:!0}:{done:!1,value:e[t++]}})},n.is=function(e){return e instanceof n?!0:typeof e==`object`&&!!e&&typeof e.next==`function`},t.exports=n})),hh=o((e=>{e.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<`u`,e.SYMBOL_SUPPORT=typeof Symbol<`u`})),gh=o(((e,t)=>{var n=hh(),r=n.ARRAY_BUFFER_SUPPORT,i=n.SYMBOL_SUPPORT;t.exports=function(e,t){var n,a,o,s,c;if(!e)throw Error(`obliterator/forEach: invalid iterable.`);if(typeof t!=`function`)throw Error(`obliterator/forEach: expecting a callback.`);if(Array.isArray(e)||r&&ArrayBuffer.isView(e)||typeof e==`string`||e.toString()===`[object Arguments]`){for(o=0,s=e.length;o<s;o++)t(e[o],o);return}if(typeof e.forEach==`function`){e.forEach(t);return}if(i&&Symbol.iterator in e&&typeof e.next!=`function`&&(e=e[Symbol.iterator]()),typeof e.next==`function`){for(n=e,o=0;c=n.next(),c.done!==!0;)t(c.value,o),o++;return}for(a in e)e.hasOwnProperty(a)&&t(e[a],a)}})),_h=o((e=>{var t=2**8-1,n=2**16-1,r=2**32-1,i=2**7-1,a=2**15-1,o=2**31-1;e.getPointerArray=function(e){var i=e-1;if(i<=t)return Uint8Array;if(i<=n)return Uint16Array;if(i<=r)return Uint32Array;throw Error(`mnemonist: Pointer Array of size > 4294967295 is not supported.`)},e.getSignedPointerArray=function(e){var t=e-1;return t<=i?Int8Array:t<=a?Int16Array:t<=o?Int32Array:Float64Array},e.getNumberType=function(e){return e===(e|0)?Math.sign(e)===-1?e<=127&&e>=-128?Int8Array:e<=32767&&e>=-32768?Int16Array:Int32Array:e<=255?Uint8Array:e<=65535?Uint16Array:Uint32Array:Float64Array};var s={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};e.getMinimalRepresentation=function(t,n){var r=null,i=0,a,o,c,l,u;for(l=0,u=t.length;l<u;l++)c=n?n(t[l]):t[l],o=e.getNumberType(c),a=s[o.name],a>i&&(i=a,r=o);return r},e.isTypedArray=function(e){return typeof ArrayBuffer<`u`&&ArrayBuffer.isView(e)},e.concat=function(){var e=0,t,n,r;for(t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var i=new arguments[0].constructor(e);for(t=0,n=0;t<r;t++)i.set(arguments[t],n),n+=arguments[t].length;return i},e.indices=function(t){for(var n=new(e.getPointerArray(t))(t),r=0;r<t;r++)n[r]=r;return n}})),vh=o((e=>{var t=gh(),n=_h();function r(e){return Array.isArray(e)||n.isTypedArray(e)}function i(e){if(typeof e.length==`number`)return e.length;if(typeof e.size==`number`)return e.size}function a(e){var n=i(e),r=typeof n==`number`?Array(n):[],a=0;return t(e,function(e){r[a++]=e}),r}function o(e){var r=i(e),a=typeof r==`number`?n.getPointerArray(r):Array,o=typeof r==`number`?Array(r):[],s=typeof r==`number`?new a(r):[],c=0;return t(e,function(e){o[c]=e,s[c]=c++}),[o,s]}e.isArrayLike=r,e.guessLength=i,e.toArray=a,e.toArrayWithIndices=o})),yh=o(((e,t)=>{var n=mh(),r=gh(),i=_h(),a=vh();function o(e,t,n){if(arguments.length<2&&(n=e,e=null,t=null),this.capacity=n,typeof this.capacity!=`number`||this.capacity<=0)throw Error(`mnemonist/lru-cache: capacity should be positive number.`);if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw Error(`mnemonist/lru-cache: capacity should be a finite positive integer.`);var r=i.getPointerArray(n);this.forward=new r(n),this.backward=new r(n),this.K=typeof e==`function`?new e(n):Array(n),this.V=typeof t==`function`?new t(n):Array(n),this.size=0,this.head=0,this.tail=0,this.items={}}o.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}},o.prototype.splayOnTop=function(e){var t=this.head;if(this.head===e)return this;var n=this.backward[e],r=this.forward[e];return this.tail===e?this.tail=n:this.backward[r]=n,this.forward[n]=r,this.backward[t]=e,this.head=e,this.forward[e]=t,this},o.prototype.set=function(e,t){var n=this.items[e];if(n!==void 0){this.splayOnTop(n),this.V[n]=t;return}this.size<this.capacity?n=this.size++:(n=this.tail,this.tail=this.backward[n],delete this.items[this.K[n]]),this.items[e]=n,this.K[n]=e,this.V[n]=t,this.forward[n]=this.head,this.backward[this.head]=n,this.head=n},o.prototype.setpop=function(e,t){var n=null,r=null,i=this.items[e];return i===void 0?(this.size<this.capacity?i=this.size++:(i=this.tail,this.tail=this.backward[i],n=this.V[i],r=this.K[i],delete this.items[r]),this.items[e]=i,this.K[i]=e,this.V[i]=t,this.forward[i]=this.head,this.backward[this.head]=i,this.head=i,r?{evicted:!0,key:r,value:n}:null):(this.splayOnTop(i),n=this.V[i],this.V[i]=t,{evicted:!1,key:e,value:n})},o.prototype.has=function(e){return e in this.items},o.prototype.get=function(e){var t=this.items[e];if(t!==void 0)return this.splayOnTop(t),this.V[t]},o.prototype.peek=function(e){var t=this.items[e];if(t!==void 0)return this.V[t]},o.prototype.forEach=function(e,t){t=arguments.length>1?t:this;for(var n=0,r=this.size,i=this.head,a=this.K,o=this.V,s=this.forward;n<r;)e.call(t,o[i],a[i],this),i=s[i],n++},o.prototype.keys=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.values=function(){var e=0,t=this.size,r=this.head,i=this.V,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.entries=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.V,o=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r],s=a[r];return e++,e<t&&(r=o[r]),{done:!1,value:[n,s]}})},typeof Symbol<`u`&&(o.prototype[Symbol.iterator]=o.prototype.entries),o.prototype.inspect=function(){for(var e=new Map,t=this.entries(),n;n=t.next(),!n.done;)e.set(n.value[0],n.value[1]);return Object.defineProperty(e,`constructor`,{value:o,enumerable:!1}),e},typeof Symbol<`u`&&(o.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=o.prototype.inspect),o.from=function(e,t,n,i){if(arguments.length<2){if(i=a.guessLength(e),typeof i!=`number`)throw Error(`mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.`)}else arguments.length===2&&(i=t,t=null,n=null);var s=new o(t,n,i);return r(e,function(e,t){s.set(t,e)}),s},t.exports=o})),bh=o(((e,t)=>{let n=yh(),r=/^[!#$%&'*+\-.^\w`|~]+$/u;function i(e){if(r.test(e)===!1)throw TypeError(`Fieldname contains invalid characters.`)}function a(e){e=e.trim().toLowerCase();let t=[];if(e.length!==0)if(e.indexOf(`,`)===-1)t.push(e);else{let n=e.length,r=0,i=0,a;for(;r<n;++r)a=e[r],a===` `?i=r+1:a===`,`&&(i!==r&&t.push(e.slice(i,r)),i=r+1);i!==r&&t.push(e.slice(i,r))}return t}function o(e){let t=new n(1e3);return i(e),function(n){let r=n.getHeader(`Vary`);if(!r){n.header(`Vary`,e);return}if(r===`*`)return;if(e===`*`){n.header(`Vary`,`*`);return}if(Array.isArray(r)&&(r=r.join(`, `)),!t.has(r)){let n=a(r);n.indexOf(`*`)===-1?n.indexOf(e.toLowerCase())===-1?t.set(r,r+`, `+e):t.set(r,null):t.set(r,`*`)}let i=t.get(r);i!==null&&n.header(`Vary`,i)}}t.exports.createAddFieldnameToVary=o,t.exports.addOriginToVaryHeader=o(`Origin`),t.exports.addAccessControlRequestHeadersToVaryHeader=o(`Access-Control-Request-Headers`),t.exports.parse=a})),xh=o(((e,t)=>{let n=ph(),{addAccessControlRequestHeadersToVaryHeader:r,addOriginToVaryHeader:i}=bh(),a={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,hook:`onRequest`,preflightContinue:!1,optionsSuccessStatus:204,credentials:!1,exposedHeaders:null,allowedHeaders:null,maxAge:null,preflight:!0,strictPreflight:!0},o=[`onRequest`,`preParsing`,`preValidation`,`preHandler`,`preSerialization`,`onSend`],s=[`preSerialization`,`preParsing`,`onSend`];function c(e,t){o.indexOf(e)===-1&&t(TypeError(`@fastify/cors: Invalid hook option provided.`))}function l(e,t,n){e.decorateRequest(`corsPreflightEnabled`,!1);let r=!0;if(typeof t==`function`)u(t,e,{hook:a.hook},n);else if(t.delegator){let{delegator:r,...i}=t;u(r,e,i,n)}else{t.hideOptionsRoute!==void 0&&(r=t.hideOptionsRoute);let i=f(t);c(i.hook,n),s.indexOf(i.hook)===-1?e.addHook(i.hook,function(t,n,r){p(e,i,t,n,r)}):e.addHook(i.hook,function(t,n,r,a){p(e,i,t,n,a)})}e.options(`*`,{schema:{hide:r}},(e,t)=>{if(!e.corsPreflightEnabled){t.callNotFound();return}t.send()}),n()}function u(e,t,n,r){let i=n?.hook||a.hook;c(i,r),e.length===2?s.indexOf(i)===-1?t.addHook(i,function(n,r,i){d(e,t,n,r,i)}):t.addHook(i,function(n,r,i,a){d(e,t,n,r,a)}):s.indexOf(i)===-1?t.addHook(i,function(n,r,i){let a=e(n);if(a&&typeof a.then==`function`){a.then(e=>p(t,f(e,!0),n,r,i)).catch(i);return}i(Error(`Invalid CORS origin option`))}):t.addHook(i,function(n,r,i,a){let o=e(n);if(o&&typeof o.then==`function`){o.then(e=>p(t,f(e,!0),n,r,a)).catch(a);return}a(Error(`Invalid CORS origin option`))})}function d(e,t,n,r,i){e(n,(e,a)=>{e?i(e):p(t,f(a,!0),n,r,i)})}function f(e,t){let n={...a,...e};return Array.isArray(e.origin)&&e.origin.indexOf(`*`)!==-1&&(n.origin=`*`),Number.isInteger(n.cacheControl)?n.cacheControl=`max-age=${n.cacheControl}`:typeof n.cacheControl!=`string`&&(n.cacheControl=null),n.dynamic=t||!1,n}function p(e,t,n,r,a){(typeof t.origin!=`string`&&t.origin!==!1||t.dynamic)&&i(r),(typeof t.origin==`function`?g(e,t.origin):(e,n)=>n(null,t.origin))(n,(e,i)=>{if(e!==null)return a(e);if(i===!1||n.routeOptions.config?.cors===!1)return a();if(!i)return a(Error(`Invalid CORS origin option`));if(m(n,r,i,t),n.raw.method===`OPTIONS`&&t.preflight===!0){if(t.strictPreflight===!0&&(!n.headers.origin||!n.headers[`access-control-request-method`])){r.status(400).type(`text/plain`).send(`Invalid Preflight Request`);return}if(n.corsPreflightEnabled=!0,h(n,r,t),!t.preflightContinue){r.code(t.optionsSuccessStatus).header(`Content-Length`,`0`).send();return}}return a()})}function m(e,t,n,r){let i=_(e.headers.origin,n);i&&t.header(`Access-Control-Allow-Origin`,i),r.credentials&&t.header(`Access-Control-Allow-Credentials`,`true`),r.exposedHeaders!==null&&t.header(`Access-Control-Expose-Headers`,Array.isArray(r.exposedHeaders)?r.exposedHeaders.join(`, `):r.exposedHeaders)}function h(e,t,n){if(t.header(`Access-Control-Allow-Methods`,Array.isArray(n.methods)?n.methods.join(`, `):n.methods),n.allowedHeaders===null){r(t);let n=e.headers[`access-control-request-headers`];n!==void 0&&t.header(`Access-Control-Allow-Headers`,n)}else t.header(`Access-Control-Allow-Headers`,Array.isArray(n.allowedHeaders)?n.allowedHeaders.join(`, `):n.allowedHeaders);n.maxAge!==null&&t.header(`Access-Control-Max-Age`,String(n.maxAge)),n.cacheControl&&t.header(`Cache-Control`,n.cacheControl)}function g(e,t){return function(n,r){let i=t.call(e,n.headers.origin,r);i&&typeof i.then==`function`&&i.then(e=>r(null,e),r)}}function _(e,t){return typeof t==`string`?t:v(e,t)?e:!1}function v(e,t){if(Array.isArray(t)){for(let n=0;n<t.length;++n)if(v(e,t[n]))return!0;return!1}else if(typeof t==`string`)return e===t;else if(t instanceof RegExp)return t.lastIndex=0,t.test(e);else return!!t}let y=n(l,{fastify:`5.x`,name:`@fastify/cors`});t.exports=y,t.exports.fastifyCors=y,t.exports.default=y})),Sh=o(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),Ch=o(((e,t)=>{let{EMPTY_BUFFER:n}=Sh(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),wh=o(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),Th=o(((e,t)=>{let n=require(`zlib`),r=Ch(),i=wh(),{kStatusCode:a}=Sh(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Eh=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=Sh(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Dh=o(((e,t)=>{let{Writable:n}=require(`stream`),r=Th(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Sh(),{concat:c,toArrayBuffer:l,unmask:u}=Ch(),{isValidStatusCode:d,isValidUTF8:f}=Eh(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),Oh=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=Th(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Sh(),{isBlob:c,isValidStatusCode:l}=Eh(),{mask:u,toBuffer:d}=Ch(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),kh=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Sh(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Ah=o(((e,t)=>{let{tokenChars:n}=Eh();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),jh=o(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=Th(),p=Dh(),m=Oh(),{isBlob:h}=Eh(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=Sh(),{EventTarget:{addEventListener:T,removeEventListener:E}}=kh(),{format:D,parse:O}=Ah(),{toBuffer:k}=Ch(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,I),i.on(`drain`,ae),i.on(`error`,oe),i.on(`message`,se),i.on(`ping`,ce),i.on(`pong`,le),a.onerror=de,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,pe),t.on(`data`,me),t.on(`end`,he),t.on(`error`,ge),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),fe(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;P(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?re:ne),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{F(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,P(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){F(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{P(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||F(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function P(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(e){return e.path=e.socketPath,a.connect(e)}function re(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(P,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ie(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function I(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,me),process.nextTick(ue,n._socket),e===1005?n.close():n.close(e,t))}function ae(){let e=this[C];e.isPaused||e._socket.resume()}function oe(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,me),process.nextTick(ue,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function L(){this[C].emitClose()}function se(e,t){this[C].emit(`message`,e,t)}function ce(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function le(e){this[C].emit(`pong`,e)}function ue(e){e.resume()}function de(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,fe(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function fe(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function pe(){let e=this[C];if(this.removeListener(`close`,pe),this.removeListener(`data`,me),this.removeListener(`end`,he),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,L),e._receiver.on(`finish`,L))}function me(e){this[C]._receiver.write(e)||this.pause()}function he(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function ge(){let e=this[C];this.removeListener(`error`,ge),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),Mh=o(((e,t)=>{jh();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Nh=o(((e,t)=>{let{tokenChars:n}=Eh();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Ph=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Ah(),s=Th(),c=Nh(),l=jh(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=Sh(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
450
+ `))}}})),Um=o(((e,t)=>{let n=Hm(),r={STATIC:0,PARAMETRIC:1,WILDCARD:2};var i=class{constructor(){this.isLeafNode=!1,this.routes=null,this.handlerStorage=null}addRoute(e,t){this.routes===null&&(this.routes=[]),this.handlerStorage===null&&(this.handlerStorage=new n),this.isLeafNode=!0,this.routes.push(e),this.handlerStorage.addHandler(t,e)}},a=class extends i{constructor(){super(),this.staticChildren={}}findStaticMatchingChild(e,t){let n=this.staticChildren[e.charAt(t)];return n===void 0||!n.matchPrefix(e,t)?null:n}getStaticChild(e,t=0){if(e.length===t)return this;let n=this.findStaticMatchingChild(e,t);return n?n.getStaticChild(e,t+n.prefix.length):null}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let n=e.charAt(0);return this.staticChildren[n]=new o(e),this.staticChildren[n]}},o=class e extends a{constructor(e){super(),this.prefix=e,this.wildcardChild=null,this.parametricChildren=[],this.kind=r.STATIC,this._compilePrefixMatch()}getParametricChild(e){let t=e&&e.source;return this.parametricChildren.find(e=>(e.regex&&e.regex.source)===t)||null}createParametricChild(e,t,n){let r=this.getParametricChild(e);return r?(r.nodePaths.add(n),r):(r=new s(e,t,n),this.parametricChildren.push(r),this.parametricChildren.sort((e,t)=>e.isRegex?t.isRegex?e.staticSuffix===null?1:t.staticSuffix===null?-1:t.staticSuffix.endsWith(e.staticSuffix)?1:e.staticSuffix.endsWith(t.staticSuffix)?-1:0:-1:1),r)}getWildcardChild(){return this.wildcardChild}createWildcardChild(){return this.wildcardChild=this.getWildcardChild()||new c,this.wildcardChild}split(t,n){let r=this.prefix.slice(0,n),i=this.prefix.slice(n);this.prefix=i,this._compilePrefixMatch();let a=new e(r);return a.staticChildren[i.charAt(0)]=this,t.staticChildren[r.charAt(0)]=a,a}getNextNode(e,t,n,r){let i=this.findStaticMatchingChild(e,t),a=0;if(i===null){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],a=1}this.wildcardChild!==null&&n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let e=this.parametricChildren.length-1;e>=a;e--)n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.parametricChildren[e]});return i}_compilePrefixMatch(){if(this.prefix.length===1){this.matchPrefix=()=>!0;return}let e=[];for(let t=1;t<this.prefix.length;t++){let n=this.prefix.charCodeAt(t);e.push(`path.charCodeAt(i + ${t}) === ${n}`)}this.matchPrefix=Function(`path`,`i`,`return ${e.join(` && `)}`)}},s=class extends a{constructor(e,t,n){super(),this.isRegex=!!e,this.regex=e||null,this.staticSuffix=t||null,this.kind=r.PARAMETRIC,this.nodePaths=new Set([n])}getNextNode(e,t){return this.findStaticMatchingChild(e,t)}},c=class extends i{constructor(){super(),this.kind=r.WILDCARD}getNextNode(){return null}};t.exports={StaticNode:o,ParametricNode:s,WildcardNode:c,NODE_TYPES:r}})),Wm=o(((e,t)=>{let n=require(`node:assert`);function r(){if(!(this instanceof r))return new r;this.store=new Map,this.maxMajor=0,this.maxMinors={},this.maxPatches={}}r.prototype.set=function(e,t){if(typeof e!=`string`)throw TypeError(`Version should be a string`);let[n,r,i]=e.split(`.`,3);if(isNaN(n))throw TypeError(`Major version must be a numeric value`);return n=Number(n),r=Number(r)||0,i=Number(i)||0,n>=this.maxMajor&&(this.maxMajor=n,this.store.set(`x`,t),this.store.set(`*`,t),this.store.set(`x.x`,t),this.store.set(`x.x.x`,t)),r>=(this.maxMinors[n]||0)&&(this.maxMinors[n]=r,this.store.set(`${n}.x`,t),this.store.set(`${n}.x.x`,t)),i>=(this.maxPatches[`${n}.${r}`]||0)&&(this.maxPatches[`${n}.${r}`]=i,this.store.set(`${n}.${r}.x`,t)),this.store.set(`${n}.${r}.${i}`,t),this},r.prototype.get=function(e){return this.store.get(e)},t.exports={name:`version`,mustMatchWhenDerived:!0,storage:r,validate(e){n(typeof e==`string`,`Version should be a string`)}}})),Gm=o(((e,t)=>{let n=require(`node:assert`);function r(){let e=new Map,t=[];return{get:n=>{let r=e.get(n);if(r)return r;for(let e of t)if(e.host.test(n))return e.value},set:(n,r)=>{n instanceof RegExp?t.push({host:n,value:r}):e.set(n,r)}}}t.exports={name:`host`,mustMatchWhenDerived:!1,storage:r,validate(e){n(typeof e==`string`||Object.prototype.toString.call(e)===`[object RegExp]`,`Host should be a string or a RegExp`)}}})),Km=o(((e,t)=>{let n=Wm(),r=Gm(),i=require(`node:assert`);t.exports=class{constructor(e){if(this.strategies={version:n,host:r},this.strategiesInUse=new Set,this.asyncStrategiesInUse=new Set,e)for(let t of Object.values(e))this.addConstraintStrategy(t)}isStrategyUsed(e){return this.strategiesInUse.has(e)||this.asyncStrategiesInUse.has(e)}hasConstraintStrategy(e){let t=this.strategies[e];return t===void 0?!1:t.isCustom||this.isStrategyUsed(e)}addConstraintStrategy(e){if(i(typeof e.name==`string`&&e.name!==``,`strategy.name is required.`),i(e.storage&&typeof e.storage==`function`,`strategy.storage function is required.`),i(e.deriveConstraint&&typeof e.deriveConstraint==`function`,`strategy.deriveConstraint function is required.`),this.strategies[e.name]&&this.strategies[e.name].isCustom)throw Error(`There already exists a custom constraint with the name ${e.name}.`);if(this.isStrategyUsed(e.name))throw Error(`There already exists a route with ${e.name} constraint.`);e.isCustom=!0,e.isAsync=e.deriveConstraint.length===3,this.strategies[e.name]=e,e.mustMatchWhenDerived&&this.noteUsage({[e.name]:e})}deriveConstraints(e,t,n){let r=this.deriveSyncConstraints(e,t);if(n===void 0)return r;this.deriveAsyncConstraints(r,e,t,n)}deriveSyncConstraints(e,t){}noteUsage(e){if(e){let t=this.strategiesInUse.size;for(let t in e)this.strategies[t].isAsync?this.asyncStrategiesInUse.add(t):this.strategiesInUse.add(t);t!==this.strategiesInUse.size&&this._buildDeriveConstraints()}}newStoreForConstraint(e){if(!this.strategies[e])throw Error(`No strategy registered for constraint key ${e}`);return this.strategies[e].storage()}validateConstraints(e){for(let t in e){let n=e[t];if(n===void 0)throw Error(`Can't pass an undefined constraint value, must pass null or no key at all`);let r=this.strategies[t];if(!r)throw Error(`No strategy registered for constraint key ${t}`);r.validate&&r.validate(n)}}deriveAsyncConstraints(e,t,n,r){let i=this.asyncStrategiesInUse.size;if(i===0){r(null,e);return}e||={};for(let a of this.asyncStrategiesInUse)this.strategies[a].deriveConstraint(t,n,(t,n)=>{if(t!==null){r(t);return}e[a]=n,--i===0&&r(null,e)})}_buildDeriveConstraints(){if(this.strategiesInUse.size===0)return;let e=[`return {`];for(let t of this.strategiesInUse){let n=this.strategies[t];n.isCustom?e.push(` ${n.name}: this.strategies.${t}.deriveConstraint(req, ctx),`):t===`version`?e.push(` version: req.headers['accept-version'],`):e.push(` host: req.headers.host || req.headers[':authority'],`)}e.push(`}`),this.deriveSyncConstraints=Function(`req`,`ctx`,e.join(`
451
+ `)).bind(this)}}})),qm=o(((e,t)=>{t.exports=`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`)})),Jm=o(((e,t)=>{function n(e,t){return e===50?t===53?`%`:t===51?`#`:t===52?`$`:t===54?`&`:t===66||t===98?`+`:t===67||t===99?`,`:t===70||t===102?`/`:null:e===51?t===65||t===97?`:`:t===66||t===98?`;`:t===68||t===100?`=`:t===70||t===102?`?`:null:e===52&&t===48?`@`:null}function r(e,t){let r=!1,i=!1,a=``;for(let o=1;o<e.length;o++){let s=e.charCodeAt(o);if(s===37){let t=e.charCodeAt(o+1),a=e.charCodeAt(o+2);n(t,a)===null?r=!0:(i=!0,t===50&&a===53&&(r=!0,e=e.slice(0,o+1)+`25`+e.slice(o+1),o+=2),o+=2)}else if(s===63||s===35||s===59&&t){a=e.slice(o+1),e=e.slice(0,o);break}}return{path:r?decodeURI(e):e,querystring:a,shouldDecodeParam:i}}function i(e){let t=e.indexOf(`%`);if(t===-1)return e;let r=``,i=t;for(let a=t;a<e.length;a++)if(e.charCodeAt(a)===37){let t=n(e.charCodeAt(a+1),e.charCodeAt(a+2));r+=e.slice(i,a)+t,i=a+3}return e.slice(0,t)+r+e.slice(i)}t.exports={safeDecodeURI:r,safeDecodeURIComponent:i}})),Ym=o(((e,t)=>{let n=require(`node:assert`),r=Em(),i=Rm(),a=Rd(),{prettyPrintTree:o}=Bm(),{StaticNode:s,NODE_TYPES:c}=Um(),l=Km(),u=qm(),d=zm(),{safeDecodeURI:f,safeDecodeURIComponent:p}=Jm(),m=/^https?:\/\/.*?\//,h=/(\/:[^/()]*?)\?(\/?)/,g=/[.*+?^${}()|[\]\\]/g,_=/\/\/+/g;if(!i(m))throw Error(`the FULL_PATH_REGEXP is not safe, update this module`);if(!i(h))throw Error(`the OPTIONAL_PARAM_REGEXP is not safe, update this module`);if(!i(g))throw Error(`the ESCAPE_REGEXP is not safe, update this module`);if(!i(_))throw Error(`the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module`);function v(e){if(!(this instanceof v))return new v(e);e||={},this._opts=e,e.defaultRoute?(n(typeof e.defaultRoute==`function`,`The default route must be a function`),this.defaultRoute=e.defaultRoute):this.defaultRoute=null,e.onBadUrl?(n(typeof e.onBadUrl==`function`,`The bad url handler must be a function`),this.onBadUrl=e.onBadUrl):this.onBadUrl=null,e.buildPrettyMeta?(n(typeof e.buildPrettyMeta==`function`,`buildPrettyMeta must be a function`),this.buildPrettyMeta=e.buildPrettyMeta):this.buildPrettyMeta=w,e.querystringParser?(n(typeof e.querystringParser==`function`,`querystringParser must be a function`),this.querystringParser=e.querystringParser):this.querystringParser=e=>e.length===0?{}:r.parse(e),this.caseSensitive=e.caseSensitive===void 0?!0:e.caseSensitive,this.ignoreTrailingSlash=e.ignoreTrailingSlash||!1,this.ignoreDuplicateSlashes=e.ignoreDuplicateSlashes||!1,this.maxParamLength=e.maxParamLength||100,this.allowUnsafeRegex=e.allowUnsafeRegex||!1,this.constrainer=new l(e.constraints),this.useSemicolonDelimiter=e.useSemicolonDelimiter||!1,this.routes=[],this.trees={}}v.prototype.on=function(e,t,r,i,a){typeof r==`function`&&(i!==void 0&&(a=i),i=r,r={}),n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(typeof i==`function`,`Handler should be a function`);let o=t.match(h);if(o){n(t.length===o.index+o[0].length,`Optional Parameter needs to be the last parameter of the path`);let s=t.replace(h,`$1$2`),c=t.replace(h,`$2`)||`/`;this.on(e,s,r,i,a),this.on(e,c,r,i,a);return}let s=t;this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let c=Array.isArray(e)?e:[e];for(let e of c)n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`),this._on(e,t,r,i,a,s)},v.prototype._on=function(e,t,r,o,c){let l={};r.constraints!==void 0&&(n(typeof r.constraints==`object`&&r.constraints!==null,`Constraints should be an object`),Object.keys(r.constraints).length!==0&&(l=r.constraints)),this.constrainer.validateConstraints(l),this.constrainer.noteUsage(l),this.trees[e]===void 0&&(this.trees[e]=new s(`/`));let u=t;if(u===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new s(``),this.trees[e].staticChildren[`/`]=t}let d=this.trees[e],f=d.prefix.length,p=[];for(let e=0;e<=u.length;e++){if(u.charCodeAt(e)===58&&u.charCodeAt(e+1)===58){e++;continue}let t=u.charCodeAt(e)===58&&u.charCodeAt(e+1)!==58,r=u.charCodeAt(e)===42;if(t||r||e===u.length&&e!==f){let t=u.slice(f,e);this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),d=d.createStaticChild(t)}if(t){let t=!1,r=!0,a=``,o=[],s=e+1;for(let c=s;;c++){let l=u.charCodeAt(c),m=l===40,h=l===45||l===46,g=l===47||c===u.length;if(m||h||g){let l=u.slice(s,c);if(p.push(l),t=t||m||h,m){let e=C(u,c),t=u.slice(c,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),o.push(S(t)),c=e+1,r=!0}else o.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=c;for(;c<u.length;c++){let e=u.charCodeAt(c);if(e===47)break;if(e===58)if(u.charCodeAt(c+1)===58)c++;else break}let v=u.slice(_,c);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),o.push(a=y(v))),s=c+1,g||u.charCodeAt(c)===47||c===u.length){let n=t?`()`+v:v,r=u.slice(e,c);u=u.slice(0,e+1)+n+u.slice(c),e+=n.length;let i=t?RegExp(`^`+o.join(``)+`$`):null;d=d.createParametricChild(i,v||null,r),f=e+1;break}}}}else if(r&&(p.push(`*`),d=d.createWildcardChild(),f=e+1,e!==u.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(u=u.toLowerCase()),u===`*`&&(u=`/*`);for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===u&&a(n,l))throw Error(`Method '${e}' already declared for route '${u}' with constraints '${JSON.stringify(l)}'`)}let m={method:e,path:t,pattern:u,params:p,opts:r,handler:o,store:c};this.routes.push(m),d.addRoute(m,this.constrainer)},v.prototype.hasRoute=function(e,t,n){return this.findRoute(e,t,n)!==null},v.prototype.findRoute=function(e,t,r={}){if(this.trees[e]===void 0)return null;let o=t,s=this.trees[e],c=s.prefix.length,l=[];for(let e=0;e<=o.length;e++){if(o.charCodeAt(e)===58&&o.charCodeAt(e+1)===58){e++;continue}let t=o.charCodeAt(e)===58&&o.charCodeAt(e+1)!==58,r=o.charCodeAt(e)===42;if(t||r||e===o.length&&e!==c){let t=o.slice(c,e);if(this.caseSensitive||(t=t.toLowerCase()),t=t.replaceAll(`::`,`:`),t=t.replaceAll(`%`,`%25`),s=s.getStaticChild(t),s===null)return null}if(t){let t=!1,r=!0,a=``,u=[],d=e+1;for(let f=d;;f++){let p=o.charCodeAt(f),m=p===40,h=p===45||p===46,g=p===47||f===o.length;if(m||h||g){let p=o.slice(d,f);if(l.push(p),t=t||m||h,m){let e=C(o,f),t=o.slice(f,e+1);this.allowUnsafeRegex||n(i(new RegExp(t)),`The regex '${t}' is not safe!`),u.push(S(t)),f=e+1,r=!1}else u.push(r?`(.*?)`:`(${a}|(?:(?!${a}).)*)`),r=!1;let _=f;for(;f<o.length;f++){let e=o.charCodeAt(f);if(e===47)break;if(e===58)if(o.charCodeAt(f+1)===58)f++;else break}let v=o.slice(_,f);if(v&&(v=v.replaceAll(`::`,`:`),v=v.replaceAll(`%`,`%25`),u.push(a=y(v))),d=f+1,g||o.charCodeAt(f)===47||f===o.length){let n=t?`()`+v:v,r=o.slice(e,f);o=o.slice(0,e+1)+n+o.slice(f),e+=n.length;let i=t?RegExp(`^`+u.join(``)+`$`):null;if(s=s.getParametricChild(i,v||null,r),s===null)return null;c=e+1;break}}}}else if(r&&(l.push(`*`),s=s.getWildcardChild(),c=e+1,e!==o.length-1))throw Error(`Wildcard must be the last character in the route`)}this.caseSensitive||(o=o.toLowerCase());for(let t of this.routes){let n=t.opts.constraints||{};if(t.method===e&&t.pattern===o&&a(n,r))return{handler:t.handler,store:t.store,params:t.params}}return null},v.prototype.hasConstraintStrategy=function(e){return this.constrainer.hasConstraintStrategy(e)},v.prototype.addConstraintStrategy=function(e){this.constrainer.addConstraintStrategy(e),this._rebuild(this.routes)},v.prototype.reset=function(){this.trees={},this.routes=[]},v.prototype.off=function(e,t,r){n(typeof t==`string`,`Path should be a string`),n(t.length>0,`The path could not be empty`),n(t[0]===`/`||t[0]===`*`,"The first character of a path should be `/` or `*`"),n(r===void 0||typeof r==`object`&&!Array.isArray(r)&&r!==null,`Constraints should be an object or undefined.`);let i=t.match(h);if(i){n(t.length===i.index+i[0].length,`Optional Parameter needs to be the last parameter of the path`);let a=t.replace(h,`$1$2`),o=t.replace(h,`$2`);this.off(e,a,r),this.off(e,o,r);return}this.ignoreDuplicateSlashes&&(t=b(t)),this.ignoreTrailingSlash&&(t=x(t));let a=Array.isArray(e)?e:[e];for(let e of a)this._off(e,t,r)},v.prototype._off=function(e,t,r){n(typeof e==`string`,`Method should be a string`),n(u.includes(e),`Method '${e}' is not an http method.`);function i(n){return e!==n.method||t!==n.path}function o(e){return i(e)||!a(r,e.opts.constraints||{})}let s=r?o:i,c=this.routes.filter(s);this._rebuild(c)},v.prototype.lookup=function(e,t,n,r){if(typeof n==`function`&&(r=n,n=void 0),r===void 0){let r=this.constrainer.deriveConstraints(e,n),i=this.find(e.method,e.url,r);return this.callHandler(i,e,t,n)}this.constrainer.deriveConstraints(e,n,(i,a)=>{if(i!==null){r(i);return}try{let i=this.find(e.method,e.url,a),o=this.callHandler(i,e,t,n);r(null,o)}catch(e){r(e)}})},v.prototype.callHandler=function(e,t,n,r){return e===null?this._defaultRoute(t,n,r):r===void 0?e.handler(t,n,e.params,e.store,e.searchParams):e.handler.call(r,t,n,e.params,e.store,e.searchParams)},v.prototype.find=function(e,t,n){let r=this.trees[e];if(r===void 0)return null;t.charCodeAt(0)!==47&&(t=t.replace(m,`/`)),this.ignoreDuplicateSlashes&&(t=b(t));let i,a,o;try{i=f(t,this.useSemicolonDelimiter),t=i.path,a=i.querystring,o=i.shouldDecodeParam}catch{return this._onBadUrl(t)}this.ignoreTrailingSlash&&(t=x(t));let s=t;this.caseSensitive===!1&&(t=t.toLowerCase());let l=this.maxParamLength,u=r.prefix.length,d=[],h=t.length,g=[];for(;;){if(u===h&&r.isLeafNode){let e=r.handlerStorage.getMatchingHandler(n);if(e!==null)return{handler:e.handler,store:e.store,params:e._createParamsObject(d),searchParams:this.querystringParser(a)}}let e=r.getNextNode(t,u,g,d.length);if(e===null){if(g.length===0)return null;let t=g.pop();u=t.brotherPathIndex,d.splice(t.paramsCount),e=t.brotherNode}if(r=e,r.kind===c.STATIC){u+=r.prefix.length;continue}if(r.kind===c.WILDCARD){let e=s.slice(u);o&&(e=p(e)),d.push(e),u=h;continue}let i=s.indexOf(`/`,u);i===-1&&(i=h);let f=s.slice(u,i);if(o&&(f=p(f)),r.isRegex){let e=r.regex.exec(f);if(e===null)continue;for(let t=1;t<e.length;t++){let n=e[t];if(n.length>l)return null;d.push(n)}}else{if(f.length>l)return null;d.push(f)}u=i}},v.prototype._rebuild=function(e){this.reset();for(let t of e){let{method:e,path:n,opts:r,handler:i,store:a}=t;this._on(e,n,r,i,a)}},v.prototype._defaultRoute=function(e,t,n){if(this.defaultRoute!==null)return n===void 0?this.defaultRoute(e,t):this.defaultRoute.call(n,e,t);t.statusCode=404,t.end()},v.prototype._onBadUrl=function(e){if(this.onBadUrl===null)return null;let t=this.onBadUrl;return{handler:(n,r,i)=>t(e,n,r),params:{},store:null}},v.prototype.prettyPrint=function(e={}){let t=e.method;e.buildPrettyMeta=this.buildPrettyMeta.bind(this);let n=null;if(t===void 0){let{version:e,host:t,...r}=this.constrainer.strategies;r[d.name]=d;let i=new v({...this._opts,constraints:r}),a=this.routes.map(e=>{let t={...e.opts.constraints,[d.name]:e.method};return{...e,method:`MERGED`,opts:{constraints:t}}});i._rebuild(a),n=i.trees.MERGED}else n=this.trees[t];return n==null?`(empty tree)`:o(n,e)};for(let e in u){if(!u.hasOwnProperty(e))continue;let t=u[e],n=t.toLowerCase();v.prototype[n]=function(e,n,r){return this.on(t,e,n,r)}}v.prototype.all=function(e,t,n){this.on(u,e,t,n)},v.sanitizeUrlPath=function(e,t){let n=f(e,t);return n.shouldDecodeParam?p(n.path):n.path},t.exports=v;function y(e){return e.replace(g,`\\$&`)}function b(e){return e.indexOf(`//`)===-1?e:e.replace(_,`/`)}function x(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function S(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function C(e,t){let n=1;for(;t<e.length;){if(t++,e.charCodeAt(t)===92){t++;continue}if(e.charCodeAt(t)===41?n--:e.charCodeAt(t)===40&&n++,!n)return t}throw TypeError(`Invalid regexp expression in "`+e+`"`)}function w(e){return!e||!e.store?{}:Object.assign({},e.store)}})),Xm=o(((e,t)=>{function n(e,t,n,r){if(n===void 0){t.header(`content-length`,`0`),r(null,null);return}if(typeof n.resume==`function`){n.on(`error`,e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),n.resume(),r(null,null);return}if(typeof n.getReader==`function`){n.cancel(`Stream cancelled by HEAD route`).catch(e=>{t.log.error({err:e},`Error on Stream found for HEAD route`)}),r(null,null);return}let i=``+Buffer.byteLength(n);t.header(`content-length`,i),r(null,null)}function r(e){return e==null?n:Array.isArray(e)?[...e,n]:[e,n]}t.exports={parseHeadOnSendHandlers:r}})),Zm=o(((e,t)=>{let n=Ym(),r=Sd(),i=Mu(),{onRequestAbortHookRunner:a,lifecycleHooks:o,preParsingHookRunner:s,onTimeoutHookRunner:c,onRequestHookRunner:l}=wu(),{normalizeSchema:u}=fd(),{parseHeadOnSendHandlers:d}=Xm(),{compileSchemasForValidation:f,compileSchemasForSerialization:p}=ju(),{FST_ERR_SCH_VALIDATION_BUILD:m,FST_ERR_SCH_SERIALIZATION_BUILD:h,FST_ERR_DUPLICATED_ROUTE:g,FST_ERR_INVALID_URL:_,FST_ERR_HOOK_INVALID_HANDLER:v,FST_ERR_ROUTE_OPTIONS_NOT_OBJ:y,FST_ERR_ROUTE_DUPLICATED_HANDLER:b,FST_ERR_ROUTE_HANDLER_NOT_FN:x,FST_ERR_ROUTE_MISSING_HANDLER:S,FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:C,FST_ERR_ROUTE_METHOD_INVALID:w,FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:T,FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:E,FST_ERR_HOOK_INVALID_ASYNC_HANDLER:D}=Cu(),{kRoutePrefix:O,kSupportedHTTPMethods:k,kLogLevel:A,kLogSerializers:j,kHooks:M,kSchemaController:ee,kOptions:N,kReplySerializerDefault:te,kReplyIsError:P,kRequestPayloadStream:ne,kDisableRequestLogging:re,kSchemaErrorFormatter:F,kErrorHandler:ie,kHasBeenDecorated:I,kRequestAcceptVersion:ae,kRouteByFastify:oe,kRouteContext:L}=bu(),{buildErrorHandler:se}=hd(),{createChildLogger:ce}=ud(),{getGenReqId:le}=xm(),{FSTDEP022:ue}=Su(),de=[`allowUnsafeRegex`,`buildPrettyMeta`,`caseSensitive`,`constraints`,`defaultRoute`,`ignoreDuplicateSlashes`,`ignoreTrailingSlash`,`maxParamLength`,`onBadUrl`,`querystringParser`,`useSemicolonDelimiter`];function fe(e){let t=n(e),i,s,c,C,w,T,E,k,P,ne,L,ue,de,fe=!1;return{setup(e,t){i=t.avvio,s=t.fourOhFour,c=e.logger,C=t.hasLogger,w=t.setupResponseListeners,T=t.throwIfAlreadyStarted,ue=e.exposeHeadRoutes,E=e.disableRequestLogging,typeof E==`function`&&(k=e.disableRequestLogging),P=e.routerOptions.ignoreTrailingSlash,ne=e.routerOptions.ignoreDuplicateSlashes,L=Object.hasOwn(e,`return503OnClosing`)?e.return503OnClosing:!0,de=t.keepAliveConnections},routing:t.lookup.bind(t),route:Ee,hasRoute:we,prepareRoute:Ce,routeHandler:De,closeRoutes:()=>{fe=!0},printRoutes:t.prettyPrint.bind(t),addConstraintStrategy:ye,hasConstraintStrategy:xe,isAsyncConstraint:Se,findRoute:Te};function ye(e){return T(`Cannot add constraint strategy!`),t.addConstraintStrategy(e)}function xe(e){return t.hasConstraintStrategy(e)}function Se(){return t.constrainer.asyncStrategiesInUse.size>0}function Ce({method:e,url:t,options:n,handler:r,isFastify:i}){if(typeof t!=`string`)throw new _(typeof t);if(!r&&typeof n==`function`)r=n,n={};else if(r&&typeof r==`function`){if(Object.prototype.toString.call(n)!==`[object Object]`)throw new y(e,t);if(n.handler)throw typeof n.handler==`function`?new b(e,t):new x(e,t)}return n=Object.assign({},n,{method:e,url:t,path:t,handler:r||n&&n.handler}),Ee.call(this,{options:n,isFastify:i})}function we({options:e}){let n=e.method?.toUpperCase()??``;return t.hasRoute(n,e.url||``,e.constraints)}function Te(e){let n=t.find(e.method,e.url||``,e.constraints);return n?{handler:n.handler,params:n.params,searchParams:n.searchParams}:null}function Ee({options:e,isFastify:n}){T(`Cannot add route!`);let a={...e},c=a.url||a.path||``;if(!a.handler)throw new S(a.method,c);if(a.errorHandler!==void 0&&typeof a.errorHandler!=`function`)throw new x(a.method,c);_e(a.bodyLimit);let l=a.exposeHeadRoute??ue,_=!1,y=!1;if(Array.isArray(a.method))for(let e=0;e<a.method.length;++e)a.method[e]=he.call(this,a.method[e]),ge.call(this,a.method[e],c,a.schema),_=a.method.includes(`GET`),y=a.method.includes(`HEAD`);else a.method=he.call(this,a.method),ge.call(this,a.method,c,a.schema),_=a.method===`GET`,y=a.method===`HEAD`;let b=l&&_?{...e}:null,C=this[O];if(c===`/`&&C.length>0&&a.method!==`HEAD`)switch(a.prefixTrailingSlash){case`slash`:w.call(this,{path:c,isFastify:n});break;case`no-slash`:w.call(this,{path:``,isFastify:n});break;default:w.call(this,{path:``,isFastify:n}),P!==!0&&(ne!==!0||!C.endsWith(`/`))&&w.call(this,{path:c,prefixing:!0,isFastify:n})}else c[0]===`/`&&C.endsWith(`/`)?w.call(this,{path:c.slice(1),isFastify:n}):w.call(this,{path:c,isFastify:n});return this;function w({path:e,prefixing:n=!1,isFastify:c=!1}){let x=C+e;if(a.url=x,a.path=x,a.routePath=e,a.prefix=C,a.logLevel=a.logLevel||this[A],(this[j]||a.logSerializers)&&(a.logSerializers=Object.assign(Object.create(this[j]),a.logSerializers)),a.attachValidation??=!1,n===!1)for(let e of this[M].onRoute)e.call(this,a);for(let e of o)if(a&&e in a){if(Array.isArray(a[e]))for(let t of a[e]){if(typeof t!=`function`)throw new v(e,Object.prototype.toString.call(t));if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new D}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new D}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new D}else if(a[e]!==void 0&&typeof a[e]!=`function`)throw new v(e,Object.prototype.toString.call(a[e]))}let S=a.constraints||{},w={...a.config,url:x,method:a.method},T=new r({schema:a.schema,handler:a.handler.bind(this),config:w,errorHandler:a.errorHandler,childLoggerFactory:a.childLoggerFactory,bodyLimit:a.bodyLimit,logLevel:a.logLevel,logSerializers:a.logSerializers,attachValidation:a.attachValidation,schemaErrorFormatter:a.schemaErrorFormatter,replySerializer:this[te],validatorCompiler:a.validatorCompiler,serializerCompiler:a.serializerCompiler,exposeHeadRoute:l,prefixTrailingSlash:a.prefixTrailingSlash||`both`,server:this,isFastify:c}),E=t.findRoute(`HEAD`,a.url,S)!==null;try{t.on(a.method,a.url,{constraints:S},De,T)}catch(e){if(!T[oe])throw e.message.includes(`Method '${a.method}' already declared for route`)?new g(a.method,a.url):e}if(this.after((e,t)=>{T.errorHandler=a.errorHandler?se(this[ie],a.errorHandler):this[ie],T._parserOptions.limit=a.bodyLimit||null,T.logLevel=a.logLevel,T.logSerializers=a.logSerializers,T.attachValidation=a.attachValidation,T[te]=this[te],T.schemaErrorFormatter=a.schemaErrorFormatter||this[F]||T.schemaErrorFormatter,i.once(`preReady`,()=>{for(let e of o){let t=this[M][e].concat(a[e]||[]).map(e=>e.bind(this));T[e]=t.length?t:null}for(;!T.Request[I]&&T.Request.parent;)T.Request=T.Request.parent;for(;!T.Reply[I]&&T.Reply.parent;)T.Reply=T.Reply.parent;if(s.setContext(this,T),a.schema){T.schema=u(T.schema,this.initialConfig);let e=this[ee],t=a.schema.body||a.schema.headers||a.schema.querystring||a.schema.params;!a.validatorCompiler&&t&&e.setupValidator(this[N]);try{let t=typeof a?.validatorCompiler==`function`||e.isCustomValidatorCompiler;f(T,a.validatorCompiler||e.validatorCompiler,t)}catch(e){throw new m(a.method,x,e.message)}a.schema.response&&!a.serializerCompiler&&e.setupSerializer(this[N]);try{p(T,a.serializerCompiler||e.serializerCompiler)}catch(e){throw new h(a.method,x,e.message)}}}),t(e)}),l&&_&&!y&&!E){let t=d(b.onSend);Ce.call(this,{method:`HEAD`,url:e,options:{...b,onSend:t},isFastify:!0})}}}function De(e,t,n,r,i){let o=le(r.server,e),s={level:r.logLevel};r.logSerializers&&(s.serializers=r.logSerializers);let u=ce(r,c,e,o,s);if(u[re]=k?!1:E,fe===!0&&(e.httpVersionMajor!==2&&t.setHeader(`Connection`,`close`),L)){t.writeHead(503,{"Content-Type":`application/json`,"Content-Length":`80`}),t.end(`{"error":"Service Unavailable","message":"Service Unavailable","statusCode":503}`),u.info({res:{statusCode:503}},`request aborted - refusing to accept new requests as server is closing`);return}String.prototype.toLowerCase.call(e.headers.connection||``)===`keep-alive`&&de.has(e.socket)===!1&&(de.add(e.socket),e.socket.on(`close`,be.bind({keepAliveConnections:de,socket:e.socket}))),e.headers[ae]!==void 0&&(e.headers[`accept-version`]=e.headers[ae],e.headers[ae]=void 0);let d=new r.Request(o,n,e,i,u,r),f=new r.Reply(t,d,u),p=k?k(d):E;u[re]=p,p===!1&&u.info({req:d},`incoming request`),(C===!0||r.onResponse!==null)&&w(f),r.onRequest===null?ve(null,d,f):l(r.onRequest,d,f,ve),r.onRequestAbort!==null&&e.on(`close`,()=>{e.aborted&&a(r.onRequestAbort,d,pe.bind(null,f))}),r.onTimeout!==null&&(d.raw.socket._meta||d.raw.socket.on(`timeout`,me),d.raw.socket._meta={context:r,request:d,reply:f})}}function pe(e,t){t&&e.log.error({err:t},`onRequestAborted hook failed`)}function me(){let{context:e,request:t,reply:n}=this._meta;c(e.onTimeout,t,n,xe)}function he(e){if(typeof e!=`string`)throw new w;if(e=e.toUpperCase(),!this[k].bodyless.has(e)&&!this[k].bodywith.has(e))throw new C(e);return e}function ge(e,t,n){if(this[k].bodyless.has(e)&&n?.body)throw new T(e,t)}function _e(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw new E(e)}function ve(e,t,n){if(n.sent!==!0){if(e!=null){n[P]=!0,n.send(e);return}t[ne]=t.raw,t[L].preParsing===null?i.call(t.server,null,t,n):s(t[L].preParsing,t,n,i.bind(t.server))}}function ye(e,t){let n=e.routerOptions||Object.create(null),r=de.filter(t=>Object.hasOwn(e,t));r.length>0&&ue(r.join(`, `));for(let r of de)Object.hasOwn(n,r)||(n[r]=e[r]??t[r]);return n}function be(){this.keepAliveConnections.delete(this.socket)}function xe(){}t.exports={buildRouting:fe,validateBodyLimitOption:_e,buildRouterOptions:ye}})),Qm=o(((e,t)=>{let n=Ym(),r=_d(),i=xd(),a=Sd(),{kRoutePrefix:o,kCanSetNotFoundHandler:s,kFourOhFourLevelInstance:c,kFourOhFourContext:l,kHooks:u,kErrorHandler:d}=bu(),{lifecycleHooks:f}=wu(),{buildErrorHandler:p}=hd(),{FST_ERR_NOT_FOUND:m}=Cu(),{createChildLogger:h}=ud(),{getGenReqId:g}=xm();function _(e){let{logger:t,disableRequestLogging:_}=e,v=n({onBadUrl:S(),defaultRoute:E}),y=null;return{router:v,setNotFoundHandler:w,setContext:C,arrange404:b};function b(e){e[c]=e,e[s]=!0,v.onBadUrl=v.onBadUrl.bind(e),v.defaultRoute=v.defaultRoute.bind(e)}function x(e,t){let{url:n,method:r}=e.raw,i=`Route ${r}:${n} not found`;(typeof _==`function`?_(e.raw):_)||e.log.info(i),t.code(404).send({message:i,error:`Not Found`,statusCode:404})}function S(){return function(e,n,a){let o=this[c][l],s=g(o.server,n),u=h(o,t,n,s),d=new i(s,null,n,null,u,o),f=new r(a,d,u);y(d,f)}}function C(e,t){let n=Object.assign({},e[l]);n.onSend=t.onSend,t[l]=n}function w(e,t,n,r){this[s]===void 0&&(this[s]=!0),this[l]===void 0&&(this[l]=null);let i=this,a=this[o]||`/`;if(this[s]===!1)throw Error(`Not found handler already set for Fastify instance with prefix: '${a}'`);typeof e==`object`&&(e.preHandler&&(Array.isArray(e.preHandler)?e.preHandler=e.preHandler.map(e=>e.bind(i)):e.preHandler=e.preHandler.bind(i)),e.preValidation&&(Array.isArray(e.preValidation)?e.preValidation=e.preValidation.map(e=>e.bind(i)):e.preValidation=e.preValidation.bind(i))),typeof e==`function`&&(t=e,e=void 0),e||={},t?(this[c][s]=!1,t=t.bind(this),y=t):(t=x,y=x),this.after((i,o)=>{T.call(this,a,e,t,n,r),o(i)})}function T(e,t,n,r,i){let o=new a({schema:t.schema,handler:n,config:t.config||{},server:this});if(r.once(`preReady`,()=>{let e=this[l];for(let n of f){let r=this[u][n].concat(t[n]||[]).map(e=>e.bind(this));e[n]=r.length?r:null}e.errorHandler=t.errorHandler?p(this[d],t.errorHandler):this[d]}),this[l]!==null&&e===`/`){Object.assign(this[l],o);return}this[c][l]=o,v.all(e+(e.endsWith(`/`)?`*`:`/*`),i,o),v.all(e,i,o)}function E(e,n){let a=this[c][l],o=g(a.server,e),s=h(a,t,e,o);s.info({req:e},`incoming request`);let u=new i(o,null,e,null,s,a),d=new r(n,u,s);u.log.warn(`the default handler for 404 did not catch this, this is likely a fastify bug, please report it`),u.log.warn(v.prettyPrint()),d.code(404).send(new m)}}t.exports=_})),$m=o(((e,t)=>{t.exports=a,t.exports.default=a;let n={type:`object`,additionalProperties:!1,properties:{connectionTimeout:{type:`integer`,default:0},keepAliveTimeout:{type:`integer`,default:72e3},forceCloseConnections:{oneOf:[{type:`string`,pattern:`idle`},{type:`boolean`}]},maxRequestsPerSocket:{type:`integer`,default:0,nullable:!0},requestTimeout:{type:`integer`,default:0},bodyLimit:{type:`integer`,default:1048576},caseSensitive:{type:`boolean`,default:!0},allowUnsafeRegex:{type:`boolean`,default:!1},http2:{type:`boolean`},https:{if:{not:{oneOf:[{type:`boolean`},{type:`null`},{type:`object`,additionalProperties:!1,required:[`allowHTTP1`],properties:{allowHTTP1:{type:`boolean`}}}]}},then:{setDefaultValue:!0}},ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},disableRequestLogging:{default:!1},maxParamLength:{type:`integer`,default:100},onProtoPoisoning:{type:`string`,default:`error`},onConstructorPoisoning:{type:`string`,default:`error`},pluginTimeout:{type:`integer`,default:1e4},requestIdHeader:{anyOf:[{type:`boolean`},{type:`string`}],default:!1},requestIdLogLabel:{type:`string`,default:`reqId`},http2SessionTimeout:{type:`integer`,default:72e3},exposeHeadRoutes:{type:`boolean`,default:!0},useSemicolonDelimiter:{type:`boolean`,default:!1},routerOptions:{type:`object`,additionalProperties:!0,properties:{ignoreTrailingSlash:{type:`boolean`,default:!1},ignoreDuplicateSlashes:{type:`boolean`,default:!1},maxParamLength:{type:`integer`,default:100},allowUnsafeRegex:{type:`boolean`,default:!1},useSemicolonDelimiter:{type:`boolean`,default:!1}}},constraints:{type:`object`,additionalProperties:{type:`object`,required:[`name`,`storage`,`validate`,`deriveConstraint`],additionalProperties:!0,properties:{name:{type:`string`},storage:{},validate:{},deriveConstraint:{}}}}}},r=Object.prototype.hasOwnProperty,i=RegExp(`idle`,`u`);function a(e,{instancePath:t=``,parentData:o,parentDataProperty:s,rootData:c=e}={}){let l=null,u=0;if(u===0)if(e&&typeof e==`object`&&!Array.isArray(e)){e.connectionTimeout===void 0&&(e.connectionTimeout=0),e.keepAliveTimeout===void 0&&(e.keepAliveTimeout=72e3),e.maxRequestsPerSocket===void 0&&(e.maxRequestsPerSocket=0),e.requestTimeout===void 0&&(e.requestTimeout=0),e.bodyLimit===void 0&&(e.bodyLimit=1048576),e.caseSensitive===void 0&&(e.caseSensitive=!0),e.allowUnsafeRegex===void 0&&(e.allowUnsafeRegex=!1),e.ignoreTrailingSlash===void 0&&(e.ignoreTrailingSlash=!1),e.ignoreDuplicateSlashes===void 0&&(e.ignoreDuplicateSlashes=!1),e.disableRequestLogging===void 0&&(e.disableRequestLogging=!1),e.maxParamLength===void 0&&(e.maxParamLength=100),e.onProtoPoisoning===void 0&&(e.onProtoPoisoning=`error`),e.onConstructorPoisoning===void 0&&(e.onConstructorPoisoning=`error`),e.pluginTimeout===void 0&&(e.pluginTimeout=1e4),e.requestIdHeader===void 0&&(e.requestIdHeader=!1),e.requestIdLogLabel===void 0&&(e.requestIdLogLabel=`reqId`),e.http2SessionTimeout===void 0&&(e.http2SessionTimeout=72e3),e.exposeHeadRoutes===void 0&&(e.exposeHeadRoutes=!0),e.useSemicolonDelimiter===void 0&&(e.useSemicolonDelimiter=!1);let o=u;for(let t in e)r.call(n.properties,t)||delete e[t];if(o===u){let n=e.connectionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/connectionTimeout`,schemaPath:`#/properties/connectionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.connectionTimeout=i))}var d=r===u;if(d){let n=e.keepAliveTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/keepAliveTimeout`,schemaPath:`#/properties/keepAliveTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.keepAliveTimeout=i))}var d=r===u;if(d){if(e.forceCloseConnections!==void 0){let n=e.forceCloseConnections,r=u,o=u,s=!1,c=null,p=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.forceCloseConnections=i))}if(u===p&&typeof n==`string`&&!i.test(n)){let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/0/pattern`,keyword:`pattern`,params:{pattern:`idle`},message:`must match pattern "idle"`};l===null?l=[e]:l.push(e),u++}var f=p===u;f&&(s=!0,c=0);let m=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf/1/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.forceCloseConnections=r))}var f=m===u;if(f&&s?(s=!1,c=[c,1]):f&&(s=!0,c=1),s)u=o,l!==null&&(o?l.length=o:l=null);else{let e={instancePath:t+`/forceCloseConnections`,schemaPath:`#/properties/forceCloseConnections/oneOf`,keyword:`oneOf`,params:{passingSchemas:c},message:`must match exactly one schema in oneOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.maxRequestsPerSocket,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))&&n!==null){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else if(n===``||n===0||n===!1)i=null;else return a.errors=[{instancePath:t+`/maxRequestsPerSocket`,schemaPath:`#/properties/maxRequestsPerSocket/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxRequestsPerSocket=i))}var d=r===u;if(d){let n=e.requestTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/requestTimeout`,schemaPath:`#/properties/requestTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestTimeout=i))}var d=r===u;if(d){let n=e.bodyLimit,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/bodyLimit`,schemaPath:`#/properties/bodyLimit/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.bodyLimit=i))}var d=r===u;if(d){let n=e.caseSensitive,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/caseSensitive`,schemaPath:`#/properties/caseSensitive/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.caseSensitive=r))}var d=r===u;if(d){let n=e.allowUnsafeRegex,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/allowUnsafeRegex`,schemaPath:`#/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.allowUnsafeRegex=r))}var d=r===u;if(d){if(e.http2!==void 0){let n=e.http2,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/http2`,schemaPath:`#/properties/http2/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.http2=r))}var d=r===u}else var d=!0;if(d){if(e.https!==void 0){let n=e.https,r=u,i=u,o=!0,s=u,c=u,f=u,h=u,g=!1,_=null,v=u;if(typeof n!=`boolean`){let t;if(t===void 0)if(n===`false`||n===0||n===null)t=!1;else if(n===`true`||n===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=v===u;p&&(g=!0,_=0);let y=u;if(n!==null){let t;if(t===void 0)if(n===``||n===0||n===!1)t=null;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(n=t,e!==void 0&&(e.https=t))}var p=y===u;if(p&&g)g=!1,_=[_,1];else{p&&(g=!0,_=1);let e=u;if(u===e)if(n&&typeof n==`object`&&!Array.isArray(n))if(n.allowHTTP1===void 0){let e={};l===null?l=[e]:l.push(e),u++}else{let e=u;for(let e in n)e!==`allowHTTP1`&&delete n[e];if(e===u&&n.allowHTTP1!==void 0){let e=n.allowHTTP1;if(typeof e!=`boolean`){let t;if(t===void 0)if(e===`false`||e===0||e===null)t=!1;else if(e===`true`||e===1)t=!0;else{let e={};l===null?l=[e]:l.push(e),u++}t!==void 0&&(e=t,n!==void 0&&(n.allowHTTP1=t))}}}else{let e={};l===null?l=[e]:l.push(e),u++}var p=e===u;p&&g?(g=!1,_=[_,2]):p&&(g=!0,_=2)}if(g)u=h,l!==null&&(h?l.length=h:l=null);else{let e={};l===null?l=[e]:l.push(e),u++}if(f===u){let e={};l===null?l=[e]:l.push(e),u++}else u=c,l!==null&&(c?l.length=c:l=null);var m=s===u;if(u=i,l!==null&&(i?l.length=i:l=null),m){let t=u;e.https=!0;var m=t===u;o=m}if(!o){let e={instancePath:t+`/https`,schemaPath:`#/properties/https/if`,keyword:`if`,params:{failingKeyword:`then`},message:`must match "then" schema`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u}else var d=!0;if(d){let n=e.ignoreTrailingSlash,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreTrailingSlash`,schemaPath:`#/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreTrailingSlash=r))}var d=r===u;if(d){let n=e.ignoreDuplicateSlashes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/ignoreDuplicateSlashes`,schemaPath:`#/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.ignoreDuplicateSlashes=r))}var d=r===u;if(d){let n=e.maxParamLength,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/maxParamLength`,schemaPath:`#/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.maxParamLength=i))}var d=r===u;if(d){let n=e.onProtoPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onProtoPoisoning`,schemaPath:`#/properties/onProtoPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onProtoPoisoning=i))}var d=r===u;if(d){let n=e.onConstructorPoisoning,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/onConstructorPoisoning`,schemaPath:`#/properties/onConstructorPoisoning/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.onConstructorPoisoning=i))}var d=r===u;if(d){let n=e.pluginTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/pluginTimeout`,schemaPath:`#/properties/pluginTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.pluginTimeout=i))}var d=r===u;if(d){let n=e.requestIdHeader,r=u,i=u,o=!1,s=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/0/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`};l===null?l=[e]:l.push(e),u++}r!==void 0&&(n=r,e!==void 0&&(e.requestIdHeader=r))}var h=s===u;if(o||=h,!o){let r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};l===null?l=[e]:l.push(e),u++}i!==void 0&&(n=i,e!==void 0&&(e.requestIdHeader=i))}var h=r===u;o||=h}if(o)u=i,l!==null&&(i?l.length=i:l=null);else{let e={instancePath:t+`/requestIdHeader`,schemaPath:`#/properties/requestIdHeader/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return l===null?l=[e]:l.push(e),u++,a.errors=l,!1}var d=r===u;if(d){let n=e.requestIdLogLabel,r=u;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else return a.errors=[{instancePath:t+`/requestIdLogLabel`,schemaPath:`#/properties/requestIdLogLabel/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.requestIdLogLabel=i))}var d=r===u;if(d){let n=e.http2SessionTimeout,r=u;if(!(typeof n==`number`&&!(n%1)&&!isNaN(n)&&isFinite(n))){let r=typeof n,i;if(i===void 0)if(r===`boolean`||n===null||r===`string`&&n&&n==+n&&!(n%1))i=+n;else return a.errors=[{instancePath:t+`/http2SessionTimeout`,schemaPath:`#/properties/http2SessionTimeout/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.http2SessionTimeout=i))}var d=r===u;if(d){let n=e.exposeHeadRoutes,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/exposeHeadRoutes`,schemaPath:`#/properties/exposeHeadRoutes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.exposeHeadRoutes=r))}var d=r===u;if(d){let n=e.useSemicolonDelimiter,r=u;if(typeof n!=`boolean`){let r;if(r===void 0)if(n===`false`||n===0||n===null)r=!1;else if(n===`true`||n===1)r=!0;else return a.errors=[{instancePath:t+`/useSemicolonDelimiter`,schemaPath:`#/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(n=r,e!==void 0&&(e.useSemicolonDelimiter=r))}var d=r===u;if(d){if(e.routerOptions!==void 0){let n=e.routerOptions,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n)){n.ignoreTrailingSlash===void 0&&(n.ignoreTrailingSlash=!1),n.ignoreDuplicateSlashes===void 0&&(n.ignoreDuplicateSlashes=!1),n.maxParamLength===void 0&&(n.maxParamLength=100),n.allowUnsafeRegex===void 0&&(n.allowUnsafeRegex=!1),n.useSemicolonDelimiter===void 0&&(n.useSemicolonDelimiter=!1);let e=n.ignoreTrailingSlash,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreTrailingSlash`,schemaPath:`#/properties/routerOptions/properties/ignoreTrailingSlash/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreTrailingSlash=r))}var g=r===u;if(g){let e=n.ignoreDuplicateSlashes,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/ignoreDuplicateSlashes`,schemaPath:`#/properties/routerOptions/properties/ignoreDuplicateSlashes/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.ignoreDuplicateSlashes=r))}var g=r===u;if(g){let e=n.maxParamLength,r=u;if(!(typeof e==`number`&&!(e%1)&&!isNaN(e)&&isFinite(e))){let r=typeof e,i;if(i===void 0)if(r===`boolean`||e===null||r===`string`&&e&&e==+e&&!(e%1))i=+e;else return a.errors=[{instancePath:t+`/routerOptions/maxParamLength`,schemaPath:`#/properties/routerOptions/properties/maxParamLength/type`,keyword:`type`,params:{type:`integer`},message:`must be integer`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.maxParamLength=i))}var g=r===u;if(g){let e=n.allowUnsafeRegex,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/allowUnsafeRegex`,schemaPath:`#/properties/routerOptions/properties/allowUnsafeRegex/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.allowUnsafeRegex=r))}var g=r===u;if(g){let e=n.useSemicolonDelimiter,r=u;if(typeof e!=`boolean`){let r;if(r===void 0)if(e===`false`||e===0||e===null)r=!1;else if(e===`true`||e===1)r=!0;else return a.errors=[{instancePath:t+`/routerOptions/useSemicolonDelimiter`,schemaPath:`#/properties/routerOptions/properties/useSemicolonDelimiter/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;r!==void 0&&(e=r,n!==void 0&&(n.useSemicolonDelimiter=r))}var g=r===u}}}}}else return a.errors=[{instancePath:t+`/routerOptions`,schemaPath:`#/properties/routerOptions/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0;if(d)if(e.constraints!==void 0){let n=e.constraints,r=u;if(u===r)if(n&&typeof n==`object`&&!Array.isArray(n))for(let e in n){let r=n[e],i=u;if(u===i)if(r&&typeof r==`object`&&!Array.isArray(r)){let n;if(r.name===void 0&&(n=`name`)||r.storage===void 0&&(n=`storage`)||r.validate===void 0&&(n=`validate`)||r.deriveConstraint===void 0&&(n=`deriveConstraint`))return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`}],!1;if(r.name!==void 0){let n=r.name;if(typeof n!=`string`){let i=typeof n,o;if(o===void 0)if(i==`number`||i==`boolean`)o=``+n;else if(n===null)o=``;else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`)+`/name`,schemaPath:`#/properties/constraints/additionalProperties/properties/name/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;o!==void 0&&(n=o,r!==void 0&&(r.name=o))}}}else return a.errors=[{instancePath:t+`/constraints/`+e.replace(/~/g,`~0`).replace(/\//g,`~1`),schemaPath:`#/properties/constraints/additionalProperties/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;if(i!==u)break}else return a.errors=[{instancePath:t+`/constraints`,schemaPath:`#/properties/constraints/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var d=r===u}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}else return a.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return a.errors=l,u===0}t.exports.defaultInitOptions={connectionTimeout:0,keepAliveTimeout:72e3,maxRequestsPerSocket:0,requestTimeout:0,bodyLimit:1048576,caseSensitive:!0,allowUnsafeRegex:!1,disableRequestLogging:!1,ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,onProtoPoisoning:`error`,onConstructorPoisoning:`error`,pluginTimeout:1e4,requestIdHeader:!1,requestIdLogLabel:`reqId`,http2SessionTimeout:72e3,exposeHeadRoutes:!0,useSemicolonDelimiter:!1,allowErrorHandlerOverride:!0,routerOptions:{ignoreTrailingSlash:!1,ignoreDuplicateSlashes:!1,maxParamLength:100,allowUnsafeRegex:!1,useSemicolonDelimiter:!1}}})),eh=o(((e,t)=>{let n=$m(),r=dd()({circles:!0,proto:!1}),{FST_ERR_INIT_OPTS_INVALID:i}=Cu();function a(e){let t=r(e);if(!n(t)){let e=new i(JSON.stringify(n.errors.map(e=>e.message)));throw e.errors=n.errors,e}return o(t)}function o(e){let t=Object.getOwnPropertyNames(e);for(let n of t){let t=e[n];ArrayBuffer.isView(t)&&!(t instanceof DataView)||(e[n]=t&&typeof t==`object`?o(t):t)}return Object.freeze(e)}t.exports=a,t.exports.defaultInitOptions=n.defaultInitOptions,t.exports.utils={deepFreezeObject:o}})),th=o(((e,t)=>{let{kAvvioBoot:n,kChildren:r,kRoutePrefix:i,kLogLevel:a,kLogSerializers:o,kHooks:s,kSchemaController:c,kContentTypeParser:l,kReply:u,kRequest:d,kFourOhFour:f,kPluginNameChain:p,kErrorHandlerAlreadySet:m}=bu(),h=_d(),g=xd(),_=Op(),v=Td(),{buildHooks:y}=wu(),b=bm();t.exports=function(e,t,S){let C=b.registerPlugin.call(e,t),w=b.getPluginName(t)||b.getFuncPreview(t);if(C)return e[p].push(w),e;let T=Object.create(e);e[r].push(T),T.ready=e[n].bind(T),T[r]=[],T[u]=h.buildReply(T[u]),T[d]=g.buildRequest(T[d]),T[l]=v.helpers.buildContentTypeParser(T[l]),T[s]=y(T[s]),T[i]=x(T[i],S.prefix),T[a]=S.logLevel||T[a],T[c]=_.buildSchemaController(e[c]),T.getSchema=T[c].getSchema.bind(T[c]),T.getSchemas=T[c].getSchemas.bind(T[c]),T[b.kRegisteredPlugins]=Object.create(T[b.kRegisteredPlugins]),T[p]=[w],T[m]=!1,(T[o]||S.logSerializers)&&(T[o]=Object.assign(Object.create(T[o]),S.logSerializers)),S.prefix&&T[f].arrange404(T);for(let t of T[s].onRegister)t.call(e,T,S);return T};function x(e,t){return t?(e.endsWith(`/`)&&t[0]===`/`?t=t.slice(1):t[0]!==`/`&&(t=`/`+t),e+t):e}})),nh=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseCookie=c,e.parse=c,e.stringifyCookie=l,e.stringifySetCookie=u,e.serialize=u,e.parseSetCookie=d,e.stringifySetCookie=u,e.serialize=u;let t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,r=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,i=/^[\u0020-\u003A\u003D-\u007E]*$/,a=/^-?\d+$/,o=Object.prototype.toString,s=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function c(e,t){let n=new s,r=e.length;if(r<2)return n;let i=t?.decode||h,a=0;do{let t=p(e,a,r);if(t===-1)break;let o=f(e,a,r);if(t>o){a=e.lastIndexOf(`;`,t-1)+1;continue}let s=m(e,a,t);n[s]===void 0&&(n[s]=i(m(e,t+1,o))),a=o+1}while(a<r);return n}function l(e,r){let i=r?.encode||encodeURIComponent,a=[];for(let r of Object.keys(e)){let o=e[r];if(o===void 0)continue;if(!t.test(r))throw TypeError(`cookie name is invalid: ${r}`);let s=i(o);if(!n.test(s))throw TypeError(`cookie val is invalid: ${o}`);a.push(`${r}=${s}`)}return a.join(`; `)}function u(e,a,o){let s=typeof e==`object`?e:{...o,name:e,value:String(a)},c=(typeof a==`object`?a:o)?.encode||encodeURIComponent;if(!t.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let l=s.value?c(s.value):``;if(!n.test(l))throw TypeError(`argument val is invalid: ${s.value}`);let u=s.name+`=`+l;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);u+=`; Max-Age=`+s.maxAge}if(s.domain){if(!r.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);u+=`; Domain=`+s.domain}if(s.path){if(!i.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);u+=`; Path=`+s.path}if(s.expires){if(!g(s.expires)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invalid: ${s.expires}`);u+=`; Expires=`+s.expires.toUTCString()}if(s.httpOnly&&(u+=`; HttpOnly`),s.secure&&(u+=`; Secure`),s.partitioned&&(u+=`; Partitioned`),s.priority)switch(typeof s.priority==`string`?s.priority.toLowerCase():void 0){case`low`:u+=`; Priority=Low`;break;case`medium`:u+=`; Priority=Medium`;break;case`high`:u+=`; Priority=High`;break;default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite==`string`?s.sameSite.toLowerCase():s.sameSite){case!0:case`strict`:u+=`; SameSite=Strict`;break;case`lax`:u+=`; SameSite=Lax`;break;case`none`:u+=`; SameSite=None`;break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return u}function d(e,t){let n=t?.decode||h,r=e.length,i=f(e,0,r),o=p(e,0,i),s=o===-1?{name:``,value:n(m(e,0,i))}:{name:m(e,0,o),value:n(m(e,o+1,i))},c=i+1;for(;c<r;){let t=f(e,c,r),n=p(e,c,t),i=n===-1?m(e,c,t):m(e,c,n),o=n===-1?void 0:m(e,n+1,t);switch(i.toLowerCase()){case`httponly`:s.httpOnly=!0;break;case`secure`:s.secure=!0;break;case`partitioned`:s.partitioned=!0;break;case`domain`:s.domain=o;break;case`path`:s.path=o;break;case`max-age`:o&&a.test(o)&&(s.maxAge=Number(o));break;case`expires`:if(!o)break;let e=new Date(o);Number.isFinite(e.valueOf())&&(s.expires=e);break;case`priority`:if(!o)break;let t=o.toLowerCase();(t===`low`||t===`medium`||t===`high`)&&(s.priority=t);break;case`samesite`:if(!o)break;let n=o.toLowerCase();(n===`lax`||n===`strict`||n===`none`)&&(s.sameSite=n);break}c=t+1}return s}function f(e,t,n){let r=e.indexOf(`;`,t);return r===-1?n:r}function p(e,t,n){let r=e.indexOf(`=`,t);return r<n?r:-1}function m(e,t,n){let r=t,i=n;do{let t=e.charCodeAt(r);if(t!==32&&t!==9)break}while(++r<i);for(;i>r;){let t=e.charCodeAt(i-1);if(t!==32&&t!==9)break;i--}return e.slice(r,i)}function h(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function g(e){return o.call(e)===`[object Date]`}})),rh=o(((e,t)=>{let{format:n}=require(`node:util`);function r(e){return i({...e,name:`DeprecationWarning`})}function i({name:e,code:t,message:r,unlimited:i=!1}={}){if(!e)throw Error(`Warning name must not be empty`);if(!t)throw Error(`Warning code must not be empty`);if(!r)throw Error(`Warning message must not be empty`);if(typeof i!=`boolean`)throw Error(`Warning opts.unlimited must be a boolean`);t=t.toUpperCase();let a={[e]:function(e,t,n){o.emitted===!0&&o.unlimited!==!0||(o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code))}};i&&(a={[e]:function(e,t,n){o.emitted=!0,process.emitWarning(o.format(e,t,n),o.name,o.code)}});let o=a[e];return o.emitted=!1,o.message=r,o.unlimited=i,o.code=t,o.format=function(e,t,i){let a;return a=e&&t&&i?n(r,e,t,i):e&&t?n(r,e,t):e?n(r,e):r,a},o}let a={createWarning:i,createDeprecation:r};t.exports=a,t.exports.default=a,t.exports.processWarning=a})),ih=o(((e,t)=>{let{URL:n}=require(`node:url`),r=`http://localhost`;t.exports=function(e,t){(typeof e==`string`||Object.prototype.toString.call(e)===`[object String]`)&&e.startsWith(`//`)&&(e=r+e);let i=typeof e==`object`?Object.assign(new n(r),e):new n(e,r);if(typeof t==`string`){t=new URLSearchParams(t);for(let e of t.keys()){i.searchParams.delete(e);for(let n of t.getAll(e))i.searchParams.append(e,n)}}else{let n=Object.assign({},e.query,t);for(let e in n){let t=n[e];if(Array.isArray(t)){i.searchParams.delete(e);for(let n of t)i.searchParams.append(e,n)}else i.searchParams.set(e,t)}}return i}})),ah=o(((e,t)=>{let{randomUUID:n}=require(`node:crypto`),{Readable:r}=require(`node:stream`),i;function a(e){return e&&typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&e[Symbol.toStringTag]===`FormData`}function o(e){i??=new TextEncoder;let t=`----formdata-${n()}`,a=`--${t}\r\nContent-Disposition: form-data`,o=e=>e.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`),s=e=>e.replace(/\r?\n|\r/g,`\r
452
+ `),c=new Uint8Array([13,10]);async function*l(){for(let[t,n]of e)if(typeof n==`string`)yield i.encode(`${a}; name="${o(s(t))}"\r\n\r\n`),yield i.encode(`${s(n)}\r\n`);else{let e=`${a}; name="${o(s(t))}"`;n.name&&(e+=`; filename="${o(n.name)}"`),e+=`\r\nContent-Type: ${n.type||`application/octet-stream`}\r\n\r\n`,yield i.encode(e),n.stream?yield*n.stream():yield n,yield c}yield i.encode(`--${t}--`)}return{stream:r.from(l()),contentType:`multipart/form-data; boundary=${t}`}}t.exports.isFormDataLike=a,t.exports.formDataToStream=o})),oh=o(((e,t)=>{let{Readable:n,addAbortSignal:r}=require(`node:stream`),i=require(`node:util`),a=nh(),o=require(`node:assert`),{createDeprecation:s}=rh(),c=ih(),{isFormDataLike:l,formDataToStream:u}=ah(),{EventEmitter:d}=require(`node:events`),f=s({name:`FastifyDeprecationLightMyRequest`,code:`FST_LIGHTMYREQUEST_DEP01`,message:`You are accessing "request.connection", use "request.socket" instead.`});function p(e){return e.port?e.host:e.hostname+(e.protocol===`https:`?`:443`:`:80`)}var m=class extends d{constructor(e){super(),this.remoteAddress=e}};function h(e){return new t(this);function t(t){g.call(t,{...e,Request:void 0}),Object.assign(this,t);for(let e of Object.keys(g.prototype))this.constructor.prototype[e]=g.prototype[e];return i.inherits(this.constructor,e.Request),this}}function g(e){n.call(this,{autoDestroy:!1});let t=c(e.url||e.path,e.query);this.url=t.pathname+t.search,this.aborted=!1,this.httpVersionMajor=1,this.httpVersionMinor=1,this.httpVersion=`1.1`,this.method=e.method?e.method.toUpperCase():`GET`,this.headers={},this.rawHeaders=[];let i=e.headers||{};for(let e in i){let t=e.toLowerCase();if((t===`user-agent`||t===`content-type`)&&i[e]===void 0){this.headers[t]=void 0;continue}let n=i[e];o(n!==void 0,`invalid value "undefined" for header `+e),this.headers[t]=``+n}if(`user-agent`in this.headers||(this.headers[`user-agent`]=`lightMyRequest`),this.headers.host=this.headers.host||e.authority||p(t),e.cookies){let{cookies:t}=e,n=Object.keys(t).map(e=>a.serialize(e,t[e]));this.headers.cookie&&n.unshift(this.headers.cookie),this.headers.cookie=n.join(`; `)}this.socket=new m(e.remoteAddress||`127.0.0.1`),Object.defineProperty(this,`connection`,{get(){return f(),this.socket},configurable:!0});let s=e.payload||e.body||null,d=s&&typeof s.resume==`function`;if(l(s)){let e=u(s);s=e.stream,d=!0,this.headers[`content-type`]=e.contentType,this.headers[`transfer-encoding`]=`chunked`}s&&typeof s!=`string`&&!d&&!Buffer.isBuffer(s)&&(s=JSON.stringify(s),`content-type`in this.headers||(this.headers[`content-type`]=`application/json`)),s&&!d&&!Object.hasOwn(this.headers,`content-length`)&&(this.headers[`content-length`]=(Buffer.isBuffer(s)?s.length:Buffer.byteLength(s)).toString());for(let e of Object.keys(this.headers))this.rawHeaders.push(e,this.headers[e]);this._lightMyRequest={payload:s,isDone:!1,simulate:e.simulate||{},payloadAsStream:e.payloadAsStream,signal:e.signal};let h=e.signal;h&&r(h,this);{let e=this._lightMyRequest.payload;e?._readableState?(this._read=_,e.on(`error`,e=>{this.destroy(e)}),e.on(`end`,()=>{this.push(null)})):this._read=v}return this}function _(){let e=this._lightMyRequest.payload,t=!0,n=!1,r;for(;t&&(r=e.read());)n=!0,t=this.push(r);t&&!n&&this._lightMyRequest.payload.once(`readable`,this._read.bind(this))}function v(){setImmediate(()=>{if(this._lightMyRequest.isDone){this._lightMyRequest.simulate.end!==!1&&this.push(null);return}this._lightMyRequest.isDone=!0,this._lightMyRequest.payload&&(this._lightMyRequest.simulate.split?(this.push(this._lightMyRequest.payload.slice(0,1)),this.push(this._lightMyRequest.payload.slice(1))):this.push(this._lightMyRequest.payload)),this._lightMyRequest.simulate.error&&this.emit(`error`,Error(`Simulated`)),this._lightMyRequest.simulate.close&&this.emit(`close`),this._lightMyRequest.simulate.end!==!1&&this.push(null)})}i.inherits(g,n),i.inherits(h,g),g.prototype.destroy=function(e){this.destroyed||this._lightMyRequest.isDone||(this.destroyed=!0,e&&(this._error=!0,process.nextTick(()=>this.emit(`error`,e))),process.nextTick(()=>this.emit(`close`)))},t.exports=g,t.exports.Request=g,t.exports.CustomRequest=h})),sh=o(((e,t)=>{var n={decodeValues:!0,map:!1,silent:!1};function r(e){return typeof e!=`string`||e in{}}function i(){return Object.create(null)}function a(e){return typeof e==`string`&&!!e.trim()}function o(e,t){var o=e.split(`;`).filter(a),c=s(o.shift()),l=c.name,u=c.value;if(t=t?Object.assign({},n,t):n,r(l))return null;try{u=t.decodeValues?decodeURIComponent(u):u}catch(e){console.error(`set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.`,e)}var d=i();return d.name=l,d.value=u,o.forEach(function(e){var t=e.split(`=`),n=t.shift().trimLeft().toLowerCase();if(!r(n)){var i=t.join(`=`);if(n===`expires`)d.expires=new Date(i);else if(n===`max-age`){var a=parseInt(i,10);Number.isNaN(a)||(d.maxAge=a)}else n===`secure`?d.secure=!0:n===`httponly`?d.httpOnly=!0:n===`samesite`?d.sameSite=i:n===`partitioned`?d.partitioned=!0:n&&(d[n]=i)}}),d}function s(e){var t=``,n=``,r=e.split(`=`);return r.length>1?(t=r.shift(),n=r.join(`=`)):n=e,{name:t,value:n}}function c(e,t){if(t=t?Object.assign({},n,t):n,!e)return t.map?i():[];if(e.headers)if(typeof e.headers.getSetCookie==`function`)e=e.headers.getSetCookie();else if(e.headers[`set-cookie`])e=e.headers[`set-cookie`];else{var s=e.headers[Object.keys(e.headers).find(function(e){return e.toLowerCase()===`set-cookie`})];!s&&e.headers.cookie&&!t.silent&&console.warn(`Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.`),e=s}if(Array.isArray(e)||(e=[e]),t.map){var c=i();return e.filter(a).reduce(function(e,n){var i=o(n,t);return i&&!r(i.name)&&(e[i.name]=i),e},c)}else return e.filter(a).map(function(e){return o(e,t)}).filter(Boolean)}function l(e){if(Array.isArray(e))return e;if(typeof e!=`string`)return[];var t=[],n=0,r,i,a,o,s;function c(){for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n<e.length}function l(){return i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`}for(;n<e.length;){for(r=n,s=!1;c();)if(i=e.charAt(n),i===`,`){for(a=n,n+=1,c(),o=n;n<e.length&&l();)n+=1;n<e.length&&e.charAt(n)===`=`?(s=!0,n=o,t.push(e.substring(r,a)),r=n):n=a+1}else n+=1;(!s||n>=e.length)&&t.push(e.substring(r,e.length))}return t}t.exports=c,t.exports.parse=c,t.exports.parseString=o,t.exports.splitCookiesString=l})),ch=o(((e,t)=>{let n=require(`node:http`),{Writable:r,Readable:i,addAbortSignal:a}=require(`node:stream`),o=require(`node:util`),s=sh();function c(e,t,r){if(n.ServerResponse.call(this,e),e._lightMyRequest?.payloadAsStream){this._lightMyRequest={headers:null,trailers:{},stream:new i({read:this.emit.bind(this,`drain`)})};let t=e._lightMyRequest.signal;t&&a(t,this._lightMyRequest.stream)}else this._lightMyRequest={headers:null,trailers:{},payloadChunks:[]};this.setHeader(`foo`,`bar`),this.removeHeader(`foo`),this.assignSocket(u()),this._promiseCallback=typeof r==`function`;let o=!1,s=e=>{if(!o){if(o=!0,this._promiseCallback)return process.nextTick(()=>t(e));process.nextTick(()=>t(null,e))}};this._lightMyRequest.onEndSuccess=s;let c=!1,d=e=>{if(o){this._lightMyRequest.stream&&!c&&(e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._lightMyRequest.stream.destroy(e),this._lightMyRequest.stream.on(`error`,()=>{}));return}if(o=!0,e||(e=Error(`response destroyed before completion`),e.code=`LIGHT_ECONNRESET`),this._promiseCallback)return process.nextTick(()=>r(e));process.nextTick(()=>t(e,null))};this._lightMyRequest.stream?this.once(`finish`,()=>{c=!0,this._lightMyRequest.stream.push(null)}):this.once(`finish`,()=>{let t=l(this);t.raw.req=e,s(t)}),this.connection.once(`error`,d),this.once(`error`,d),this.once(`close`,d)}o.inherits(c,n.ServerResponse),c.prototype.setTimeout=function(e,t){return this.timeoutHandle=setTimeout(()=>{this.emit(`timeout`)},e),this.on(`timeout`,t),this},c.prototype.writeHead=function(){let e=n.ServerResponse.prototype.writeHead.apply(this,arguments);return f(this),this._lightMyRequest.stream&&this._lightMyRequest.onEndSuccess(l(this)),e},c.prototype.write=function(e,t,r){return this.timeoutHandle&&clearTimeout(this.timeoutHandle),n.ServerResponse.prototype.write.call(this,e,t,r),this._lightMyRequest.stream?this._lightMyRequest.stream.push(Buffer.from(e,t)):(this._lightMyRequest.payloadChunks.push(Buffer.from(e,t)),!0)},c.prototype.end=function(e,t,r){e&&this.write(e,t),n.ServerResponse.prototype.end.call(this,r),this.emit(`finish`),this.destroy()},c.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,e&&process.nextTick(()=>this.emit(`error`,e)),process.nextTick(()=>this.emit(`close`)))},c.prototype.addTrailers=function(e){for(let t in e)this._lightMyRequest.trailers[t.toLowerCase().trim()]=e[t].toString().trim()};function l(e){e._lightMyRequest.headers===null&&f(e),d(e);let t={raw:{res:e},headers:e._lightMyRequest.headers,statusCode:e.statusCode,statusMessage:e.statusMessage,trailers:{},get cookies(){return s.parse(this)}};if(t.trailers=e._lightMyRequest.trailers,e._lightMyRequest.payloadChunks){let n=Buffer.concat(e._lightMyRequest.payloadChunks);t.rawPayload=n,t.payload=n.toString(),t.body=t.payload,t.json=function(){return JSON.parse(t.payload)}}else t.json=function(){throw Error(`Response payload is not available with payloadAsStream: true`)};return t.stream=function(){return e._lightMyRequest.stream?e._lightMyRequest.stream:i.from(e._lightMyRequest.payloadChunks)},t}function u(){return new r({write(e,t,n){setImmediate(n)}})}function d(e){let t=e._lightMyRequest.headers;for(let e of Object.keys(t)){let n=t[e];Array.isArray(n)?t[e]=n.map(e=>``+e):t[e]=``+n}}function f(e){e._lightMyRequest.headers=Object.assign({},e.getHeaders()),[`Date`,`Connection`,`Transfer-Encoding`].forEach(t=>{let n=RegExp(`\\r\\n`+t+`: ([^\\r]*)\\r\\n`),r=e._header?.match(n);r&&(e._lightMyRequest.headers[t.toLowerCase()]=r[1])})}t.exports=c})),lh=o(((e,t)=>{t.exports=r,t.exports.default=r;let n={type:`object`,properties:{url:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},path:{oneOf:[{type:`string`},{type:`object`,properties:{protocol:{type:`string`},hostname:{type:`string`},pathname:{type:`string`}},additionalProperties:!0,required:[`pathname`]}]},cookies:{type:`object`,additionalProperties:!0},headers:{type:`object`,additionalProperties:!0},query:{anyOf:[{type:`object`,additionalProperties:!0},{type:`string`}]},simulate:{type:`object`,properties:{end:{type:`boolean`},split:{type:`boolean`},error:{type:`boolean`},close:{type:`boolean`}}},authority:{type:`string`},remoteAddress:{type:`string`},method:{type:`string`,enum:`ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE.acl.bind.checkout.connect.copy.delete.get.head.link.lock.m-search.merge.mkactivity.mkcalendar.mkcol.move.notify.options.patch.post.propfind.proppatch.purge.put.query.rebind.report.search.source.subscribe.trace.unbind.unlink.unlock.unsubscribe`.split(`.`)},validate:{type:`boolean`}},additionalProperties:!0,oneOf:[{required:[`url`]},{required:[`path`]}]};function r(e,{instancePath:t=``,parentData:i,parentDataProperty:a,rootData:o=e}={}){let s=null,c=0,l=c,u=!1,d=null,f=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.url===void 0&&(n=`url`)){let e={instancePath:t,schemaPath:`#/oneOf/0/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=f===c;p&&(u=!0,d=0);let m=c;if(e&&typeof e==`object`&&!Array.isArray(e)){let n;if(e.path===void 0&&(n=`path`)){let e={instancePath:t,schemaPath:`#/oneOf/1/required`,keyword:`required`,params:{missingProperty:n},message:`must have required property '`+n+`'`};s===null?s=[e]:s.push(e),c++}}var p=m===c;if(p&&u?(u=!1,d=[d,1]):p&&(u=!0,d=1),u)c=l,s!==null&&(l?s.length=l:s=null);else{let e={instancePath:t,schemaPath:`#/oneOf`,keyword:`oneOf`,params:{passingSchemas:d},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}if(c===0)if(e&&typeof e==`object`&&!Array.isArray(e)){if(e.url!==void 0){let n=e.url,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.url=i))}var h=u===c;h&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/protocol`,schemaPath:`#/properties/url/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var g=r===c}else var g=!0;if(g){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/hostname`,schemaPath:`#/properties/url/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var g=r===c}else var g=!0;if(g)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/url/pathname`,schemaPath:`#/properties/url/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var g=r===c}else var g=!0}}}else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var h=d===c;if(h&&o?(o=!1,l=[l,1]):h&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/url`,schemaPath:`#/properties/url/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.path!==void 0){let n=e.path,i=c,a=c,o=!1,l=null,u=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/0/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.path=i))}var v=u===c;v&&(o=!0,l=0);let d=c;if(c===d)if(n&&typeof n==`object`&&!Array.isArray(n)){let e;if(n.pathname===void 0&&(e=`pathname`)){let n={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/required`,keyword:`required`,params:{missingProperty:e},message:`must have required property '`+e+`'`};s===null?s=[n]:s.push(n),c++}else{if(n.protocol!==void 0){let e=n.protocol,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/protocol`,schemaPath:`#/properties/path/oneOf/1/properties/protocol/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.protocol=i))}var y=r===c}else var y=!0;if(y){if(n.hostname!==void 0){let e=n.hostname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/hostname`,schemaPath:`#/properties/path/oneOf/1/properties/hostname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.hostname=i))}var y=r===c}else var y=!0;if(y)if(n.pathname!==void 0){let e=n.pathname,r=c;if(typeof e!=`string`){let r=typeof e,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+e;else if(e===null)i=``;else{let e={instancePath:t+`/path/pathname`,schemaPath:`#/properties/path/oneOf/1/properties/pathname/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(e=i,n!==void 0&&(n.pathname=i))}var y=r===c}else var y=!0}}}else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf/1/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var v=d===c;if(v&&o?(o=!1,l=[l,1]):v&&(o=!0,l=1),o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/path`,schemaPath:`#/properties/path/oneOf`,keyword:`oneOf`,params:{passingSchemas:l},message:`must match exactly one schema in oneOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.cookies!==void 0){let n=e.cookies,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/cookies`,schemaPath:`#/properties/cookies/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.headers!==void 0){let n=e.headers,i=c;if(c===i&&!(n&&typeof n==`object`&&!Array.isArray(n)))return r.errors=[{instancePath:t+`/headers`,schemaPath:`#/properties/headers/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.query!==void 0){let n=e.query,i=c,a=c,o=!1,l=c;if(c===l&&!(n&&typeof n==`object`&&!Array.isArray(n))){let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/0/type`,keyword:`type`,params:{type:`object`},message:`must be object`};s===null?s=[e]:s.push(e),c++}var b=l===c;if(o||=b,!o){let r=c;if(typeof n!=`string`){let r=typeof n,i;if(i===void 0)if(r==`number`||r==`boolean`)i=``+n;else if(n===null)i=``;else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf/1/type`,keyword:`type`,params:{type:`string`},message:`must be string`};s===null?s=[e]:s.push(e),c++}i!==void 0&&(n=i,e!==void 0&&(e.query=i))}var b=r===c;o||=b}if(o)c=a,s!==null&&(a?s.length=a:s=null);else{let e={instancePath:t+`/query`,schemaPath:`#/properties/query/anyOf`,keyword:`anyOf`,params:{},message:`must match a schema in anyOf`};return s===null?s=[e]:s.push(e),c++,r.errors=s,!1}var _=i===c}else var _=!0;if(_){if(e.simulate!==void 0){let n=e.simulate,i=c;if(c===i)if(n&&typeof n==`object`&&!Array.isArray(n)){if(n.end!==void 0){let e=n.end,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/end`,schemaPath:`#/properties/simulate/properties/end/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.end=i))}var x=i===c}else var x=!0;if(x){if(n.split!==void 0){let e=n.split,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/split`,schemaPath:`#/properties/simulate/properties/split/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.split=i))}var x=i===c}else var x=!0;if(x){if(n.error!==void 0){let e=n.error,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/error`,schemaPath:`#/properties/simulate/properties/error/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.error=i))}var x=i===c}else var x=!0;if(x)if(n.close!==void 0){let e=n.close,i=c;if(typeof e!=`boolean`){let i;if(i===void 0)if(e===`false`||e===0||e===null)i=!1;else if(e===`true`||e===1)i=!0;else return r.errors=[{instancePath:t+`/simulate/close`,schemaPath:`#/properties/simulate/properties/close/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(e=i,n!==void 0&&(n.close=i))}var x=i===c}else var x=!0}}}else return r.errors=[{instancePath:t+`/simulate`,schemaPath:`#/properties/simulate/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;var _=i===c}else var _=!0;if(_){if(e.authority!==void 0){let n=e.authority,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/authority`,schemaPath:`#/properties/authority/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.authority=a))}var _=i===c}else var _=!0;if(_){if(e.remoteAddress!==void 0){let n=e.remoteAddress,i=c;if(typeof n!=`string`){let i=typeof n,a;if(a===void 0)if(i==`number`||i==`boolean`)a=``+n;else if(n===null)a=``;else return r.errors=[{instancePath:t+`/remoteAddress`,schemaPath:`#/properties/remoteAddress/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(n=a,e!==void 0&&(e.remoteAddress=a))}var _=i===c}else var _=!0;if(_){if(e.method!==void 0){let i=e.method,a=c;if(typeof i!=`string`){let n=typeof i,a;if(a===void 0)if(n==`number`||n==`boolean`)a=``+i;else if(i===null)a=``;else return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/type`,keyword:`type`,params:{type:`string`},message:`must be string`}],!1;a!==void 0&&(i=a,e!==void 0&&(e.method=a))}if(!(i===`ACL`||i===`BIND`||i===`CHECKOUT`||i===`CONNECT`||i===`COPY`||i===`DELETE`||i===`GET`||i===`HEAD`||i===`LINK`||i===`LOCK`||i===`M-SEARCH`||i===`MERGE`||i===`MKACTIVITY`||i===`MKCALENDAR`||i===`MKCOL`||i===`MOVE`||i===`NOTIFY`||i===`OPTIONS`||i===`PATCH`||i===`POST`||i===`PROPFIND`||i===`PROPPATCH`||i===`PURGE`||i===`PUT`||i===`QUERY`||i===`REBIND`||i===`REPORT`||i===`SEARCH`||i===`SOURCE`||i===`SUBSCRIBE`||i===`TRACE`||i===`UNBIND`||i===`UNLINK`||i===`UNLOCK`||i===`UNSUBSCRIBE`||i===`acl`||i===`bind`||i===`checkout`||i===`connect`||i===`copy`||i===`delete`||i===`get`||i===`head`||i===`link`||i===`lock`||i===`m-search`||i===`merge`||i===`mkactivity`||i===`mkcalendar`||i===`mkcol`||i===`move`||i===`notify`||i===`options`||i===`patch`||i===`post`||i===`propfind`||i===`proppatch`||i===`purge`||i===`put`||i===`query`||i===`rebind`||i===`report`||i===`search`||i===`source`||i===`subscribe`||i===`trace`||i===`unbind`||i===`unlink`||i===`unlock`||i===`unsubscribe`))return r.errors=[{instancePath:t+`/method`,schemaPath:`#/properties/method/enum`,keyword:`enum`,params:{allowedValues:n.properties.method.enum},message:`must be equal to one of the allowed values`}],!1;var _=a===c}else var _=!0;if(_)if(e.validate!==void 0){let n=e.validate,i=c;if(typeof n!=`boolean`){let i;if(i===void 0)if(n===`false`||n===0||n===null)i=!1;else if(n===`true`||n===1)i=!0;else return r.errors=[{instancePath:t+`/validate`,schemaPath:`#/properties/validate/type`,keyword:`type`,params:{type:`boolean`},message:`must be boolean`}],!1;i!==void 0&&(n=i,e!==void 0&&(e.validate=i))}var _=i===c}else var _=!0}}}}}}}}}else return r.errors=[{instancePath:t,schemaPath:`#/type`,keyword:`type`,params:{type:`object`},message:`must be object`}],!1;return r.errors=s,c===0}})),uh=o(((e,t)=>{let n=require(`node:assert`),r=oh(),i=ch(),a=`The dispatch function has already been invoked`,o=lh();function s(e,t,n){return n===void 0?new d(e,t):u(e,t,n)}function c(e,t){let n=e._lightMyRequest.payload;if(!n||n._readableState||typeof n.resume!=`function`)return t();let r=[];n.on(`data`,e=>r.push(Buffer.from(e))),n.on(`end`,()=>{let n=Buffer.concat(r);return e.headers[`content-length`]=e.headers[`content-length`]||``+n.length,delete e.headers[`transfer-encoding`],e._lightMyRequest.payload=n,t()}),n.resume()}function l(e,t,n,r){return n.once(`error`,function(e){this.destroyed&&r.destroy(e)}),n.once(`close`,function(){this.destroyed&&!this._error&&r.destroy()}),c(n,()=>e.call(t,n,r))}function u(e,t,a){if(t=typeof t==`string`?{url:t}:t,t.validate!==!1&&(n(typeof e==`function`,`dispatchFunc should be a function`),!o(t)))throw Error(o.errors.map(e=>e.message));let s=t.server||{},c=t.Request?r.CustomRequest:r;if(e.request&&e.request.app===e&&(Object.setPrototypeOf(Object.getPrototypeOf(e.request),c.prototype),Object.setPrototypeOf(Object.getPrototypeOf(e.response),i.prototype)),typeof a==`function`){let n=new c(t);return l(e,s,n,new i(n,a))}else return new Promise((n,r)=>{let a=new c(t);l(e,s,a,new i(a,n,r))})}function d(e,t){typeof t==`string`?this.option={url:t}:this.option=Object.assign({},t),this.dispatch=e,this._hasInvoked=!1,this._promise=null,this.option.autoStart!==!1&&process.nextTick(()=>{this._hasInvoked||this.end()})}[`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option.url=t,this.option.method=e.toUpperCase(),this}}),[`body`,`cookies`,`headers`,`payload`,`query`].forEach(e=>{d.prototype[e]=function(t){if(this._hasInvoked===!0||this._promise)throw Error(a);return this.option[e]=t,this}}),d.prototype.end=function(e){if(this._hasInvoked===!0||this._promise)throw Error(a);if(this._hasInvoked=!0,typeof e==`function`)u(this.dispatch,this.option,e);else return this._promise=u(this.dispatch,this.option),this._promise},Object.getOwnPropertyNames(Promise.prototype).forEach(e=>{e!==`constructor`&&(d.prototype[e]=function(...t){if(!this._promise){if(this._hasInvoked===!0)throw Error(a);this._hasInvoked=!0,this._promise=u(this.dispatch,this.option)}return this._promise[e](...t)})});function f(e){return e instanceof r||e instanceof i||e?.constructor?.name===`_CustomLMRRequest`}t.exports=s,t.exports.default=s,t.exports.inject=s,t.exports.isInjection=f})),dh=o(((e,t)=>{let n=yu(),r=require(`node:http`),i=require(`node:diagnostics_channel`),a,{kAvvioBoot:o,kChildren:s,kServerBindings:c,kBodyLimit:l,kSupportedHTTPMethods:u,kRoutePrefix:d,kLogLevel:f,kLogSerializers:p,kHooks:m,kSchemaController:h,kRequestAcceptVersion:g,kReplySerializerDefault:_,kContentTypeParser:v,kReply:y,kRequest:b,kFourOhFour:x,kState:S,kOptions:C,kPluginNameChain:w,kSchemaErrorFormatter:T,kErrorHandler:E,kKeepAliveConnections:D,kChildLoggerFactory:O,kGenReqId:k,kErrorHandlerAlreadySet:A}=bu(),{createServer:j}=Du(),M=_d(),ee=xd(),N=Sd(),te=gd(),P=Td(),ne=Op(),{Hooks:re,hookRunnerApplication:F,supportedHooks:ie}=wu(),{createChildLogger:I,defaultChildLoggerFactory:ae,createLogger:oe}=ud(),L=bm(),{getGenReqId:se,reqIdGenFactory:ce}=xm(),{buildRouting:le,validateBodyLimitOption:ue,buildRouterOptions:de}=Zm(),fe=Qm(),pe=eh(),me=th(),{appendStackTrace:he,AVVIO_ERRORS_MAP:ge,..._e}=Cu(),ve=Eu(),{defaultInitOptions:ye}=pe,{FST_ERR_ASYNC_CONSTRAINT:be,FST_ERR_BAD_URL:xe,FST_ERR_OPTIONS_NOT_OBJ:Se,FST_ERR_QSP_NOT_FN:Ce,FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:we,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:Te,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:Ee,FST_ERR_INSTANCE_ALREADY_LISTENING:De,FST_ERR_REOPENED_CLOSE_SERVER:Oe,FST_ERR_ROUTE_REWRITE_NOT_STR:ke,FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:Ae,FST_ERR_ERROR_HANDLER_NOT_FN:je,FST_ERR_ERROR_HANDLER_ALREADY_SET:Me,FST_ERR_ROUTE_METHOD_INVALID:Ne}=_e,{buildErrorHandler:Pe}=hd(),{FSTWRN004:Fe}=Su(),Ie=i.channel(`fastify.initialization`);function Le(e){let{options:t,genReqId:i,disableRequestLogging:oe,hasLogger:ue,initialConfig:de}=Re(e,Qe,$e),pe=le(t.routerOptions),Se=fe(t),Ce=ut(pe,t),{server:we,listen:Te,forceCloseConnections:Ee,serverHasCloseAllConnections:Ae,serverHasCloseHttp2Sessions:Le,keepAliveConnections:ze}=j(t,Ce),Be=M.setupResponseListeners,He=ne.buildSchemaController(null,t.schemaController),R={[S]:{listening:!1,closing:!1,started:!1,ready:!1,booting:!1,aborted:!1,readyResolver:null},[D]:ze,[u]:{bodyless:new Set([`GET`,`HEAD`,`TRACE`]),bodywith:new Set([`DELETE`,`OPTIONS`,`PATCH`,`PUT`,`POST`])},[C]:t,[s]:[],[c]:[],[l]:t.bodyLimit,[d]:``,[f]:``,[p]:null,[m]:new re,[h]:He,[T]:null,[E]:Pe(),[A]:!1,[O]:t.childLoggerFactory||ae,[_]:null,[v]:new P(t.bodyLimit,t.onProtoPoisoning||ye.onProtoPoisoning,t.onConstructorPoisoning||ye.onConstructorPoisoning),[y]:M.buildReply(M),[b]:ee.buildRequest(ee,t.trustProxy),[x]:Se,[L.kRegisteredPlugins]:[],[w]:[`fastify`],[o]:null,[k]:i,routing:Ce,delete:function(e,t,n){return pe.prepareRoute.call(this,{method:`DELETE`,url:e,options:t,handler:n})},get:function(e,t,n){return pe.prepareRoute.call(this,{method:`GET`,url:e,options:t,handler:n})},head:function(e,t,n){return pe.prepareRoute.call(this,{method:`HEAD`,url:e,options:t,handler:n})},trace:function(e,t,n){return pe.prepareRoute.call(this,{method:`TRACE`,url:e,options:t,handler:n})},patch:function(e,t,n){return pe.prepareRoute.call(this,{method:`PATCH`,url:e,options:t,handler:n})},post:function(e,t,n){return pe.prepareRoute.call(this,{method:`POST`,url:e,options:t,handler:n})},put:function(e,t,n){return pe.prepareRoute.call(this,{method:`PUT`,url:e,options:t,handler:n})},options:function(e,t,n){return pe.prepareRoute.call(this,{method:`OPTIONS`,url:e,options:t,handler:n})},all:function(e,t,n){return pe.prepareRoute.call(this,{method:this.supportedMethods,url:e,options:t,handler:n})},route:function(e){return pe.route.call(this,{options:e})},hasRoute:function(e){return pe.hasRoute.call(this,{options:e})},findRoute:function(e){return pe.findRoute(e)},log:t.logger,withTypeProvider:Ye,addHook:Xe,addSchema:Ze,getSchema:He.getSchema.bind(He),getSchemas:He.getSchemas.bind(He),setValidatorCompiler:nt,setSerializerCompiler:it,setSchemaController:at,setReplySerializer:ot,setSchemaErrorFormatter:rt,setGenReqId:dt,addContentTypeParser:P.helpers.addContentTypeParser,hasContentTypeParser:P.helpers.hasContentTypeParser,getDefaultJsonParser:P.defaultParsers.getDefaultJsonParser,defaultTextParser:P.defaultParsers.defaultTextParser,removeContentTypeParser:P.helpers.removeContentTypeParser,removeAllContentTypeParsers:P.helpers.removeAllContentTypeParsers,register:null,after:null,ready:null,onClose:null,close:null,printPlugins:null,hasPlugin:function(e){return this[L.kRegisteredPlugins].includes(e)||this[w].includes(e)},listen:Te,server:we,addresses:function(){let e=this[c].map(e=>e.address());return e.push(this.server.address()),e.filter(e=>e)},decorate:te.add,hasDecorator:te.exist,decorateReply:te.decorateReply,decorateRequest:te.decorateRequest,hasRequestDecorator:te.existRequest,hasReplyDecorator:te.existReply,getDecorator:te.getInstanceDecorator,addHttpMethod:ft,inject:qe,printRoutes:lt,setNotFoundHandler:tt,setErrorHandler:st,setChildLoggerFactory:ct,initialConfig:de,addConstraintStrategy:pe.addConstraintStrategy.bind(pe),hasConstraintStrategy:pe.hasConstraintStrategy.bind(pe)};Object.defineProperties(R,{listeningOrigin:{get(){let e=this.addresses().slice(-1).pop();if(typeof e==`string`)return e;let t=e.family===`IPv6`?`[${e.address}]`:e.address;return`${this[C].https?`https`:`http`}://${t}:${e.port}`}},pluginName:{configurable:!0,get(){return this[w].length>1?this[w].join(` -> `):this[w][0]}},prefix:{configurable:!0,get(){return this[d]}},validatorCompiler:{configurable:!0,get(){return this[h].getValidatorCompiler()}},serializerCompiler:{configurable:!0,get(){return this[h].getSerializerCompiler()}},childLoggerFactory:{configurable:!0,get(){return this[O]}},version:{configurable:!0,get(){return`5.7.4`}},errorHandler:{configurable:!0,get(){return this[E].func}},genReqId:{configurable:!0,get(){return this[k]}},supportedMethods:{configurable:!1,get(){return[...this[u].bodyless,...this[u].bodywith]}}}),t.schemaErrorFormatter&&(Ve(t.schemaErrorFormatter),R[T]=t.schemaErrorFormatter.bind(R));let Ue=Number(t.pluginTimeout),We=n(R,{autostart:!1,timeout:isNaN(Ue)===!1?Ue:ye.pluginTimeout,expose:{use:`register`}});We.override=me,We.on(`start`,()=>R[S].started=!0),R[o]=R.ready,R.ready=Je,R.printPlugins=We.prettyPrint.bind(We),We.once(`preReady`,()=>{R.onClose((e,n)=>{R[S].closing=!0,pe.closeRoutes(),F(`preClose`,R[o],R,function(){if(R[S].listening){if(Ee===`idle`)e.server.closeIdleConnections();else if(Ae&&Ee)e.server.closeAllConnections();else if(Ee===!0)for(let e of R[D])e.destroy(),R[D].delete(e)}Le&&e.server.closeHttp2Sessions(),!t.serverFactory||R[S].listening?e.server.close(function(e){e&&e.code!==`ERR_SERVER_NOT_RUNNING`?n(null):n()}):process.nextTick(n,null)})})});let Ge=new N({server:R,config:{}});return R.setNotFoundHandler(),Se.arrange404(R),pe.setup(t,{avvio:We,fourOhFour:Se,hasLogger:ue,setupResponseListeners:Be,throwIfAlreadyStarted:Ke,keepAliveConnections:ze}),we.on(`clientError`,t.clientErrorHandler.bind(R)),Ie.hasSubscribers&&Ie.publish({fastify:R}),`asyncDispose`in Symbol&&(R[Symbol.asyncDispose]=function(){return R.close()}),R;function Ke(e){if(R[S].started)throw new De(e)}function qe(e,t){if(a===void 0&&(a=uh()),R[S].started){if(R[S].closing){let e=new Oe;if(t){t(e);return}else return Promise.reject(e)}return a(Ce,e,t)}if(t)this.ready(n=>{n?t(n,null):a(Ce,e,t)});else return a((e,t)=>{this.ready(function(n){if(n){t.emit(`error`,n);return}Ce(e,t)})},e)}function Je(e){if(this[S].readyResolver!==null){if(e!=null){this[S].readyResolver.promise.then(()=>e(null,R),e);return}return this[S].readyResolver.promise}if(process.nextTick(t),this[S].readyResolver=ve.withResolvers(),e)this[S].readyResolver.promise.then(()=>e(null,R),e);else return this[S].readyResolver.promise;function t(){R[o]((e,t)=>{e||R[S].started||R[S].ready||R[S].booting?n(e):(R[S].booting=!0,F(`onReady`,R[o],R,n)),t()})}function n(e){if(e=e!=null&&ge[e.code]!=null?he(e,new ge[e.code](e.message)):e,e)return R[S].readyResolver.reject(e);R[S].readyResolver.resolve(R),R[S].booting=!1,R[S].ready=!0,R[S].readyResolver=null}}function Ye(){return this}function Xe(e,t){if(Ke(`Cannot call "addHook"!`),t==null)throw new _e.FST_ERR_HOOK_INVALID_HANDLER(e,t);if(e===`onSend`||e===`preSerialization`||e===`onError`||e===`preParsing`){if(t.constructor.name===`AsyncFunction`&&t.length===4)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onReady`||e===`onListen`){if(t.constructor.name===`AsyncFunction`&&t.length!==0)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new _e.FST_ERR_HOOK_INVALID_ASYNC_HANDLER;return e===`onClose`?this.onClose(t.bind(this)):e===`onReady`||e===`onListen`||e===`onRoute`?this[m].add(e,t):this.after((r,i)=>{try{n.call(this,e,t),i(r)}catch(e){i(e)}}),this;function n(e,t){this[m].add(e,t),this[s].forEach(r=>n.call(r,e,t))}}function Ze(e){return Ke(`Cannot call "addSchema"!`),this[h].add(e),this[s].forEach(t=>t.addSchema(e)),this}function Qe(e,t){e.headers[`accept-version`]!==void 0&&(e.headers[g]=e.headers[`accept-version`],e.headers[`accept-version`]=void 0),Se.router.lookup(e,t)}function $e(e,n,r){if(t.frameworkErrors){let i=se(Ge.server,n),a=I(Ge,t.logger,n,i),o=new ee(i,null,n,null,a,Ge),s=new M(r,o,a);return(typeof oe==`function`?oe(n):oe)===!1&&a.info({req:o},`incoming request`),t.frameworkErrors(new xe(e),o,s)}let i=JSON.stringify({error:`Bad Request`,code:`FST_ERR_BAD_URL`,message:`'${e}' is not a valid url component`,statusCode:400});r.writeHead(400,{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(i)}),r.end(i)}function et(e,n,r){if(e!==!1)return function(e){if(e){if(t.frameworkErrors){let e=se(Ge.server,n),i=I(Ge,t.logger,n,e),a=new ee(e,null,n,null,i,Ge),o=new M(r,a,i);return(typeof oe==`function`?oe(n):oe)===!1&&i.info({req:a},`incoming request`),t.frameworkErrors(new be,a,o)}r.writeHead(500,{"Content-Type":`application/json`,"Content-Length":101}),r.end(`{"error":"Internal Server Error","message":"Unexpected error from async constraint","statusCode":500}`)}}}function tt(e,t){return Ke(`Cannot call "setNotFoundHandler"!`),Se.setNotFoundHandler.call(this,e,t,We,pe.routeHandler),this}function nt(e){return Ke(`Cannot call "setValidatorCompiler"!`),this[h].setValidatorCompiler(e),this}function rt(e){return Ke(`Cannot call "setSchemaErrorFormatter"!`),Ve(e),this[T]=e.bind(this),this}function it(e){return Ke(`Cannot call "setSerializerCompiler"!`),this[h].setSerializerCompiler(e),this}function at(e){Ke(`Cannot call "setSchemaController"!`);let t=this[h],n=ne.buildSchemaController(t,Object.assign({},t.opts,e));return this[h]=n,this.getSchema=n.getSchema.bind(n),this.getSchemas=n.getSchemas.bind(n),this}function ot(e){return Ke(`Cannot call "setReplySerializer"!`),this[_]=e,this}function st(e){if(Ke(`Cannot call "setErrorHandler"!`),typeof e!=`function`)throw new je;if(!t.allowErrorHandlerOverride&&this[A])throw new Me;return this[A]&&Fe(`To disable this behavior, set 'allowErrorHandlerOverride' to false or ignore this message. For more information, visit: https://fastify.dev/docs/latest/Reference/Server/#allowerrorhandleroverride`),this[A]=!0,this[E]=Pe(this[E],e.bind(this)),this}function ct(e){return Ke(`Cannot call "setChildLoggerFactory"!`),this[O]=e,this}function lt(e={}){return e.includeMeta=e.includeHooks?e.includeMeta?ie.concat(e.includeMeta):ie:e.includeMeta,pe.printRoutes(e)}function ut(e,{rewriteUrl:t,logger:n}){let r;return function(n,i){if(r===void 0&&(r=e.isAsyncConstraint()),t){n.originalUrl=n.url;let e=t.call(R,n);if(typeof e==`string`)n.url=e;else{let t=new ke(n.url,typeof e);n.destroy(t)}}e.routing(n,i,et(r,n,i))}}function dt(e){return Ke(`Cannot call "setGenReqId"!`),this[k]=ce(this[C].requestIdHeader,e),this}function ft(e,{hasBody:t=!1}={}){if(typeof e!=`string`||r.METHODS.indexOf(e)===-1)throw new Ne;t===!0?(this[u].bodywith.add(e),this[u].bodyless.delete(e)):(this[u].bodywith.delete(e),this[u].bodyless.add(e));let n=e.toLowerCase();return this.hasDecorator(n)||this.decorate(n,function(t,n,r){return pe.prepareRoute.call(this,{method:e,url:t,options:n,handler:r})}),this}}function Re(e,t,n){if(e&&typeof e!=`object`)throw new Se;if(e=Object.assign({},e),e.querystringParser&&typeof e.querystringParser!=`function`||e.routerOptions?.querystringParser&&typeof e.routerOptions.querystringParser!=`function`)throw new Ce(typeof(e.querystringParser??e.routerOptions.querystringParser));if(e.schemaController&&e.schemaController.bucket&&typeof e.schemaController.bucket!=`function`)throw new we(typeof e.schemaController.bucket);ue(e.bodyLimit);let r=typeof e.requestIdHeader==`string`&&e.requestIdHeader.length!==0?e.requestIdHeader.toLowerCase():e.requestIdHeader===!0&&`request-id`,i=ce(r,e.genReqId),a=e.requestIdLogLabel||`reqId`;e.bodyLimit=e.bodyLimit||ye.bodyLimit;let o=e.disableRequestLogging||!1,s=Object.assign({customOptions:{},plugins:[]},e.ajv);if(!s.customOptions||Object.prototype.toString.call(s.customOptions)!==`[object Object]`)throw new Te(typeof s.customOptions);if(!s.plugins||!Array.isArray(s.plugins))throw new Ee(typeof s.plugins);let{logger:c,hasLogger:l}=oe(e);e.connectionTimeout=e.connectionTimeout||ye.connectionTimeout,e.keepAliveTimeout=e.keepAliveTimeout||ye.keepAliveTimeout,e.maxRequestsPerSocket=e.maxRequestsPerSocket||ye.maxRequestsPerSocket,e.requestTimeout=e.requestTimeout||ye.requestTimeout,e.logger=c,e.requestIdHeader=r,e.requestIdLogLabel=a,e.disableRequestLogging=o,e.ajv=s,e.clientErrorHandler=e.clientErrorHandler||Be,e.allowErrorHandlerOverride=e.allowErrorHandlerOverride??ye.allowErrorHandlerOverride;let u=pe(e);return e.exposeHeadRoutes=u.exposeHeadRoutes,e.http2SessionTimeout=u.http2SessionTimeout,e.routerOptions=de(e,{defaultRoute:t,onBadUrl:n,ignoreTrailingSlash:ye.ignoreTrailingSlash,ignoreDuplicateSlashes:ye.ignoreDuplicateSlashes,maxParamLength:ye.maxParamLength,allowUnsafeRegex:ye.allowUnsafeRegex,buildPrettyMeta:ze,useSemicolonDelimiter:ye.useSemicolonDelimiter}),{options:e,genReqId:i,disableRequestLogging:o,hasLogger:l,initialConfig:u}}function ze(e){let t={};return[`errorHandler`,`logLevel`,`logSerializers`].concat(ie).forEach(n=>{t[n]=e.store[n]}),Object.assign({},t)}function Be(e,t){if(e.code===`ECONNRESET`||t.destroyed)return;let n,i,a,o;e.code===`ERR_HTTP_REQUEST_TIMEOUT`?(i=`408`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Timeout","statusCode":408}`,o=`timeout`):e.code===`HPE_HEADER_OVERFLOW`?(i=`431`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`,o=`header_overflow`):(i=`400`,a=r.STATUS_CODES[i],n=`{"error":"${a}","message":"Client Error","statusCode":400}`,o=`error`),this.log.trace({err:e},`client ${o}`),t.writable&&t.write(`HTTP/1.1 ${i} ${a}\r\nContent-Length: ${n.length}\r\nContent-Type: application/json\r\n\r\n${n}`),t.destroy(e)}function Ve(e){if(typeof e!=`function`)throw new Ae(typeof e);if(e.constructor.name===`AsyncFunction`)throw new Ae(`AsyncFunction`)}t.exports=Le,t.exports.errorCodes=_e,t.exports.fastify=Le,t.exports.default=Le})),fh=o(((e,t)=>{let n=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,r=/(\w*(\.\w*)*)\..*/;t.exports=function(e){if(e.name.length>0)return e.name;let t=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw Error(`anonymous function`)}catch(e){return Error.stackTraceLimit=t,i(e.stack)}};function i(e){let t=e.match(n);return t?t[1].split(/[/\\]/).slice(-1)[0].match(r)[1]:`anonymous`}t.exports.extractPluginName=i})),ph=o(((e,t)=>{t.exports=function(e){return e[0]===`@`&&(e=e.slice(1).replace(`/`,`-`)),e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}})),mh=o(((e,t)=>{let n=fh(),r=ph(),i=0;function a(e,t={}){let a=!1;if(e.default!==void 0&&(e=e.default),typeof e!=`function`)throw TypeError(`fastify-plugin expects a function, instead got a '${typeof e}'`);if(typeof t==`string`&&(t={fastify:t}),typeof t!=`object`||Array.isArray(t)||t===null)throw TypeError(`The options object should be an object`);if(t.fastify!==void 0&&typeof t.fastify!=`string`)throw TypeError(`fastify-plugin expects a version string, instead got '${typeof t.fastify}'`);t.name||(a=!0,t.name=n(e)+`-auto-`+ i++),e[Symbol.for(`skip-override`)]=t.encapsulate!==!0,e[Symbol.for(`fastify.display-name`)]=t.name,e[Symbol.for(`plugin-meta`)]=t,e.default||=e;let o=r(t.name);return!a&&!e[o]&&(e[o]=e),e}t.exports=a,t.exports.default=a,t.exports.fastifyPlugin=a})),hh=o(((e,t)=>{function n(e){if(typeof e!=`function`)throw Error(`obliterator/iterator: expecting a function!`);this.next=e}typeof Symbol<`u`&&(n.prototype[Symbol.iterator]=function(){return this}),n.of=function(){var e=arguments,t=e.length,r=0;return new n(function(){return r>=t?{done:!0}:{done:!1,value:e[r++]}})},n.empty=function(){return new n(function(){return{done:!0}})},n.fromSequence=function(e){var t=0,r=e.length;return new n(function(){return t>=r?{done:!0}:{done:!1,value:e[t++]}})},n.is=function(e){return e instanceof n?!0:typeof e==`object`&&!!e&&typeof e.next==`function`},t.exports=n})),gh=o((e=>{e.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<`u`,e.SYMBOL_SUPPORT=typeof Symbol<`u`})),_h=o(((e,t)=>{var n=gh(),r=n.ARRAY_BUFFER_SUPPORT,i=n.SYMBOL_SUPPORT;t.exports=function(e,t){var n,a,o,s,c;if(!e)throw Error(`obliterator/forEach: invalid iterable.`);if(typeof t!=`function`)throw Error(`obliterator/forEach: expecting a callback.`);if(Array.isArray(e)||r&&ArrayBuffer.isView(e)||typeof e==`string`||e.toString()===`[object Arguments]`){for(o=0,s=e.length;o<s;o++)t(e[o],o);return}if(typeof e.forEach==`function`){e.forEach(t);return}if(i&&Symbol.iterator in e&&typeof e.next!=`function`&&(e=e[Symbol.iterator]()),typeof e.next==`function`){for(n=e,o=0;c=n.next(),c.done!==!0;)t(c.value,o),o++;return}for(a in e)e.hasOwnProperty(a)&&t(e[a],a)}})),vh=o((e=>{var t=2**8-1,n=2**16-1,r=2**32-1,i=2**7-1,a=2**15-1,o=2**31-1;e.getPointerArray=function(e){var i=e-1;if(i<=t)return Uint8Array;if(i<=n)return Uint16Array;if(i<=r)return Uint32Array;throw Error(`mnemonist: Pointer Array of size > 4294967295 is not supported.`)},e.getSignedPointerArray=function(e){var t=e-1;return t<=i?Int8Array:t<=a?Int16Array:t<=o?Int32Array:Float64Array},e.getNumberType=function(e){return e===(e|0)?Math.sign(e)===-1?e<=127&&e>=-128?Int8Array:e<=32767&&e>=-32768?Int16Array:Int32Array:e<=255?Uint8Array:e<=65535?Uint16Array:Uint32Array:Float64Array};var s={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};e.getMinimalRepresentation=function(t,n){var r=null,i=0,a,o,c,l,u;for(l=0,u=t.length;l<u;l++)c=n?n(t[l]):t[l],o=e.getNumberType(c),a=s[o.name],a>i&&(i=a,r=o);return r},e.isTypedArray=function(e){return typeof ArrayBuffer<`u`&&ArrayBuffer.isView(e)},e.concat=function(){var e=0,t,n,r;for(t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var i=new arguments[0].constructor(e);for(t=0,n=0;t<r;t++)i.set(arguments[t],n),n+=arguments[t].length;return i},e.indices=function(t){for(var n=new(e.getPointerArray(t))(t),r=0;r<t;r++)n[r]=r;return n}})),yh=o((e=>{var t=_h(),n=vh();function r(e){return Array.isArray(e)||n.isTypedArray(e)}function i(e){if(typeof e.length==`number`)return e.length;if(typeof e.size==`number`)return e.size}function a(e){var n=i(e),r=typeof n==`number`?Array(n):[],a=0;return t(e,function(e){r[a++]=e}),r}function o(e){var r=i(e),a=typeof r==`number`?n.getPointerArray(r):Array,o=typeof r==`number`?Array(r):[],s=typeof r==`number`?new a(r):[],c=0;return t(e,function(e){o[c]=e,s[c]=c++}),[o,s]}e.isArrayLike=r,e.guessLength=i,e.toArray=a,e.toArrayWithIndices=o})),bh=o(((e,t)=>{var n=hh(),r=_h(),i=vh(),a=yh();function o(e,t,n){if(arguments.length<2&&(n=e,e=null,t=null),this.capacity=n,typeof this.capacity!=`number`||this.capacity<=0)throw Error(`mnemonist/lru-cache: capacity should be positive number.`);if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw Error(`mnemonist/lru-cache: capacity should be a finite positive integer.`);var r=i.getPointerArray(n);this.forward=new r(n),this.backward=new r(n),this.K=typeof e==`function`?new e(n):Array(n),this.V=typeof t==`function`?new t(n):Array(n),this.size=0,this.head=0,this.tail=0,this.items={}}o.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}},o.prototype.splayOnTop=function(e){var t=this.head;if(this.head===e)return this;var n=this.backward[e],r=this.forward[e];return this.tail===e?this.tail=n:this.backward[r]=n,this.forward[n]=r,this.backward[t]=e,this.head=e,this.forward[e]=t,this},o.prototype.set=function(e,t){var n=this.items[e];if(n!==void 0){this.splayOnTop(n),this.V[n]=t;return}this.size<this.capacity?n=this.size++:(n=this.tail,this.tail=this.backward[n],delete this.items[this.K[n]]),this.items[e]=n,this.K[n]=e,this.V[n]=t,this.forward[n]=this.head,this.backward[this.head]=n,this.head=n},o.prototype.setpop=function(e,t){var n=null,r=null,i=this.items[e];return i===void 0?(this.size<this.capacity?i=this.size++:(i=this.tail,this.tail=this.backward[i],n=this.V[i],r=this.K[i],delete this.items[r]),this.items[e]=i,this.K[i]=e,this.V[i]=t,this.forward[i]=this.head,this.backward[this.head]=i,this.head=i,r?{evicted:!0,key:r,value:n}:null):(this.splayOnTop(i),n=this.V[i],this.V[i]=t,{evicted:!1,key:e,value:n})},o.prototype.has=function(e){return e in this.items},o.prototype.get=function(e){var t=this.items[e];if(t!==void 0)return this.splayOnTop(t),this.V[t]},o.prototype.peek=function(e){var t=this.items[e];if(t!==void 0)return this.V[t]},o.prototype.forEach=function(e,t){t=arguments.length>1?t:this;for(var n=0,r=this.size,i=this.head,a=this.K,o=this.V,s=this.forward;n<r;)e.call(t,o[i],a[i],this),i=s[i],n++},o.prototype.keys=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.values=function(){var e=0,t=this.size,r=this.head,i=this.V,a=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r];return e++,e<t&&(r=a[r]),{done:!1,value:n}})},o.prototype.entries=function(){var e=0,t=this.size,r=this.head,i=this.K,a=this.V,o=this.forward;return new n(function(){if(e>=t)return{done:!0};var n=i[r],s=a[r];return e++,e<t&&(r=o[r]),{done:!1,value:[n,s]}})},typeof Symbol<`u`&&(o.prototype[Symbol.iterator]=o.prototype.entries),o.prototype.inspect=function(){for(var e=new Map,t=this.entries(),n;n=t.next(),!n.done;)e.set(n.value[0],n.value[1]);return Object.defineProperty(e,`constructor`,{value:o,enumerable:!1}),e},typeof Symbol<`u`&&(o.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=o.prototype.inspect),o.from=function(e,t,n,i){if(arguments.length<2){if(i=a.guessLength(e),typeof i!=`number`)throw Error(`mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.`)}else arguments.length===2&&(i=t,t=null,n=null);var s=new o(t,n,i);return r(e,function(e,t){s.set(t,e)}),s},t.exports=o})),xh=o(((e,t)=>{let n=bh(),r=/^[!#$%&'*+\-.^\w`|~]+$/u;function i(e){if(r.test(e)===!1)throw TypeError(`Fieldname contains invalid characters.`)}function a(e){e=e.trim().toLowerCase();let t=[];if(e.length!==0)if(e.indexOf(`,`)===-1)t.push(e);else{let n=e.length,r=0,i=0,a;for(;r<n;++r)a=e[r],a===` `?i=r+1:a===`,`&&(i!==r&&t.push(e.slice(i,r)),i=r+1);i!==r&&t.push(e.slice(i,r))}return t}function o(e){let t=new n(1e3);return i(e),function(n){let r=n.getHeader(`Vary`);if(!r){n.header(`Vary`,e);return}if(r===`*`)return;if(e===`*`){n.header(`Vary`,`*`);return}if(Array.isArray(r)&&(r=r.join(`, `)),!t.has(r)){let n=a(r);n.indexOf(`*`)===-1?n.indexOf(e.toLowerCase())===-1?t.set(r,r+`, `+e):t.set(r,null):t.set(r,`*`)}let i=t.get(r);i!==null&&n.header(`Vary`,i)}}t.exports.createAddFieldnameToVary=o,t.exports.addOriginToVaryHeader=o(`Origin`),t.exports.addAccessControlRequestHeadersToVaryHeader=o(`Access-Control-Request-Headers`),t.exports.parse=a})),Sh=o(((e,t)=>{let n=mh(),{addAccessControlRequestHeadersToVaryHeader:r,addOriginToVaryHeader:i}=xh(),a={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,hook:`onRequest`,preflightContinue:!1,optionsSuccessStatus:204,credentials:!1,exposedHeaders:null,allowedHeaders:null,maxAge:null,preflight:!0,strictPreflight:!0},o=[`onRequest`,`preParsing`,`preValidation`,`preHandler`,`preSerialization`,`onSend`],s=[`preSerialization`,`preParsing`,`onSend`];function c(e,t){o.indexOf(e)===-1&&t(TypeError(`@fastify/cors: Invalid hook option provided.`))}function l(e,t,n){e.decorateRequest(`corsPreflightEnabled`,!1);let r=!0;if(typeof t==`function`)u(t,e,{hook:a.hook},n);else if(t.delegator){let{delegator:r,...i}=t;u(r,e,i,n)}else{t.hideOptionsRoute!==void 0&&(r=t.hideOptionsRoute);let i=f(t);c(i.hook,n),s.indexOf(i.hook)===-1?e.addHook(i.hook,function(t,n,r){p(e,i,t,n,r)}):e.addHook(i.hook,function(t,n,r,a){p(e,i,t,n,a)})}e.options(`*`,{schema:{hide:r}},(e,t)=>{if(!e.corsPreflightEnabled){t.callNotFound();return}t.send()}),n()}function u(e,t,n,r){let i=n?.hook||a.hook;c(i,r),e.length===2?s.indexOf(i)===-1?t.addHook(i,function(n,r,i){d(e,t,n,r,i)}):t.addHook(i,function(n,r,i,a){d(e,t,n,r,a)}):s.indexOf(i)===-1?t.addHook(i,function(n,r,i){let a=e(n);if(a&&typeof a.then==`function`){a.then(e=>p(t,f(e,!0),n,r,i)).catch(i);return}i(Error(`Invalid CORS origin option`))}):t.addHook(i,function(n,r,i,a){let o=e(n);if(o&&typeof o.then==`function`){o.then(e=>p(t,f(e,!0),n,r,a)).catch(a);return}a(Error(`Invalid CORS origin option`))})}function d(e,t,n,r,i){e(n,(e,a)=>{e?i(e):p(t,f(a,!0),n,r,i)})}function f(e,t){let n={...a,...e};return Array.isArray(e.origin)&&e.origin.indexOf(`*`)!==-1&&(n.origin=`*`),Number.isInteger(n.cacheControl)?n.cacheControl=`max-age=${n.cacheControl}`:typeof n.cacheControl!=`string`&&(n.cacheControl=null),n.dynamic=t||!1,n}function p(e,t,n,r,a){(typeof t.origin!=`string`&&t.origin!==!1||t.dynamic)&&i(r),(typeof t.origin==`function`?g(e,t.origin):(e,n)=>n(null,t.origin))(n,(e,i)=>{if(e!==null)return a(e);if(i===!1||n.routeOptions.config?.cors===!1)return a();if(!i)return a(Error(`Invalid CORS origin option`));if(m(n,r,i,t),n.raw.method===`OPTIONS`&&t.preflight===!0){if(t.strictPreflight===!0&&(!n.headers.origin||!n.headers[`access-control-request-method`])){r.status(400).type(`text/plain`).send(`Invalid Preflight Request`);return}if(n.corsPreflightEnabled=!0,h(n,r,t),!t.preflightContinue){r.code(t.optionsSuccessStatus).header(`Content-Length`,`0`).send();return}}return a()})}function m(e,t,n,r){let i=_(e.headers.origin,n);i&&t.header(`Access-Control-Allow-Origin`,i),r.credentials&&t.header(`Access-Control-Allow-Credentials`,`true`),r.exposedHeaders!==null&&t.header(`Access-Control-Expose-Headers`,Array.isArray(r.exposedHeaders)?r.exposedHeaders.join(`, `):r.exposedHeaders)}function h(e,t,n){if(t.header(`Access-Control-Allow-Methods`,Array.isArray(n.methods)?n.methods.join(`, `):n.methods),n.allowedHeaders===null){r(t);let n=e.headers[`access-control-request-headers`];n!==void 0&&t.header(`Access-Control-Allow-Headers`,n)}else t.header(`Access-Control-Allow-Headers`,Array.isArray(n.allowedHeaders)?n.allowedHeaders.join(`, `):n.allowedHeaders);n.maxAge!==null&&t.header(`Access-Control-Max-Age`,String(n.maxAge)),n.cacheControl&&t.header(`Cache-Control`,n.cacheControl)}function g(e,t){return function(n,r){let i=t.call(e,n.headers.origin,r);i&&typeof i.then==`function`&&i.then(e=>r(null,e),r)}}function _(e,t){return typeof t==`string`?t:v(e,t)?e:!1}function v(e,t){if(Array.isArray(t)){for(let n=0;n<t.length;++n)if(v(e,t[n]))return!0;return!1}else if(typeof t==`string`)return e===t;else if(t instanceof RegExp)return t.lastIndex=0,t.test(e);else return!!t}let y=n(l,{fastify:`5.x`,name:`@fastify/cors`});t.exports=y,t.exports.fastifyCors=y,t.exports.default=y})),Ch=o(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),wh=o(((e,t)=>{let{EMPTY_BUFFER:n}=Ch(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),Th=o(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),Eh=o(((e,t)=>{let n=require(`zlib`),r=wh(),i=Th(),{kStatusCode:a}=Ch(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Dh=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=Ch(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Oh=o(((e,t)=>{let{Writable:n}=require(`stream`),r=Eh(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Ch(),{concat:c,toArrayBuffer:l,unmask:u}=wh(),{isValidStatusCode:d,isValidUTF8:f}=Dh(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),kh=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=Eh(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Ch(),{isBlob:c,isValidStatusCode:l}=Dh(),{mask:u,toBuffer:d}=wh(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),Ah=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Ch(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),jh=o(((e,t)=>{let{tokenChars:n}=Dh();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),Mh=o(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=Eh(),p=Oh(),m=kh(),{isBlob:h}=Dh(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=Ch(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Ah(),{format:D,parse:O}=jh(),{toBuffer:k}=wh(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,I),i.on(`drain`,ae),i.on(`error`,oe),i.on(`message`,se),i.on(`ping`,ce),i.on(`pong`,le),a.onerror=de,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,pe),t.on(`data`,me),t.on(`end`,he),t.on(`error`,ge),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),fe(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;P(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?re:ne),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{F(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,P(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){F(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{P(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||F(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function P(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(e){return e.path=e.socketPath,a.connect(e)}function re(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(P,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ie(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function I(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,me),process.nextTick(ue,n._socket),e===1005?n.close():n.close(e,t))}function ae(){let e=this[C];e.isPaused||e._socket.resume()}function oe(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,me),process.nextTick(ue,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function L(){this[C].emitClose()}function se(e,t){this[C].emit(`message`,e,t)}function ce(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function le(e){this[C].emit(`pong`,e)}function ue(e){e.resume()}function de(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,fe(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function fe(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function pe(){let e=this[C];if(this.removeListener(`close`,pe),this.removeListener(`data`,me),this.removeListener(`end`,he),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,L),e._receiver.on(`finish`,L))}function me(e){this[C]._receiver.write(e)||this.pause()}function he(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function ge(){let e=this[C];this.removeListener(`error`,ge),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),Nh=o(((e,t)=>{Mh();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Ph=o(((e,t)=>{let{tokenChars:n}=Dh();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Fh=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=jh(),s=Eh(),c=Ph(),l=Mh(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=Ch(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
453
453
  `).join(`\r
454
454
  `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
455
455
  `)+`\r
456
456
  \r
457
- `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}})),Fh=o(((e,t)=>{let n=jh();n.createWebSocketStream=Mh(),n.Server=Ph(),n.Receiver=Dh(),n.Sender=Oh(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})),Ih=o(((e,t)=>{t.exports=require(`stream`)})),Lh=o(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=require(`buffer`).Buffer,d=require(`util`).inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),Rh=o(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),zh=o(((e,t)=>{let n={};function r(e,t,r){r||=Error;function i(e,n,r){return typeof t==`string`?t:t(e,n,r)}class a extends r{constructor(e,t,n){super(i(e,t,n))}}a.prototype.name=r.name,a.prototype.code=e,n[e]=a}function i(e,t){if(Array.isArray(e)){let n=e.length;return e=e.map(e=>String(e)),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function o(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}r(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),r(`ERR_INVALID_ARG_TYPE`,function(e,t,n){let r;typeof t==`string`&&a(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;let c;return c=o(e,` argument`)?`The ${e} ${r} ${i(t,`type`)}`:`The "${e}" ${s(e,`.`)?`property`:`argument`} ${r} ${i(t,`type`)}`,c+=`. Received type ${typeof n}`,c},TypeError),r(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),r(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),r(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),r(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),r(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),r(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),r(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),r(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),r(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),r(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=n})),Bh=o(((e,t)=>{var n=zh().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16*1024}t.exports={getHighWaterMark:i}})),Vh=o(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Hh=o(((e,t)=>{try{var n=require(`util`);if(typeof n.inherits!=`function`)throw``;t.exports=n.inherits}catch{t.exports=Vh()}})),Uh=o(((e,t)=>{t.exports=require(`util`).deprecate})),Wh=o(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ae(t,e)}}var r;T.WritableState=C;var i={deprecate:Uh()},a=Ih(),o=require(`buffer`).Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=Rh(),d=Bh().getHighWaterMark,f=zh().codes,p=f.ERR_INVALID_ARG_TYPE,m=f.ERR_METHOD_NOT_IMPLEMENTED,h=f.ERR_MULTIPLE_CALLBACK,g=f.ERR_STREAM_CANNOT_PIPE,_=f.ERR_STREAM_DESTROYED,v=f.ERR_STREAM_NULL_VALUES,y=f.ERR_STREAM_WRITE_AFTER_END,b=f.ERR_UNKNOWN_ENCODING,x=u.errorOrDestroy;Hh()(T,a);function S(){}function C(e,t,i){r||=Gh(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1,this.decodeStrings=e.decodeStrings!==!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){ee(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,`buffer`,{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T?e&&e._writableState instanceof C:!1}})):w=function(e){return e instanceof this};function T(e){r||=Gh();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),i?(x(e,i),process.nextTick(r,i),!1):!0}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=k(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&P(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function k(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else A(e,t,!1,s,r,i,a);return c}function A(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function j(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(ie,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),ie(e,t))}function M(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function ee(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(M(n),t)j(e,n,r,t,i);else{var a=ne(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&P(e,n),r?process.nextTick(N,e,n,a,i):N(e,n,a,i)}}function N(e,t,n,r){n||te(e,t),t.pendingcb--,r(),ie(e,t)}function te(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function P(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,A(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(A(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||I(this,r,n),this},Object.defineProperty(T.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function ne(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function re(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),ie(e,t)})}function F(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(re,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function ie(e,t){var n=ne(t);if(n&&(F(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function I(e,t,n){t.ending=!0,ie(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ae(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,`destroyed`,{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),Gh=o(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Zh(),i=Wh();Hh()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),Kh=o(((e,t)=>{
457
+ `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}})),Ih=o(((e,t)=>{let n=Mh();n.createWebSocketStream=Nh(),n.Server=Fh(),n.Receiver=Oh(),n.Sender=kh(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})),Lh=o(((e,t)=>{t.exports=require(`stream`)})),Rh=o(((e,t)=>{function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]==null?{}:arguments[t];t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function s(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:String(t)}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var u=require(`buffer`).Buffer,d=require(`util`).inspect,f=d&&d.custom||`inspect`;function p(e,t,n){u.prototype.copy.call(e,t,n)}t.exports=function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return s(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return u.alloc(0);for(var t=u.allocUnsafe(e>>>0),n=this.head,r=0;n;)p(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=u.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:f,value:function(e,t){return d(this,r(r({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),zh=o(((e,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Bh=o(((e,t)=>{let n={};function r(e,t,r){r||=Error;function i(e,n,r){return typeof t==`string`?t:t(e,n,r)}class a extends r{constructor(e,t,n){super(i(e,t,n))}}a.prototype.name=r.name,a.prototype.code=e,n[e]=a}function i(e,t){if(Array.isArray(e)){let n=e.length;return e=e.map(e=>String(e)),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function o(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}r(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),r(`ERR_INVALID_ARG_TYPE`,function(e,t,n){let r;typeof t==`string`&&a(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;let c;return c=o(e,` argument`)?`The ${e} ${r} ${i(t,`type`)}`:`The "${e}" ${s(e,`.`)?`property`:`argument`} ${r} ${i(t,`type`)}`,c+=`. Received type ${typeof n}`,c},TypeError),r(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),r(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),r(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),r(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),r(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),r(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),r(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),r(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),r(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),r(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=n})),Vh=o(((e,t)=>{var n=Bh().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16*1024}t.exports={getHighWaterMark:i}})),Hh=o(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Uh=o(((e,t)=>{try{var n=require(`util`);if(typeof n.inherits!=`function`)throw``;t.exports=n.inherits}catch{t.exports=Hh()}})),Wh=o(((e,t)=>{t.exports=require(`util`).deprecate})),Gh=o(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ae(t,e)}}var r;T.WritableState=C;var i={deprecate:Wh()},a=Lh(),o=require(`buffer`).Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=zh(),d=Vh().getHighWaterMark,f=Bh().codes,p=f.ERR_INVALID_ARG_TYPE,m=f.ERR_METHOD_NOT_IMPLEMENTED,h=f.ERR_MULTIPLE_CALLBACK,g=f.ERR_STREAM_CANNOT_PIPE,_=f.ERR_STREAM_DESTROYED,v=f.ERR_STREAM_NULL_VALUES,y=f.ERR_STREAM_WRITE_AFTER_END,b=f.ERR_UNKNOWN_ENCODING,x=u.errorOrDestroy;Uh()(T,a);function S(){}function C(e,t,i){r||=Kh(),e||={},typeof i!=`boolean`&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=d(this,e,`writableHighWaterMark`,i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1,this.decodeStrings=e.decodeStrings!==!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){ee(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}C.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(C.prototype,`buffer`,{get:i.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var w;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(w=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return w.call(this,e)?!0:this===T?e&&e._writableState instanceof C:!1}})):w=function(e){return e instanceof this};function T(e){r||=Kh();var t=this instanceof r;if(!t&&!w.call(T,this))return new T(e);this._writableState=new C(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),a.call(this)}T.prototype.pipe=function(){x(this,new g)};function E(e,t){var n=new y;x(e,n),process.nextTick(t,n)}function D(e,t,n,r){var i;return n===null?i=new v:typeof n!=`string`&&!t.objectMode&&(i=new p(`chunk`,[`string`,`Buffer`],n)),i?(x(e,i),process.nextTick(r,i),!1):!0}T.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&l(e);return a&&!o.isBuffer(e)&&(e=c(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=S),r.ending?E(this,n):(a||D(this,r,e,n))&&(r.pendingcb++,i=k(this,r,a,e,t,n)),i},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&P(this,e))},T.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new b(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function O(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=o.from(t,n)),t}Object.defineProperty(T.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function k(e,t,n,r,i,a){if(!n){var o=O(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else A(e,t,!1,s,r,i,a);return c}function A(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function j(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(ie,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),ie(e,t))}function M(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function ee(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new h;if(M(n),t)j(e,n,r,t,i);else{var a=ne(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&P(e,n),r?process.nextTick(N,e,n,a,i):N(e,n,a,i)}}function N(e,t,n,r){n||te(e,t),t.pendingcb--,r(),ie(e,t)}function te(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function P(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)a[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;a.allBuffers=c,A(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(A(e,t,!1,t.objectMode?1:l.length,l,u,d),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}T.prototype._write=function(e,t,n){n(new m(`_write()`))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||I(this,r,n),this},Object.defineProperty(T.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function ne(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function re(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),ie(e,t)})}function F(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(re,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function ie(e,t){var n=ne(t);if(n&&(F(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function I(e,t,n){t.ending=!0,ie(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ae(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(T.prototype,`destroyed`,{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=u.destroy,T.prototype._undestroy=u.undestroy,T.prototype._destroy=function(e,t){t(e)}})),Kh=o(((e,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=Qh(),i=Gh();Uh()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),qh=o(((e,t)=>{
458
458
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
459
- var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),qh=o((e=>{var t=Kh().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Jh=o(((e,t)=>{var n=zh().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),Yh=o(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Jh(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),Xh=o(((e,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=zh().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),Zh=o(((e,t)=>{t.exports=E;var n;E.ReadableState=T,require(`events`).EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Ih(),a=require(`buffer`).Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=require(`util`),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Lh(),f=Rh(),p=Bh().getHighWaterMark,m=zh().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;Hh()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=Gh(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=qh().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Gh(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0)if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1);else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=qh().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?se(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&se(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?L(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&se(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,te(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(te,e))}function te(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,oe(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(ne,e,t))}function ne(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=re(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&le(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function re(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,oe(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=le(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(ie,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(F,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(F,this),t};function F(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function ie(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,I(this,e)),e.paused=!1,this};function I(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ae,e,t))}function ae(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),oe(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function oe(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Yh()),b(this)}),Object.defineProperty(E.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=L,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function L(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function se(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ce,t,e))}function ce(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=Xh()),x(E,e,t)});function le(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),Qh=o(((e,t)=>{t.exports=l;var n=zh().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=Gh();Hh()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),$h=o(((e,t)=>{t.exports=r;var n=Qh();Hh()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),eg=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=zh().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Jh()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a(`streams`);var i,o=t.map(function(e,n){var a=n<t.length-1;return l(e,a,n>0,function(e){i||=e,e&&o.forEach(u),!a&&(o.forEach(u),r(i))})});return t.reduce(d)}t.exports=p})),tg=o(((e,t)=>{var n=require(`stream`);process.env.READABLE_STREAM===`disable`&&n?(t.exports=n.Readable,Object.assign(t.exports,n),t.exports.Stream=n):(e=t.exports=Zh(),e.Stream=n||e,e.Readable=e,e.Writable=Wh(),e.Duplex=Gh(),e.Transform=Qh(),e.PassThrough=$h(),e.finished=Jh(),e.pipeline=eg())})),ng=o(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),rg=o(((e,t)=>{var n=ng();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),ig=o(((e,t)=>{var n=rg(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),ag=o(((e,t)=>{t.exports=n;function n(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState==`number`?e.read():e.read(r(t)):null}function r(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}})),og=o(((e,t)=>{var n=tg(),r=ig(),i=Hh(),a=ag(),o=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),s=function(e,t){e._corked?e.once(`uncork`,t):t()},c=function(e,t){e._autoDestroy&&e.destroy(t)},l=function(e,t){return function(n){n?c(e,n.message===`premature close`?null:n):t&&!e._ended&&e.end()}},u=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t()},d=function(){},f=function(e){return new n.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},p=function(e,t,r){if(!(this instanceof p))return new p(e,t,r);n.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==!1,this._forwardDestroy=!r||r.destroy!==!1,this._forwardEnd=!r||r.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};i(p,n.Duplex),p.obj=function(e,t,n){return n||={},n.objectMode=!0,n.highWaterMark=16,new p(e,t,n)},p.prototype.cork=function(){++this._corked===1&&this.emit(`cork`)},p.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit(`uncork`)},p.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.end();return}var t=this,n=r(e,{writable:!0,readable:!1},l(this,this._forwardEnd)),i=function(){var e=t._ondrain;t._ondrain=null,e&&e()};this._unwrite&&process.nextTick(i),this._writable=e,this._writable.on(`drain`,i),this._unwrite=function(){t._writable.removeListener(`drain`,i),n()},this.uncork()},p.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.push(null),this.resume();return}var t=this,n=r(e,{writable:!1,readable:!0},l(this)),i=function(){t._forward()},a=function(){t.push(null)};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on(`readable`,i),this._readable2.on(`end`,a),this._unread=function(){t._readable2.removeListener(`readable`,i),t._readable2.removeListener(`end`,a),n()},this._forward()},p.prototype._read=function(){this._drained=!0,this._forward()},p.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var e;this._drained&&(e=a(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},p.prototype.destroy=function(e,t){if(t||=d,this.destroyed)return t(null);this.destroyed=!0;var n=this;process.nextTick(function(){n._destroy(e),t(null)})},p.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit(`error`,e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit(`close`)},p.prototype._write=function(e,t,n){if(!this.destroyed){if(this._corked)return s(this,this._write.bind(this,e,t,n));if(e===o)return this._finish(n);if(!this._writable)return n();this._writable.write(e)===!1?this._ondrain=n:this.destroyed||n()}},p.prototype._finish=function(e){var t=this;this.emit(`preend`),s(this,function(){u(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===!1&&(t._writableState.prefinished=!0),t.emit(`prefinish`),s(t,e)})})},p.prototype.end=function(e,t,r){return typeof e==`function`?this.end(null,null,e):typeof t==`function`?this.end(e,null,t):(this._ended=!0,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(o),n.Writable.prototype.end.call(this,r))},t.exports=p})),sg=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=ph(),o=Fh(),s=og(),c=Symbol(`ws-socket`),l=Symbol(`ws-head`),u=/HTTP\/1.1 (\d+)/u;function d(e,t,a){e.decorateRequest(`ws`,null);let d=x;if(t.errorHandler){if(typeof t.errorHandler!=`function`)return a(Error(`invalid errorHandler function`));d=t.errorHandler}let f=y;if(t?.preClose){if(typeof t.preClose!=`function`)return a(Error(`invalid preClose function`));f=t.preClose}if(t.options?.noServer)return a(Error(`fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly.`));let p=Object.assign({noServer:!0},t.options);p.path&&e.log.warn(`ws server path option shouldn't be provided, use a route instead`);let m=p.server||e.server;delete p.server;let h=new o.Server(p);e.decorate(`websocketServer`,h);async function g(e=`/`,t={},n={}){let a=new r,d=new r,f=new s(a,d),p=new s(d,a),h=new o(null,void 0,{isServer:!1}),g=Buffer.from([]),_,v,y=new Promise((e,t)=>{_=e,v=t});typeof n.onInit==`function`&&n.onInit(h),h.on(`open`,()=>{typeof n.onOpen==`function`&&n.onOpen(h),p.removeListener(`data`,b),_(h)});let b=e=>{if(e.toString().includes(`HTTP/1.1 101 Switching Protocols`))h._isServer=!1,h.setSocket(p,g,{maxPayload:0});else{p.removeListener(`data`,b);let t=Number(u.exec(e.toString())[1]);v(Error(`Unexpected server response: `+t))}};p.on(`data`,b);let x={...t,method:`GET`,headers:{...t.headers,connection:`upgrade`,upgrade:`websocket`,"sec-websocket-version":13,"sec-websocket-key":i(16).toString(`base64`)},httpVersion:`1.1`,url:e,[c]:f,[l]:g};return m.emit(`upgrade`,x,x[c],x[l]),y}e.decorate(`injectWS`,g);function _(t,r,i){t[c]=r,t[l]=i;let a=new n(t);try{a.assignSocket(r),e.routing(t,a)}catch(t){e.log.warn({err:t},`websocket upgrade failed`)}}m.on(`upgrade`,_);let v=(t,n)=>{h.handleUpgrade(t,t[c],t[l],r=>{h.emit(`connection`,r,t),r.on(`error`,t=>{e.log.error(t)}),n(r)})};e.addHook(`onRequest`,(e,t,n)=>{e.raw[c]?e.ws=!0:e.ws=!1,n()}),e.addHook(`onResponse`,(e,t,n)=>{e.ws&&e.raw[c].destroy(),n()}),e.addHook(`onRoute`,e=>{let t=!1,n=e.wsHandler,r=e.handler;if(e.websocket||e.wsHandler){if(e.method===`HEAD`)return;if(e.method!==`GET`)throw Error(`websocket handler can only be declared in GET method`);if(t=!0,e.websocket&&(e.schema||={},e.schema.hide=!0,n=e.handler,r=function(e,t){t.code(404).send()}),typeof n!=`function`)throw TypeError(`invalid wsHandler function`)}e.handler=function(e,i){if(e.raw[c])i.hijack(),v(e.raw,r=>{let a;try{a=t?n.call(this,r,e):b.call(this,r,e)}catch(t){return d.call(this,t,r,e,i)}a&&typeof a.catch==`function`&&a.catch(t=>d.call(this,t,r,e,i))});else return r.call(this,e,i)}}),e.addHook(`preClose`,f);function y(t){let n=this.websocketServer;if(n.clients)for(let e of n.clients)e.close();e.server.removeListener(`upgrade`,_),n.close(t),t()}function b(e,t){this.log.info({path:t.url},`closed incoming websocket connection for path with no websocket handler`),e.close()}function x(e,t,n){n.log.error(e),t.terminate()}a()}t.exports=a(d,{fastify:`5.x`,name:`@fastify/websocket`}),t.exports.default=d,t.exports.fastifyWebsocket=d}))(),1),cg=c(xh(),1),lg=c(uh(),1);let ug,dg;function fg(e){!ug||ug.length<e?(ug=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(ug),dg=0):dg+e>ug.length&&(l.webcrypto.getRandomValues(ug),dg=0),dg+=e}function pg(e=21){fg(e|=0);let t=``;for(let n=dg-e;n<dg;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[ug[n]&63];return t}var mg=o(((e,t)=>{var n=Kh().Buffer,r=require(`stream`),i=require(`util`);function a(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if(typeof e.pipe==`function`)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||typeof e==`object`)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit(`end`,e),this.readable=!1,this.emit(`close`)}.bind(this)),this;throw TypeError(`Unexpected data type (`+typeof e+`)`)}i.inherits(a,r),a.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit(`data`,e)},a.prototype.end=function(e){e&&this.write(e),this.emit(`end`,e),this.emit(`close`),this.writable=!1,this.readable=!1},t.exports=a})),hg=o(((e,t)=>{function n(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:n(256),ES384:n(384),ES512:n(521)};function i(e){var t=r[e];if(t)return t;throw Error(`Unknown algorithm "`+e+`"`)}t.exports=i})),gg=o(((e,t)=>{var n=Kh().Buffer,r=hg(),i=128,a=0,o=32,s=16,c=2,l=s|o|a<<6,u=c|a<<6;function d(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function f(e){if(n.isBuffer(e))return e;if(typeof e==`string`)return n.from(e,`base64`);throw TypeError(`ECDSA signature must be a Base64 string or a Buffer`)}function p(e,t){e=f(e);var a=r(t),o=a+1,s=e.length,c=0;if(e[c++]!==l)throw Error(`Could not find expected "seq"`);var p=e[c++];if(p===(i|1)&&(p=e[c++]),s-c<p)throw Error(`"seq" specified length of "`+p+`", only "`+(s-c)+`" remaining`);if(e[c++]!==u)throw Error(`Could not find expected "int" for "r"`);var m=e[c++];if(s-c-2<m)throw Error(`"r" specified length of "`+m+`", only "`+(s-c-2)+`" available`);if(o<m)throw Error(`"r" specified length of "`+m+`", max of "`+o+`" is acceptable`);var h=c;if(c+=m,e[c++]!==u)throw Error(`Could not find expected "int" for "s"`);var g=e[c++];if(s-c!==g)throw Error(`"s" specified length of "`+g+`", expected "`+(s-c)+`"`);if(o<g)throw Error(`"s" specified length of "`+g+`", max of "`+o+`" is acceptable`);var _=c;if(c+=g,c!==s)throw Error(`Expected to consume entire buffer, but "`+(s-c)+`" bytes remain`);var v=a-m,y=a-g,b=n.allocUnsafe(v+m+y+g);for(c=0;c<v;++c)b[c]=0;e.copy(b,c,h+Math.max(-v,0),h+m),c=a;for(var x=c;c<x+y;++c)b[c]=0;return e.copy(b,c,_+Math.max(-y,0),_+g),b=b.toString(`base64`),b=d(b),b}function m(e,t,n){for(var r=0;t+r<n&&e[t+r]===0;)++r;return e[t+r]>=i&&--r,r}function h(e,t){e=f(e);var a=r(t),o=e.length;if(o!==a*2)throw TypeError(`"`+t+`" signatures must be "`+a*2+`" bytes, saw "`+o+`"`);var s=m(e,0,a),c=m(e,a,e.length),d=a-s,p=a-c,h=2+d+1+1+p,g=h<i,_=n.allocUnsafe((g?2:3)+h),v=0;return _[v++]=l,g?_[v++]=h:(_[v++]=i|1,_[v++]=h&255),_[v++]=u,_[v++]=d,s<0?(_[v++]=0,v+=e.copy(_,v,0,a)):v+=e.copy(_,v,s,a),_[v++]=u,_[v++]=p,c<0?(_[v++]=0,e.copy(_,v,a)):e.copy(_,v,a+c),_}t.exports={derToJose:p,joseToDer:h}})),_g=o(((e,t)=>{var n=require(`buffer`).Buffer,r=require(`buffer`).SlowBuffer;t.exports=i;function i(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}i.install=function(){n.prototype.equal=r.prototype.equal=function(e){return i(this,e)}};var a=n.prototype.equal,o=r.prototype.equal;i.restore=function(){n.prototype.equal=a,r.prototype.equal=o}})),vg=o(((e,t)=>{var n=Kh().Buffer,r=require(`crypto`),i=gg(),a=require(`util`),o=`"%s" is not a valid algorithm.
459
+ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Jh=o((e=>{var t=qh().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}e.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function _(e){return e&&e.length?this.write(e):``}})),Yh=o(((e,t)=>{var n=Bh().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},_=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?_():e.on(`request`,_)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,_),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),Xh=o(((e,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=Yh(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function _(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var v=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(_(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),v);t.exports=function(e){var t,n=Object.create(y,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),Zh=o(((e,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=Bh().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),Qh=o(((e,t)=>{t.exports=E;var n;E.ReadableState=T,require(`events`).EventEmitter;var r=function(e,t){return e.listeners(t).length},i=Lh(),a=require(`buffer`).Buffer,o=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function s(e){return a.from(e)}function c(e){return a.isBuffer(e)||e instanceof o}var l=require(`util`),u=l&&l.debuglog?l.debuglog(`stream`):function(){},d=Rh(),f=zh(),p=Vh().getHighWaterMark,m=Bh().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,y,b,x;Uh()(E,i);var S=f.errorOrDestroy,C=[`error`,`close`,`destroy`,`pause`,`resume`];function w(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function T(e,t,r){n||=Kh(),e||={},typeof r!=`boolean`&&(r=t instanceof n),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,`readableHighWaterMark`,r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(y||=Jh().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=Kh(),!(this instanceof E))return new E(e);var t=this instanceof n;this._readableState=new T(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),i.call(this)}Object.defineProperty(E.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=f.destroy,E.prototype._undestroy=f.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=a.from(e,t),t=``),r=!0),D(this,e,t,!1,r)},E.prototype.unshift=function(e){return D(this,e,null,!0,!1)};function D(e,t,n,r,i){u(`readableAddChunk`,t);var o=e._readableState;if(t===null)o.reading=!1,ee(e,o);else{var c;if(i||(c=k(o,t)),c)S(e,c);else if(o.objectMode||t&&t.length>0)if(typeof t!=`string`&&!o.objectMode&&Object.getPrototypeOf(t)!==a.prototype&&(t=s(t)),r)o.endEmitted?S(e,new v):O(e,o,t,!0);else if(o.ended)S(e,new g);else if(o.destroyed)return!1;else o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||t.length!==0?O(e,o,t,!1):P(e,o)):O(e,o,t,!1);else r||(o.reading=!1,P(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function O(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&N(e)),P(e,t)}function k(e,t){var n;return!c(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new h(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}E.prototype.isPaused=function(){return this._readableState.flowing===!1},E.prototype.setEncoding=function(e){y||=Jh().StringDecoder;var t=new y(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var A=1073741824;function j(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function M(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}E.prototype.read=function(e){u(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return u(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?se(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&se(this),null;var r=t.needReadable;u(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,u(`length less than watermark`,r)),t.ended||t.reading?(r=!1,u(`reading or ended`,r)):r&&(u(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=M(n,t)));var i=e>0?L(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&se(this)),i!==null&&this.emit(`data`,i),i};function ee(e,t){if(u(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?N(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,te(e)))}}function N(e){var t=e._readableState;u(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(te,e))}function te(e){var t=e._readableState;u(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,oe(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(ne,e,t))}function ne(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(u(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}E.prototype._read=function(e){S(this,new _(`_read()`))},E.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,u(`pipe count=%d opts=%j`,i.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;i.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){u(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,d())}function s(){u(`onend`),e.end()}var c=re(n);e.on(`drain`,c);var l=!1;function d(){u(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){u(`ondata`);var r=e.write(t);u(`dest.write`,r),r===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&le(i.pipes,e)!==-1)&&!l&&(u(`false write response, pause`,i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){u(`onerror`,t),g(),e.removeListener(`error`,p),r(e,`error`)===0&&S(e,t)}w(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){u(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){u(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),i.flowing||(u(`pipe resume`),n.resume()),e};function re(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,oe(e))}}E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=le(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},E.prototype.on=function(e,t){var n=i.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u(`on readable`,r.length,r.reading),r.length?N(this):r.reading||process.nextTick(ie,this)),n},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var n=i.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(F,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(F,this),t};function F(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function ie(e){u(`readable nexttick read 0`),e.read(0)}E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u(`resume`),e.flowing=!e.readableListening,I(this,e)),e.paused=!1,this};function I(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ae,e,t))}function ae(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),oe(e),t.flowing&&!t.reading&&e.read(0)}E.prototype.pause=function(){return u(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(u(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function oe(e){var t=e._readableState;for(u(`flow`,t.flowing);t.flowing&&e.read()!==null;);}E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(u(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){u(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<C.length;a++)e.on(C[a],this.emit.bind(this,C[a]));return this._read=function(t){u(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(E.prototype[Symbol.asyncIterator]=function(){return b===void 0&&(b=Xh()),b(this)}),Object.defineProperty(E.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=L,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function L(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function se(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(ce,t,e))}function ce(e,t){if(u(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(E.from=function(e,t){return x===void 0&&(x=Zh()),x(E,e,t)});function le(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),$h=o(((e,t)=>{t.exports=l;var n=Bh().codes,r=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,s=Kh();Uh()(l,s);function c(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(r===null)return this.emit(`error`,new i);n.writechunk=null,n.writecb=null,t!=null&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform==`function`&&(this._transform=e.transform),typeof e.flush==`function`&&(this._flush=e.flush)),this.on(`prefinish`,u)}function u(){var e=this;typeof this._flush==`function`&&!this._readableState.destroyed?this._flush(function(t,n){d(e,t,n)}):d(this,null,null)}l.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},l.prototype._transform=function(e,t,n){n(new r(`_transform()`))},l.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},l.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},l.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,function(e){t(e)})};function d(e,t,n){if(t)return e.emit(`error`,t);if(n!=null&&e.push(n),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}})),eg=o(((e,t)=>{t.exports=r;var n=$h();Uh()(r,n);function r(e){if(!(this instanceof r))return new r(e);n.call(this,e)}r.prototype._transform=function(e,t,n){n(null,e)}})),tg=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Bh().codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function c(e){return e.setHeader&&typeof e.abort==`function`}function l(e,t,i,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),n===void 0&&(n=Yh()),n(e,{readable:t,writable:i},function(e){if(e)return a(e);s=!0,a()});var l=!1;return function(t){if(!s&&!l){if(l=!0,c(e))return e.abort();if(typeof e.destroy==`function`)return e.destroy();a(t||new o(`pipe`))}}}function u(e){e()}function d(e,t){return e.pipe(t)}function f(e){return!e.length||typeof e[e.length-1]!=`function`?s:e.pop()}function p(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a(`streams`);var i,o=t.map(function(e,n){var a=n<t.length-1;return l(e,a,n>0,function(e){i||=e,e&&o.forEach(u),!a&&(o.forEach(u),r(i))})});return t.reduce(d)}t.exports=p})),ng=o(((e,t)=>{var n=require(`stream`);process.env.READABLE_STREAM===`disable`&&n?(t.exports=n.Readable,Object.assign(t.exports,n),t.exports.Stream=n):(e=t.exports=Qh(),e.Stream=n||e,e.Readable=e,e.Writable=Gh(),e.Duplex=Kh(),e.Transform=$h(),e.PassThrough=eg(),e.finished=Yh(),e.pipeline=tg())})),rg=o(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),ig=o(((e,t)=>{var n=rg();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),ag=o(((e,t)=>{var n=ig(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),og=o(((e,t)=>{t.exports=n;function n(e){var t=e._readableState;return t?t.objectMode||typeof e._duplexState==`number`?e.read():e.read(r(t)):null}function r(e){if(e.buffer.length){var t=e.bufferIndex||0;if(e.buffer.head)return e.buffer.head.data.length;if(e.buffer.length-t>0&&e.buffer[t])return e.buffer[t].length}return e.length}})),sg=o(((e,t)=>{var n=ng(),r=ag(),i=Uh(),a=og(),o=Buffer.from&&Buffer.from!==Uint8Array.from?Buffer.from([0]):new Buffer([0]),s=function(e,t){e._corked?e.once(`uncork`,t):t()},c=function(e,t){e._autoDestroy&&e.destroy(t)},l=function(e,t){return function(n){n?c(e,n.message===`premature close`?null:n):t&&!e._ended&&e.end()}},u=function(e,t){if(!e||e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end(),t()},d=function(){},f=function(e){return new n.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},p=function(e,t,r){if(!(this instanceof p))return new p(e,t,r);n.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||r.autoDestroy!==!1,this._forwardDestroy=!r||r.destroy!==!1,this._forwardEnd=!r||r.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};i(p,n.Duplex),p.obj=function(e,t,n){return n||={},n.objectMode=!0,n.highWaterMark=16,new p(e,t,n)},p.prototype.cork=function(){++this._corked===1&&this.emit(`cork`)},p.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit(`uncork`)},p.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.end();return}var t=this,n=r(e,{writable:!0,readable:!1},l(this,this._forwardEnd)),i=function(){var e=t._ondrain;t._ondrain=null,e&&e()};this._unwrite&&process.nextTick(i),this._writable=e,this._writable.on(`drain`,i),this._unwrite=function(){t._writable.removeListener(`drain`,i),n()},this.uncork()},p.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed){e&&e.destroy&&e.destroy();return}if(e===null||e===!1){this.push(null),this.resume();return}var t=this,n=r(e,{writable:!1,readable:!0},l(this)),i=function(){t._forward()},a=function(){t.push(null)};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on(`readable`,i),this._readable2.on(`end`,a),this._unread=function(){t._readable2.removeListener(`readable`,i),t._readable2.removeListener(`end`,a),n()},this._forward()},p.prototype._read=function(){this._drained=!0,this._forward()},p.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var e;this._drained&&(e=a(this._readable2))!==null;)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},p.prototype.destroy=function(e,t){if(t||=d,this.destroyed)return t(null);this.destroyed=!0;var n=this;process.nextTick(function(){n._destroy(e),t(null)})},p.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit(`error`,e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit(`close`)},p.prototype._write=function(e,t,n){if(!this.destroyed){if(this._corked)return s(this,this._write.bind(this,e,t,n));if(e===o)return this._finish(n);if(!this._writable)return n();this._writable.write(e)===!1?this._ondrain=n:this.destroyed||n()}},p.prototype._finish=function(e){var t=this;this.emit(`preend`),s(this,function(){u(t._forwardEnd&&t._writable,function(){t._writableState.prefinished===!1&&(t._writableState.prefinished=!0),t.emit(`prefinish`),s(t,e)})})},p.prototype.end=function(e,t,r){return typeof e==`function`?this.end(null,null,e):typeof t==`function`?this.end(e,null,t):(this._ended=!0,e&&this.write(e),!this._writableState.ending&&!this._writableState.destroyed&&this.write(o),n.Writable.prototype.end.call(this,r))},t.exports=p})),cg=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=mh(),o=Ih(),s=sg(),c=Symbol(`ws-socket`),l=Symbol(`ws-head`),u=/HTTP\/1.1 (\d+)/u;function d(e,t,a){e.decorateRequest(`ws`,null);let d=x;if(t.errorHandler){if(typeof t.errorHandler!=`function`)return a(Error(`invalid errorHandler function`));d=t.errorHandler}let f=y;if(t?.preClose){if(typeof t.preClose!=`function`)return a(Error(`invalid preClose function`));f=t.preClose}if(t.options?.noServer)return a(Error(`fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly.`));let p=Object.assign({noServer:!0},t.options);p.path&&e.log.warn(`ws server path option shouldn't be provided, use a route instead`);let m=p.server||e.server;delete p.server;let h=new o.Server(p);e.decorate(`websocketServer`,h);async function g(e=`/`,t={},n={}){let a=new r,d=new r,f=new s(a,d),p=new s(d,a),h=new o(null,void 0,{isServer:!1}),g=Buffer.from([]),_,v,y=new Promise((e,t)=>{_=e,v=t});typeof n.onInit==`function`&&n.onInit(h),h.on(`open`,()=>{typeof n.onOpen==`function`&&n.onOpen(h),p.removeListener(`data`,b),_(h)});let b=e=>{if(e.toString().includes(`HTTP/1.1 101 Switching Protocols`))h._isServer=!1,h.setSocket(p,g,{maxPayload:0});else{p.removeListener(`data`,b);let t=Number(u.exec(e.toString())[1]);v(Error(`Unexpected server response: `+t))}};p.on(`data`,b);let x={...t,method:`GET`,headers:{...t.headers,connection:`upgrade`,upgrade:`websocket`,"sec-websocket-version":13,"sec-websocket-key":i(16).toString(`base64`)},httpVersion:`1.1`,url:e,[c]:f,[l]:g};return m.emit(`upgrade`,x,x[c],x[l]),y}e.decorate(`injectWS`,g);function _(t,r,i){t[c]=r,t[l]=i;let a=new n(t);try{a.assignSocket(r),e.routing(t,a)}catch(t){e.log.warn({err:t},`websocket upgrade failed`)}}m.on(`upgrade`,_);let v=(t,n)=>{h.handleUpgrade(t,t[c],t[l],r=>{h.emit(`connection`,r,t),r.on(`error`,t=>{e.log.error(t)}),n(r)})};e.addHook(`onRequest`,(e,t,n)=>{e.raw[c]?e.ws=!0:e.ws=!1,n()}),e.addHook(`onResponse`,(e,t,n)=>{e.ws&&e.raw[c].destroy(),n()}),e.addHook(`onRoute`,e=>{let t=!1,n=e.wsHandler,r=e.handler;if(e.websocket||e.wsHandler){if(e.method===`HEAD`)return;if(e.method!==`GET`)throw Error(`websocket handler can only be declared in GET method`);if(t=!0,e.websocket&&(e.schema||={},e.schema.hide=!0,n=e.handler,r=function(e,t){t.code(404).send()}),typeof n!=`function`)throw TypeError(`invalid wsHandler function`)}e.handler=function(e,i){if(e.raw[c])i.hijack(),v(e.raw,r=>{let a;try{a=t?n.call(this,r,e):b.call(this,r,e)}catch(t){return d.call(this,t,r,e,i)}a&&typeof a.catch==`function`&&a.catch(t=>d.call(this,t,r,e,i))});else return r.call(this,e,i)}}),e.addHook(`preClose`,f);function y(t){let n=this.websocketServer;if(n.clients)for(let e of n.clients)e.close();e.server.removeListener(`upgrade`,_),n.close(t),t()}function b(e,t){this.log.info({path:t.url},`closed incoming websocket connection for path with no websocket handler`),e.close()}function x(e,t,n){n.log.error(e),t.terminate()}a()}t.exports=a(d,{fastify:`5.x`,name:`@fastify/websocket`}),t.exports.default=d,t.exports.fastifyWebsocket=d}))(),1),lg=c(Sh(),1),ug=c(dh(),1);let dg,fg;function pg(e){!dg||dg.length<e?(dg=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(dg),fg=0):fg+e>dg.length&&(l.webcrypto.getRandomValues(dg),fg=0),fg+=e}function mg(e=21){pg(e|=0);let t=``;for(let n=fg-e;n<fg;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[dg[n]&63];return t}var hg=o(((e,t)=>{var n=qh().Buffer,r=require(`stream`),i=require(`util`);function a(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if(typeof e.pipe==`function`)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||typeof e==`object`)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit(`end`,e),this.readable=!1,this.emit(`close`)}.bind(this)),this;throw TypeError(`Unexpected data type (`+typeof e+`)`)}i.inherits(a,r),a.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit(`data`,e)},a.prototype.end=function(e){e&&this.write(e),this.emit(`end`,e),this.emit(`close`),this.writable=!1,this.readable=!1},t.exports=a})),gg=o(((e,t)=>{function n(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:n(256),ES384:n(384),ES512:n(521)};function i(e){var t=r[e];if(t)return t;throw Error(`Unknown algorithm "`+e+`"`)}t.exports=i})),_g=o(((e,t)=>{var n=qh().Buffer,r=gg(),i=128,a=0,o=32,s=16,c=2,l=s|o|a<<6,u=c|a<<6;function d(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function f(e){if(n.isBuffer(e))return e;if(typeof e==`string`)return n.from(e,`base64`);throw TypeError(`ECDSA signature must be a Base64 string or a Buffer`)}function p(e,t){e=f(e);var a=r(t),o=a+1,s=e.length,c=0;if(e[c++]!==l)throw Error(`Could not find expected "seq"`);var p=e[c++];if(p===(i|1)&&(p=e[c++]),s-c<p)throw Error(`"seq" specified length of "`+p+`", only "`+(s-c)+`" remaining`);if(e[c++]!==u)throw Error(`Could not find expected "int" for "r"`);var m=e[c++];if(s-c-2<m)throw Error(`"r" specified length of "`+m+`", only "`+(s-c-2)+`" available`);if(o<m)throw Error(`"r" specified length of "`+m+`", max of "`+o+`" is acceptable`);var h=c;if(c+=m,e[c++]!==u)throw Error(`Could not find expected "int" for "s"`);var g=e[c++];if(s-c!==g)throw Error(`"s" specified length of "`+g+`", expected "`+(s-c)+`"`);if(o<g)throw Error(`"s" specified length of "`+g+`", max of "`+o+`" is acceptable`);var _=c;if(c+=g,c!==s)throw Error(`Expected to consume entire buffer, but "`+(s-c)+`" bytes remain`);var v=a-m,y=a-g,b=n.allocUnsafe(v+m+y+g);for(c=0;c<v;++c)b[c]=0;e.copy(b,c,h+Math.max(-v,0),h+m),c=a;for(var x=c;c<x+y;++c)b[c]=0;return e.copy(b,c,_+Math.max(-y,0),_+g),b=b.toString(`base64`),b=d(b),b}function m(e,t,n){for(var r=0;t+r<n&&e[t+r]===0;)++r;return e[t+r]>=i&&--r,r}function h(e,t){e=f(e);var a=r(t),o=e.length;if(o!==a*2)throw TypeError(`"`+t+`" signatures must be "`+a*2+`" bytes, saw "`+o+`"`);var s=m(e,0,a),c=m(e,a,e.length),d=a-s,p=a-c,h=2+d+1+1+p,g=h<i,_=n.allocUnsafe((g?2:3)+h),v=0;return _[v++]=l,g?_[v++]=h:(_[v++]=i|1,_[v++]=h&255),_[v++]=u,_[v++]=d,s<0?(_[v++]=0,v+=e.copy(_,v,0,a)):v+=e.copy(_,v,s,a),_[v++]=u,_[v++]=p,c<0?(_[v++]=0,e.copy(_,v,a)):e.copy(_,v,a+c),_}t.exports={derToJose:p,joseToDer:h}})),vg=o(((e,t)=>{var n=require(`buffer`).Buffer,r=require(`buffer`).SlowBuffer;t.exports=i;function i(e,t){if(!n.isBuffer(e)||!n.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}i.install=function(){n.prototype.equal=r.prototype.equal=function(e){return i(this,e)}};var a=n.prototype.equal,o=r.prototype.equal;i.restore=function(){n.prototype.equal=a,r.prototype.equal=o}})),yg=o(((e,t)=>{var n=qh().Buffer,r=require(`crypto`),i=_g(),a=require(`util`),o=`"%s" is not a valid algorithm.
460
460
  Supported algorithms are:
461
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=_g(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),yg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),bg=o(((e,t)=>{var n=Kh().Buffer,r=mg(),i=vg(),a=require(`stream`),o=yg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),xg=o(((e,t)=>{var n=Kh().Buffer,r=mg(),i=vg(),a=require(`stream`),o=yg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),Sg=o((e=>{var t=bg(),n=xg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),Cg=o(((e,t)=>{var n=Sg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),wg=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),Tg=o(((e,t)=>{var n=wg(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),Eg=o(((e,t)=>{var n=wg(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),Dg=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Og=o(((e,t)=>{var n=Dg();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),kg=o(((e,t)=>{t.exports=vm().satisfies(process.version,`>=15.7.0`)})),Ag=o(((e,t)=>{t.exports=vm().satisfies(process.version,`>=16.9.0`)})),jg=o(((e,t)=>{let n=kg(),r=Ag(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),Mg=o(((e,t)=>{t.exports=vm().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Ng=o(((e,t)=>{let n=wg(),r=Tg(),i=Eg(),a=Cg(),o=Og(),s=jg(),c=Mg(),l=Sg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Pg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:de(e),n=n&&!r?ce(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),oe(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return re(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&ie(e.length)&&!F(e)}function re(e){return ae(e)&&ne(e)}function F(e){var t=I(e)?E.call(e):``;return t==s||t==c}function ie(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function I(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ae(e){return!!e&&typeof e==`object`}function oe(e){return typeof e==`string`||!P(e)&&ae(e)&&E.call(e)==l}function L(e){return typeof e==`symbol`||ae(e)&&E.call(e)==u}function se(e){return e?(e=le(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function ce(e){var t=se(e),n=t%1;return t===t?n?t-n:t:0}function le(e){if(typeof e==`number`)return e;if(L(e))return a;if(I(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=I(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function ue(e){return ne(e)?A(e):j(e)}function de(e){return e?S(e,ue(e)):[]}t.exports=N})),Fg=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),Ig=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),Lg=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),Rg=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),zg=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Bg=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Vg=o(((e,t)=>{let n=Og(),r=Mg(),i=jg(),a=Sg(),o=Pg(),s=Fg(),c=Ig(),l=Lg(),u=Rg(),d=zg(),f=Bg(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Hg=c(o(((e,t)=>{t.exports={decode:Cg(),verify:Ng(),sign:Vg(),JsonWebTokenError:wg(),NotBeforeError:Tg(),TokenExpiredError:Eg()}}))(),1),Ug=c(sd(),1),Wg=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Gg(e){return e instanceof Wg}function Kg(){return new Wg({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function qg(){return new Wg({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Jg(){return new Wg({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function Yg(e=`Device revoked`){return new Wg({code:`DEVICE_REVOKED`,status:401,message:e})}function Xg(){return new Wg({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function Zg(e){return new Wg({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function Qg(e,t){return new Wg({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function $g(e){return new Wg({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function e_(e){return new Wg({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function t_(e){return new Wg({code:`CODEX_APP_SERVER_RESTART_CONFLICT`,status:409,message:`Codex app-server restart requires idle runtime, found ${e} running session${e===1?``:`s`}`})}function n_(e){return new Wg({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function r_(){return new Wg({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function i_(){return new Wg({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function a_(e){return new Wg({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function o_(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var s_=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=c_(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw Kg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),qg();this.pairingCodes.delete(e);let i=`dev_${pg(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...o,gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Hg.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n||n.revoked)throw Jg();let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Yg();let i=new Date().toISOString();n.revoked=!0,n.revokedAt=i,this.refreshTokens.set(t.jti,n);let a=this.issueTokenPair(t.sub);return await this.persistState(),{...a,deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Hg.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw Yg(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw Yg(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw r_();if(!u_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw i_();if(n.identityStatus!==`active`)throw a_(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}inspectRefreshToken(e){let t=Hg.default.decode(e),n=t&&typeof t==`object`?t:null,r=typeof n?.jti==`string`?n.jti:void 0,i=typeof n?.sub==`string`?n.sub:void 0,a=r?this.refreshTokens.get(r):void 0,o=i||a?.deviceId?[...this.refreshTokens.values()].filter(e=>e.deviceId===(i??a?.deviceId)&&!e.revoked).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]:void 0;return{claimDeviceId:i,claimExpAt:typeof n?.exp==`number`?new Date(n.exp*1e3).toISOString():void 0,claimIssuedAt:typeof n?.iat==`number`?new Date(n.iat*1e3).toISOString():void 0,claimJti:r,claimType:typeof n?.type==`string`?n.type:void 0,latestActiveTokenCreatedAt:o?.createdAt,latestActiveTokenJti:o?.jti,tokenRecordCreatedAt:a?.createdAt,tokenRecordDeviceId:a?.deviceId,tokenRecordRevokedAt:a?.revokedAt,tokenRecordState:a?a.revoked?`revoked`:`active`:`missing`}}issueTokenPair(e){let t=Hg.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${pg(14)}`,r=Hg.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Hg.default.decode(r);this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0});let a=Hg.default.decode(t);return{accessToken:t,refreshToken:r,expiresInSeconds:a.exp-a.iat}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await f_(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await f_(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await f_(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:l_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return d_(this.pairingCodes,e),d_(this.devices,t),d_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function c_(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function l_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function u_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function d_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function f_(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var p_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function m_(){}m_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(h_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(h_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function h_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new m_;function g_(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function __(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function v_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function y_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function b_(e,t){return v_(e,t,``)}function x_(e,t){return y_(e,t,``)}function S_(e,t){return t.slice(0,C_(e,t))}function C_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var w_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,T_=RegExp(`[${w_}]+|\\s+|[^${w_}]`,`ug`),E_=new m_;E_.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},E_.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(T_)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},E_.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},E_.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&D_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&D_(n,i,r,null),e};function D_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=g_(i,o);e.value=y_(e.value,o,c),t.value=b_(t.value,c),n.value=b_(n.value,c)}if(r){var l=__(a,s);r.value=v_(r.value,s,l),t.value=x_(t.value,l),n.value=x_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=g_(u,d);t.value=b_(t.value,p);var m=__(b_(u,p),f);t.value=x_(t.value,m),r.value=v_(r.value,u,m),e.value=y_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=S_(g,h);t.value=x_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=S_(v,y);t.value=b_(t.value,b)}}var O_=new m_;O_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${w_}]+|[^\\S\\n\\r]+|[^${w_}]`,`ug`);return e.match(t)||[]};var k_=new m_;k_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
462
- `));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var i=0;i<r.length;i++){var a=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n},k_.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
461
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,s=`secret must be a string or buffer`,c=`key must be a string or a buffer`,l=`key must be a string, a buffer or an object`,u=typeof r.createPublicKey==`function`;u&&(c+=` or a KeyObject`,s+=`or a KeyObject`);function d(e){if(!n.isBuffer(e)&&typeof e!=`string`&&(!u||typeof e!=`object`||typeof e.type!=`string`||typeof e.asymmetricKeyType!=`string`||typeof e.export!=`function`))throw g(c)}function f(e){if(!n.isBuffer(e)&&typeof e!=`string`&&typeof e!=`object`)throw g(l)}function p(e){if(!n.isBuffer(e)){if(typeof e==`string`)return e;if(!u||typeof e!=`object`||e.type!==`secret`||typeof e.export!=`function`)throw g(s)}}function m(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function h(e){e=e.toString();var t=4-e.length%4;if(t!==4)for(var n=0;n<t;++n)e+=`=`;return e.replace(/\-/g,`+`).replace(/_/g,`/`)}function g(e){var t=[].slice.call(arguments,1),n=a.format.bind(a,e).apply(null,t);return TypeError(n)}function _(e){return n.isBuffer(e)||typeof e==`string`}function v(e){return _(e)||(e=JSON.stringify(e)),e}function y(e){return function(t,n){p(n),t=v(t);var i=r.createHmac(`sha`+e,n);return m((i.update(t),i.digest(`base64`)))}}var b,x=`timingSafeEqual`in r?function(e,t){return e.byteLength===t.byteLength?r.timingSafeEqual(e,t):!1}:function(e,t){return b||=vg(),b(e,t)};function S(e){return function(t,r,i){var a=y(e)(t,i);return x(n.from(r),n.from(a))}}function C(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign(n,`base64`)))}}function w(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify(i,n,`base64`)}}function T(e){return function(t,n){f(n),t=v(t);var i=r.createSign(`RSA-SHA`+e);return m((i.update(t),i.sign({key:n,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},`base64`)))}}function E(e){return function(t,n,i){d(i),t=v(t),n=h(n);var a=r.createVerify(`RSA-SHA`+e);return a.update(t),a.verify({key:i,padding:r.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.constants.RSA_PSS_SALTLEN_DIGEST},n,`base64`)}}function D(e){var t=C(e);return function(){var n=t.apply(null,arguments);return n=i.derToJose(n,`ES`+e),n}}function O(e){var t=w(e);return function(n,r,a){return r=i.joseToDer(r,`ES`+e).toString(`base64`),t(n,r,a)}}function k(){return function(){return``}}function A(){return function(e,t){return t===``}}t.exports=function(e){var t={hs:y,rs:C,ps:T,es:D,none:k},n={hs:S,rs:w,ps:E,es:O,none:A},r=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!r)throw g(o,e);var i=(r[1]||r[3]).toLowerCase(),a=r[2];return{sign:t[i](a),verify:n[i](a)}}})),bg=o(((e,t)=>{var n=require(`buffer`).Buffer;t.exports=function(e){return typeof e==`string`?e:typeof e==`number`||n.isBuffer(e)?e.toString():JSON.stringify(e)}})),xg=o(((e,t)=>{var n=qh().Buffer,r=hg(),i=yg(),a=require(`stream`),o=bg(),s=require(`util`);function c(e,t){return n.from(e,t).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function l(e,t,n){n||=`utf8`;var r=c(o(e),`binary`),i=c(o(t),n);return s.format(`%s.%s`,r,i)}function u(e){var t=e.header,n=e.payload,r=e.secret||e.privateKey,a=e.encoding,o=i(t.alg),c=l(t,n,a),u=o.sign(c,r);return s.format(`%s.%s`,c,u)}function d(e){var t=e.secret;if(t??=e.privateKey,t??=e.key,/^hs/i.test(e.header.alg)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=n,this.payload=new r(e.payload),this.secret.once(`close`,function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once(`close`,function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}s.inherits(d,a),d.prototype.sign=function(){try{var e=u({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit(`done`,e),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},d.sign=u,t.exports=d})),Sg=o(((e,t)=>{var n=qh().Buffer,r=hg(),i=yg(),a=require(`stream`),o=bg(),s=require(`util`),c=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){if(l(e))return e;try{return JSON.parse(e)}catch{return}}function d(e){var t=e.split(`.`,1)[0];return u(n.from(t,`base64`).toString(`binary`))}function f(e){return e.split(`.`,2).join(`.`)}function p(e){return e.split(`.`)[2]}function m(e,t){t||=`utf8`;var r=e.split(`.`)[1];return n.from(r,`base64`).toString(t)}function h(e){return c.test(e)&&!!d(e)}function g(e,t,n){if(!t){var r=Error(`Missing algorithm parameter for jws.verify`);throw r.code=`MISSING_ALGORITHM`,r}e=o(e);var a=p(e),s=f(e);return i(t).verify(s,a,n)}function _(e,t){if(t||={},e=o(e),!h(e))return null;var n=d(e);if(!n)return null;var r=m(e);return(n.typ===`JWT`||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:p(e)}}function v(e){e||={};var t=e.secret;if(t??=e.publicKey,t??=e.key,/^hs/i.test(e.algorithm)===!0&&t==null)throw TypeError(`secret must be a string or buffer or a KeyObject`);var n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once(`close`,function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once(`close`,function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}s.inherits(v,a),v.prototype.verify=function(){try{var e=g(this.signature.buffer,this.algorithm,this.key.buffer),t=_(this.signature.buffer,this.encoding);return this.emit(`done`,e,t),this.emit(`data`,e),this.emit(`end`),this.readable=!1,e}catch(e){this.readable=!1,this.emit(`error`,e),this.emit(`close`)}},v.decode=_,v.isValid=h,v.verify=g,t.exports=v})),Cg=o((e=>{var t=xg(),n=Sg();e.ALGORITHMS=[`HS256`,`HS384`,`HS512`,`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`],e.sign=t.sign,e.verify=n.verify,e.decode=n.decode,e.isValid=n.isValid,e.createSign=function(e){return new t(e)},e.createVerify=function(e){return new n(e)}})),wg=o(((e,t)=>{var n=Cg();t.exports=function(e,t){t||={};var r=n.decode(e,t);if(!r)return null;var i=r.payload;if(typeof i==`string`)try{var a=JSON.parse(i);typeof a==`object`&&a&&(i=a)}catch{}return t.complete===!0?{header:r.header,payload:i,signature:r.signature}:i}})),Tg=o(((e,t)=>{var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=`JsonWebTokenError`,this.message=e,t&&(this.inner=t)};n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports=n})),Eg=o(((e,t)=>{var n=Tg(),r=function(e,t){n.call(this,e),this.name=`NotBeforeError`,this.date=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),Dg=o(((e,t)=>{var n=Tg(),r=function(e,t){n.call(this,e),this.name=`TokenExpiredError`,this.expiredAt=t};r.prototype=Object.create(n.prototype),r.prototype.constructor=r,t.exports=r})),Og=o(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),kg=o(((e,t)=>{var n=Og();t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if(typeof e==`string`){var i=n(e);return i===void 0?void 0:Math.floor(r+i/1e3)}else if(typeof e==`number`)return r+e;else return}})),Ag=o(((e,t)=>{t.exports=ym().satisfies(process.version,`>=15.7.0`)})),jg=o(((e,t)=>{t.exports=ym().satisfies(process.version,`>=16.9.0`)})),Mg=o(((e,t)=>{let n=Ag(),r=jg(),i={ec:[`ES256`,`ES384`,`ES512`],rsa:[`RS256`,`PS256`,`RS384`,`PS384`,`RS512`,`PS512`],"rsa-pss":[`PS256`,`PS384`,`PS512`]},a={ES256:`prime256v1`,ES384:`secp384r1`,ES512:`secp521r1`};t.exports=function(e,t){if(!e||!t)return;let o=t.asymmetricKeyType;if(!o)return;let s=i[o];if(!s)throw Error(`Unknown key type "${o}".`);if(!s.includes(e))throw Error(`"alg" parameter for "${o}" key type must be one of: ${s.join(`, `)}.`);if(n)switch(o){case`ec`:let n=t.asymmetricKeyDetails.namedCurve,i=a[e];if(n!==i)throw Error(`"alg" parameter "${e}" requires curve "${i}".`);break;case`rsa-pss`:if(r){let n=parseInt(e.slice(-3),10),{hashAlgorithm:r,mgf1HashAlgorithm:i,saltLength:a}=t.asymmetricKeyDetails;if(r!==`sha${n}`||i!==r)throw Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}.`);if(a!==void 0&&a>n>>3)throw Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}.`)}break}}})),Ng=o(((e,t)=>{t.exports=ym().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Pg=o(((e,t)=>{let n=Tg(),r=Eg(),i=Dg(),a=wg(),o=kg(),s=Mg(),c=Ng(),l=Cg(),{KeyObject:u,createSecretKey:d,createPublicKey:f}=require(`crypto`),p=[`RS256`,`RS384`,`RS512`],m=[`ES256`,`ES384`,`ES512`],h=[`RS256`,`RS384`,`RS512`],g=[`HS256`,`HS384`,`HS512`];c&&(p.splice(p.length,0,`PS256`,`PS384`,`PS512`),h.splice(h.length,0,`PS256`,`PS384`,`PS512`)),t.exports=function(e,t,c,_){typeof c==`function`&&!_&&(_=c,c={}),c||={},c=Object.assign({},c);let v;if(v=_||function(e,t){if(e)throw e;return t},c.clockTimestamp&&typeof c.clockTimestamp!=`number`)return v(new n(`clockTimestamp must be a number`));if(c.nonce!==void 0&&(typeof c.nonce!=`string`||c.nonce.trim()===``))return v(new n(`nonce must be a non-empty string`));if(c.allowInvalidAsymmetricKeyTypes!==void 0&&typeof c.allowInvalidAsymmetricKeyTypes!=`boolean`)return v(new n(`allowInvalidAsymmetricKeyTypes must be a boolean`));let y=c.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return v(new n(`jwt must be provided`));if(typeof e!=`string`)return v(new n(`jwt must be a string`));let b=e.split(`.`);if(b.length!==3)return v(new n(`jwt malformed`));let x;try{x=a(e,{complete:!0})}catch(e){return v(e)}if(!x)return v(new n(`invalid token`));let S=x.header,C;if(typeof t==`function`){if(!_)return v(new n(`verify must be called asynchronous if secret or public key is provided as a callback`));C=t}else C=function(e,n){return n(null,t)};return C(S,function(t,a){if(t)return v(new n(`error in secret or public key callback: `+t.message));let _=b[2].trim()!==``;if(!_&&a)return v(new n(`jwt signature is required`));if(_&&!a)return v(new n(`secret or public key must be provided`));if(!_&&!c.algorithms)return v(new n(`please specify "none" in "algorithms" to verify unsigned tokens`));if(a!=null&&!(a instanceof u))try{a=f(a)}catch{try{a=d(typeof a==`string`?Buffer.from(a):a)}catch{return v(new n(`secretOrPublicKey is not valid key material`))}}if(c.algorithms||(a.type===`secret`?c.algorithms=g:[`rsa`,`rsa-pss`].includes(a.asymmetricKeyType)?c.algorithms=h:a.asymmetricKeyType===`ec`?c.algorithms=m:c.algorithms=p),c.algorithms.indexOf(x.header.alg)===-1)return v(new n(`invalid algorithm`));if(S.alg.startsWith(`HS`)&&a.type!==`secret`)return v(new n(`secretOrPublicKey must be a symmetric key when using ${S.alg}`));if(/^(?:RS|PS|ES)/.test(S.alg)&&a.type!==`public`)return v(new n(`secretOrPublicKey must be an asymmetric key when using ${S.alg}`));if(!c.allowInvalidAsymmetricKeyTypes)try{s(S.alg,a)}catch(e){return v(e)}let C;try{C=l.verify(e,x.header.alg,a)}catch(e){return v(e)}if(!C)return v(new n(`invalid signature`));let w=x.payload;if(w.nbf!==void 0&&!c.ignoreNotBefore){if(typeof w.nbf!=`number`)return v(new n(`invalid nbf value`));if(w.nbf>y+(c.clockTolerance||0))return v(new r(`jwt not active`,new Date(w.nbf*1e3)))}if(w.exp!==void 0&&!c.ignoreExpiration){if(typeof w.exp!=`number`)return v(new n(`invalid exp value`));if(y>=w.exp+(c.clockTolerance||0))return v(new i(`jwt expired`,new Date(w.exp*1e3)))}if(c.audience){let e=Array.isArray(c.audience)?c.audience:[c.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(t){return e.some(function(e){return e instanceof RegExp?e.test(t):e===t})}))return v(new n(`jwt audience invalid. expected: `+e.join(` or `)))}if(c.issuer&&(typeof c.issuer==`string`&&w.iss!==c.issuer||Array.isArray(c.issuer)&&c.issuer.indexOf(w.iss)===-1))return v(new n(`jwt issuer invalid. expected: `+c.issuer));if(c.subject&&w.sub!==c.subject)return v(new n(`jwt subject invalid. expected: `+c.subject));if(c.jwtid&&w.jti!==c.jwtid)return v(new n(`jwt jwtid invalid. expected: `+c.jwtid));if(c.nonce&&w.nonce!==c.nonce)return v(new n(`jwt nonce invalid. expected: `+c.nonce));if(c.maxAge){if(typeof w.iat!=`number`)return v(new n(`iat required when maxAge is specified`));let e=o(c.maxAge,w.iat);if(e===void 0)return v(new n(`"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`));if(y>=e+(c.clockTolerance||0))return v(new i(`maxAge exceeded`,new Date(e*1e3)))}if(c.complete===!0){let e=x.signature;return v(null,{header:S,payload:w,signature:e})}return v(null,w)})}})),Fg=o(((e,t)=>{var n=1/0,r=9007199254740991,i=17976931348623157e292,a=NaN,o=`[object Arguments]`,s=`[object Function]`,c=`[object GeneratorFunction]`,l=`[object String]`,u=`[object Symbol]`,d=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,m=/^0o[0-7]+$/i,h=/^(?:0|[1-9]\d*)$/,g=parseInt;function _(e,t){for(var n=-1,r=e?e.length:0,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}function v(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a<i;)if(t(e[a],a,e))return a;return-1}function y(e,t,n){if(t!==t)return v(e,b,n);for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}function b(e){return e!==e}function x(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function S(e,t){return _(t,function(t){return e[t]})}function C(e,t){return function(n){return e(t(n))}}var w=Object.prototype,T=w.hasOwnProperty,E=w.toString,D=w.propertyIsEnumerable,O=C(Object.keys,Object),k=Math.max;function A(e,t){var n=P(e)||te(e)?x(e.length,String):[],r=n.length,i=!!r;for(var a in e)(t||T.call(e,a))&&!(i&&(a==`length`||M(a,r)))&&n.push(a);return n}function j(e){if(!ee(e))return O(e);var t=[];for(var n in Object(e))T.call(e,n)&&n!=`constructor`&&t.push(n);return t}function M(e,t){return t??=r,!!t&&(typeof e==`number`||h.test(e))&&e>-1&&e%1==0&&e<t}function ee(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||w)}function N(e,t,n,r){e=ne(e)?e:de(e),n=n&&!r?ce(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),oe(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return re(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function ne(e){return e!=null&&ie(e.length)&&!F(e)}function re(e){return ae(e)&&ne(e)}function F(e){var t=I(e)?E.call(e):``;return t==s||t==c}function ie(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function I(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ae(e){return!!e&&typeof e==`object`}function oe(e){return typeof e==`string`||!P(e)&&ae(e)&&E.call(e)==l}function L(e){return typeof e==`symbol`||ae(e)&&E.call(e)==u}function se(e){return e?(e=le(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function ce(e){var t=se(e),n=t%1;return t===t?n?t-n:t:0}function le(e){if(typeof e==`number`)return e;if(L(e))return a;if(I(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=I(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(d,``);var n=p.test(e);return n||m.test(e)?g(e.slice(2),n?2:8):f.test(e)?a:+e}function ue(e){return ne(e)?A(e):j(e)}function de(e){return e?S(e,ue(e)):[]}t.exports=N})),Ig=o(((e,t)=>{var n=`[object Boolean]`,r=Object.prototype.toString;function i(e){return e===!0||e===!1||a(e)&&r.call(e)==n}function a(e){return!!e&&typeof e==`object`}t.exports=i})),Lg=o(((e,t)=>{var n=1/0,r=17976931348623157e292,i=NaN,a=`[object Symbol]`,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt,d=Object.prototype.toString;function f(e){return typeof e==`number`&&e==_(e)}function p(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&d.call(e)==a}function g(e){return e?(e=v(e),e===n||e===-n?(e<0?-1:1)*r:e===e?e:0):e===0?e:0}function _(e){var t=g(e),n=t%1;return t===t?n?t-n:t:0}function v(e){if(typeof e==`number`)return e;if(h(e))return i;if(p(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=p(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(o,``);var n=c.test(e);return n||l.test(e)?u(e.slice(2),n?2:8):s.test(e)?i:+e}t.exports=f})),Rg=o(((e,t)=>{var n=`[object Number]`,r=Object.prototype.toString;function i(e){return!!e&&typeof e==`object`}function a(e){return typeof e==`number`||i(e)&&r.call(e)==n}t.exports=a})),zg=o(((e,t)=>{var n=`[object Object]`;function r(e){var t=!1;if(e!=null&&typeof e.toString!=`function`)try{t=!!(e+``)}catch{}return t}function i(e,t){return function(n){return e(t(n))}}var a=Function.prototype,o=Object.prototype,s=a.toString,c=o.hasOwnProperty,l=s.call(Object),u=o.toString,d=i(Object.getPrototypeOf,Object);function f(e){return!!e&&typeof e==`object`}function p(e){if(!f(e)||u.call(e)!=n||r(e))return!1;var t=d(e);if(t===null)return!0;var i=c.call(t,`constructor`)&&t.constructor;return typeof i==`function`&&i instanceof i&&s.call(i)==l}t.exports=p})),Bg=o(((e,t)=>{var n=`[object String]`,r=Object.prototype.toString,i=Array.isArray;function a(e){return!!e&&typeof e==`object`}function o(e){return typeof e==`string`||!i(e)&&a(e)&&r.call(e)==n}t.exports=o})),Vg=o(((e,t)=>{var n=`Expected a function`,r=1/0,i=17976931348623157e292,a=NaN,o=`[object Symbol]`,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,f=Object.prototype.toString;function p(e,t){var r;if(typeof t!=`function`)throw TypeError(n);return e=y(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function m(e){return p(2,e)}function h(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function g(e){return!!e&&typeof e==`object`}function _(e){return typeof e==`symbol`||g(e)&&f.call(e)==o}function v(e){return e?(e=b(e),e===r||e===-r?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function y(e){var t=v(e),n=t%1;return t===t?n?t-n:t:0}function b(e){if(typeof e==`number`)return e;if(_(e))return a;if(h(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=h(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=e.replace(s,``);var n=l.test(e);return n||u.test(e)?d(e.slice(2),n?2:8):c.test(e)?a:+e}t.exports=m})),Hg=o(((e,t)=>{let n=kg(),r=Ng(),i=Mg(),a=Cg(),o=Fg(),s=Ig(),c=Lg(),l=Rg(),u=zg(),d=Bg(),f=Vg(),{KeyObject:p,createSecretKey:m,createPrivateKey:h}=require(`crypto`),g=[`RS256`,`RS384`,`RS512`,`ES256`,`ES384`,`ES512`,`HS256`,`HS384`,`HS512`,`none`];r&&g.splice(3,0,`PS256`,`PS384`,`PS512`);let _={expiresIn:{isValid:function(e){return c(e)||d(e)&&e},message:`"expiresIn" should be a number of seconds or string representing a timespan`},notBefore:{isValid:function(e){return c(e)||d(e)&&e},message:`"notBefore" should be a number of seconds or string representing a timespan`},audience:{isValid:function(e){return d(e)||Array.isArray(e)},message:`"audience" must be a string or array`},algorithm:{isValid:o.bind(null,g),message:`"algorithm" must be a valid string enum value`},header:{isValid:u,message:`"header" must be an object`},encoding:{isValid:d,message:`"encoding" must be a string`},issuer:{isValid:d,message:`"issuer" must be a string`},subject:{isValid:d,message:`"subject" must be a string`},jwtid:{isValid:d,message:`"jwtid" must be a string`},noTimestamp:{isValid:s,message:`"noTimestamp" must be a boolean`},keyid:{isValid:d,message:`"keyid" must be a string`},mutatePayload:{isValid:s,message:`"mutatePayload" must be a boolean`},allowInsecureKeySizes:{isValid:s,message:`"allowInsecureKeySizes" must be a boolean`},allowInvalidAsymmetricKeyTypes:{isValid:s,message:`"allowInvalidAsymmetricKeyTypes" must be a boolean`}},v={iat:{isValid:l,message:`"iat" should be a number of seconds`},exp:{isValid:l,message:`"exp" should be a number of seconds`},nbf:{isValid:l,message:`"nbf" should be a number of seconds`}};function y(e,t,n,r){if(!u(n))throw Error(`Expected "`+r+`" to be a plain object.`);Object.keys(n).forEach(function(i){let a=e[i];if(!a){if(!t)throw Error(`"`+i+`" is not allowed in "`+r+`"`);return}if(!a.isValid(n[i]))throw Error(a.message)})}function b(e){return y(_,!1,e,`options`)}function x(e){return y(v,!0,e,`payload`)}let S={audience:`aud`,issuer:`iss`,subject:`sub`,jwtid:`jti`},C=[`expiresIn`,`notBefore`,`noTimestamp`,`audience`,`issuer`,`subject`,`jwtid`];t.exports=function(e,t,r,o){typeof r==`function`?(o=r,r={}):r||={};let s=typeof e==`object`&&!Buffer.isBuffer(e),c=Object.assign({alg:r.algorithm||`HS256`,typ:s?`JWT`:void 0,kid:r.keyid},r.header);function l(e){if(o)return o(e);throw e}if(!t&&r.algorithm!==`none`)return l(Error(`secretOrPrivateKey must have a value`));if(t!=null&&!(t instanceof p))try{t=h(t)}catch{try{t=m(typeof t==`string`?Buffer.from(t):t)}catch{return l(Error(`secretOrPrivateKey is not valid key material`))}}if(c.alg.startsWith(`HS`)&&t.type!==`secret`)return l(Error(`secretOrPrivateKey must be a symmetric key when using ${c.alg}`));if(/^(?:RS|PS|ES)/.test(c.alg)){if(t.type!==`private`)return l(Error(`secretOrPrivateKey must be an asymmetric key when using ${c.alg}`));if(!r.allowInsecureKeySizes&&!c.alg.startsWith(`ES`)&&t.asymmetricKeyDetails!==void 0&&t.asymmetricKeyDetails.modulusLength<2048)return l(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`))}if(e===void 0)return l(Error(`payload is required`));if(s){try{x(e)}catch(e){return l(e)}r.mutatePayload||(e=Object.assign({},e))}else{let t=C.filter(function(e){return r[e]!==void 0});if(t.length>0)return l(Error(`invalid `+t.join(`,`)+` option for `+typeof e+` payload`))}if(e.exp!==void 0&&r.expiresIn!==void 0)return l(Error(`Bad "options.expiresIn" option the payload already has an "exp" property.`));if(e.nbf!==void 0&&r.notBefore!==void 0)return l(Error(`Bad "options.notBefore" option the payload already has an "nbf" property.`));try{b(r)}catch(e){return l(e)}if(!r.allowInvalidAsymmetricKeyTypes)try{i(c.alg,t)}catch(e){return l(e)}let u=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:s&&(e.iat=u),r.notBefore!==void 0){try{e.nbf=n(r.notBefore,u)}catch(e){return l(e)}if(e.nbf===void 0)return l(Error(`"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}if(r.expiresIn!==void 0&&typeof e==`object`){try{e.exp=n(r.expiresIn,u)}catch(e){return l(e)}if(e.exp===void 0)return l(Error(`"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60`))}Object.keys(S).forEach(function(t){let n=S[t];if(r[t]!==void 0){if(e[n]!==void 0)return l(Error(`Bad "options.`+t+`" option. The payload already has an "`+n+`" property.`));e[n]=r[t]}});let d=r.encoding||`utf8`;if(typeof o==`function`)o&&=f(o),a.createSign({header:c,privateKey:t,payload:e,encoding:d}).once(`error`,o).once(`done`,function(e){if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&e.length<256)return o(Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`));o(null,e)});else{let n=a.sign({header:c,payload:e,secret:t,encoding:d});if(!r.allowInsecureKeySizes&&/^(?:RS|PS)/.test(c.alg)&&n.length<256)throw Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${c.alg}`);return n}}})),Ug=c(o(((e,t)=>{t.exports={decode:wg(),verify:Pg(),sign:Hg(),JsonWebTokenError:Tg(),NotBeforeError:Eg(),TokenExpiredError:Dg()}}))(),1),Wg=c(cd(),1),Gg=class extends Error{code;status;details;constructor(e){super(e.message),this.name=`Error`,this.code=e.code,this.status=e.status,this.details=e.details}};function Kg(e){return e instanceof Gg}function qg(){return new Gg({code:`PAIRING_CODE_INVALID`,status:400,message:`Invalid pairing code`})}function Jg(){return new Gg({code:`PAIRING_CODE_EXPIRED`,status:400,message:`Pairing code expired`})}function Yg(){return new Gg({code:`REFRESH_TOKEN_REVOKED`,status:401,message:`Refresh token revoked`})}function Xg(e=`Device revoked`){return new Gg({code:`DEVICE_REVOKED`,status:401,message:e})}function Zg(){return new Gg({code:`REFRESH_TOKEN_DEVICE_MISMATCH`,status:401,message:`Refresh token device mismatch`})}function Qg(e){return new Gg({code:`PROJECT_NOT_FOUND`,status:404,message:`Project not found: ${e}`})}function $g(e,t){return new Gg({code:`PROJECT_SESSION_NOT_FOUND`,status:404,message:`Session ${t} not found in project ${e}`})}function e_(e){return new Gg({code:`SESSION_NOT_FOUND`,status:404,message:`Session not found: ${e}`})}function t_(e){return new Gg({code:`PROJECT_DELETE_CONFLICT`,status:409,message:`Cannot delete project ${e} while sessions are running`})}function n_(e){return new Gg({code:`CODEX_APP_SERVER_RESTART_CONFLICT`,status:409,message:`Codex app-server restart requires idle runtime, found ${e} running session${e===1?``:`s`}`})}function r_(e){return new Gg({code:`DISCOVERED_PROJECT_NOT_FOUND`,status:404,message:`Discovered project not found: ${e}`})}function i_(){return new Gg({code:`DEVICE_IDENTITY_NOT_REGISTERED`,status:400,message:`Device identity not registered`})}function a_(){return new Gg({code:`DEVICE_IDENTITY_MISMATCH`,status:400,message:`Device identity mismatch`})}function o_(e){return new Gg({code:`DEVICE_IDENTITY_NOT_ACTIVE`,status:400,message:`Device identity not active: ${e}`})}function s_(e){return e instanceof Error&&(e.name===`TokenExpiredError`||e.name===`JsonWebTokenError`||e.name===`NotBeforeError`)}var c_=class{indexPath;pairingCodes=new Map;devices=new Map;refreshTokens=new Map;ready;mutationQueue=Promise.resolve();constructor(e){this.config=e,this.indexPath=p.default.join(e.authStoreDir,`auth-state.json`),this.ready=this.loadFromDisk()}async init(){await this.ready}async createPairingCode(e=300){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=l_(),n=Date.now()+e*1e3;return this.pairingCodes.set(t,{code:t,expiresAtMs:n}),await this.persistState(),{code:t,expiresAt:new Date(n).toISOString()}})}async claimPairingCode(e,t,n){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let r=this.pairingCodes.get(e);if(!r)throw qg();if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),Jg();this.pairingCodes.delete(e);let i=`dev_${mg(12)}`,a=new Date().toISOString();this.devices.set(i,{id:i,name:t,createdAt:a,identityAlgorithm:n?.algorithm,publicKey:n?.publicKey,publicKeyFingerprint:n?.publicKeyFingerprint,identityStatus:n?`active`:void 0,lastVerifiedAt:n?a:void 0});let o=this.issueTokenPair(i);return await this.persistState(),{...o,gatewayId:this.config.gatewayId,deviceId:i,deviceIdentityFingerprint:n?.publicKeyFingerprint,deviceIdentityStatus:n?`active`:void 0}})}async refreshAccessToken(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=Ug.default.verify(e,this.config.refreshSecret);if(t.type!==`refresh`)throw Error(`Invalid token type`);let n=this.refreshTokens.get(t.jti);if(!n||n.revoked)throw Yg();let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Xg();let i=new Date().toISOString();n.revoked=!0,n.revokedAt=i,this.refreshTokens.set(t.jti,n);let a=this.issueTokenPair(t.sub);return await this.persistState(),{...a,deviceId:t.sub,deviceIdentityFingerprint:r.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus}})}verifyAccessToken(e){let t=Ug.default.verify(e,this.config.accessSecret);if(t.type!==`access`)throw Error(`Invalid token type`);let n=this.devices.get(t.sub);if(!n||n.revokedAt)throw Xg(`Device revoked or not found`);return t}async revokeDevice(e){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let t=this.devices.get(e);if(!t)return!1;let n=new Date().toISOString();t.revokedAt=n,t.identityStatus=`revoked`,this.devices.set(e,t);for(let t of this.refreshTokens.values())t.deviceId===e&&(t.revoked=!0,t.revokedAt=n);return await this.persistState(),!0})}async verifyDeviceIdentityBinding(e,t){return await this.ready,this.enqueueMutation(async()=>{await this.reloadStateFromDisk();let n=this.devices.get(e);if(!n||n.revokedAt)throw Xg(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw i_();if(!d_(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw a_();if(n.identityStatus!==`active`)throw o_(n.identityStatus??`unknown`);n.lastVerifiedAt=new Date().toISOString(),this.devices.set(e,n),await this.persistState();let{publicKey:r,...i}=n;return i})}listDevices(){return[...this.devices.values()].map(({publicKey:e,...t})=>t)}inspectRefreshToken(e){let t=Ug.default.decode(e),n=t&&typeof t==`object`?t:null,r=typeof n?.jti==`string`?n.jti:void 0,i=typeof n?.sub==`string`?n.sub:void 0,a=r?this.refreshTokens.get(r):void 0,o=i||a?.deviceId?[...this.refreshTokens.values()].filter(e=>e.deviceId===(i??a?.deviceId)&&!e.revoked).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]:void 0;return{claimDeviceId:i,claimExpAt:typeof n?.exp==`number`?new Date(n.exp*1e3).toISOString():void 0,claimIssuedAt:typeof n?.iat==`number`?new Date(n.iat*1e3).toISOString():void 0,claimJti:r,claimType:typeof n?.type==`string`?n.type:void 0,latestActiveTokenCreatedAt:o?.createdAt,latestActiveTokenJti:o?.jti,tokenRecordCreatedAt:a?.createdAt,tokenRecordDeviceId:a?.deviceId,tokenRecordRevokedAt:a?.revokedAt,tokenRecordState:a?a.revoked?`revoked`:`active`:`missing`}}issueTokenPair(e){let t=Ug.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${mg(14)}`,r=Ug.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=Ug.default.decode(r);this.refreshTokens.set(n,{jti:n,deviceId:e,revoked:!1,createdAt:new Date().toISOString(),expiresAtMs:typeof i.exp==`number`?i.exp*1e3:void 0});let a=Ug.default.decode(t);return{accessToken:t,refreshToken:r,expiresInSeconds:a.exp-a.iat}}async loadFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async reloadStateFromDisk(){await this.readStateFromDisk()&&await this.persistState()}async readStateFromDisk(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e=new Map,t=new Map,n=new Map,r=!1;try{let i=await d.default.readFile(this.indexPath,`utf8`);if(!i.trim())await p_(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await p_(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await p_(this.indexPath),r=!0;else{for(let t of a.pairingCodes){if(typeof t?.code!=`string`||typeof t?.expiresAtMs!=`number`){r=!0;continue}e.set(t.code,{code:t.code,expiresAtMs:t.expiresAtMs})}for(let e of a.devices){if(typeof e?.id!=`string`||typeof e?.name!=`string`||typeof e?.createdAt!=`string`){r=!0;continue}t.set(e.id,{id:e.id,name:e.name,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,identityAlgorithm:e.identityAlgorithm===`ed25519`?`ed25519`:void 0,publicKey:typeof e.publicKey==`string`?e.publicKey:void 0,publicKeyFingerprint:typeof e.publicKeyFingerprint==`string`?e.publicKeyFingerprint:void 0,identityStatus:u_(e.identityStatus)?e.identityStatus:void 0,lastVerifiedAt:typeof e.lastVerifiedAt==`string`?e.lastVerifiedAt:void 0})}for(let e of a.refreshTokens){if(typeof e?.jti!=`string`||typeof e?.deviceId!=`string`||typeof e?.revoked!=`boolean`||typeof e?.createdAt!=`string`){r=!0;continue}n.set(e.jti,{jti:e.jti,deviceId:e.deviceId,revoked:e.revoked,createdAt:e.createdAt,revokedAt:typeof e.revokedAt==`string`?e.revokedAt:void 0,expiresAtMs:typeof e.expiresAtMs==`number`?e.expiresAtMs:void 0})}}}}catch(e){if(e.code!==`ENOENT`)throw e}return f_(this.pairingCodes,e),f_(this.devices,t),f_(this.refreshTokens,n),r=this.pruneExpiredPairingCodes()||r,r=this.pruneRefreshTokens()||r,r}pruneExpiredPairingCodes(e=Date.now()){let t=!1;for(let[n,r]of this.pairingCodes.entries())r.expiresAtMs<=e&&(this.pairingCodes.delete(n),t=!0);return t}pruneRefreshTokens(e=Date.now()){let t=!1;for(let[n,r]of this.refreshTokens.entries()){if(!this.devices.has(r.deviceId)){this.refreshTokens.delete(n),t=!0;continue}typeof r.expiresAtMs==`number`&&r.expiresAtMs<=e&&(this.refreshTokens.delete(n),t=!0)}return t}async persistState(){await d.default.mkdir(this.config.authStoreDir,{recursive:!0});let e={v:1,pairingCodes:[...this.pairingCodes.values()].sort((e,t)=>e.code.localeCompare(t.code)),devices:[...this.devices.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),refreshTokens:[...this.refreshTokens.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt))},t=`${this.indexPath}.${process.pid}.${Date.now()}.tmp`,n=!1;try{await d.default.writeFile(t,`${JSON.stringify(e,null,2)}\n`,`utf8`),await d.default.rename(t,this.indexPath),n=!0}finally{n||await d.default.rm(t,{force:!0})}}enqueueMutation(e){let t=this.mutationQueue.then(e,e);return this.mutationQueue=t.then(()=>void 0,()=>void 0),t}};function l_(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function u_(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function d_(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function f_(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function p_(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var m_=class{constructor(e){this.logPath=e}async record(e){let t=p.default.dirname(this.logPath);await d.default.mkdir(t,{recursive:!0}),await d.default.appendFile(this.logPath,`${JSON.stringify(e)}\n`,`utf8`)}};function h_(){}h_.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={});var i=this;function a(e){return e=i.postProcess(e,n),r?(setTimeout(function(){r(e)},0),!0):e}e=this.castInput(e,n),t=this.castInput(t,n),e=this.removeEmpty(this.tokenize(e,n)),t=this.removeEmpty(this.tokenize(t,n));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength!=null&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0,n);if(f[0].oldPos+1>=s&&p+1>=o)return a(g_(i,f[0].lastComponent,t,e,i.useLongestToken));var m=-1/0,h=1/0;function g(){for(var r=Math.max(m,-c);r<=Math.min(h,c);r+=2){var l=void 0,u=f[r-1],d=f[r+1];u&&(f[r-1]=void 0);var g=!1;if(d){var _=d.oldPos-r;g=d&&0<=_&&_<o}var v=u&&u.oldPos+1<s;if(!g&&!v){f[r]=void 0;continue}if(l=!v||g&&u.oldPos<d.oldPos?i.addToPath(d,!0,!1,0,n):i.addToPath(u,!1,!0,1,n),p=i.extractCommon(l,t,e,r,n),l.oldPos+1>=s&&p+1>=o)return a(g_(i,l.lastComponent,t,e,i.useLongestToken));f[r]=l,l.oldPos+1>=s&&(h=Math.min(h,r-1)),p+1>=o&&(m=Math.max(m,r+1))}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}},extractCommon:function(e,t,n,r,i){for(var a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c},equals:function(e,t,n){return n.comparator?n.comparator(e,t):e===t||n.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join(``)},postProcess:function(e){return e}};function g_(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(d.removed)d.value=e.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return a}new h_;function __(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function v_(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function y_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function b_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function x_(e,t){return y_(e,t,``)}function S_(e,t){return b_(e,t,``)}function C_(e,t){return t.slice(0,w_(e,t))}function w_(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var i=Array(r),a=0;i[0]=0;for(var o=1;o<r;o++){for(t[o]==t[a]?i[o]=i[a]:i[o]=a;a>0&&t[o]!=t[a];)a=i[a];t[o]==t[a]&&a++}a=0;for(var s=n;s<e.length;s++){for(;a>0&&e[s]!=t[a];)a=i[a];e[s]==t[a]&&a++}return a}var T_=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,E_=RegExp(`[${T_}]+|\\s+|[^${T_}]`,`ug`),D_=new h_;D_.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},D_.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(t.intlSegmenter.segment(e),function(e){return e.segment})}else n=e.match(E_)||[];var r=[],i=null;return n.forEach(function(e){/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r},D_.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},D_.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,i=null;return e.forEach(function(e){e.added?r=e:e.removed?i=e:((r||i)&&O_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&O_(n,i,r,null),e};function O_(e,t,n,r){if(t&&n){var i=t.value.match(/^\s*/)[0],a=t.value.match(/\s*$/)[0],o=n.value.match(/^\s*/)[0],s=n.value.match(/\s*$/)[0];if(e){var c=__(i,o);e.value=b_(e.value,o,c),t.value=x_(t.value,c),n.value=x_(n.value,c)}if(r){var l=v_(a,s);r.value=y_(r.value,s,l),t.value=S_(t.value,l),n.value=S_(n.value,l)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,``)),r&&(r.value=r.value.replace(/^\s*/,``));else if(e&&r){var u=r.value.match(/^\s*/)[0],d=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],p=__(u,d);t.value=x_(t.value,p);var m=v_(x_(u,p),f);t.value=S_(t.value,m),r.value=y_(r.value,u,m),e.value=b_(e.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=t.value.match(/\s*$/)[0],_=C_(g,h);t.value=S_(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=C_(v,y);t.value=x_(t.value,b)}}var k_=new h_;k_.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${T_}]+|[^\\S\\n\\r]+|[^${T_}]`,`ug`);return e.match(t)||[]};var A_=new h_;A_.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
462
+ `));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var i=0;i<r.length;i++){var a=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=a:n.push(a)}return n},A_.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
463
463
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
464
464
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
465
465
  `)&&(e=e.slice(0,-1)),t.endsWith(`
466
- `)&&(t=t.slice(0,-1))),m_.prototype.equals.call(this,e,t,n)};function A_(e,t,n){return k_.diff(e,t,n)}var j_=new m_;j_.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var M_=new m_;M_.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function N_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function P_(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?N_(Object(n),!0).forEach(function(t){R_(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):N_(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function F_(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function I_(e){var t=F_(e,`string`);return typeof t==`symbol`?t:t+``}function L_(e){"@babel/helpers - typeof";return L_=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},L_(e)}function R_(e,t,n){return t=I_(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function z_(e){return B_(e)||V_(e)||H_(e)||W_()}function B_(e){if(Array.isArray(e))return U_(e)}function V_(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function H_(e,t){if(e){if(typeof e==`string`)return U_(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return U_(e,t)}}function U_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function W_(){throw TypeError(`Invalid attempt to spread non-iterable instance.
467
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var G_=new m_;G_.useLongestToken=!0,G_.tokenize=k_.tokenize,G_.castInput=function(e,t){var n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(K_(e,null,null,i),i,` `)},G_.equals=function(e,t,n){return m_.prototype.equals.call(G_,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)};function K_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));var a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=K_(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),L_(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=K_(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var q_=new m_;q_.tokenize=function(e){return e.slice()},q_.join=q_.removeEmpty=function(e){return e};function J_(e,t,n,r,i,a,o){if(o||={},typeof o==`function`&&(o={callback:o}),o.context===void 0&&(o.context=4),o.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(o.callback){var s=o.callback;A_(n,r,P_(P_({},o),{},{callback:function(e){s(c(e))}}))}else return c(A_(n,r,o));function c(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}for(var s=[],c=0,l=0,u=[],d=1,f=1,p=function(){var e=n[m],t=e.lines||Z_(e.value);if(e.lines=t,e.added||e.removed){var i;if(!c){var a=n[m-1];c=d,l=f,a&&(u=o.context>0?r(a.lines.slice(-o.context)):[],c-=u.length,l-=u.length)}(i=u).push.apply(i,z_(t.map(function(t){return(e.added?`+`:`-`)+t}))),e.added?f+=t.length:d+=t.length}else{if(c)if(t.length<=o.context*2&&m<n.length-2){var p;(p=u).push.apply(p,z_(r(t)))}else{var h,g=Math.min(t.length,o.context);(h=u).push.apply(h,z_(r(t.slice(0,g))));var _={oldStart:c,oldLines:d-c+g,newStart:l,newLines:f-l+g,lines:u};s.push(_),c=0,l=0,u=[]}d+=t.length,f+=t.length}},m=0;m<n.length;m++)p();for(var h=0,g=s;h<g.length;h++)for(var _=g[h],v=0;v<_.lines.length;v++)_.lines[v].endsWith(`
468
- `)?_.lines[v]=_.lines[v].slice(0,-1):(_.lines.splice(v+1,0,`\`),v++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:s}}}function Y_(e){if(Array.isArray(e))return e.map(Y_).join(`
466
+ `)&&(t=t.slice(0,-1))),h_.prototype.equals.call(this,e,t,n)};function j_(e,t,n){return A_.diff(e,t,n)}var M_=new h_;M_.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var N_=new h_;N_.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function P_(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function F_(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?P_(Object(n),!0).forEach(function(t){z_(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):P_(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function I_(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function L_(e){var t=I_(e,`string`);return typeof t==`symbol`?t:t+``}function R_(e){"@babel/helpers - typeof";return R_=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},R_(e)}function z_(e,t,n){return t=L_(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function B_(e){return V_(e)||H_(e)||U_(e)||G_()}function V_(e){if(Array.isArray(e))return W_(e)}function H_(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function U_(e,t){if(e){if(typeof e==`string`)return W_(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return W_(e,t)}}function W_(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function G_(){throw TypeError(`Invalid attempt to spread non-iterable instance.
467
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var K_=new h_;K_.useLongestToken=!0,K_.tokenize=A_.tokenize,K_.castInput=function(e,t){var n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(q_(e,null,null,i),i,` `)},K_.equals=function(e,t,n){return h_.prototype.equals.call(K_,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)};function q_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));var a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=q_(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),R_(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=q_(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var J_=new h_;J_.tokenize=function(e){return e.slice()},J_.join=J_.removeEmpty=function(e){return e};function Y_(e,t,n,r,i,a,o){if(o||={},typeof o==`function`&&(o={callback:o}),o.context===void 0&&(o.context=4),o.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(o.callback){var s=o.callback;j_(n,r,F_(F_({},o),{},{callback:function(e){s(c(e))}}))}else return c(j_(n,r,o));function c(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}for(var s=[],c=0,l=0,u=[],d=1,f=1,p=function(){var e=n[m],t=e.lines||Q_(e.value);if(e.lines=t,e.added||e.removed){var i;if(!c){var a=n[m-1];c=d,l=f,a&&(u=o.context>0?r(a.lines.slice(-o.context)):[],c-=u.length,l-=u.length)}(i=u).push.apply(i,B_(t.map(function(t){return(e.added?`+`:`-`)+t}))),e.added?f+=t.length:d+=t.length}else{if(c)if(t.length<=o.context*2&&m<n.length-2){var p;(p=u).push.apply(p,B_(r(t)))}else{var h,g=Math.min(t.length,o.context);(h=u).push.apply(h,B_(r(t.slice(0,g))));var _={oldStart:c,oldLines:d-c+g,newStart:l,newLines:f-l+g,lines:u};s.push(_),c=0,l=0,u=[]}d+=t.length,f+=t.length}},m=0;m<n.length;m++)p();for(var h=0,g=s;h<g.length;h++)for(var _=g[h],v=0;v<_.lines.length;v++)_.lines[v].endsWith(`
468
+ `)?_.lines[v]=_.lines[v].slice(0,-1):(_.lines.splice(v+1,0,`\`),v++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:s}}}function X_(e){if(Array.isArray(e))return e.map(X_).join(`
469
469
  `);var t=[];e.oldFileName==e.newFileName&&t.push(`Index: `+e.oldFileName),t.push(`===================================================================`),t.push(`--- `+e.oldFileName+(e.oldHeader===void 0?``:` `+e.oldHeader)),t.push(`+++ `+e.newFileName+(e.newHeader===void 0?``:` `+e.newHeader));for(var n=0;n<e.hunks.length;n++){var r=e.hunks[n];r.oldLines===0&&--r.oldStart,r.newLines===0&&--r.newStart,t.push(`@@ -`+r.oldStart+`,`+r.oldLines+` +`+r.newStart+`,`+r.newLines+` @@`),t.push.apply(t,r.lines)}return t.join(`
470
470
  `)+`
471
- `}function X_(e,t,n,r,i,a,o){var s;if(typeof o==`function`&&(o={callback:o}),(s=o)!=null&&s.callback){var c=o.callback;J_(e,t,n,r,i,a,P_(P_({},o),{},{callback:function(e){e?c(Y_(e)):c()}}))}else{var l=J_(e,t,n,r,i,a,o);return l?Y_(l):void 0}}function Z_(e){var t=e.endsWith(`
471
+ `}function Z_(e,t,n,r,i,a,o){var s;if(typeof o==`function`&&(o={callback:o}),(s=o)!=null&&s.callback){var c=o.callback;Y_(e,t,n,r,i,a,F_(F_({},o),{},{callback:function(e){e?c(X_(e)):c()}}))}else{var l=Y_(e,t,n,r,i,a,o);return l?X_(l):void 0}}function Q_(e){var t=e.endsWith(`
472
472
  `),n=e.split(`
473
473
  `).map(function(e){return e+`
474
- `});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var Q_=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return ov(r,await iv(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await av(e,n),i=p.default.parse(r).root;return ov(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await $_(e,t);return{path:r,absolutePath:n,content:await d.default.readFile(n,`utf8`)}}async diffFile(e,t,n=``){let{absolutePath:r,normalizedPath:i}=await $_(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:X_(i,i,n,a,`base`,`current`),currentContent:a}}async listTree(e,t=`.`,n=500){let r=await d.default.realpath(p.default.resolve(e)),i=ev(t),a=await tv(r,i),o=[];async function s(e,t){let r=await d.default.readdir(e,{withFileTypes:!0});for(let i of r){if(o.length>=n)return;let r=p.default.join(e,i.name),a=t?p.default.join(t,i.name):i.name;i.isSymbolicLink()||(i.isDirectory()?(o.push({path:a,kind:`dir`}),await s(r,a)):o.push({path:a,kind:`file`}))}}return await s(a,``),{root:i,entries:o}}};async function $_(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=ev(t),i=await tv(n,r),a=await d.default.realpath(i);return nv(n,a,r),{absolutePath:a,normalizedPath:r}}function ev(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function tv(e,t){if(p.default.isAbsolute(t))throw Error(`Path must be relative to project root: ${t}`);let n=p.default.resolve(e,t);return nv(e,n,t),n}function nv(e,t,n){let r=rv(e),i=rv(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function rv(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function iv(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;nv(e,r,n??`.`);let i=await d.default.realpath(r);if(nv(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function av(e,t=f.default.homedir()){let n=e?.trim(),r=p.default.resolve(t),i=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(r,n):r,a=await d.default.realpath(i);if(!(await d.default.stat(a)).isDirectory())throw Error(`Path is not a directory: ${a}`);return a}async function ov(e,t,n){let r=(await d.default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,Math.max(1,n)).map(e=>({name:e.name,path:p.default.join(t,e.name)}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),directories:r}}var sv=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await lv(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=cv(t)??(p.default.basename(n)||n),o=r?{...r,title:cv(t)??r.title,updatedAt:i}:{id:`proj_${pg(12)}`,title:a,path:n,createdAt:i,updatedAt:i};return this.projects.set(o.id,o),this.projectByPath.set(n,o),await this.enqueueWrite(async()=>{await this.persistIndex()}),o}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await lv(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`||(this.projects.set(e.id,e),this.projectByPath.set(e.path,e))}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function cv(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function lv(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}Mh(),Dh(),Oh();var uv=c(jh(),1);Ph();var dv=uv.default,fv=120,pv=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${pg(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await mv(fv);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function mv(e){return new Promise(t=>setTimeout(t,e))}var hv=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new pv(this.provider,e)}};function gv(e){let t=bv(vv(e)),n=Q(t.type);return n&&(t.type=_v(n)),t}function _v(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return yv(e)}}function vv(e){if(Array.isArray(e))return e.map(e=>vv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[yv(n)]=vv(r);return t}return e}function yv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function bv(e){return typeof e==`object`&&e?e:{}}function Q(e){if(typeof e==`string`)return e}function xv(e){return typeof e==`string`||typeof e==`number`?String(e):``}var Sv=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],Cv=[x.default.join(x.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),x.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function wv(e,t){let n=Tv(e);if(!n)return null;let r=JSON.parse(b.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:x.default.resolve(x.default.dirname(n),i)}function Tv(e){for(let t of Cv)try{return(0,S.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}var Ev=1e4,Dv=100,Ov=2e3;function kv(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function Av(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var jv=new Map;async function Mv(e){return Iv(e).createConnection()}async function Nv(){let e=[...jv.values()];await Promise.allSettled(e.map(e=>e.shutdown())),jv.clear()}async function Pv(e){let t=jv.size>0?[...jv.values()]:[Iv(e)];await Promise.all(t.map(e=>e.restart()))}function Fv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[x.default.resolve(t)]};try{let e=wv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function Iv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=jv.get(t);if(n)return n;let r=new Lv(e);return jv.set(t,r),r}var Lv=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await zv(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise){await this.shutdownPromise;return}this.shutdownPromise=this.shutdownInternal();try{await this.shutdownPromise}finally{this.shutdownPromise=null}}async restart(){await this.shutdown();let e=await this.ensureRunning();await(await zv(e.url,()=>this.buildStartupError(e.stderrTail))).close()}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await Uv(e.child,Ov)||(e.child.kill(`SIGKILL`),await Uv(e.child,Ov)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await Hv()}`,t=Fv(this.codexBinOverride),n=(0,w.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await Vv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await Uv(n,Ov)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},Rv=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){if(!this.closed){if(this.closed=!0,this.socket.readyState<=1)try{this.socket.close(1e3,`Client closing`)}catch(e){Av(`connection.close_failed`,{readyState:this.socket.readyState,...kv(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=Wv(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function zv(e,t){let n=Date.now()+Ev,r=null;for(;Date.now()<n;)try{return await Bv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await Gv(Dv)}throw r??Error(t())}async function Bv(e,t){let n=new dv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),Av(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){Av(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...kv(r)})}i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new Rv(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(r,o)=>{if(a)return;a=!0,s();let c=typeof r==`number`?r:`unknown`,l=o.length>0?`: ${o.toString(`utf8`)}`:``;Av(`connect.closed_before_open`,{url:e,timeoutMs:t,readyState:n.readyState,closeCode:c,closeReason:l||null}),i(Error(`Connection closed before open (${String(c)})${l}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function Vv(e,t,n){let r=Date.now()+Ev;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Bv(e,500)).close(),!0}catch{await Gv(Dv)}}return!1}async function Hv(){let e=(0,C.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function Uv(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function Wv(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function Gv(e){return new Promise(t=>{setTimeout(t,e)})}var Kv=15e3,qv=5e3,Jv={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Yv=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??Kv,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:Jv,capabilities:{experimentalApi:!1,optOutNotificationMethods:Sv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=xv(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=Q(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=xv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=bv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function Xv(e,t={}){let n=new Yv(await Qv(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function Zv(e={}){try{return await Xv(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??qv}),!0}catch{return!1}}async function Qv(e){return e.spawnProcess?new ey(e.spawnProcess()):new $v(await Mv(e.codexBinOverride))}var $v=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},ey=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
474
+ `});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var $_=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return sv(r,await av(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await ov(e,n),i=p.default.parse(r).root;return sv(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await ev(e,t);return{path:r,absolutePath:n,content:await d.default.readFile(n,`utf8`)}}async diffFile(e,t,n=``){let{absolutePath:r,normalizedPath:i}=await ev(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:Z_(i,i,n,a,`base`,`current`),currentContent:a}}async listTree(e,t=`.`,n=500){let r=await d.default.realpath(p.default.resolve(e)),i=tv(t),a=await nv(r,i),o=[];async function s(e,t){let r=await d.default.readdir(e,{withFileTypes:!0});for(let i of r){if(o.length>=n)return;let r=p.default.join(e,i.name),a=t?p.default.join(t,i.name):i.name;i.isSymbolicLink()||(i.isDirectory()?(o.push({path:a,kind:`dir`}),await s(r,a)):o.push({path:a,kind:`file`}))}}return await s(a,``),{root:i,entries:o}}};async function ev(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=tv(t),i=await nv(n,r),a=await d.default.realpath(i);return rv(n,a,r),{absolutePath:a,normalizedPath:r}}function tv(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function nv(e,t){if(p.default.isAbsolute(t))throw Error(`Path must be relative to project root: ${t}`);let n=p.default.resolve(e,t);return rv(e,n,t),n}function rv(e,t,n){let r=iv(e),i=iv(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function iv(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function av(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;rv(e,r,n??`.`);let i=await d.default.realpath(r);if(rv(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function ov(e,t=f.default.homedir()){let n=e?.trim(),r=p.default.resolve(t),i=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(r,n):r,a=await d.default.realpath(i);if(!(await d.default.stat(a)).isDirectory())throw Error(`Path is not a directory: ${a}`);return a}async function sv(e,t,n){let r=(await d.default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,Math.max(1,n)).map(e=>({name:e.name,path:p.default.join(t,e.name)}));return{rootPath:e,currentPath:t,parentPath:t===e?null:p.default.dirname(t),directories:r}}var cv=class{indexPath;projects=new Map;projectByPath=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`project-index.json`),this.ready=this.loadFromDisk()}async upsertByPath(e,t){await this.ready;let n=await uv(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=lv(t)??(p.default.basename(n)||n),o=r?{...r,title:lv(t)??r.title,updatedAt:i}:{id:`proj_${mg(12)}`,title:a,path:n,createdAt:i,updatedAt:i};return this.projects.set(o.id,o),this.projectByPath.set(n,o),await this.enqueueWrite(async()=>{await this.persistIndex()}),o}async list(){return await this.ready,[...this.projects.values()].sort((e,t)=>e.title.localeCompare(t.title))}async getById(e){return await this.ready,this.projects.get(e)}async getByPath(e){await this.ready;let t=await uv(e);return this.projectByPath.get(t)}async remove(e){await this.ready;let t=this.projects.get(e);return t?(this.projects.delete(e),this.projectByPath.delete(t.path),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.projects))return;for(let e of t.projects)typeof e?.id!=`string`||typeof e?.title!=`string`||typeof e?.path!=`string`||typeof e?.createdAt!=`string`||typeof e?.updatedAt!=`string`||(this.projects.set(e.id,e),this.projectByPath.set(e.path,e))}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,projects:[...this.projects.values()].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};function lv(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function uv(e){if(!p.default.isAbsolute(e))throw Error(`Project path must be absolute: ${e}`);let t=p.default.resolve(e),n;try{n=await d.default.stat(t)}catch(e){throw Error(`Project path does not exist: ${t}; ${String(e)}`)}if(!n.isDirectory())throw Error(`Project path is not a directory: ${t}`);return d.default.realpath(t)}Nh(),Oh(),kh();var dv=c(Mh(),1);Fh();var fv=dv.default,pv=120,mv=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(this.ensureOpen(),this.emit({type:`turn.started`,text:e}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(e)){let t=`req_${mg(8)}`;this.pendingApprovals.set(t,{input:e}),this.emit({type:`tool.permission.requested`,requestId:t,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${e}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await hv(pv);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function hv(e){return new Promise(t=>setTimeout(t,e))}var gv=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new mv(this.provider,e)}};function _v(e){let t=xv(yv(e)),n=Q(t.type);return n&&(t.type=vv(n)),t}function vv(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return bv(e)}}function yv(e){if(Array.isArray(e))return e.map(e=>yv(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[bv(n)]=yv(r);return t}return e}function bv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function xv(e){return typeof e==`object`&&e?e:{}}function Q(e){if(typeof e==`string`)return e}function Sv(e){return typeof e==`string`||typeof e==`number`?String(e):``}var Cv=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],wv=[x.default.join(x.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),x.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function Tv(e,t){let n=Ev(e);if(!n)return null;let r=JSON.parse(b.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:x.default.resolve(x.default.dirname(n),i)}function Ev(e){for(let t of wv)try{return(0,S.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}var Dv=1e4,Ov=100,kv=2e3;function Av(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function jv(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var Mv=new Map;async function Nv(e){return Lv(e).createConnection()}async function Pv(){let e=[...Mv.values()];await Promise.allSettled(e.map(e=>e.shutdown())),Mv.clear()}async function Fv(e){let t=Mv.size>0?[...Mv.values()]:[Lv(e)];await Promise.all(t.map(e=>e.restart()))}function Iv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[x.default.resolve(t)]};try{let e=Tv(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function Lv(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=Mv.get(t);if(n)return n;let r=new Rv(e);return Mv.set(t,r),r}var Rv=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await Bv(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise){await this.shutdownPromise;return}this.shutdownPromise=this.shutdownInternal();try{await this.shutdownPromise}finally{this.shutdownPromise=null}}async restart(){await this.shutdown();let e=await this.ensureRunning();await(await Bv(e.url,()=>this.buildStartupError(e.stderrTail))).close()}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await Wv(e.child,kv)||(e.child.kill(`SIGKILL`),await Wv(e.child,kv)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await Uv()}`,t=Iv(this.codexBinOverride),n=(0,w.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await Hv(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await Wv(n,kv)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},zv=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){if(!this.closed){if(this.closed=!0,this.socket.readyState<=1)try{this.socket.close(1e3,`Client closing`)}catch(e){jv(`connection.close_failed`,{readyState:this.socket.readyState,...Av(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=Gv(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function Bv(e,t){let n=Date.now()+Dv,r=null;for(;Date.now()<n;)try{return await Vv(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await Kv(Ov)}throw r??Error(t())}async function Vv(e,t){let n=new fv(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),jv(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){jv(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...Av(r)})}i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new zv(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(r,o)=>{if(a)return;a=!0,s();let c=typeof r==`number`?r:`unknown`,l=o.length>0?`: ${o.toString(`utf8`)}`:``;jv(`connect.closed_before_open`,{url:e,timeoutMs:t,readyState:n.readyState,closeCode:c,closeReason:l||null}),i(Error(`Connection closed before open (${String(c)})${l}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function Hv(e,t,n){let r=Date.now()+Dv;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await Vv(e,500)).close(),!0}catch{await Kv(Ov)}}return!1}async function Uv(){let e=(0,C.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function Wv(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function Gv(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function Kv(e){return new Promise(t=>{setTimeout(t,e)})}var qv=15e3,Jv=5e3,Yv={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Xv=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??qv,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:Yv,capabilities:{experimentalApi:!1,optOutNotificationMethods:Cv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=Sv(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=Q(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=Sv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=xv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function Zv(e,t={}){let n=new Xv(await $v(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function Qv(e={}){try{return await Zv(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??Jv}),!0}catch{return!1}}async function $v(e){return e.spawnProcess?new ty(e.spawnProcess()):new ey(await Nv(e.codexBinOverride))}var ey=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},ty=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
475
475
  `)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}async close(){this.closed||(this.closed=!0,this.process.stdin.destroyed||this.process.stdin.end(),!this.process.killed&&this.process.exitCode===null&&this.process.kill())}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}),this.process.on(`error`,e=>{this.fail(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.closed)return;let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.fail(`Codex app-server exited unexpectedly (${i})${r}`)})}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
476
- `);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},ty=3,ny=250;function ry(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function iy(e,t){let n=Math.max(1,t?.maxAttempts??ty),r=Math.max(0,t?.retryDelayMs??ny),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!ry(e)||t>=n)throw e;r>0&&await ay(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function ay(e){return new Promise(t=>{setTimeout(t,e)})}function oy(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function sy(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var cy=3e4,ly=8,uy=160,dy={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},fy=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await Mv(),n.requestTimeoutMs??cy);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0;try{let n=t?.model??this.activeModel,r=oy(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=xy(this.activeSessionConfig.reasoningEffort),o,s=Sy(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&Cy(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:Sy(t?.mode,n,`low`)})}let c=Q(o.turn?.id);c&&(this.activeTurnId=c)}catch(e){throw this.turnInProgress=!1,e}}async interrupt(){if(this.ensureOpen(),!this.threadId||!this.activeTurnId)return;let e={threadId:this.threadId,turnId:this.activeTurnId};await this.sendRequest(`turn/interrupt`,e)}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=Ty(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:sy(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:dy,capabilities:{experimentalApi:!0,optOutNotificationMethods:Sv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return Q((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return Q((await iy(()=>this.sendRequest(`thread/resume`,i))).thread?.id)}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0;for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:vy(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=Q(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=xv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=bv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=bv(r),a=Q(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${pg(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:Q(i.reason),threadId:a,turnId:Q(i.turnId),itemId:Q(i.itemId),approvalMethod:t,rawParams:vv(i)})}registerUserInputRequest(e,t,n){let r=Q(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${pg(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(wy).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:vv(n)})}handleNotification(e){switch(e.method){case`thread/started`:{let t=e.params,n=Q(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:vv(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Q(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.emit({type:`turn.started`,turn:vv(t.turn)});return}case`turn/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.status);if(this.turnInProgress=!1,this.activeTurnId=void 0,n===`failed`){this.emit({type:`turn.failed`,status:n,turn:vv(t.turn),error:vv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:vv(t.turn)}),this.tryEmitTitleFromThreadRead();return}case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.started`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:gv(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.completed`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:gv(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=bv(e.params);if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:Q(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Q(t.delta)??Q(t.text)??``,original_method:e.method,payload:vv(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`error`,message:Q(t.error?.message)??`Codex app-server error`,error:vv(t.error),will_retry:t.willRetry===!0,thread_id:Q(t.threadId),turn_id:Q(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=xv(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=py(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated(Q(e.thread?.name)??Q(e.thread?.preview),Q(e.thread?.name)?`codex.thread_read_name`:`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleConnectionFailure(e){if(this.closed)return;let t=yy(e),n=by(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(xv(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Q(bv(e.params).threadId)}extractThreadIdFromNotification(e){let t=bv(e.params);return Q(t.threadId)||Q(bv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Q(bv(bv(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(my({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(my({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>ly&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-ly)}};function py(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function my(e){let t=Q(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=bv(e.message.error),i=gy(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:hy(t,n,e.direction),method:t,requestId:n?xv(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??vy(Q(r.message))}}function hy(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function gy(e,t){let n=bv(t),r=bv(n.thread),i=bv(n.turn),a=bv(n.item),o=Q(n.delta)??Q(n.text),s=_y(e,n,o);return{threadId:Q(n.threadId)??Q(r.id),turnId:Q(n.turnId)??Q(i.id),itemId:Q(n.itemId)??Q(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:vy(s)}}function _y(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return Q(bv(t.error).message)??Q(t.message)}function vy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=uy?t:`${t.slice(0,uy)}...`}function yy(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function by(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function xy(e){return e?e===`max`?`xhigh`:e:null}function Sy(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function Cy(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function wy(e){let t=bv(e),n=Q(t.id),r=Q(t.header),i=Q(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=bv(e),n=Q(t.label),r=Q(t.description)??n,i=Q(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function Ty(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var Ey=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new hv(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await Zv()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??fy.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function Dy(e){let t=[],n=null;do{let r=await Oy({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function Oy(e){return Xv(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>My(e)),nextCursor:n.nextCursor}})}async function ky(e,t=!0){return Xv(async n=>My((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function Ay(e){return Xv(async t=>{let n=!1;try{let r=await iy(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,Py(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function jy(){let e=[],t=null;do{let n=await Xv(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>Ny(e))),t=n.nextCursor}while(t);return e}function My(e){let t=Q(bv(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:Iy(e.source),gitInfo:e.gitInfo?bv(vv(e.gitInfo)):null,turns:e.turns.map(e=>Fy(e))}}function Ny(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function Py(e){let t=Ly(e.model),n=Ry(e.reasoningEffort),r=zy(e.approvalPolicy),i=By(e.sandbox),a=r!==null||i!==null;return t||n!==null||a?{model:t,sessionTurnConfig:{mode:`default`,model:t??null,reasoningEffort:n,...a?{execution:{codex:{approvalPolicy:r,sandboxMode:i}}}:{}},sessionTurnConfigUpdatedAt:new Date(e.thread.updatedAt*1e3).toISOString()}:null}function Fy(e){return{id:e.id,status:e.status,error:e.error?bv(vv(e.error)):null,items:e.items.map(e=>gv(e))}}function Iy(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function Ly(e){return Q(e)?.trim()||void 0}function Ry(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function zy(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function By(e){let t=typeof e==`string`?e:Q(bv(e).type);return t===`read-only`||t===`readOnly`?`read-only`:t===`workspace-write`||t===`workspaceWrite`?`workspace-write`:t===`danger-full-access`||t===`dangerFullAccess`?`danger-full-access`:null}var Vy=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=oy(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=Ky(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:sy(r),questions:Wy(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=db(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:fb(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(t){if(this.closed||this.activeQuery!==e)return;let n=t instanceof Error?t.message:String(t);this.interruptRequested||this.emit({type:`error`,message:n})}finally{if(this.closed||this.activeQuery!==e)return;this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>Uy(e,t)?this.requestUserInput(e,t,n):Hy(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${pg(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=Wy(t),i=`req_${pg(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1}captureResumeSessionId(e){let t=db(e),n=fb(t.session_id)??fb(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${pg(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=gb(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=fb(e.tool_id)??fb(e.tool_use_id)??mb(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=fb(e.uuid);if(n)return this.activeToolItemId=n,n;let r=_b(fb(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}mapClaudeMessage(e){let t=db(e),n=fb(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!ob(t))return[];let n=sb(db(t.message));return n?[{type:`item.completed`,item:{id:fb(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:fb(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=ab(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=db(t.event);if(fb(e.type)===`message_start`){let t=gb(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=cb(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||fb(t.subtype)?.startsWith(`error_`)===!0){let n=lb(t);return[...e,{type:`turn.failed`,error:{message:n},usage:ub(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:ub(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=fb(t.summary)??`tool summary`,i=fb(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=fb(t.tool_name)??`tool`,i=fb(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=fb(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(fb(t.session_id)??fb(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:fb(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=fb(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=qy(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=Jy(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Yy({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function Hy(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function Uy(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function Wy(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=Gy(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function Gy(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function Ky(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function qy(e){let t=db(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=db(e);if(t.type!==`tool_use`)continue;let n=fb(t.id),i=fb(t.name),a=db(t.input);if(!(!n||!i)){if(i===`Task`){let e=fb(a.subagent_type),t=fb(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:fb(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=fb(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=fb(a.file_path);r.push({id:n,toolName:`Write`,title:eb(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Jy(e){let t=db(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=db(e);if(t.type!==`tool_result`)continue;let n=fb(t.tool_use_id);if(n)return{toolUseId:n}}return null}function Yy(e){let t=db(e.raw.tool_use_result),n=Xy(t.content)??sb(db(e.raw.message)),r=db(t.usage),i=hb(t.totalTokens)??hb(r.total_tokens)??hb(r.output_tokens),a=hb(t.totalToolUseCount),o=hb(t.totalDurationMs),s=fb(t.agentId),c=fb(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=Qy(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=Zy(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=pb(t.content),r=$y(nb(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function Xy(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=db(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
477
- `):void 0}function Zy(e){return pb(db(e.file).content)||Xy(e.content)}function Qy(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${rb(t)} tokens`),typeof n==`number`&&r.push(ib(n)),r.join(` · `)}function $y(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function eb(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${tb(e)})`:`Write`}function tb(e){let t=e.split(`/`);return t[t.length-1]||e}function nb(e){if(e)return e.split(`
478
- `).length}function rb(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function ib(e){let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}m`:`${n}m ${r}s`}function ab(e){return sb(db(e.message))||(pb(e.result)??``)}function ob(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=db(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>db(e).type===`tool_result`)}function sb(e){let t=pb(e.content);if(t)return t;let n=pb(e.text)??pb(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=db(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
479
- `)}function cb(e){let t=db(db(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function lb(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):fb(e.subtype)||`Claude turn failed`}function ub(e){let t=db(e);return{input_tokens:hb(t.input_tokens)??hb(t.inputTokens)??0,cached_input_tokens:hb(t.cached_input_tokens)??hb(t.cache_read_input_tokens)??hb(t.cacheReadInputTokens)??0,output_tokens:hb(t.output_tokens)??hb(t.outputTokens)??0}}function db(e){return typeof e==`object`&&e?e:{}}function fb(e){if(typeof e==`string`&&e.trim())return e}function pb(e){if(typeof e==`string`&&e.length>0)return e}function mb(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function hb(e){if(typeof e==`number`&&Number.isFinite(e))return e}function gb(e){let t=fb(db(e.message).id);if(t)return t;let n=fb(db(db(e.event).message).id);if(n)return n}function _b(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var vb=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=yb(e);for(let e of this.listeners)e(t)};if(typeof e?.subscribe==`function`){let n=e.subscribe(e=>t(e));typeof n==`function`&&(this.unsubscribe=n);return}if(typeof e?.on==`function`){let n=e=>t(e);e.on(`event`,n),this.unsubscribe=()=>{typeof e?.off==`function`&&e.off(`event`,n)};return}throw Error(`Native session does not expose a known event subscription API`)}};function yb(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var bb=`@anthropic-ai/claude-agent-sdk`,xb=`claude-sonnet-4-6`,Sb=1e4,Cb=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(bb),!0}catch{return!1}}async createSession(e){if(!this.preferNative)throw Error(`Claude native provider is disabled. Set ENABLE_NATIVE_PROVIDERS=true to use Claude sessions.`);try{let t=await import(bb),n=await wb(Tb(t,e),Sb,`Claude native query session creation timed out`);if(n)return n;let r=await wb(Eb(t,e),Sb,`Claude legacy native session creation timed out`);if(r)return r;throw this.requireNative,Error(`Claude SDK loaded but no supported stable session API was found`)}catch(e){throw Error(`Claude native session creation failed: ${String(e)}`)}}};async function wb(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}async function Tb(e,t){let n=Db(e);if(!n)return null;let r=t.model??xb;return new Vy(t.sessionId,r,({prompt:e,model:i,sessionConfig:a,resume:o,abortController:s,canUseTool:c})=>{let l=a?.permissionMode??t.sessionConfig?.permissionMode??`default`,u={model:i??r,includePartialMessages:!0,abortController:s,canUseTool:c,permissionMode:l},d=Ob(a?.reasoningEffort??t.sessionConfig?.reasoningEffort);return d&&(u.effort=d),l===`bypassPermissions`&&(u.allowDangerouslySkipPermissions=!0),t.cwd&&(u.cwd=t.cwd),o&&(u.resume=o,u.forkSession=!1),n({prompt:e,options:u})},t.resumeSessionId,{cwd:t.cwd})}async function Eb(e,t){if(typeof e?.createSession==`function`){let n=await e.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new vb(`claude`,t.sessionId,t.model,n)}if(typeof e?.ClaudeAgentClient==`function`){let n=new e.ClaudeAgentClient;if(typeof n?.createSession==`function`){let e=await n.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new vb(`claude`,t.sessionId,t.model,e)}}if(typeof e?.default?.createSession==`function`){let n=await e.default.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new vb(`claude`,t.sessionId,t.model,n)}return null}function Db(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function Ob(e){if(e){if(e===`max`)return`max`;if(e===`high`||e===`medium`||e===`low`)return e;if(e===`xhigh`)return`max`;if(e===`minimal`||e===`none`)return`low`}}function kb(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new Ey(n,r):new Cb(n,r)}const Ab=p.default.join(`.claude`,`projects`),jb=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function Mb(e){return(await(0,T.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>Rb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Nb(e,t){let n=Ib(e,t?.homeDir),r=p.default.resolve(e),i=[];try{i=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}let a=[];for(let e of i){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),i=await Wb(t);if(!Vb(i))continue;let o=await d.default.stat(t),s=Bb(i,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});a.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}let o;try{o=new Map((await(0,T.listSessions)({dir:e})).map(e=>Rb(e)).filter(e=>typeof e.cwd==`string`?p.default.resolve(e.cwd)===r:!1).map(e=>[e.nativeSessionId,e]))}catch{}if(o)for(let e=0;e<a.length;e+=1){let t=a[e];if(!t)continue;let n=o.get(t.nativeSessionId);n&&(a[e]={...t,title:n.title??t.title,updatedAt:n.updatedAt})}return a.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Pb(e){let t=await Gb(e.nativeSessionId,e.projectPath),n=await Kb(e.projectPath,e.nativeSessionId,e.homeDir);return zb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function Fb(e,t,n){return p.default.join(Ib(e,n),`${t}.jsonl`)}function Ib(e,t){let n=t??f.default.homedir();return p.default.join(n,Ab,Lb(e))}function Lb(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function Rb(e){let t=tx(e.customTitle)??tx(e.summary)??tx(e.firstPrompt),n=Ub(e.lastModified);return{nativeSessionId:e.sessionId,cwd:Hb(e.cwd),title:t,createdAt:n,updatedAt:n}}function zb(e){let t=[],n=Bb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function Bb(e,t){let n,r,i,a;for(let t of e)t.timestampMs!==void 0&&(i=i===void 0?t.timestampMs:Math.min(i,t.timestampMs),a=a===void 0?t.timestampMs:Math.max(a,t.timestampMs)),!r&&t.type===`user`&&(r=Qb(Xb($b(t.raw.message)))),!n&&t.type===`assistant`&&(n=ex($b(t.raw.message).model));let o=i??ax(t.createdAtFallbackMs)??0,s=a??ax(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function Vb(e){for(let t of e){if(t.type===`user`){let e=$b(t.raw.message);if(Xb(e)||Yb(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=$b(t.raw.message);if(Xb(e)||Jb(e).length>0||ex(t.raw.error))return!0}return!1}function Hb(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ub(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Wb(e){let t=(await d.default.readFile(e,`utf8`)).split(`
480
- `),n=[];for(let e=0;e<t.length;e+=1){let r=t[e]?.trim();if(!r)continue;let i;try{i=JSON.parse(r)}catch{continue}let a=$b(i),o=ex(a.timestamp),s=o?ix(o):void 0;n.push({line:e+1,raw:a,type:ex(a.type),timestamp:o,timestampMs:s})}return n}async function Gb(e,t){let n=await(0,T.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>qb(e,t+1))}async function Kb(e,t,n){let r=Fb(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function qb(e,t){let n=$b(e),r=$b(n.message),i=ex(n.timestamp)??ex(r.timestamp)??ex(r.created_at)??ex(r.createdAt);return{line:t,raw:{...n,message:r},type:ex(n.type),timestamp:i,timestampMs:i?ix(i):void 0}}function Jb(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=$b(e);if(ex(t.type)!==`tool_use`)continue;let r=$b(t.input),i=ex(r.command),a=ex(t.name)??`tool`,o=ex(r.description);n.push({id:ex(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function Yb(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=$b(e);if(ex(t.type)!==`tool_result`)continue;let r=nx(ex(t.content)??ex($b(t.toolUseResult).stdout)??ex($b(t.tool_use_result).stdout)??ex(t.text));n.push({toolUseId:ex(t.tool_use_id)??ex(t.toolUseId),toolName:ex(t.tool_name)??ex(t.toolName),text:r,isError:t.is_error===!0})}return n}function Xb(e){let t=ex(e.content);if(t)return nx(t);let n=ex(e.text)??ex(e.prompt);if(n)return nx(n);let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push(e);continue}let t=$b(e),n=ex(t.type);if(n&&n!==`text`)continue;let r=ex(t.text)??ex(t.content)??Zb(t);r&&i.push(r)}if(i.length!==0)return nx(i.join(`
481
- `))}function Zb(e){let t=Array.isArray(e.text_elements)?e.text_elements:Array.isArray(e.textElements)?e.textElements:[];if(t.length===0)return;let n=[];for(let e of t){let t=$b(e),r=ex(t.text)??ex(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function Qb(e,t=60){if(!e)return;let n=rx(e).replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function $b(e){return typeof e==`object`&&e?e:{}}function ex(e){return typeof e==`string`&&e.trim()||void 0}function tx(e){if(typeof e==`string`)return nx(e)}function nx(e){if(!e)return;let t=rx(e).trim();return t.length>0?t:void 0}function rx(e){return e.replace(jb,``)}function ix(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function ax(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var ox=class{constructor(e){this.options=e}async init(){await this.options.store.init()}async getProjects(){await this.init();let e=await this.options.store.getIndex();return e?{generatedAt:e.generatedAt,source:`cache`,providers:e.providers,projects:e.projects}:this.refreshProjects()}async refreshProjects(){await this.init();let e=new Map,[t,n]=await Promise.all([this.scanCodexSessions(e),this.scanClaudeSessions(e)]),r=new Date().toISOString(),i={codex:t.status,claude:n.status},{projects:a,projectSessions:o}=cx(r,[t,n]);if(lx(i)){let e=await this.options.store.getSnapshot();if(e)return await this.options.store.writeSnapshot({...e,providers:i}),{generatedAt:e.generatedAt,source:`cache`,providers:i,projects:e.projects}}return await this.options.store.writeSnapshot({generatedAt:r,providers:i,projects:a,projectSessions:o}),{generatedAt:r,source:`fresh_scan`,providers:i,projects:a}}async listProjectSessions(e){await this.init();let t=e.trim(),n=await this.options.store.getIndex(),r=!1;n||(n=dx(await this.refreshProjects()),r=!0);let i=await ux(n.projects,t);if(!i)throw n_(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=dx(await this.refreshProjects()),i=await ux(n.projects,t),!i)throw n_(t);if(a=await this.options.store.getProject(i.key),!a)throw Error(`Discovery cache missing project sessions: ${i.path}`)}if(!a)throw Error(`Discovery cache missing project sessions: ${i.path}`);return{canonicalProjectPath:i.path,project:a.project,providers:a.providers,sessions:a.sessions}}async scanCodexSessions(e){let t=new Date().toISOString();try{let n=new Map;for(let e of[!1,!0]){let t=null;do{let r=await Oy({archived:e,cursor:t,limit:100});for(let e of r.threads)n.set(e.id,e);t=r.nextCursor}while(t)}let r=await sx({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>mx(e.cwd),mapSession:e=>{let t=hx(e.createdAt),n=hx(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:mx(e.name)??mx(e.preview),model:mx(e.model),createdAt:t,updatedAt:n}}});return{records:r.records,status:{scannedAt:t,sessionCount:r.records.length,status:r.skippedCount>0?`partial`:`ready`,...r.skippedCount>0?{error:`Skipped ${r.skippedCount} Codex session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}async scanClaudeSessions(e){let t=new Date().toISOString();try{let n=await sx({sessions:await Mb(),canonicalPathCache:e,getRawPath:e=>mx(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:mx(e.title),model:mx(e.model),createdAt:mx(e.createdAt),updatedAt:e.updatedAt})});return{records:n.records,status:{scannedAt:t,sessionCount:n.records.length,status:n.skippedCount>0?`partial`:`ready`,...n.skippedCount>0?{error:`Skipped ${n.skippedCount} Claude session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}};async function sx(e){let t=[],n=0;for(let r of e.sessions){let i=e.getRawPath(r);if(!i){n+=1;continue}try{let n=await fx(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function cx(e,t){let n=new Map;for(let e of t)for(let t of e.records){let e=n.get(t.canonicalProjectPath);e||(e={path:t.canonicalProjectPath,key:px(t.canonicalProjectPath),title:p.default.basename(t.canonicalProjectPath)||t.canonicalProjectPath,providerCounts:{codex:0,claude:0},sessionsByKey:new Map},n.set(t.canonicalProjectPath,e));let r=`${t.session.provider}:${t.session.nativeSessionId}`,i=e.sessionsByKey.get(r);i||(e.providerCounts[t.session.provider]+=1);let a=gx(i,t.session);e.sessionsByKey.set(r,a),(!e.lastSessionAt||t.session.updatedAt>e.lastSessionAt)&&(e.lastSessionAt=t.session.updatedAt)}let r=[...n.values()].map(t=>({project:{key:t.key,path:t.path,title:t.title,lastSessionAt:t.lastSessionAt,sessionCount:t.sessionsByKey.size,providerCounts:t.providerCounts,lastDiscoveryAt:e},sessions:[...t.sessionsByKey.values()].sort(vx)})).sort((e,t)=>_x(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function lx(e){return Object.values(e).some(e=>e?.status===`failed`)}async function ux(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await lv(t);return e.find(e=>e.path===r)}function dx(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function fx(e,t){let n=t.get(e);return n||(n=lv(e),t.set(e,n)),n}function px(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function mx(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function hx(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function gx(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function _x(e,t){let n=e.lastSessionAt??e.lastDiscoveryAt,r=t.lastSessionAt??t.lastDiscoveryAt;return n===r?e.path.localeCompare(t.path):r.localeCompare(n)}function vx(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var yx=class{indexPath;projectsDir;ready;writeQueue=Promise.resolve();indexCache=null;projectCache=new Map;constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`discovery-index.json`),this.projectsDir=p.default.join(e,`discovery-projects`),this.ready=this.loadFromDisk()}async init(){await this.ready}async getIndex(){return await this.ready,this.indexCache?structuredClone(this.indexCache):null}async getProject(e){await this.ready;let t=this.projectCache.get(e);if(t)return structuredClone(t);let n=await bx(this.getProjectPath(e),Cx);return n?(this.projectCache.set(e,n),structuredClone(n)):null}async getSnapshot(){if(await this.ready,!this.indexCache)return null;let e=[];for(let t of this.indexCache.projects){let n=await this.getProject(t.key);if(!n)return null;e.push({project:n.project,sessions:n.sessions})}return{generatedAt:this.indexCache.generatedAt,providers:structuredClone(this.indexCache.providers),projects:structuredClone(this.indexCache.projects),projectSessions:e}}async writeSnapshot(e){await this.ready;let t={v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects},n=e.projectSessions.map(t=>({v:1,projectKey:t.project.key,canonicalProjectPath:t.project.path,project:t.project,providers:e.providers,sessions:t.sessions}));await this.enqueueWrite(async()=>{await d.default.mkdir(this.projectsDir,{recursive:!0});let e=new Set(n.map(e=>e.projectKey)),r=[];try{r=await d.default.readdir(this.projectsDir,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}await Promise.all(n.map(async e=>{await xx(this.getProjectPath(e.projectKey),e)})),await Promise.all(r.map(async t=>{if(!t.isFile()||!t.name.endsWith(`.json`))return;let n=t.name.slice(0,-5);e.has(n)||(await d.default.rm(p.default.join(this.projectsDir,t.name),{force:!0}),this.projectCache.delete(n))})),await xx(this.indexPath,t),this.indexCache=t,this.projectCache.clear();for(let e of n)this.projectCache.set(e.projectKey,e)})}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0}),await d.default.mkdir(this.projectsDir,{recursive:!0}),this.indexCache=await bx(this.indexPath,Sx)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function bx(e,t){try{let n=await d.default.readFile(e,`utf8`),r=JSON.parse(n);return t(r)?r:null}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function xx(e,t){let n=`${JSON.stringify(t,null,2)}\n`;try{if(await d.default.readFile(e,`utf8`)===n)return}catch(e){if(e.code!==`ENOENT`)throw e}await d.default.mkdir(p.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await d.default.writeFile(r,n,`utf8`),await d.default.rename(r,e)}function Sx(e){return!wx(e)||e.v!==1||typeof e.generatedAt!=`string`||!qa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ja.safeParse(e).success)}function Cx(e){return!wx(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ja.safeParse(e.project).success||!qa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ya.safeParse(e).success)}function wx(e){return typeof e==`object`&&!!e}const Tx=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function Ex(e){let t=xo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=ss(us(Ax(i.export({format:`jwk`})))),o=Zo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a}}),s=(0,l.sign)(null,Buffer.from(o,`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`);return{gatewayHello:So.parse({version:t.version,securityLevel:t.securityLevel,cipherSuite:t.cipherSuite,gatewayId:e.gatewayId,deviceId:t.deviceId,clientNonce:t.clientNonce,gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a,signatureAlgorithm:`ed25519`,signature:s}),gatewayEphemeralPrivateKey:r}}function Dx(e){let t=xo.parse(e.clientHello),n=So.parse(e.gatewayHello),r=Co.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!uo.safeParse(t.cipherSuite).success||n.cipherSuite!==t.cipherSuite||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported_version`);if(r.gatewayId!==e.gatewayId||n.gatewayId!==e.gatewayId)throw Error(`transcript_invalid`);if(r.deviceId!==t.deviceId||n.deviceId!==t.deviceId||r.deviceIdentityFingerprint!==t.deviceIdentity.publicKeyFingerprint)throw Error(`identity_mismatch`);let i=(0,l.createPublicKey)({format:`der`,type:`spki`,key:Buffer.concat([Tx,cs(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Qo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,cs(r.signature)))throw Error(`transcript_invalid`)}function Ox(e){let t=So.parse(e.gatewayHello),n=Co.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:ls(cs(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return ts({role:`gateway`,keySchedule:es({gatewayId:e.gatewayId,clientHello:xo.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function kx(e){return Do.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function Ax(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var jx=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}sendProviderRaw(e){this.onPayload(e)}close(){this.readyState=3}},Mx=class{mobileConnections=new Map;constructor(e){this.dependencies=e}async handleFrame(e){switch(e.type){case`mobile.connected`:this.addMobileConnection(e.mobileId??``,e.payload.deviceId,e.payload.deliveryMode,e.payload.gatewayAvailableAtConnect);return;case`mobile.disconnected`:this.removeMobileConnection(e.mobileId??``);return;case`secure.client_hello`:await this.handleSecureClientHello(e.mobileId,e.payload);return;case`secure.client_auth`:await this.handleSecureClientAuth(e.mobileId,e.payload);return;case`from_mobile`:await this.handleFromMobile(e);return;case`rpc.request`:await this.handleRpcRequest(e);return;case`pairing.claim.forward`:await this.handlePairingClaim(e.requestId,e.payload);return;case`auth.refresh.forward`:await this.handleRefresh(e.requestId,e.payload);return;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e)}addMobileConnection(e,t,n,r){e&&(this.removeMobileConnection(e),this.mobileConnections.set(e,{mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}}),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(Jo.parse({type:`secure.handshake_required`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,gatewayId:this.dependencies.gatewayId,deviceId:t,reason:r?`gateway_restarted`:`gateway_available`,retryable:!0}})))}removeMobileConnection(e){let t=this.mobileConnections.get(e);t&&(t.socket?.close(),t.clientId&&this.dependencies.sessionHub.removeClient(t.clientId),this.mobileConnections.delete(e))}async handleFromMobile(e){let t=e.mobileId;if(!t){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile frame requires mobileId`});return}let n=this.mobileConnections.get(t);if(!n){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${t}`});return}if(n.handshake.status!==`ready`||!n.clientId){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let r=n,i=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>ca.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});i&&await this.dependencies.dispatchCommand(i,r.deviceId,r.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(Jo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Px(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Jo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Px(t,`auth.refresh`)})}}async handleRpcRequest(e){let t=e.mobileId,n=e.requestId,r=this.mobileConnections.get(t);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:{...Nx(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status!==`ready`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>Oo.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(a)try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(Jo.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let r=jo.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...r.success?r.data:Nx(`INTERNAL`,500,String(e)),method:a.method})})}}async handleSecureClientHello(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_hello frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status!==`awaiting_client_hello`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_hello`);return}if(t.deviceId!==n.deviceId){this.sendSecureError(e,n.deviceId,`identity_mismatch`,`deviceId does not match relay token`);return}if(t.version!==1||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`){this.sendSecureError(e,n.deviceId,`unsupported_version`,`unsupported secure handshake version`);return}let r=Ex({gatewayId:this.dependencies.gatewayId,gatewayIdentity:this.dependencies.gatewayIdentity,privateKeyPem:this.dependencies.gatewayIdentityPrivateKeyPem,clientHello:t});n.handshake={status:`awaiting_client_auth`,clientHello:t,gatewayHello:r.gatewayHello,gatewayEphemeralPrivateKey:r.gatewayEphemeralPrivateKey},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Jo.parse({type:`secure.gateway_hello`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:r.gatewayHello}))}async handleSecureClientAuth(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_auth frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status===`ready`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_auth`);return}if(n.handshake.status!==`awaiting_client_auth`){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure.client_hello missing`);return}try{Dx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Fx(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=Ox({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t,gatewayEphemeralPrivateKey:n.handshake.gatewayEphemeralPrivateKey});this.ensureReadyMobileClient(n),n.handshake={status:`ready`,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,session:i},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Jo.parse({type:`secure.ready`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,securityLevel:`e2ee-relay`,cipherSuite:i.cipherSuite,gatewayId:this.dependencies.gatewayId,deviceId:n.deviceId,keyEpoch:i.keyEpoch,deviceIdentityFingerprint:r.publicKeyFingerprint??n.handshake.clientHello.deviceIdentity.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus??`active`}}))}catch(t){this.sendSecureError(e,n.deviceId,Lx(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new jx(t=>{try{let n=Jo.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,...this.createRelayBusinessPayloadFields(e,{frameType:`to_mobile`,messageType:`event`},t)});this.dependencies.sendFrame(n)}catch(t){this.sendSecureError(e.mobileId,e.deviceId,Ix(t),`relay secure payload failed: ${String(t)}`)}}),n=this.dependencies.sessionHub.addClient(e.deviceId,t);e.socket=t,e.clientId=n}sendSecureError(e,t,n,r){this.dependencies.sendFrame({type:`secure.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:kx({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`||n===`key_epoch_mismatch`})})}sendRelayError(e){this.dependencies.sendFrame({type:`relay.error`,gatewayId:this.dependencies.gatewayId,...e.mobileId?{mobileId:e.mobileId}:{},...e.requestId?{requestId:e.requestId}:{},messageType:`system`,payload:Nx(e.code,e.status,e.message)})}decodeRelayBusinessPayload(e){if(e.payload!==void 0)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload must be encrypted`),null;if(!e.encryptedPayload)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload missing`),null;try{return os({session:e.connection.handshake.session,metadata:{frameType:e.frameType,messageType:e.messageType,gatewayId:this.dependencies.gatewayId,...e.requestId?{requestId:e.requestId}:{}},encryptedPayload:e.encryptedPayload,parse:e.parse})}catch(t){return this.sendSecureError(e.mobileId,e.connection.deviceId,Ix(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:as({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},payload:n})}:{payload:n}}};function Nx(e,t,n){return jo.parse({code:e,status:t,message:n})}function Px(e,t){if(Gg(e))switch(e.code){case`PAIRING_CODE_INVALID`:case`PAIRING_CODE_EXPIRED`:return{code:`BAD_REQUEST`,status:e.status,message:String(e)};case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return{code:`UNAUTHORIZED`,status:e.status,message:String(e)};default:return{code:e.status>=500?`INTERNAL`:`BAD_REQUEST`,status:e.status,message:String(e)}}let n=String(e),r=Rx(e);return t===`pairing.claim`&&(r===`Invalid pairing code`||r===`Pairing code expired`)?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(r===`Refresh token revoked`||r===`Device revoked`||r===`Device revoked or not found`||r===`Refresh token device mismatch`||o_(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Fx(e){return zx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function Ix(e){return zx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function Lx(e){if(Gg(e))switch(e.code){case`DEVICE_REVOKED`:return`device_revoked`;case`DEVICE_IDENTITY_NOT_REGISTERED`:case`DEVICE_IDENTITY_MISMATCH`:return`identity_mismatch`;default:return`transcript_invalid`}let t=Rx(e);return t===`Device revoked`||t===`Device revoked or not found`?`device_revoked`:t===`Device identity mismatch`||t===`Device identity not registered`?`identity_mismatch`:`transcript_invalid`}function Rx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function zx(e,t){let n=Rx(e);return t.find(e=>e===n)}function Bx(e){return e?e.readyState:null}var Vx=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;heartbeatIntervalMs;heartbeatTimeoutMs;webSocketFactory;socket;reconnectTimer;heartbeatIntervalTimer;heartbeatTimeoutTimer;reconnectAttempt=0;connectAttemptId=0;state=`idle`;stopped=!1;constructor(e){this.options=e,this.logger=e.logger??{},this.reconnectBaseDelayMs=e.reconnectBaseDelayMs??1e3,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??15e3,this.heartbeatIntervalMs=e.heartbeatIntervalMs??15e3,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??1e4,this.webSocketFactory=e.webSocketFactory??Wx}start(){this.stopped&&=!1,!(this.socket||this.reconnectTimer)&&this.connect()}close(){this.stopped=!0,this.state=`stopped`,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),void 0);let e=this.socket;if(this.socket=void 0,this.stopHeartbeat(),!e)return;let t=Bx(e);try{e.close(1e3,`Gateway shutting down`)}catch(n){this.logger.error?.({err:n,readyState:t},`relay websocket close threw during shutdown`);try{e.terminate()}catch(e){this.logger.error?.({err:e,readyState:t},`relay websocket terminate threw after close failure`)}}}isConnected(){let e=this.socket;return this.state===`connected`&&!!e&&e.readyState===e.OPEN}send(e){let t=this.socket;if(!t||t.readyState!==t.OPEN)return!1;let n=Jo.parse(e);return t.send(JSON.stringify(n)),!0}async connect(){if(this.stopped)return;let e=++this.connectAttemptId,t;try{t=await this.resolveGatewayAccessToken()}catch(e){this.state=`idle`,this.logger.warn?.({err:e},`failed to resolve relay gateway access token`),this.scheduleReconnect();return}if(this.stopped||e!==this.connectAttemptId)return;let n=Hx(this.options.relayUrl);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.on(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,this.startHeartbeat(r),this.logger.info?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId},`relay gateway websocket connected`),this.send({type:`gateway.hello`,gatewayId:this.options.gatewayId,messageType:`system`,payload:{name:this.options.machineName,relayBaseUrl:this.options.relayUrl,directBaseUrls:this.options.directBaseUrls,transportSecurityLevel:`e2ee-relay`,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=Jo.parse(JSON.parse(Ux(e)));Promise.resolve(this.options.onFrame(t)).catch(e=>{this.logger.error?.({err:e},`failed to handle relay frame`)})}catch(e){this.logger.warn?.({err:e},`failed to parse relay frame from relay`)}}}),r.on(`error`,e=>{this.socket===r&&this.logger.warn?.({err:e},`relay websocket emitted error`)}),r.on(`pong`,()=>{this.socket===r&&this.ackHeartbeat(r)}),r.on(`close`,(e,t)=>{if(this.socket===r){if(this.socket=void 0,this.stopHeartbeat(),this.stopped){this.state=`stopped`;return}this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,closeCode:e,closeReason:t.toString(`utf8`)},`relay websocket closed`),this.state=`idle`,this.scheduleReconnect()}})}async resolveGatewayAccessToken(){let e=this.options.relayGatewayAccessToken.trim();if(e)return e;let t=this.options.resolveRelayGatewayAccessToken;if(t)return t();throw Error(`Gateway relay access token is not configured`)}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;let e=Math.min(this.reconnectMaxDelayMs,this.reconnectBaseDelayMs*Math.max(1,2**this.reconnectAttempt));this.reconnectAttempt+=1,this.logger.info?.({delayMs:e},`scheduling relay reconnect`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatIntervalTimer=setInterval(()=>{if(!(this.socket!==e||this.stopped)&&!(e.readyState!==e.OPEN||this.heartbeatTimeoutTimer)){try{e.ping()}catch(t){this.logger.warn?.({err:t},`failed to send relay websocket heartbeat ping`),e.terminate();return}this.heartbeatTimeoutTimer=setTimeout(()=>{this.heartbeatTimeoutTimer=void 0,!(this.socket!==e||this.stopped||e.readyState!==e.OPEN)&&(this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,heartbeatTimeoutMs:this.heartbeatTimeoutMs},`relay websocket heartbeat timed out`),e.terminate())},this.heartbeatTimeoutMs)}},this.heartbeatIntervalMs)}ackHeartbeat(e){this.socket===e&&(this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0))}stopHeartbeat(){this.heartbeatIntervalTimer&&=(clearInterval(this.heartbeatIntervalTimer),void 0),this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0)}};function Hx(e){let t=new URL(e);return t.protocol===`http:`?t.protocol=`ws:`:t.protocol===`https:`&&(t.protocol=`wss:`),t.pathname=`/ws/gateway`,t.toString()}function Ux(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):String(e)}function Wx(e){return new dv(e)}function Gx(e){let t={gatewayId:e.gatewayId.trim(),gatewayIdentity:e.gatewayIdentity,requestedAt:e.requestedAt??new Date().toISOString()};if(!t.gatewayId)throw Error(`gatewayId must not be empty when requesting a guest relay gateway access token.`);return{grantType:`guest`,payload:t,signatureAlgorithm:`ed25519`,signature:(0,l.sign)(null,Buffer.from(Yo(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function Kx(e){let t=e.fetchImpl??globalThis.fetch;if(!t)throw Error(`fetch is not available when requesting a guest relay gateway access token.`);let n=await t(qx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Gx({gatewayId:e.gatewayId,gatewayIdentity:e.gatewayIdentity,privateKeyPem:e.privateKeyPem}))}),r=await n.text();if(!n.ok)throw Error(`Failed to request a guest relay gateway access token (${n.status}): ${r}`);return Lo.parse(JSON.parse(r)).token}function qx(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=`/api/gateway-token/guest`,t.search=``,t.toString()}function Jx(e){return e?.trim()||void 0}function Yx(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function Xx(e,t){return{modeDefault:`default`,model:Jx(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function Zx(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function Qx(e,t){let n=Zx(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function $x(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function eS(e){let t=Qx(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Jx(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?tS({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function tS(e){let t=Qx(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?$x(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=Qx(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=Jx(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??Jx(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:Yx(r.execution)}}}const nS=[],rS=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],iS=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],aS=Ni.options,oS=[`read-only`,`workspace-write`,`danger-full-access`],sS=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],cS=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function lS(e,t){cS&&(!e.startsWith(`config.get`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function uS(e){return e?{sessionFound:!0,sessionId:e.id,nativeSessionId:e.nativeSessionId??null,sessionSource:e.source??null,sessionModel:e.model??null,sessionUpdatedAt:e.updatedAt,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt??null,sessionTurnConfigModel:e.sessionTurnConfig?.model??null,sessionTurnConfigReasoningEffort:e.sessionTurnConfig?.reasoningEffort??null,sessionTurnConfigApprovalPolicy:e.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,sessionTurnConfigSandboxMode:e.sessionTurnConfig?.execution?.codex?.sandboxMode??null,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null}:{sessionFound:!1}}const dS={codex:[{version:`codex-mobile-v1`,defaults:{reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]},fS={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function pS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function mS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function hS(e,t){let n=t?.trim().toLowerCase();return n?(dS[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function gS(e,t,n){return e.some(e=>e.id===t)?e.map(e=>({...e,isDefault:e.id===t})):[{id:t,label:t,isDefault:!0,...n===`codex`?{supportedReasoningEfforts:iS}:{}},...e.map(e=>({...e,isDefault:!1}))]}function _S(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function vS(e){let t=new Set;for(let n of e){let e=_S(n);e&&t.add(e)}return[...t]}function yS(e){return e?.trim()||void 0}function bS(e){let t=yS(e.runtimeModel);if(t)return t;let n=yS(e.discoveredModel);if(n)return n;let r=yS(e.existingModel),i=yS(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function xS(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,description:e.description,isDefault:e.isDefault,supportedReasoningEfforts:vS(e.supportedReasoningEfforts)}));return t.length===0?nS:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function SS(e){let t=Date.now();try{let n=xS(await jy());return e?.info?.({provider:`codex`,durationMs:Date.now()-t,modelCount:n.length},`provider capabilities codex model load completed`),n}catch(n){return e?.warn?.({provider:`codex`,durationMs:Date.now()-t,err:n},`provider capabilities codex model load failed`),null}}async function CS(e){let t=Date.now();try{let n=await import(`@anthropic-ai/claude-agent-sdk`),r=n.query??n.default?.query;if(typeof r!=`function`)return null;let i=r,a=p.default.join(nc(),`claude-capability-probe`);await d.default.mkdir(a,{recursive:!0,mode:448});let o=i({prompt:`/clear`,options:{cwd:a,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let n=await o.supportedModels(),r=[];for(let e of n){let t=typeof e.value==`string`?e.value:``;if(!t)continue;let n=Array.isArray(e.supportedEffortLevels)&&e.supportedEffortLevels.length>0,i=TS(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?vS(e.supportedEffortLevels??[]):i===`haiku`?[]:void 0;r.push({id:t,label:e.displayName||t,description:typeof e.description==`string`&&e.description.trim()?e.description.trim():void 0,isDefault:t===`default`,supportedReasoningEfforts:a})}return r.length===0?null:(r.some(e=>e.isDefault)||(r[0]={...r[0],isDefault:!0}),e?.info?.({provider:`claude`,durationMs:Date.now()-t,modelCount:r.length},`provider capabilities claude model load completed`),r)}finally{o.close()}}catch(n){return e?.warn?.({provider:`claude`,durationMs:Date.now()-t,err:n},`provider capabilities claude model load failed`),null}}function wS(e){let t=(e.find(e=>e.isDefault)??e[0])?.supportedReasoningEfforts??[];if(t.includes(`medium`))return`medium`;if(t.includes(`high`))return`high`;if(t.length>0)return t[0]}function TS(...e){for(let t of e){let e=t?.trim().toLowerCase();if(e){if(e.includes(`haiku`))return`haiku`;if(e.includes(`opus`))return`opus`;if(e.includes(`sonnet`)||e.includes(`sonnect`))return`sonnet`}}}var ES=class{sessions=new Map;providerCapabilitiesCache=new Map;providerCapabilitiesInFlight=new Map;nextRawSeqBySession=new Map;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.runtimeLifecycle={idleTtlMs:pS(e.runtimeLifecycle?.idleTtlMs,fS.idleTtlMs),sweepIntervalMs:mS(e.runtimeLifecycle?.sweepIntervalMs,fS.sweepIntervalMs),maxSessions:pS(e.runtimeLifecycle?.maxSessions,fS.maxSessions),maxCodexSessions:pS(e.runtimeLifecycle?.maxCodexSessions,fS.maxCodexSessions),maxClaudeSessions:pS(e.runtimeLifecycle?.maxClaudeSessions,fS.maxClaudeSessions)},this.runtimeLifecycle.sweepIntervalMs<=0){this.sweepTimer=null;return}this.sweepTimer=setInterval(()=>{this.sweepRuntimeSessions().catch(e=>{console.error(`[session-runtime] sweep failed: ${String(e)}`)})},this.runtimeLifecycle.sweepIntervalMs),this.sweepTimer.unref?.()}async shutdown(){this.shuttingDown=!0,this.sweepTimer&&clearInterval(this.sweepTimer);let e=[...this.sessions.keys()];this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown starting`),await Promise.allSettled(e.map(e=>this.closeRuntimeSession(e,`shutdown`))),await Nv(),this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown completed`)}async listProjects(){let e=await this.options.projectStore.list(),t=this.buildProjectStatsMap();return e.map(e=>this.attachProjectStats(e,t))}async createProject(e){let t=await this.options.projectStore.upsertByPath(e.path,e.title);return this.attachProjectStats(t,this.buildProjectStatsMap())}async deleteProject(e){if(this.listProjectSessionsWithRuntime(e,`running`).length>0)throw e_(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.listAllSessionsWithRuntime(`running`).length;if(e>0)throw t_(e);let t=[...this.sessions.values()].filter(e=>e.provider===`codex`).map(e=>e.id);return await Promise.allSettled(t.map(e=>this.closeRuntimeSession(e,`codex_restart`))),await Pv(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.app_server.restart`,detail:{closedRuntimeSessionCount:t.length}}),{restarted:!0,closedRuntimeSessionCount:t.length}}async getProject(e){return this.options.projectStore.getById(e)}buildProjectStatsMap(){let e=new Map,t=this.listAllSessionsWithRuntime(`all`);for(let n of t){let t=e.get(n.projectId)??{runningCount:0,idleCount:0,totalCount:0,lastSessionAt:void 0};n.status===`running`?t.runningCount+=1:t.idleCount+=1,t.totalCount+=1;let r=n.updatedAt||n.createdAt;(!t.lastSessionAt||r>t.lastSessionAt)&&(t.lastSessionAt=r),e.set(n.projectId,t)}return e}attachProjectStats(e,t){let n=t.get(e.id),r=n?.idleCount??0;return{...e,lastSessionAt:n?.lastSessionAt,runningCount:n?.runningCount??0,idleCount:r,totalCount:n?.totalCount??0,endedCount:r}}async getProviderCapabilities(e,t,n){return(await this.resolveProviderCapabilities(e,t,n)).capabilities}async getAgentConfig(e,t){let n=await this.resolveProviderCapabilities(e,t?.projectId,t?.agentVersion);return{agent:{provider:e,requestedVersion:t?.agentVersion?.trim()||null,resolvedVersion:n.resolvedAgentVersion},capabilities:n.capabilities}}async warmStartupProviderCapabilities(){if(!this.options.preferNativeProviders||this.shuttingDown)return;let e=dS.claude.length>0?dS.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw Zg(t);let r=hS(e,n),i=r?.version??`default`,a=`${e}::${i}`,o={provider:e,projectId:t??null,requestedAgentVersion:n?.trim()||null,resolvedAgentVersion:i},s=Date.now(),c=this.providerCapabilitiesCache.get(a);if(c){if(c.expiresAt>s)return this.options.logger?.info?.({...o,cacheStatus:`hit`,source:c.value.capabilities.source,modelCount:c.value.capabilities.models.length},`provider capabilities cache hit`),c.value;this.providerCapabilitiesCache.delete(a)}let l=this.providerCapabilitiesInFlight.get(a);if(l)return this.options.logger?.info?.({...o,cacheStatus:`in_flight`},`provider capabilities awaiting in-flight load`),l;let u=Date.now(),d=(async()=>{let t=kb(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=Date.now(),a=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1;this.options.logger?.info?.({...o,cacheStatus:`miss`,nativeAvailable:a,durationMs:Date.now()-n},`provider capabilities native availability checked`);let s=a?`native`:`fallback`,c=e===`codex`&&a?await SS(this.options.logger)??nS:nS,l=e===`claude`&&a?await CS(this.options.logger)??rS:rS,d=vS(l.flatMap(e=>e.supportedReasoningEfforts??[])),f=e===`codex`?{provider:e,source:s,models:c,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:iS,approvalPolicies:aS,sandboxModes:oS,permissionModes:[]},defaults:{model:c.find(e=>e.isDefault)?.id??c[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:s,models:l,support:{reasoningEffort:d.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:d,approvalPolicies:[],sandboxModes:[],permissionModes:sS},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:wS(l),permissionMode:`default`}};if(!r){let e={capabilities:f,resolvedAgentVersion:i};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:e.capabilities.source,modelCount:e.capabilities.models.length},`provider capabilities resolved`),e}let p={...f.defaults,...r.defaults},m=p.model?.trim(),h=s===`native`?f.models:m?gS(f.models,m,e):f.models,g={capabilities:{...f,models:h,defaults:p},resolvedAgentVersion:r.version};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:g.capabilities.source,modelCount:g.capabilities.models.length},`provider capabilities resolved`),g})();this.providerCapabilitiesInFlight.set(a,d);try{let e=await d;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}catch(e){throw this.options.logger?.warn?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,err:e},`provider capabilities resolution failed`),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return Xx(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Zg(e);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){let n=this.options.historyStore.getProjectSession(e,t);return this.getRuntimeSessionSummary(e,t,n)||n}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(lS(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:uS(n),runtime:uS(r)}),r)return lS(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...uS(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return lS(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...uS(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw Zg(e);let r=this.options.historyStore.getProjectSession(e,t);if(!r&&this.options.preferNativeProviders&&(await this.syncCodexSessionsForProject(n),await this.syncClaudeSessionsForProject(n),r=this.options.historyStore.getProjectSession(e,t)),!r)throw Qg(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.syncExternalRawHistory(r,e,i);return{session:this.options.historyStore.getProjectSession(e,r.id)??r,rawEvents:a}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw Zg(e);let i=0,a=0,o,s=(s,c)=>{lS(`raw-events.read`,{projectId:e,sessionId:t,limit:n,provider:o?.provider,source:o?.source,providerMode:o?.providerMode,localReadDurationMs:i,finalCount:a,outcome:s,totalDurationMs:Date.now()-r,...c})},c=this.options.historyStore.getProjectSession(e,t);if(!c&&this.getRuntimeSessionSummary(e,t))return s(`runtime_session_empty`),[];if(!c)throw Qg(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEvents(c.id,Math.max(n,300));return i=Date.now()-l,a=u.slice(-Math.max(1,n)).length,s(`local_only_cached`,{localEventCount:u.length}),u.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompacted(r.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3){let i=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsSinceSeq(i.id,n,r)}async getProjectSessionRawSeqRange(e,t){let n=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawSeqRange(n.id)}async resolveProjectSessionForRawRead(e,t){if(!await this.options.projectStore.getById(e))throw Zg(e);let n=this.options.historyStore.getProjectSession(e,t);if(!n)throw Qg(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${pg(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=kb(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?Qx(e.provider,e.sessionTurnConfig):eS({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=tS({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw $g(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=tS({provider:i.provider,providerDefaults:a,currentSessionTurnConfig:i.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});i.dispatchInFlight=!0,this.touchSession(i);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),!i.title){let e=XS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=Qx(i.provider,o.sessionTurnConfig),i.sessionTurnConfigUpdatedAt=a,o.model&&i.model!==o.model&&(i.model=o.model),i.updatedAt=a,await this.persistSessionSnapshot(i)}finally{i.dispatchInFlight=!1,this.touchSession(i)}}async respondToolPermission(e,t,n,r,i){let a=this.mustGetSession(e);if(!a.pendingToolApprovals.has(t))throw Error(`Unknown tool approval request: ${t}`);if(typeof a.providerSession.respondToolPermission!=`function`){a.pendingToolApprovals.delete(t),a.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(a);return}await a.providerSession.respondToolPermission(t,n,r),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`tool.approval.respond`,deviceId:i,sessionId:e,detail:{requestId:t,decision:n,reason:r}})}async respondUserInput(e,t,n,r){let i=this.mustGetSession(e);if(!i.pendingUserInputs.has(t))throw Error(`Unknown user input request: ${t}`);if(typeof i.providerSession.respondUserInput!=`function`){i.pendingUserInputs.delete(t),i.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(i);return}await i.providerSession.respondUserInput(t,n),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`user.input.respond`,deviceId:r,sessionId:e,detail:{requestId:t,answeredCount:QS(n)}})}async interruptSession(e,t){let n=this.sessions.get(e);n&&await n.providerSession.interrupt(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.interrupt`,deviceId:t,sessionId:e,detail:{runtimeSessionFound:!!n}})}async closeSession(e){throw Error(`session.close is deprecated. Use session.interrupt instead.`)}getSessionExecutionContext(e){let t=this.sessions.get(e);if(t)return{provider:t.provider,projectId:t.projectId,projectPath:t.projectPath};let n=this.options.historyStore.getSession(e);if(!n)throw $g(e);return{provider:n.provider,projectId:n.projectId,projectPath:n.projectPath}}async emitExternalEvent(e){let t=this.options.historyStore.getSession(e.sessionId),n={v:`1.0`,kind:`provider.raw`,rawSeq:await this.nextRawSeq(e.sessionId),provider:e.provider,sessionId:e.sessionId,projectId:e.projectId??t?.projectId,eventId:`raw_${pg(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:e.type,payload:{raw:{...e.raw,type:e.type}}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}async resumeSessionFromHistory(e){let t=this.options.historyStore.getSession(e);if(!t)return;let n=t.provider===`codex`&&this.options.requireNativeCodex,r=kb(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=Qx(t.provider,t.sessionTurnConfig),o=tS({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}async syncCodexSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await Dy(e.path)}catch{return}let n=new Set(t.filter(t=>t.cwd===e.path).map(e=>e.id)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`codex`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){if(n.cwd!==e.path)continue;let t=[...r.values()].find(e=>e.provider===`codex`&&(e.id===n.id||e.nativeSessionId===n.id)),i=t?.id??n.id,a=this.sessions.get(i)??this.sessions.get(n.id),o=$S(n.createdAt),s=$S(n.updatedAt),c=a?.status===`running`?`running`:`idle`,l=c===`running`?a?.pendingToolApprovals.size??0:0,u=c===`running`?a?.pendingUserInputs.size??0:0,d={id:i,nativeSessionId:n.id,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:a?.providerMode??t?.providerMode??`native`,model:bS({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??XS(n.name??n.preview)??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??o,updatedAt:c===`running`?a?.updatedAt??s:s,status:c,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),r.set(i,d)}}async syncClaudeSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await Nb(e.path)}catch{return}let n=new Set(t.map(e=>e.nativeSessionId)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`claude`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){let t=[...r.values()].find(e=>e.provider===`claude`&&(e.id===n.nativeSessionId||e.nativeSessionId===n.nativeSessionId)),i=t?.id??n.nativeSessionId,a=this.sessions.get(i),o=a?.status===`running`?`running`:`idle`,s=o===`running`?a?.pendingToolApprovals.size??0:0,c=o===`running`?a?.pendingUserInputs.size??0:0,l={id:i,nativeSessionId:n.nativeSessionId,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:a?.providerMode??t?.providerMode??`native`,model:a?.model??t?.model??n.model,title:a?.title??n.title??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??n.createdAt,updatedAt:o===`running`?a?.updatedAt??n.updatedAt:n.updatedAt,status:o,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c};await this.options.historyStore.upsertSession(l),r.set(i,l)}}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=VS([e.nativeSessionId,e.id]);for(let n of t)try{lS(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:n,...uS(e)});let t=await Ay(n);if(!t){lS(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:n});continue}let r={...e,model:yS(t.model)??e.model,sessionTurnConfig:t.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt};return await this.options.historyStore.upsertSession(r),lS(`config.get.probe.result`,{projectId:e.projectId,sessionId:e.id,threadId:n,snapshotModel:t.model??null,snapshotSessionTurnConfigModel:t.sessionTurnConfig?.model??null,snapshotReasoningEffort:t.sessionTurnConfig?.reasoningEffort??null,snapshotApprovalPolicy:t.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,snapshotSandboxMode:t.sessionTurnConfig?.execution?.codex?.sandboxMode??null,snapshotUpdatedAt:t.sessionTurnConfigUpdatedAt,next:uS(r)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??r}catch(t){lS(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:n,error:String(t)})}return e}shouldHydrateCodexExternalSessionConfig(e){if(!this.options.preferNativeProviders||e.provider!==`codex`||e.source!==`native_discovered`||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt,n=e.sessionTurnConfigUpdatedAt||``;return!e.sessionTurnConfig||!yS(e.model)||!n?!0:t?n.localeCompare(t)>0?!0:t.localeCompare(n)>0:!1}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw Zg(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await eC(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Zg(e);return await eC(t.path),t}return this.options.projectStore.upsertByPath(t)}async attachRuntimeSession(e){let t=this.sessions.get(e.id);t&&await this.closeRuntimeSession(t.id,`replaced`,{suppressAudit:!0});let n={...e,unsubscribe:()=>{}};return await this.initializeRawSeqCursor(n.id),n.unsubscribe=n.providerSession.onEvent(e=>{if(!n.streamReady){n.bufferedProviderEvents.push(e);return}this.handleProviderEvent(n,e)}),this.sessions.set(n.id,n),n}handleProviderEvent(e,t){let n=this.ensureProviderRequestId(t);if(this.emitRawEnvelope(e,n),this.maybePersistUpdatedNativeSessionId(e),e.updatedAt=new Date().toISOString(),this.touchSession(e),n.type===`thread.title.updated`){let t=ZS(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=ZS(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingToolApprovals.add(t),this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.resolved`&&typeof n.requestId==`string`){e.pendingToolApprovals.delete(n.requestId),this.persistSessionSnapshot(e);return}if(n.type===`user.input.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingUserInputs.add(t),this.persistSessionSnapshot(e);return}if(n.type===`user.input.resolved`&&typeof n.requestId==`string`){e.pendingUserInputs.delete(n.requestId),this.persistSessionSnapshot(e);return}}emitRawEnvelope(e,t){let n={v:`1.0`,kind:`provider.raw`,rawSeq:this.nextRawSeqSync(e.id),provider:e.provider,sessionId:e.id,projectId:e.projectId,eventId:`raw_${pg(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:t.type,payload:{raw:t}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}nextRawEnvelopeTimestamp(){let e=Date.now(),t=e>this.lastRawEnvelopeTimestampMs?e:this.lastRawEnvelopeTimestampMs+1;return this.lastRawEnvelopeTimestampMs=t,new Date(t).toISOString()}async initializeRawSeqCursor(e){if(this.nextRawSeqBySession.has(e))return;let t=await this.options.historyStore.getSessionRawSeqRange(e),n=t?t.max+1:1;this.nextRawSeqBySession.set(e,n)}async nextRawSeq(e){return await this.initializeRawSeqCursor(e),this.nextRawSeqSync(e)}nextRawSeqSync(e){let t=this.nextRawSeqBySession.get(e)??1;return this.nextRawSeqBySession.set(e,t+1),t}touchSession(e){e.lastActiveAtMs=Date.now()}isSessionEvictable(e){return!(e.closing||e.status!==`idle`||e.pendingToolApprovals.size>0||e.pendingUserInputs.size>0||e.dispatchInFlight)}async closeRuntimeSession(e,t,n){let r=this.sessions.get(e);if(!r||r.closing)return!1;r.closing=!0;let i=Date.now();this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,statusBefore:r.status,projectId:r.projectId,projectPath:r.projectPath,model:r.model,pendingApprovalCount:r.pendingToolApprovals.size,pendingUserInputCount:r.pendingUserInputs.size,dispatchInFlight:r.dispatchInFlight},`provider runtime session close starting`);try{r.unsubscribe()}catch{}let a;try{await r.providerSession.close()}catch(n){a=n,console.error(`[session-runtime] failed closing session ${e}:`,n),this.options.logger?.error?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,error:String(n),err:n},`provider runtime session close failed`)}finally{r.status=`idle`,r.updatedAt=new Date().toISOString(),r.pendingToolApprovals.clear(),r.pendingUserInputs.clear();try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}this.sessions.delete(e),r.dispatchInFlight=!1,r.closing=!1}if(this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,result:a?`error`:`success`,durationMs:Date.now()-i},`provider runtime session close completed`),!n?.suppressAudit)try{await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.runtime.close`,sessionId:e,detail:{reason:t,provider:r.provider}})}catch(e){console.error(`[session-runtime] failed to record runtime close audit log: ${String(e)}`)}return!0}async sweepRuntimeSessions(){if(this.shuttingDown||this.sessions.size===0)return;let e=Date.now(),t=this.runtimeLifecycle.idleTtlMs,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs);for(let r of n)e-r.lastActiveAtMs<t||await this.closeRuntimeSession(r.id,`idle_ttl`);await this.enforceProviderSessionCap(`codex`,this.runtimeLifecycle.maxCodexSessions),await this.enforceProviderSessionCap(`claude`,this.runtimeLifecycle.maxClaudeSessions),await this.enforceGlobalSessionCap(this.runtimeLifecycle.maxSessions)}async enforceProviderSessionCap(e,t){let n=[...this.sessions.values()].filter(t=>t.provider===e);if(n.length<=t)return;let r=n.length-t,i=n.filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),a=0;for(let e of i){if(a>=r)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(a+=1)}a<r&&console.warn(`[session-runtime] ${e} sessions exceed cap (${n.length}/${t}), no more idle sessions to evict`)}async enforceGlobalSessionCap(e){if(this.sessions.size<=e)return;let t=this.sessions.size-e,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),r=0;for(let e of n){if(r>=t)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(r+=1)}r<t&&console.warn(`[session-runtime] session count exceeds cap (${this.sessions.size}/${e}), no more idle sessions to evict`)}ensureProviderRequestId(e){return e.type===`tool.permission.requested`||e.type===`user.input.requested`?typeof e.requestId==`string`&&e.requestId.trim()?e:{...e,requestId:`req_${pg(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n)return t;let r=await this.options.historyStore.mergeSessionRawEvents(e.id,t),i=r[r.length-1]?.rawSeq;return typeof i==`number`&&Number.isFinite(i)&&i>0&&this.nextRawSeqBySession.set(e.id,i+1),r}async syncExternalRawHistory(e,t,n){if(e.provider===`claude`){let r=US(e);if(!r)return n;try{let i=Date.now(),a=await Pb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t}),o=Date.now(),s=await this.finalizeExternalRawHistorySync(e,n,a);return lS(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,historyEventCount:a.length,resultEventCount:s.length,readHistoryDurationMs:o-i,finalizeDurationMs:Date.now()-o}),s}catch(r){return e.source===`native_discovered`&&HS(r)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),lS(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,error:r instanceof Error?r.message:String(r)}),n}}if(e.provider!==`codex`)return n;let r=VS([e.nativeSessionId,e.id]);for(let i of r)try{let r=Date.now(),a=await ky(i,!0),o=Date.now(),s=e.source===`gateway`&&n.length>0?qS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):WS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localTerminalTurnStatusById:GS(n),localTurnLastEventTsById:KS(n)}),c=Date.now(),l=await this.finalizeExternalRawHistorySync(e,n,s,$S(a.updatedAt));return lS(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,localEventCount:n.length,historyEventCount:s.length,resultEventCount:l.length,readThreadDurationMs:o-r,buildHistoryDurationMs:c-o,finalizeDurationMs:Date.now()-c}),l}catch{}return n}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt){let i=Date.now(),a=OS(e.provider,t,n),o=Date.now(),s=await this.maybePersistSyncedExternalRawEvents(e,a,!0);return await this.markExternalHistoryHydrated(e.id,r),lS(`sync-external.finalize`,{sessionId:e.id,provider:e.provider,source:e.source,localEventCount:t.length,historyEventCount:n.length,mergedEventCount:a.length,persistedEventCount:s.length,hydratedExternalUpdatedAt:r,mergeDurationMs:o-i,persistDurationMs:Date.now()-o}),s}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw $g(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=YS(t);!n||n===e.title||(e.title=n,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}resolveCanonicalSessionId(e,t,n){return e===`codex`&&t.getNativeSessionId?.()||n}resolveNativeSessionId(e,t,n){return e!==`codex`&&e!==`claude`?n:t.getNativeSessionId?.()||n}maybePersistUpdatedNativeSessionId(e){let t=this.resolveNativeSessionId(e.provider,e.providerSession,e.nativeSessionId);!t||t===e.nativeSessionId||this.shouldPersistNativeSessionId(e,t)&&(e.nativeSessionId=t,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}shouldPersistNativeSessionId(e,t){return e.source===`native_discovered`?!1:e.nativeSessionId?e.nativeSessionId===e.id&&e.id.startsWith(`sess_`)?t!==e.nativeSessionId:!1:!0}};const DS=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function OS(e,t,n){let r=new Map,i=new Set,a=kS(e),o=kS(e);for(let n of t){r.set(n.eventId,n);for(let t of AS(e,n,a))i.add(t)}for(let t of n){if(r.has(t.eventId))continue;let n=AS(e,t,o);if(!(n.length>0&&n.every(e=>i.has(e)))){r.set(t.eventId,t);for(let e of n)i.add(e)}}return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function kS(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function AS(e,t,n){return e===`codex`?jS(t,n):e===`claude`?PS(t):[]}function jS(e,t){let n=LS(e.payload.raw),r=new Set,i=FS(e.type,n);if(i){let a=MS(e.type,n);a?r.add(NS(a,t)):r.add(i)}if(e.type!==`native.raw`||$(n.source)!==`codex.history.thread_read`)return[...r];let a=LS(n.message),o=$(a.scope);if(o===`thread`){let e=LS(a.thread),t=$(e.id);t&&r.add(IS(`thread.started`,{thread_id:t,thread:e}));let n=XS(RS(e.preview)??RS(e.name)??``);return n&&r.add(IS(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(o===`turn`){let e=LS(a.turn),t=$(e.status);return r.add(IS(`turn.started`,{turn:e})),t===`completed`?r.add(IS(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(IS(`turn.failed`,{status:t,turn:e})),[...r]}if(o===`item`){let e={turn_id:$(a.turn_id)??$(LS(a.item).turn_id),item:LS(a.item)},n=MS(`item.completed`,e);return n?r.add(NS(n,t)):r.add(IS(`item.completed`,e)),[...r]}return[...r]}function MS(e,t){if(!e.startsWith(`item.`))return;let n=LS(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=$(n.type);if(!(!r||!i))return[`codex`,e,r,i,$(n.phase)??``,$(n.status)??``,$(n.command)??``,zS(n)??``].join(`|`)}function NS(e,t){let n=t?.codexTurnScopedItemOccurrences;if(!n)return e;let r=(n.get(e)??0)+1;return n.set(e,r),`${e}|${r}`}function PS(e){let t=LS(e.payload.raw),n=FS(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!DS.has(r))return[];let i=LS(t.message),a=$(t.native_type)??$(i.type),o=LS(i.message);if(a===`user`){let e=BS(o),t=$(i.uuid);return!e||!t?[]:[IS(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=BS(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[IS(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function FS(e,t){switch(e){case`thread.started`:case`thread.title.updated`:case`turn.started`:case`turn.completed`:case`turn.failed`:case`item.started`:case`item.updated`:case`item.completed`:return IS(e,t);default:return}}function IS(e,t){let n=LS(t.item),r=LS(t.turn),i=LS(t.thread),a=$(n.id)??``,o=$(t.turn_id)??$(t.turnId)??$(r.id)??$(n.turn_id)??``,s=$(r.status)??$(t.status)??``,c=$(t.thread_id)??$(t.threadId)??$(i.id)??``,l=$(n.type)??``,u=$(n.phase)??``,d=$(n.status)??``,f=$(n.command)??``,p=zS(n),m=RS(t.message)??``,h=RS(t.title)??``;return e.startsWith(`item.`)?[e,a,l,u,d,f,p||m].join(`|`):e.startsWith(`turn.`)?[e,o,s].join(`|`):e===`thread.title.updated`?[e,c,h].join(`|`):[e,c,o,a,l,h||m].join(`|`)}function LS(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function RS(e){if(typeof e==`string`)return e.length>0?e:void 0}function zS(e){let t=RS(e.text);if(t)return t;let n=Array.isArray(e.content)?e.content:[];if(n.length>0){let e=[];for(let t of n){let n=RS(LS(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
482
- `)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>RS(e)).filter(e=>!!e);if(e.length>0)return e.join(`
483
- `)}return``}function BS(e){let t=$(e.content);if(t)return t;let n=$(e.text)??$(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`){let t=e.trim();t&&i.push(t);continue}let t=LS(e),n=$(t.type);if(n&&n!==`text`)continue;let r=$(t.text)??$(t.content);r&&i.push(r)}if(i.length!==0)return i.join(`
484
- `)}function VS(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function HS(e){return String(e).includes(`returned no messages from getSessionMessages`)}function US(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function WS(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,n+=1,new Date(n).toISOString()),a=t=>{let r=e.localTurnLastEventTsById?.get(t);typeof r==`number`&&Number.isFinite(r)&&(n=Math.max(n,r))},o=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),s=t=>{let n=t.map(o).filter(e=>e.length>0);return n.length===0?`raw_hist_codex_${e.sessionId}_${r.toString().padStart(6,`0`)}`:`raw_hist_codex_${e.sessionId}_${n.join(`_`)}`},c=(n,r)=>{let a=t.length+1;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:s(r),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};c({scope:`thread`,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo}},[`thread`,e.thread.id,e.thread.updatedAt]);for(let t of e.thread.turns){if(e.localTerminalTurnStatusById?.get(t.id)===t.status&&JS(t.status)){a(t.id);continue}c({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}},[`turn`,t.id,t.status]);for(let n of t.items)c({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,ZS(n.id)??null])}return t}function GS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=LS(n.payload.raw);if(n.type===`turn.completed`||n.type===`turn.failed`){let r=$(e.turn_id)??$(e.turnId)??$(LS(e.turn).id)??$(LS(e.item).turn_id)??$(LS(e.item).turnId),i=$(e.status)??(n.type===`turn.completed`?`completed`:`failed`);r&&t.set(r,i);continue}if(n.type!==`native.raw`||$(e.source)!==`codex.history.thread_read`)continue;let r=LS(e.message);if($(r.scope)===`turn`){let e=LS(r.turn),n=$(e.id),i=$(e.status);n&&i&&JS(i)&&t.set(n,i)}}return t}function KS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=Date.parse(n.ts);if(!Number.isFinite(e))continue;let r=LS(n.payload.raw),i=$(r.turn_id)??$(r.turnId)??$(LS(r.turn).id);if(!i&&n.type===`native.raw`){if($(r.source)!==`codex.history.thread_read`)continue;let e=LS(r.message),t=$(e.scope);t===`turn`?i=$(LS(e.turn).id):t===`item`&&(i=$(e.turn_id)??$(e.turnId))}i&&t.set(i,Math.max(t.get(i)??0,e))}return t}function qS(e){let t=new Set,n=new Set,r=new Map,i=0,a=1;for(let o of e.localEvents){let e=Date.parse(o.ts);Number.isFinite(e)&&(i=Math.max(i,e)),a=Math.max(a,o.rawSeq+1);let s=LS(o.payload.raw);if(o.type===`item.started`||o.type===`item.updated`||o.type===`item.completed`){if(o.type===`item.completed`){let e=$(LS(s.item).id);e&&n.add(e)}}else if(o.type===`turn.started`){let e=$(s.turn_id)??$(LS(s.turn).id);e&&t.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=$(s.turn_id)??$(LS(s.turn).id);if(!e)continue;t.add(e);let n=$(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||$(s.source)!==`codex.history.thread_read`)continue;let c=LS(s.message),l=$(c.scope);if(l===`turn`){let e=LS(c.turn),n=$(e.id);if(!n)continue;t.add(n);let i=$(e.status);i&&JS(i)&&r.set(n,i);continue}if(l===`item`){let e=$(LS(c.item).id);e&&n.add(e)}}let o=Math.max(i,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),s=0,c=()=>(s+=1,new Date(o+s).toISOString()),l=[],u=(t,n)=>{let r=c();l.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_sync_codex_${e.sessionId}_${a.toString().padStart(6,`0`)}`,ts:r,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),a+=1};for(let i of e.thread.turns){let e=r.get(i.id);if(!(e===i.status&&JS(i.status))){t.has(i.id)||u(`turn.started`,{type:`turn.started`,turn:{id:i.id,status:i.status,items:[],error:i.error}});for(let e of i.items){let t=$(e.id);t&&n.has(t)||u(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e})}if(JS(i.status)&&e!==i.status){if(i.status===`completed`){u(`turn.completed`,{type:`turn.completed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error}});continue}u(`turn.failed`,{type:`turn.failed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error},...i.error?{error:i.error}:{}})}}}return l}function JS(e){return e===`completed`||e===`failed`||e===`interrupted`}function YS(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function XS(e,t=60){let n=YS(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function ZS(e){if(typeof e!=`string`)return;let t=YS(e);if(t)return t}function QS(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function $S(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function eC(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var tC=class{indexPath;eventsDir;sessions=new Map;rawEventsCacheBySession=new Map;compactedRawEventsCacheBySession=new Map;pendingRawMutationsBySession=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`session-index.json`),this.eventsDir=p.default.join(e,`session-events`),this.ready=this.loadFromDisk()}async init(){await this.ready}async flushRawCompactions(e){await this.ready}async shutdown(){await this.ready}async upsertSession(e){await this.ready;let t=this.sessions.get(e.id);this.sessions.set(e.id,{...t,...e}),await this.enqueueWrite(async()=>{await this.persistIndex()})}async patchSession(e,t){await this.ready;let n=this.sessions.get(e);return n?(this.sessions.set(e,{...n,...t}),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async setSessionStatus(e,t,n){await this.ready;let r=this.sessions.get(e);r&&(this.sessions.set(e,{...r,status:t,updatedAt:n,pendingApprovals:t===`running`?r.pendingApprovals:0,pendingUserInputs:t===`running`?r.pendingUserInputs:0,pendingActions:t===`running`?r.pendingActions:0}),await this.enqueueWrite(async()=>{await this.persistIndex()}))}async removeSession(e){if(await this.ready,!this.sessions.has(e))return;this.sessions.delete(e),this.rawEventsCacheBySession.delete(e),this.compactedRawEventsCacheBySession.delete(e);let t=p.default.join(this.eventsDir,`${e}.jsonl`),n=p.default.join(this.eventsDir,`${e}.raw.jsonl`);await this.enqueueWrite(async()=>{await Promise.all([this.persistIndex(),d.default.rm(t,{force:!0}),d.default.rm(n,{force:!0})])})}hasSession(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}getProjectSession(e,t){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return n}listSessions(e=`all`){return[...this.sessions.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessions(e,t=`all`){return this.listSessions(t).filter(t=>t.projectId===e)}async appendRawEvent(e){await this.ready,this.sessions.has(e.sessionId)&&await this.enqueueRawSessionWrite(e.sessionId,async()=>{if(fC(e)){let t=As([...await this.readSessionRawEventsLocked(e.sessionId),e]);await this.replaceRawEventFile(e.sessionId,t),this.rawEventsCacheBySession.set(e.sessionId,t),this.compactedRawEventsCacheBySession.set(e.sessionId,sC(t));return}await this.appendRawEventLine(e),this.appendRawEventToCache(e)})}async mergeSessionRawEvents(e,t){if(await this.ready,!this.sessions.has(e))return[];let n=t.filter(t=>t.sessionId===e),r=[];return await this.enqueueRawSessionWrite(e,async()=>{r=pC(await this.readSessionRawEventsLocked(e),n),await this.replaceRawEventFile(e,r),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.set(e,sC(r))}),r}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionRawEventsCompacted(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsCompactedFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),i}async getSessionRawEventsSinceSeq(e,t,n=2e3){if(await this.ready,!this.sessions.has(e))return[];let r=Math.max(1,n),i=this.readSessionRawEventsFromCache(e);if(i!==void 0)return As(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=As((await this.readSessionRawEventsLocked(e)).filter(e=>e.rawSeq>t)).slice(0,r)}),a}async getSessionRawSeqRange(e){if(await this.ready,!this.sessions.has(e))return null;let t=this.readSessionRawEventsFromCache(e);if(t!==void 0)return aC(t);let n=null;return await this.enqueueWrite(async()=>{n=aC(await this.readSessionRawEventsLocked(e))}),n}async loadFromDisk(){await d.default.mkdir(this.eventsDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.sessions))return;for(let e of t.sessions)e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath&&this.sessions.set(e.id,{...e,status:`idle`,pendingApprovals:0,pendingUserInputs:0,pendingActions:0})}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,sessions:[...this.sessions.values()].sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}async enqueueRawSessionWrite(e,t){this.incrementPendingRawMutation(e);try{let e;return await this.enqueueWrite(async()=>{e=await t()}),e}finally{this.decrementPendingRawMutation(e)}}async appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${iC(e)}\n`;await d.default.appendFile(t,n,`utf8`)}async replaceRawEventFile(e,t){let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r=t.map(e=>iC(e)).join(`
485
- `);await oC(n,r?`${r}\n`:``)}appendRawEventToCache(e){let t=this.rawEventsCacheBySession.get(e.sessionId),n=t?.[t.length-1];t&&t.push(e);let r=this.compactedRawEventsCacheBySession.get(e.sessionId);if(r){if(dC(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&uC(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}lC(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return cC(t);let n=sC(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),cC(n)}async readSessionRawEventsLocked(e){let t=this.rawEventsCacheBySession.get(e);if(t)return t;let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r;try{r=await d.default.readFile(n,`utf8`)}catch(t){if(t.code===`ENOENT`)return this.rawEventsCacheBySession.set(e,[]),[];throw t}let i=r.split(`
486
- `).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!nC(t)||t.kind!==`provider.raw`)continue;let n=rC(t.rawSeq);a.push({value:t,...n===void 0?{}:{rawSeq:n}})}catch{}if(a.length===0)return this.rawEventsCacheBySession.set(e,[]),[];let o=a.some(e=>e.rawSeq===void 0),s=a.map((e,t)=>({...e.value,rawSeq:e.rawSeq??t+1})),c=[];for(let e of s){let t=fa.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>iC(e)).join(`
487
- `),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return cC(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=sC(n);return this.compactedRawEventsCacheBySession.set(e,r),cC(r)}incrementPendingRawMutation(e){this.pendingRawMutationsBySession.set(e,(this.pendingRawMutationsBySession.get(e)??0)+1)}decrementPendingRawMutation(e){let t=(this.pendingRawMutationsBySession.get(e)??0)-1;if(t>0){this.pendingRawMutationsBySession.set(e,t);return}this.pendingRawMutationsBySession.delete(e)}hasPendingRawMutation(e){return(this.pendingRawMutationsBySession.get(e)??0)>0}};function nC(e){return typeof e==`object`&&!!e}function rC(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function iC(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n})}function aC(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function oC(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{await d.default.writeFile(n,t,`utf8`),await d.default.rename(n,e)}catch(e){try{await d.default.rm(n,{force:!0})}catch{}throw e}}function sC(e){let t=ks(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=js(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function cC(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function lC(e,t){let n=js(t);if(!n){e.slots.push(t),e.dense=null;return}let r=e.indexByKey.get(n.key);if(r===void 0){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let i=e.slots[r];if(!i){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let a=Ms(i,t);if(!a){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}e.slots[r]=null,e.slots.push(a),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null}function uC(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function dC(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=nC(e.payload.raw)?e.payload.raw:{},n=nC(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function fC(e){return dC(e)}function pC(e,t){let n=new Map;for(let t of e)n.set(t.eventId,t);for(let e of t)n.set(e.eventId,e);return As([...n.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n})).map((e,t)=>({...e,rawSeq:t+1}))}var mC=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${pg(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=null;for(let r of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);if(!(!i||i.socket.readyState!==i.socket.OPEN)){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),i.socket.send(n)}}}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}i.socket.send(JSON.stringify(e))}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}};async function hC(e,t={}){await tu(e.gatewayLogPath);let n=_C(e,t),r=gC(e,n.instance);await r.register(cg.default,{origin:!0}),await r.register(sg.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new s_(e);await s.init();let c=new p_(e.auditLogPath),l=new mC,u=new Q_,d=new sv(e.projectStoreDir),f=new tC(e.sessionHistoryDir);await f.init();let m=new yx(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new ox({store:m});await h.init();let g,_=null,v=await qs(e.authStoreDir),y=new ES({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let b=new xl({packageName:P.packageName,currentVersion:P.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>(await y.listProjects()).reduce((e,t)=>e+(t.runningCount??0),0),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{_?.close(),x.close(),await b.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:N(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:il(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>$c({gatewayId:e.gatewayId,machineName:il(),relayBaseUrl:e.relayEnabled?fl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:ul({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ee(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(e,t)=>{let n=xa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=fe(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),DC(v,t,n.data.code,n.data.deviceIdentity)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=wa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await bC({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(I(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(I(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!I(e,t))return;let n=e.body,r=ja.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Ia.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.post(`/api/codex/app-server/restart`,async(e,t)=>{if(I(e,t))try{return Da.parse(await y.restartCodexAppServer())}catch(e){let n=Gg(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(I(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(I(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!I(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return Gg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):jC(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!I(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!I(e,t))return;let n=L(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Gg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!I(e,t))return;let n=L(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Gg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!I(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!I(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=e.query,i=ae(r.status,t);if(!i)return;let a=oe(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Gg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/config`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=await y.getProjectSessionConfig(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.post(`/api/projects/:projectId/sessions/:sessionId/history-sync`,async(e,t)=>{if(!I(e,t))return;let n=e.params;try{let e=await y.syncProjectSessionHistory(n.projectId,n.sessionId);return{session:e.session,rawEventCount:e.rawEvents.length}}catch(e){return Gg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})();try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i)}}catch(e){return Gg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>ee(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ee(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=se(t.headers.authorization)??ce(t.url);if(!n){e.close(1008,`Missing access token`);return}let r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await C(la(e),r.sub,i)}catch(e){await w({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{l.removeClient(i)})});let x=new Mx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=fe(e.deviceName);return DC(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await bC({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return yC(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>TC(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:b,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await C(e,t,n)}catch(r){await w({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),S=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.stream.subscribe`:{let t=e.payload.sessions.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`}}));await T(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},C=async(e,t,n)=>{await S(e,t,n)},w=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},T=async(e,t,n)=>{let r=E(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await D(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},E=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},D=async(e,t)=>{let n=await O(t);if(t.cursor.kind===`all`){await k(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await k(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await k(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,j({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},O=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw Qg(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},k=async(e,t,n)=>{let r=`snap_${pg(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,j({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=A(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},A=(e,t)=>{if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r},j=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${pg(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),M=e=>({v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events}}}),ee=t=>t.headers[`x-api-key`]===e.apiKey,N=e=>{if(e==null)return e;if(typeof e==`string`){let t=te(e);return t===void 0?ne(e,a):F(re(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=te(t);return n===void 0?ne(t,a):F(re(n))}return typeof e==`object`?F(re(e)):String(e)},te=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,re=e=>{if(Array.isArray(e))return e.map(e=>re(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=re(r)}return n}return e},F=e=>{let t=ie(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},ie=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},I=(e,t)=>{let n=se(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},ae=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},oe=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},L=(e,t)=>{let n=e.params,r=e.query,i=ji.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},se=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},ce=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},le=e.httpsEnabled?e.httpsPort:e.port,ue=e.httpsEnabled?`https`:`http`,de=il(),fe=e=>e?.trim()||de||`Gateway`;await r.listen({host:e.host,port:le});let pe=r.server.address(),me=typeof pe==`object`&&pe?pe.port:le;if(r.log.info({host:e.host,port:me,protocol:ue,machineName:de},vC(ue,e.host,me)),e.relayEnabled&&(_=new Vx({gatewayId:e.gatewayId,machineName:de,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>Kx({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:ul({protocol:ue,host:e.host,port:me}),logger:r.log,onFrame:async e=>{await x.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await b.start(),{protocol:ue,listenPort:me,machineName:de,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function gC(e,t){let n=t;if(!e.httpsEnabled)return(0,lg.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,lg.default)({disableRequestLogging:!0,loggerInstance:n,https:{key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}}})}function _C(e,t){let n=process.env.NODE_ENV!==`production`,r=Ug.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Ug.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Ug.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function vC(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function yC(e,t){if(e&&e!==t)throw Xg()}async function bC(e){let t=xC(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:SC(t)},`auth refresh attempt`);try{let t=await e.execute(),n=xC(e.authService,e.refreshToken),r=xC(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:SC(n),nextRefreshToken:SC(r)},`auth refresh succeeded`),t}catch(t){let n=xC(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:SC(n),error:CC(t)},`auth refresh failed`),t}}function xC(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function SC(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:wC(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:wC(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function CC(e){return Gg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function wC(e){return e?e.slice(-8):null}async function TC(e,t){try{let n=Oo.parse(e);switch(n.method){case`auth.refresh`:{let e=await bC({authService:t.authService,execute:()=>t.authService.refreshAccessToken(n.params.refreshToken),logger:t.logger,refreshToken:n.params.refreshToken,requestedDeviceId:n.params.deviceId??t.relayDeviceId,source:`relay_rpc`});return yC(n.params.deviceId??t.relayDeviceId,e.deviceId),ko.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return ko.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return ko.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return ko.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return ko.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return ko.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return ko.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return ko.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw kC(n.method,`NOT_FOUND`,404,`Project not found`);return ko.parse({method:n.method,result:{removed:!0}});case`workspace.directories.list`:{let e=await t.fsService.listDirectoriesUnrestricted(n.params.path,n.params.limit??200);return ko.parse({method:n.method,result:e})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return ko.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return ko.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw kC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.parse({method:n.method,result:{session:e}})}case`sessions.config.get`:{let e=await t.sessionManager.getProjectSessionConfig(n.params.projectId,n.params.sessionId);if(!e)throw kC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return ko.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=await t.sessionManager.getProjectSessionRawEvents(n.params.projectId,n.params.sessionId,n.params.limit===`all`?2**53-1:n.params.limit);return ko.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),ko.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return ko.parse({method:n.method,result:e})}case`devices.list`:return ko.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw kC(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return ko.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw kC(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw EC(e)}}function EC(e){if(Gg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return kC(`UNAUTHORIZED`,e.status,String(e),e.details);case`PROJECT_NOT_FOUND`:case`DISCOVERED_PROJECT_NOT_FOUND`:case`PROJECT_SESSION_NOT_FOUND`:case`SESSION_NOT_FOUND`:return kC(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return kC(`BAD_REQUEST`,e.status,String(e),e.details);default:return kC(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=jo.safeParse(e);if(t.success)return t.data;let n=Ao.safeParse(e);if(n.success)return kC(void 0,n.data.code,n.data.status,n.data.message,n.data.details);if(e&&typeof e==`object`&&`code`in e&&`status`in e&&`message`in e&&typeof e.code==`string`&&typeof e.status==`number`&&typeof e.message==`string`){let t=e;return kC(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?kC(`BAD_REQUEST`,400,r):AC(e)?kC(`UNAUTHORIZED`,401,r):jC(r)?kC(`BAD_REQUEST`,400,r):kC(`INTERNAL`,500,r)}function DC(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:OC(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Xs(e.identity,e.privateKeyPem,i)}}function OC(e){return e.replace(/\s+/gu,``).toUpperCase()}function kC(e,t,n,r,i){let a=typeof t==`string`,o=a?e:void 0,s=a?t:e,c=a?n:t,l=a?r:n,u=a?i:r;return jo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function AC(e){return Gg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||o_(e)}function jC(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}function MC(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function NC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await hC(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{FC({type:`worker.update.prepared`,payload:e})}});FC({type:`worker.ready`,payload:PC(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=IC(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${MC(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${MC(e)}`),i(1)});async function a(e){try{switch(e.method){case`gateway.update.apply`:{if(!n.requestGatewayUpdate)throw Error(`gateway update is unavailable`);let t=await n.requestGatewayUpdate(e.requestedBy);FC({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}case`codex.appServer.restart`:{if(!n.requestCodexAppServerRestart)throw Error(`codex app-server restart is unavailable`);let t=await n.requestCodexAppServerRestart(e.requestedBy);FC({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){FC({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function PC(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function FC(e){process.send&&process.send(e)}function IC(e){if(!LC(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:e.method,requestedBy:e.requestedBy};default:return null}}function LC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}RC(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function RC(e){let t=ne(e);switch(t.command){case`help`:UC();return;case`version`:console.log(P.version);return;case`init`:await BC(t);return;case`doctor`:await VC(t);return;case`start`:await zC(t);return;case`__worker`:await HC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function zC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await ql({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(nu(e,t.config))}Oc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function BC(e){let t=await ic({configPath:e.configPath,overwrite:e.force});t.created?console.log(`[gateway] wrote config to ${t.configPath}`):(console.log(`[gateway] config already exists at ${t.configPath}`),console.log(`[gateway] rerun with --force to overwrite`));let n=await ac({configPath:t.configPath,ensureConfigFile:!1}),r=await Dc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(kc(r))}async function VC(e){let t=await ac({configPath:rc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(kc(n)),Oc(n)&&(process.exitCode=1)}async function HC(e){try{await NC(e)}catch(t){let n=await ac({configPath:e.configPath,ensureConfigFile:!0});throw Error(nu(t,n.config))}}function UC(){console.log(`${P.cliName} ${P.version}`),console.log(``),console.log(`Usage:`),console.log(` ${P.cliName} [start] [--config <path>] [--log]`),console.log(` ${P.cliName} init [--config <path>] [--force]`),console.log(` ${P.cliName} doctor [--config <path>]`),console.log(` ${P.cliName} --version`)}exports.runCli=RC;
476
+ `);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},ny=3,ry=250;function iy(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function ay(e,t){let n=Math.max(1,t?.maxAttempts??ny),r=Math.max(0,t?.retryDelayMs??ry),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!iy(e)||t>=n)throw e;r>0&&await oy(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function oy(e){return new Promise(t=>{setTimeout(t,e)})}function sy(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function cy(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var ly=3e4,uy=8,dy=160,fy={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},py=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await Nv(),n.requestTimeoutMs??ly);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0;try{let n=t?.model??this.activeModel,r=sy(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=Sy(this.activeSessionConfig.reasoningEffort),o,s=Cy(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&wy(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:Cy(t?.mode,n,`low`)})}let c=Q(o.turn?.id);c&&(this.activeTurnId=c)}catch(e){throw this.turnInProgress=!1,e}}async interrupt(){if(this.ensureOpen(),!this.threadId||!this.activeTurnId)return;let e={threadId:this.threadId,turnId:this.activeTurnId};await this.sendRequest(`turn/interrupt`,e)}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=Ey(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:cy(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:fy,capabilities:{experimentalApi:!0,optOutNotificationMethods:Cv}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return Q((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return Q((await ay(()=>this.sendRequest(`thread/resume`,i))).thread?.id)}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0;for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:yy(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=Q(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=Sv(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=xv(e.error),r=Q(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=xv(r),a=Q(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${mg(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:Q(i.reason),threadId:a,turnId:Q(i.turnId),itemId:Q(i.itemId),approvalMethod:t,rawParams:yv(i)})}registerUserInputRequest(e,t,n){let r=Q(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${mg(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(Ty).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:yv(n)})}handleNotification(e){switch(e.method){case`thread/started`:{let t=e.params,n=Q(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:yv(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Q(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Q(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.emit({type:`turn.started`,turn:yv(t.turn)});return}case`turn/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;let n=Q(t.turn?.status);if(this.turnInProgress=!1,this.activeTurnId=void 0,n===`failed`){this.emit({type:`turn.failed`,status:n,turn:yv(t.turn),error:yv(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:yv(t.turn)}),this.tryEmitTitleFromThreadRead();return}case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.started`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:_v(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.completed`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:_v(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=xv(e.params);if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Q(t.threadId),turn_id:Q(t.turnId),item:{id:Q(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Q(t.delta)??Q(t.text)??``,original_method:e.method,payload:yv(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Q(t.threadId)))return;this.emit({type:`error`,message:Q(t.error?.message)??`Codex app-server error`,error:yv(t.error),will_retry:t.willRetry===!0,thread_id:Q(t.threadId),turn_id:Q(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=Sv(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=my(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}async tryEmitTitleFromThreadRead(){if(!(!this.threadId||this.threadTitle||this.closed||this.titleReadInFlight)){this.titleReadInFlight=!0;try{let e=await this.sendRequest(`thread/read`,{threadId:this.threadId,includeTurns:!1});this.emitThreadTitleUpdated(Q(e.thread?.name)??Q(e.thread?.preview),Q(e.thread?.name)?`codex.thread_read_name`:`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleConnectionFailure(e){if(this.closed)return;let t=by(e),n=xy(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(Sv(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Q(xv(e.params).threadId)}extractThreadIdFromNotification(e){let t=xv(e.params);return Q(t.threadId)||Q(xv(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Q(xv(xv(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(hy({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(hy({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>uy&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-uy)}};function my(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function hy(e){let t=Q(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=xv(e.message.error),i=_y(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:gy(t,n,e.direction),method:t,requestId:n?Sv(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??yy(Q(r.message))}}function gy(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function _y(e,t){let n=xv(t),r=xv(n.thread),i=xv(n.turn),a=xv(n.item),o=Q(n.delta)??Q(n.text),s=vy(e,n,o);return{threadId:Q(n.threadId)??Q(r.id),turnId:Q(n.turnId)??Q(i.id),itemId:Q(n.itemId)??Q(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:yy(s)}}function vy(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return Q(xv(t.error).message)??Q(t.message)}function yy(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=dy?t:`${t.slice(0,dy)}...`}function by(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function xy(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function Sy(e){return e?e===`max`?`xhigh`:e:null}function Cy(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function wy(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function Ty(e){let t=xv(e),n=Q(t.id),r=Q(t.header),i=Q(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=xv(e),n=Q(t.label),r=Q(t.description)??n,i=Q(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function Ey(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var Dy=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new gv(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await Qv()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??py.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function Oy(e){let t=[],n=null;do{let r=await ky({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function ky(e){return Zv(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>Ny(e)),nextCursor:n.nextCursor}})}async function Ay(e,t=!0){return Zv(async n=>Ny((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function jy(e){return Zv(async t=>{let n=!1;try{let r=await ay(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,Fy(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function My(){let e=[],t=null;do{let n=await Zv(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>Py(e))),t=n.nextCursor}while(t);return e}function Ny(e){let t=Q(xv(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:Ly(e.source),gitInfo:e.gitInfo?xv(yv(e.gitInfo)):null,turns:e.turns.map(e=>Iy(e))}}function Py(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}function Fy(e){let t=Ry(e.model),n=zy(e.reasoningEffort),r=By(e.approvalPolicy),i=Vy(e.sandbox),a=r!==null||i!==null;return t||n!==null||a?{model:t,sessionTurnConfig:{mode:`default`,model:t??null,reasoningEffort:n,...a?{execution:{codex:{approvalPolicy:r,sandboxMode:i}}}:{}},sessionTurnConfigUpdatedAt:new Date(e.thread.updatedAt*1e3).toISOString()}:null}function Iy(e){return{id:e.id,status:e.status,error:e.error?xv(yv(e.error)):null,items:e.items.map(e=>_v(e))}}function Ly(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function Ry(e){return Q(e)?.trim()||void 0}function zy(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function By(e){return e===`untrusted`||e===`on-failure`||e===`on-request`||e===`never`?e:null}function Vy(e){let t=typeof e==`string`?e:Q(xv(e).type);return t===`read-only`||t===`readOnly`?`read-only`:t===`workspace-write`||t===`workspaceWrite`?`workspace-write`:t===`danger-full-access`||t===`dangerFullAccess`?`danger-full-access`:null}var Hy=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;closePromise=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=sy(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0,this.activeAbortController&&this.activeAbortController.abort();let e=this.activeQuery;if(e){if(typeof e.interrupt==`function`)try{await e.interrupt()}catch{}typeof e.close==`function`&&e.close()}}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=qy(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:cy(r),questions:Gy(n.input),answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=fb(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:pb(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(t){if(this.closed||this.activeQuery!==e)return;let n=t instanceof Error?t.message:String(t);this.interruptRequested||this.emit({type:`error`,message:n})}finally{if(this.closed||this.activeQuery!==e)return;this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.activeAbortController&&=(this.activeAbortController.abort(),null);let e=this.activeQuery;if(this.activeQuery=null,typeof e?.interrupt==`function`)try{await e.interrupt()}catch{}typeof e?.close==`function`&&e.close(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>Wy(e,t)?this.requestUserInput(e,t,n):Uy(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${mg(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=Gy(t),i=`req_${mg(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1}captureResumeSessionId(e){let t=fb(e),n=pb(t.session_id)??pb(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${mg(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=_b(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=pb(e.tool_id)??pb(e.tool_use_id)??hb(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=pb(e.uuid);if(n)return this.activeToolItemId=n,n;let r=vb(pb(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}mapClaudeMessage(e){let t=fb(e),n=pb(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!sb(t))return[];let n=cb(fb(t.message));return n?[{type:`item.completed`,item:{id:pb(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:pb(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=ob(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=fb(t.event);if(pb(e.type)===`message_start`){let t=_b(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=lb(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||pb(t.subtype)?.startsWith(`error_`)===!0){let n=ub(t);return[...e,{type:`turn.failed`,error:{message:n},usage:db(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:db(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=pb(t.summary)??`tool summary`,i=pb(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=pb(t.tool_name)??`tool`,i=pb(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=pb(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(pb(t.session_id)??pb(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:pb(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=pb(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=Jy(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=Yy(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Xy({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function Uy(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function Wy(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function Gy(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=Ky(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function Ky(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function qy(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function Jy(e){let t=fb(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=fb(e);if(t.type!==`tool_use`)continue;let n=pb(t.id),i=pb(t.name),a=fb(t.input);if(!(!n||!i)){if(i===`Task`){let e=pb(a.subagent_type),t=pb(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:pb(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=pb(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=pb(a.file_path);r.push({id:n,toolName:`Write`,title:tb(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Yy(e){let t=fb(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=fb(e);if(t.type!==`tool_result`)continue;let n=pb(t.tool_use_id);if(n)return{toolUseId:n}}return null}function Xy(e){let t=fb(e.raw.tool_use_result),n=Zy(t.content)??cb(fb(e.raw.message)),r=fb(t.usage),i=gb(t.totalTokens)??gb(r.total_tokens)??gb(r.output_tokens),a=gb(t.totalToolUseCount),o=gb(t.totalDurationMs),s=pb(t.agentId),c=pb(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=$y(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=Qy(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=mb(t.content),r=eb(rb(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function Zy(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=fb(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
477
+ `):void 0}function Qy(e){return mb(fb(e.file).content)||Zy(e.content)}function $y(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${ib(t)} tokens`),typeof n==`number`&&r.push(ab(n)),r.join(` · `)}function eb(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function tb(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${nb(e)})`:`Write`}function nb(e){let t=e.split(`/`);return t[t.length-1]||e}function rb(e){if(e)return e.split(`
478
+ `).length}function ib(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function ab(e){let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}m`:`${n}m ${r}s`}function ob(e){return cb(fb(e.message))||(mb(e.result)??``)}function sb(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=fb(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>fb(e).type===`tool_result`)}function cb(e){let t=mb(e.content);if(t)return t;let n=mb(e.text)??mb(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=fb(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
479
+ `)}function lb(e){let t=fb(fb(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function ub(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):pb(e.subtype)||`Claude turn failed`}function db(e){let t=fb(e);return{input_tokens:gb(t.input_tokens)??gb(t.inputTokens)??0,cached_input_tokens:gb(t.cached_input_tokens)??gb(t.cache_read_input_tokens)??gb(t.cacheReadInputTokens)??0,output_tokens:gb(t.output_tokens)??gb(t.outputTokens)??0}}function fb(e){return typeof e==`object`&&e?e:{}}function pb(e){if(typeof e==`string`&&e.trim())return e}function mb(e){if(typeof e==`string`&&e.length>0)return e}function hb(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function gb(e){if(typeof e==`number`&&Number.isFinite(e))return e}function _b(e){let t=pb(fb(e.message).id);if(t)return t;let n=pb(fb(fb(e.event).message).id);if(n)return n}function vb(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var yb=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=bb(e);for(let e of this.listeners)e(t)};if(typeof e?.subscribe==`function`){let n=e.subscribe(e=>t(e));typeof n==`function`&&(this.unsubscribe=n);return}if(typeof e?.on==`function`){let n=e=>t(e);e.on(`event`,n),this.unsubscribe=()=>{typeof e?.off==`function`&&e.off(`event`,n)};return}throw Error(`Native session does not expose a known event subscription API`)}};function bb(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var xb=`@anthropic-ai/claude-agent-sdk`,Sb=`claude-sonnet-4-6`,Cb=1e4,wb=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(xb),!0}catch{return!1}}async createSession(e){if(!this.preferNative)throw Error(`Claude native provider is disabled. Set ENABLE_NATIVE_PROVIDERS=true to use Claude sessions.`);try{let t=await import(xb),n=await Tb(Eb(t,e),Cb,`Claude native query session creation timed out`);if(n)return n;let r=await Tb(Db(t,e),Cb,`Claude legacy native session creation timed out`);if(r)return r;throw this.requireNative,Error(`Claude SDK loaded but no supported stable session API was found`)}catch(e){throw Error(`Claude native session creation failed: ${String(e)}`)}}};async function Tb(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}async function Eb(e,t){let n=Ob(e);if(!n)return null;let r=t.model??Sb;return new Hy(t.sessionId,r,({prompt:e,model:i,sessionConfig:a,resume:o,abortController:s,canUseTool:c})=>{let l=a?.permissionMode??t.sessionConfig?.permissionMode??`default`,u={model:i??r,includePartialMessages:!0,abortController:s,canUseTool:c,permissionMode:l},d=kb(a?.reasoningEffort??t.sessionConfig?.reasoningEffort);return d&&(u.effort=d),l===`bypassPermissions`&&(u.allowDangerouslySkipPermissions=!0),t.cwd&&(u.cwd=t.cwd),o&&(u.resume=o,u.forkSession=!1),n({prompt:e,options:u})},t.resumeSessionId,{cwd:t.cwd})}async function Db(e,t){if(typeof e?.createSession==`function`){let n=await e.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new yb(`claude`,t.sessionId,t.model,n)}if(typeof e?.ClaudeAgentClient==`function`){let n=new e.ClaudeAgentClient;if(typeof n?.createSession==`function`){let e=await n.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new yb(`claude`,t.sessionId,t.model,e)}}if(typeof e?.default?.createSession==`function`){let n=await e.default.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new yb(`claude`,t.sessionId,t.model,n)}return null}function Ob(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function kb(e){if(e){if(e===`max`)return`max`;if(e===`high`||e===`medium`||e===`low`)return e;if(e===`xhigh`)return`max`;if(e===`minimal`||e===`none`)return`low`}}function Ab(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new Dy(n,r):new wb(n,r)}const jb=p.default.join(`.claude`,`projects`),Mb=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function Nb(e){return(await(0,T.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>zb(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Pb(e,t){let n=Lb(e,t?.homeDir),r=p.default.resolve(e),i=[];try{i=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}let a=[];for(let e of i){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),i=await Gb(t);if(!Hb(i))continue;let o=await d.default.stat(t),s=Vb(i,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});a.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}let o;try{o=new Map((await(0,T.listSessions)({dir:e})).map(e=>zb(e)).filter(e=>typeof e.cwd==`string`?p.default.resolve(e.cwd)===r:!1).map(e=>[e.nativeSessionId,e]))}catch{}if(o)for(let e=0;e<a.length;e+=1){let t=a[e];if(!t)continue;let n=o.get(t.nativeSessionId);n&&(a[e]={...t,title:n.title??t.title,updatedAt:n.updatedAt})}return a.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function Fb(e){let t=await Kb(e.nativeSessionId,e.projectPath),n=await qb(e.projectPath,e.nativeSessionId,e.homeDir);return Bb({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function Ib(e,t,n){return p.default.join(Lb(e,n),`${t}.jsonl`)}function Lb(e,t){let n=t??f.default.homedir();return p.default.join(n,jb,Rb(e))}function Rb(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function zb(e){let t=nx(e.customTitle)??nx(e.summary)??nx(e.firstPrompt),n=Wb(e.lastModified);return{nativeSessionId:e.sessionId,cwd:Ub(e.cwd),title:t,createdAt:n,updatedAt:n}}function Bb(e){let t=[],n=Vb(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}});return t}function Vb(e,t){let n,r,i,a;for(let t of e)t.timestampMs!==void 0&&(i=i===void 0?t.timestampMs:Math.min(i,t.timestampMs),a=a===void 0?t.timestampMs:Math.max(a,t.timestampMs)),!r&&t.type===`user`&&(r=$b(Zb(ex(t.raw.message)))),!n&&t.type===`assistant`&&(n=tx(ex(t.raw.message).model));let o=i??ox(t.createdAtFallbackMs)??0,s=a??ox(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function Hb(e){for(let t of e){if(t.type===`user`){let e=ex(t.raw.message);if(Zb(e)||Xb(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=ex(t.raw.message);if(Zb(e)||Yb(e).length>0||tx(t.raw.error))return!0}return!1}function Ub(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Wb(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Gb(e){let t=(await d.default.readFile(e,`utf8`)).split(`
480
+ `),n=[];for(let e=0;e<t.length;e+=1){let r=t[e]?.trim();if(!r)continue;let i;try{i=JSON.parse(r)}catch{continue}let a=ex(i),o=tx(a.timestamp),s=o?ax(o):void 0;n.push({line:e+1,raw:a,type:tx(a.type),timestamp:o,timestampMs:s})}return n}async function Kb(e,t){let n=await(0,T.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>Jb(e,t+1))}async function qb(e,t,n){let r=Ib(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function Jb(e,t){let n=ex(e),r=ex(n.message),i=tx(n.timestamp)??tx(r.timestamp)??tx(r.created_at)??tx(r.createdAt);return{line:t,raw:{...n,message:r},type:tx(n.type),timestamp:i,timestampMs:i?ax(i):void 0}}function Yb(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=ex(e);if(tx(t.type)!==`tool_use`)continue;let r=ex(t.input),i=tx(r.command),a=tx(t.name)??`tool`,o=tx(r.description);n.push({id:tx(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function Xb(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=ex(e);if(tx(t.type)!==`tool_result`)continue;let r=rx(tx(t.content)??tx(ex(t.toolUseResult).stdout)??tx(ex(t.tool_use_result).stdout)??tx(t.text));n.push({toolUseId:tx(t.tool_use_id)??tx(t.toolUseId),toolName:tx(t.tool_name)??tx(t.toolName),text:r,isError:t.is_error===!0})}return n}function Zb(e){let t=tx(e.content);if(t)return rx(t);let n=tx(e.text)??tx(e.prompt);if(n)return rx(n);let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push(e);continue}let t=ex(e),n=tx(t.type);if(n&&n!==`text`)continue;let r=tx(t.text)??tx(t.content)??Qb(t);r&&i.push(r)}if(i.length!==0)return rx(i.join(`
481
+ `))}function Qb(e){let t=Array.isArray(e.text_elements)?e.text_elements:Array.isArray(e.textElements)?e.textElements:[];if(t.length===0)return;let n=[];for(let e of t){let t=ex(e),r=tx(t.text)??tx(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function $b(e,t=60){if(!e)return;let n=ix(e).replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function ex(e){return typeof e==`object`&&e?e:{}}function tx(e){return typeof e==`string`&&e.trim()||void 0}function nx(e){if(typeof e==`string`)return rx(e)}function rx(e){if(!e)return;let t=ix(e).trim();return t.length>0?t:void 0}function ix(e){return e.replace(Mb,``)}function ax(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function ox(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var sx=class{constructor(e){this.options=e}async init(){await this.options.store.init()}async getProjects(){await this.init();let e=await this.options.store.getIndex();return e?{generatedAt:e.generatedAt,source:`cache`,providers:e.providers,projects:e.projects}:this.refreshProjects()}async refreshProjects(){await this.init();let e=new Map,[t,n]=await Promise.all([this.scanCodexSessions(e),this.scanClaudeSessions(e)]),r=new Date().toISOString(),i={codex:t.status,claude:n.status},{projects:a,projectSessions:o}=lx(r,[t,n]);if(ux(i)){let e=await this.options.store.getSnapshot();if(e)return await this.options.store.writeSnapshot({...e,providers:i}),{generatedAt:e.generatedAt,source:`cache`,providers:i,projects:e.projects}}return await this.options.store.writeSnapshot({generatedAt:r,providers:i,projects:a,projectSessions:o}),{generatedAt:r,source:`fresh_scan`,providers:i,projects:a}}async listProjectSessions(e){await this.init();let t=e.trim(),n=await this.options.store.getIndex(),r=!1;n||(n=fx(await this.refreshProjects()),r=!0);let i=await dx(n.projects,t);if(!i)throw r_(t);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=fx(await this.refreshProjects()),i=await dx(n.projects,t),!i)throw r_(t);if(a=await this.options.store.getProject(i.key),!a)throw Error(`Discovery cache missing project sessions: ${i.path}`)}if(!a)throw Error(`Discovery cache missing project sessions: ${i.path}`);return{canonicalProjectPath:i.path,project:a.project,providers:a.providers,sessions:a.sessions}}async scanCodexSessions(e){let t=new Date().toISOString();try{let n=new Map;for(let e of[!1,!0]){let t=null;do{let r=await ky({archived:e,cursor:t,limit:100});for(let e of r.threads)n.set(e.id,e);t=r.nextCursor}while(t)}let r=await cx({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>hx(e.cwd),mapSession:e=>{let t=gx(e.createdAt),n=gx(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:hx(e.name)??hx(e.preview),model:hx(e.model),createdAt:t,updatedAt:n}}});return{records:r.records,status:{scannedAt:t,sessionCount:r.records.length,status:r.skippedCount>0?`partial`:`ready`,...r.skippedCount>0?{error:`Skipped ${r.skippedCount} Codex session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}async scanClaudeSessions(e){let t=new Date().toISOString();try{let n=await cx({sessions:await Nb(),canonicalPathCache:e,getRawPath:e=>hx(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:hx(e.title),model:hx(e.model),createdAt:hx(e.createdAt),updatedAt:e.updatedAt})});return{records:n.records,status:{scannedAt:t,sessionCount:n.records.length,status:n.skippedCount>0?`partial`:`ready`,...n.skippedCount>0?{error:`Skipped ${n.skippedCount} Claude session(s) with missing or invalid cwd`}:{}}}}catch(e){return{records:[],status:{scannedAt:t,sessionCount:0,status:`failed`,error:String(e)}}}}};async function cx(e){let t=[],n=0;for(let r of e.sessions){let i=e.getRawPath(r);if(!i){n+=1;continue}try{let n=await px(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function lx(e,t){let n=new Map;for(let e of t)for(let t of e.records){let e=n.get(t.canonicalProjectPath);e||(e={path:t.canonicalProjectPath,key:mx(t.canonicalProjectPath),title:p.default.basename(t.canonicalProjectPath)||t.canonicalProjectPath,providerCounts:{codex:0,claude:0},sessionsByKey:new Map},n.set(t.canonicalProjectPath,e));let r=`${t.session.provider}:${t.session.nativeSessionId}`,i=e.sessionsByKey.get(r);i||(e.providerCounts[t.session.provider]+=1);let a=_x(i,t.session);e.sessionsByKey.set(r,a),(!e.lastSessionAt||t.session.updatedAt>e.lastSessionAt)&&(e.lastSessionAt=t.session.updatedAt)}let r=[...n.values()].map(t=>({project:{key:t.key,path:t.path,title:t.title,lastSessionAt:t.lastSessionAt,sessionCount:t.sessionsByKey.size,providerCounts:t.providerCounts,lastDiscoveryAt:e},sessions:[...t.sessionsByKey.values()].sort(yx)})).sort((e,t)=>vx(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function ux(e){return Object.values(e).some(e=>e?.status===`failed`)}async function dx(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await uv(t);return e.find(e=>e.path===r)}function fx(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function px(e,t){let n=t.get(e);return n||(n=uv(e),t.set(e,n)),n}function mx(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function hx(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function gx(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function _x(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function vx(e,t){let n=e.lastSessionAt??e.lastDiscoveryAt,r=t.lastSessionAt??t.lastDiscoveryAt;return n===r?e.path.localeCompare(t.path):r.localeCompare(n)}function yx(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var bx=class{indexPath;projectsDir;ready;writeQueue=Promise.resolve();indexCache=null;projectCache=new Map;constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`discovery-index.json`),this.projectsDir=p.default.join(e,`discovery-projects`),this.ready=this.loadFromDisk()}async init(){await this.ready}async getIndex(){return await this.ready,this.indexCache?structuredClone(this.indexCache):null}async getProject(e){await this.ready;let t=this.projectCache.get(e);if(t)return structuredClone(t);let n=await xx(this.getProjectPath(e),wx);return n?(this.projectCache.set(e,n),structuredClone(n)):null}async getSnapshot(){if(await this.ready,!this.indexCache)return null;let e=[];for(let t of this.indexCache.projects){let n=await this.getProject(t.key);if(!n)return null;e.push({project:n.project,sessions:n.sessions})}return{generatedAt:this.indexCache.generatedAt,providers:structuredClone(this.indexCache.providers),projects:structuredClone(this.indexCache.projects),projectSessions:e}}async writeSnapshot(e){await this.ready;let t={v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects},n=e.projectSessions.map(t=>({v:1,projectKey:t.project.key,canonicalProjectPath:t.project.path,project:t.project,providers:e.providers,sessions:t.sessions}));await this.enqueueWrite(async()=>{await d.default.mkdir(this.projectsDir,{recursive:!0});let e=new Set(n.map(e=>e.projectKey)),r=[];try{r=await d.default.readdir(this.projectsDir,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}await Promise.all(n.map(async e=>{await Sx(this.getProjectPath(e.projectKey),e)})),await Promise.all(r.map(async t=>{if(!t.isFile()||!t.name.endsWith(`.json`))return;let n=t.name.slice(0,-5);e.has(n)||(await d.default.rm(p.default.join(this.projectsDir,t.name),{force:!0}),this.projectCache.delete(n))})),await Sx(this.indexPath,t),this.indexCache=t,this.projectCache.clear();for(let e of n)this.projectCache.set(e.projectKey,e)})}async loadFromDisk(){await d.default.mkdir(this.baseDir,{recursive:!0}),await d.default.mkdir(this.projectsDir,{recursive:!0}),this.indexCache=await xx(this.indexPath,Cx)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function xx(e,t){try{let n=await d.default.readFile(e,`utf8`),r=JSON.parse(n);return t(r)?r:null}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Sx(e,t){let n=`${JSON.stringify(t,null,2)}\n`;try{if(await d.default.readFile(e,`utf8`)===n)return}catch(e){if(e.code!==`ENOENT`)throw e}await d.default.mkdir(p.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await d.default.writeFile(r,n,`utf8`),await d.default.rename(r,e)}function Cx(e){return!Tx(e)||e.v!==1||typeof e.generatedAt!=`string`||!qa.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>Ja.safeParse(e).success)}function wx(e){return!Tx(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!Ja.safeParse(e.project).success||!qa.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Ya.safeParse(e).success)}function Tx(e){return typeof e==`object`&&!!e}const Ex=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function Dx(e){let t=xo.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=ss(us(jx(i.export({format:`jwk`})))),o=Zo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a}}),s=(0,l.sign)(null,Buffer.from(o,`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`);return{gatewayHello:So.parse({version:t.version,securityLevel:t.securityLevel,cipherSuite:t.cipherSuite,gatewayId:e.gatewayId,deviceId:t.deviceId,clientNonce:t.clientNonce,gatewayNonce:n,gatewayPublicKeyFingerprint:e.gatewayIdentity.publicKeyFingerprint,gatewayEphemeralPublicKey:a,signatureAlgorithm:`ed25519`,signature:s}),gatewayEphemeralPrivateKey:r}}function Ox(e){let t=xo.parse(e.clientHello),n=So.parse(e.gatewayHello),r=Co.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!uo.safeParse(t.cipherSuite).success||n.cipherSuite!==t.cipherSuite||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported_version`);if(r.gatewayId!==e.gatewayId||n.gatewayId!==e.gatewayId)throw Error(`transcript_invalid`);if(r.deviceId!==t.deviceId||n.deviceId!==t.deviceId||r.deviceIdentityFingerprint!==t.deviceIdentity.publicKeyFingerprint)throw Error(`identity_mismatch`);let i=(0,l.createPublicKey)({format:`der`,type:`spki`,key:Buffer.concat([Ex,cs(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(Qo({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,cs(r.signature)))throw Error(`transcript_invalid`)}function kx(e){let t=So.parse(e.gatewayHello),n=Co.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:ls(cs(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return ts({role:`gateway`,keySchedule:es({gatewayId:e.gatewayId,clientHello:xo.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function Ax(e){return Do.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function jx(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var Mx=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}sendProviderRaw(e){this.onPayload(e)}close(){this.readyState=3}},Nx=class{mobileConnections=new Map;constructor(e){this.dependencies=e}async handleFrame(e){switch(e.type){case`mobile.connected`:this.addMobileConnection(e.mobileId??``,e.payload.deviceId,e.payload.deliveryMode,e.payload.gatewayAvailableAtConnect);return;case`mobile.disconnected`:this.removeMobileConnection(e.mobileId??``);return;case`secure.client_hello`:await this.handleSecureClientHello(e.mobileId,e.payload);return;case`secure.client_auth`:await this.handleSecureClientAuth(e.mobileId,e.payload);return;case`from_mobile`:await this.handleFromMobile(e);return;case`rpc.request`:await this.handleRpcRequest(e);return;case`pairing.claim.forward`:await this.handlePairingClaim(e.requestId,e.payload);return;case`auth.refresh.forward`:await this.handleRefresh(e.requestId,e.payload);return;default:return}}close(){for(let e of this.mobileConnections.keys())this.removeMobileConnection(e)}addMobileConnection(e,t,n,r){e&&(this.removeMobileConnection(e),this.mobileConnections.set(e,{mobileId:e,deviceId:t,handshake:{status:`awaiting_client_hello`}}),this.dependencies.relayTransportSecurityLevel===`e2ee-relay`&&n===`gateway_replay`&&this.dependencies.sendFrame(Jo.parse({type:`secure.handshake_required`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,gatewayId:this.dependencies.gatewayId,deviceId:t,reason:r?`gateway_restarted`:`gateway_available`,retryable:!0}})))}removeMobileConnection(e){let t=this.mobileConnections.get(e);t&&(t.socket?.close(),t.clientId&&this.dependencies.sessionHub.removeClient(t.clientId),this.mobileConnections.delete(e))}async handleFromMobile(e){let t=e.mobileId;if(!t){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile frame requires mobileId`});return}let n=this.mobileConnections.get(t);if(!n){this.sendRelayError({mobileId:t,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${t}`});return}if(n.handshake.status!==`ready`||!n.clientId){this.sendSecureError(t,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let r=n,i=this.decodeRelayBusinessPayload({connection:r,mobileId:t,frameType:`from_mobile`,messageType:e.messageType,parse:e=>ca.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});i&&await this.dependencies.dispatchCommand(i,r.deviceId,r.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(Jo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Fx(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(Jo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Fx(t,`auth.refresh`)})}}async handleRpcRequest(e){let t=e.mobileId,n=e.requestId,r=this.mobileConnections.get(t);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,payload:{...Px(`BAD_REQUEST`,400,`Unknown mobile ${t}`)}});return}if(r.handshake.status!==`ready`){this.sendSecureError(t,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}let i=r,a=this.decodeRelayBusinessPayload({connection:i,mobileId:t,frameType:`rpc.request`,messageType:e.messageType,requestId:n,parse:e=>Oo.parse(e),payload:e.payload,encryptedPayload:e.encryptedPayload});if(a)try{let e=await this.dependencies.handleRpcRequest(a,{mobileId:t,deviceId:i.deviceId});this.dependencies.sendFrame(Jo.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.response`,messageType:`rpc`,requestId:n},e)}))}catch(e){let r=jo.safeParse(e);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:t,requestId:n,messageType:`rpc`,...this.createRelayBusinessPayloadFields(i,{frameType:`rpc.error`,messageType:`rpc`,requestId:n},{...r.success?r.data:Px(`INTERNAL`,500,String(e)),method:a.method})})}}async handleSecureClientHello(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_hello frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status!==`awaiting_client_hello`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_hello`);return}if(t.deviceId!==n.deviceId){this.sendSecureError(e,n.deviceId,`identity_mismatch`,`deviceId does not match relay token`);return}if(t.version!==1||t.cipherSuite!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`){this.sendSecureError(e,n.deviceId,`unsupported_version`,`unsupported secure handshake version`);return}let r=Dx({gatewayId:this.dependencies.gatewayId,gatewayIdentity:this.dependencies.gatewayIdentity,privateKeyPem:this.dependencies.gatewayIdentityPrivateKeyPem,clientHello:t});n.handshake={status:`awaiting_client_auth`,clientHello:t,gatewayHello:r.gatewayHello,gatewayEphemeralPrivateKey:r.gatewayEphemeralPrivateKey},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Jo.parse({type:`secure.gateway_hello`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:r.gatewayHello}))}async handleSecureClientAuth(e,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`secure.client_auth frame requires mobileId`});return}let n=this.mobileConnections.get(e);if(!n){this.sendRelayError({mobileId:e,code:`BAD_REQUEST`,status:400,message:`Unknown mobile ${e}`});return}if(n.handshake.status===`ready`){this.sendSecureError(e,n.deviceId,`counter_replay`,`duplicate secure.client_auth`);return}if(n.handshake.status!==`awaiting_client_auth`){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure.client_hello missing`);return}try{Ox({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Ix(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=kx({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t,gatewayEphemeralPrivateKey:n.handshake.gatewayEphemeralPrivateKey});this.ensureReadyMobileClient(n),n.handshake={status:`ready`,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,session:i},this.mobileConnections.set(e,n),this.dependencies.sendFrame(Jo.parse({type:`secure.ready`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:{version:1,securityLevel:`e2ee-relay`,cipherSuite:i.cipherSuite,gatewayId:this.dependencies.gatewayId,deviceId:n.deviceId,keyEpoch:i.keyEpoch,deviceIdentityFingerprint:r.publicKeyFingerprint??n.handshake.clientHello.deviceIdentity.publicKeyFingerprint,deviceIdentityStatus:r.identityStatus??`active`}}))}catch(t){this.sendSecureError(e,n.deviceId,Rx(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new Mx(t=>{try{let n=Jo.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,...this.createRelayBusinessPayloadFields(e,{frameType:`to_mobile`,messageType:`event`},t)});this.dependencies.sendFrame(n)}catch(t){this.sendSecureError(e.mobileId,e.deviceId,Lx(t),`relay secure payload failed: ${String(t)}`)}}),n=this.dependencies.sessionHub.addClient(e.deviceId,t);e.socket=t,e.clientId=n}sendSecureError(e,t,n,r){this.dependencies.sendFrame({type:`secure.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,messageType:`system`,payload:Ax({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`||n===`key_epoch_mismatch`})})}sendRelayError(e){this.dependencies.sendFrame({type:`relay.error`,gatewayId:this.dependencies.gatewayId,...e.mobileId?{mobileId:e.mobileId}:{},...e.requestId?{requestId:e.requestId}:{},messageType:`system`,payload:Px(e.code,e.status,e.message)})}decodeRelayBusinessPayload(e){if(e.payload!==void 0)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload must be encrypted`),null;if(!e.encryptedPayload)return this.sendSecureError(e.mobileId,e.connection.deviceId,`decrypt_failed`,`relay secure payload missing`),null;try{return os({session:e.connection.handshake.session,metadata:{frameType:e.frameType,messageType:e.messageType,gatewayId:this.dependencies.gatewayId,...e.requestId?{requestId:e.requestId}:{}},encryptedPayload:e.encryptedPayload,parse:e.parse})}catch(t){return this.sendSecureError(e.mobileId,e.connection.deviceId,Lx(t),`relay secure payload failed: ${String(t)}`),null}}createRelayBusinessPayloadFields(e,t,n){return e.handshake.status===`ready`?{encryptedPayload:as({session:e.handshake.session,metadata:{frameType:t.frameType,messageType:t.messageType,gatewayId:this.dependencies.gatewayId,...t.requestId?{requestId:t.requestId}:{}},payload:n})}:{payload:n}}};function Px(e,t,n){return jo.parse({code:e,status:t,message:n})}function Fx(e,t){if(Kg(e))switch(e.code){case`PAIRING_CODE_INVALID`:case`PAIRING_CODE_EXPIRED`:return{code:`BAD_REQUEST`,status:e.status,message:String(e)};case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return{code:`UNAUTHORIZED`,status:e.status,message:String(e)};default:return{code:e.status>=500?`INTERNAL`:`BAD_REQUEST`,status:e.status,message:String(e)}}let n=String(e),r=zx(e);return t===`pairing.claim`&&(r===`Invalid pairing code`||r===`Pairing code expired`)?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(r===`Refresh token revoked`||r===`Device revoked`||r===`Device revoked or not found`||r===`Refresh token device mismatch`||s_(e))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Ix(e){return Bx(e,[`identity_mismatch`,`counter_replay`,`unsupported_version`,`transcript_invalid`])??`transcript_invalid`}function Lx(e){return Bx(e,[`counter_gap_too_large`,`counter_replay`,`key_epoch_mismatch`,`decrypt_failed`])??`decrypt_failed`}function Rx(e){if(Kg(e))switch(e.code){case`DEVICE_REVOKED`:return`device_revoked`;case`DEVICE_IDENTITY_NOT_REGISTERED`:case`DEVICE_IDENTITY_MISMATCH`:return`identity_mismatch`;default:return`transcript_invalid`}let t=zx(e);return t===`Device revoked`||t===`Device revoked or not found`?`device_revoked`:t===`Device identity mismatch`||t===`Device identity not registered`?`identity_mismatch`:`transcript_invalid`}function zx(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function Bx(e,t){let n=zx(e);return t.find(e=>e===n)}function Vx(e){return e?e.readyState:null}var Hx=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;heartbeatIntervalMs;heartbeatTimeoutMs;webSocketFactory;socket;reconnectTimer;heartbeatIntervalTimer;heartbeatTimeoutTimer;reconnectAttempt=0;connectAttemptId=0;state=`idle`;stopped=!1;constructor(e){this.options=e,this.logger=e.logger??{},this.reconnectBaseDelayMs=e.reconnectBaseDelayMs??1e3,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??15e3,this.heartbeatIntervalMs=e.heartbeatIntervalMs??15e3,this.heartbeatTimeoutMs=e.heartbeatTimeoutMs??1e4,this.webSocketFactory=e.webSocketFactory??Gx}start(){this.stopped&&=!1,!(this.socket||this.reconnectTimer)&&this.connect()}close(){this.stopped=!0,this.state=`stopped`,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),void 0);let e=this.socket;if(this.socket=void 0,this.stopHeartbeat(),!e)return;let t=Vx(e);try{e.close(1e3,`Gateway shutting down`)}catch(n){this.logger.error?.({err:n,readyState:t},`relay websocket close threw during shutdown`);try{e.terminate()}catch(e){this.logger.error?.({err:e,readyState:t},`relay websocket terminate threw after close failure`)}}}isConnected(){let e=this.socket;return this.state===`connected`&&!!e&&e.readyState===e.OPEN}send(e){let t=this.socket;if(!t||t.readyState!==t.OPEN)return!1;let n=Jo.parse(e);return t.send(JSON.stringify(n)),!0}async connect(){if(this.stopped)return;let e=++this.connectAttemptId,t;try{t=await this.resolveGatewayAccessToken()}catch(e){this.state=`idle`,this.logger.warn?.({err:e},`failed to resolve relay gateway access token`),this.scheduleReconnect();return}if(this.stopped||e!==this.connectAttemptId)return;let n=Ux(this.options.relayUrl);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.on(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,this.startHeartbeat(r),this.logger.info?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId},`relay gateway websocket connected`),this.send({type:`gateway.hello`,gatewayId:this.options.gatewayId,messageType:`system`,payload:{name:this.options.machineName,relayBaseUrl:this.options.relayUrl,directBaseUrls:this.options.directBaseUrls,transportSecurityLevel:`e2ee-relay`,gatewayIdentity:this.options.gatewayIdentity,gatewayAccessToken:t,connectedAt:new Date().toISOString()}}))}),r.on(`message`,e=>{if(this.socket===r){this.ackHeartbeat(r);try{let t=Jo.parse(JSON.parse(Wx(e)));Promise.resolve(this.options.onFrame(t)).catch(e=>{this.logger.error?.({err:e},`failed to handle relay frame`)})}catch(e){this.logger.warn?.({err:e},`failed to parse relay frame from relay`)}}}),r.on(`error`,e=>{this.socket===r&&this.logger.warn?.({err:e},`relay websocket emitted error`)}),r.on(`pong`,()=>{this.socket===r&&this.ackHeartbeat(r)}),r.on(`close`,(e,t)=>{if(this.socket===r){if(this.socket=void 0,this.stopHeartbeat(),this.stopped){this.state=`stopped`;return}this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,closeCode:e,closeReason:t.toString(`utf8`)},`relay websocket closed`),this.state=`idle`,this.scheduleReconnect()}})}async resolveGatewayAccessToken(){let e=this.options.relayGatewayAccessToken.trim();if(e)return e;let t=this.options.resolveRelayGatewayAccessToken;if(t)return t();throw Error(`Gateway relay access token is not configured`)}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;let e=Math.min(this.reconnectMaxDelayMs,this.reconnectBaseDelayMs*Math.max(1,2**this.reconnectAttempt));this.reconnectAttempt+=1,this.logger.info?.({delayMs:e},`scheduling relay reconnect`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatIntervalTimer=setInterval(()=>{if(!(this.socket!==e||this.stopped)&&!(e.readyState!==e.OPEN||this.heartbeatTimeoutTimer)){try{e.ping()}catch(t){this.logger.warn?.({err:t},`failed to send relay websocket heartbeat ping`),e.terminate();return}this.heartbeatTimeoutTimer=setTimeout(()=>{this.heartbeatTimeoutTimer=void 0,!(this.socket!==e||this.stopped||e.readyState!==e.OPEN)&&(this.logger.warn?.({relayUrl:this.options.relayUrl,gatewayId:this.options.gatewayId,heartbeatTimeoutMs:this.heartbeatTimeoutMs},`relay websocket heartbeat timed out`),e.terminate())},this.heartbeatTimeoutMs)}},this.heartbeatIntervalMs)}ackHeartbeat(e){this.socket===e&&(this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0))}stopHeartbeat(){this.heartbeatIntervalTimer&&=(clearInterval(this.heartbeatIntervalTimer),void 0),this.heartbeatTimeoutTimer&&=(clearTimeout(this.heartbeatTimeoutTimer),void 0)}};function Ux(e){let t=new URL(e);return t.protocol===`http:`?t.protocol=`ws:`:t.protocol===`https:`&&(t.protocol=`wss:`),t.pathname=`/ws/gateway`,t.toString()}function Wx(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):String(e)}function Gx(e){return new fv(e)}function Kx(e){let t={gatewayId:e.gatewayId.trim(),gatewayIdentity:e.gatewayIdentity,requestedAt:e.requestedAt??new Date().toISOString()};if(!t.gatewayId)throw Error(`gatewayId must not be empty when requesting a guest relay gateway access token.`);return{grantType:`guest`,payload:t,signatureAlgorithm:`ed25519`,signature:(0,l.sign)(null,Buffer.from(Yo(t),`utf8`),(0,l.createPrivateKey)(e.privateKeyPem)).toString(`base64`)}}async function qx(e){let t=e.fetchImpl??globalThis.fetch;if(!t)throw Error(`fetch is not available when requesting a guest relay gateway access token.`);let n=await t(Jx(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Kx({gatewayId:e.gatewayId,gatewayIdentity:e.gatewayIdentity,privateKeyPem:e.privateKeyPem}))}),r=await n.text();if(!n.ok)throw Error(`Failed to request a guest relay gateway access token (${n.status}): ${r}`);return Lo.parse(JSON.parse(r)).token}function Jx(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=`/api/gateway-token/guest`,t.search=``,t.toString()}function Yx(e){return e?.trim()||void 0}function Xx(e){if(e)return{codex:e.codex?{approvalPolicy:e.codex.approvalPolicy,sandboxMode:e.codex.sandboxMode}:void 0,claude:e.claude?{permissionMode:e.claude.permissionMode}:void 0}}function Zx(e,t){return{modeDefault:`default`,model:Yx(t.defaults.model),reasoningEffort:t.defaults.reasoningEffort,execution:e===`codex`?{codex:{approvalPolicy:t.defaults.approvalPolicy??null,sandboxMode:t.defaults.sandboxMode??null}}:{claude:{permissionMode:t.defaults.permissionMode??null}}}}function Qx(e){return{mode:`default`,model:null,reasoningEffort:null,execution:e===`codex`?{codex:{approvalPolicy:null,sandboxMode:null}}:{claude:{permissionMode:null}}}}function $x(e,t){let n=Qx(e);return t?e===`codex`?{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{codex:{approvalPolicy:t.execution?.codex?.approvalPolicy??null,sandboxMode:t.execution?.codex?.sandboxMode??null}}}:{mode:t.mode,model:t.model,reasoningEffort:t.reasoningEffort,execution:{claude:{permissionMode:t.execution?.claude?.permissionMode??null}}}:n}function eS(e,t){return e===`claude`&&t?.permissionMode===`plan`?`plan`:`default`}function tS(e){let t=$x(e.provider,e.sessionTurnConfig);return e.sessionTurnConfig!==void 0||Yx(e.legacyModel)!==void 0||e.legacySessionConfig!==void 0?nS({provider:e.provider,providerDefaults:{modeDefault:`default`},currentSessionTurnConfig:t,legacyModel:e.legacyModel,legacySessionConfig:e.legacySessionConfig}).sessionTurnConfig:t}function nS(e){let t=$x(e.provider,e.currentSessionTurnConfig),n=e.mode??(e.legacySessionConfig?eS(e.provider,e.legacySessionConfig):void 0)??t.mode??e.providerDefaults.modeDefault,r=$x(e.provider,{...t,mode:n});e.config&&(e.config.model!==void 0&&(r.model=e.config.model),e.config.reasoningEffort!==void 0&&(r.reasoningEffort=e.config.reasoningEffort),e.provider===`codex`&&e.config.execution?.codex&&(r.execution={codex:{approvalPolicy:e.config.execution.codex.approvalPolicy,sandboxMode:e.config.execution.codex.sandboxMode}}),e.provider===`claude`&&e.config.execution?.claude&&(r.execution={claude:{permissionMode:e.config.execution.claude.permissionMode}}));let i=Yx(e.legacyModel);i&&(r.model=i),e.legacySessionConfig?.reasoningEffort!==void 0&&(r.reasoningEffort=e.legacySessionConfig.reasoningEffort),e.provider===`codex`&&e.legacySessionConfig&&(r.execution={codex:{approvalPolicy:e.legacySessionConfig.approvalPolicy??r.execution?.codex?.approvalPolicy??null,sandboxMode:e.legacySessionConfig.sandboxMode??r.execution?.codex?.sandboxMode??null}}),e.provider===`claude`&&e.legacySessionConfig&&(r.execution={claude:{permissionMode:e.legacySessionConfig.permissionMode===`plan`?r.execution?.claude?.permissionMode??null:e.legacySessionConfig.permissionMode??r.execution?.claude?.permissionMode??null}});let a=r.model??Yx(e.providerDefaults.model),o={},s=r.reasoningEffort??e.providerDefaults.reasoningEffort;if(s&&(o.reasoningEffort=s),e.provider===`codex`){let t=r.execution?.codex?.approvalPolicy??e.providerDefaults.execution?.codex?.approvalPolicy??void 0,n=r.execution?.codex?.sandboxMode??e.providerDefaults.execution?.codex?.sandboxMode??void 0;t&&(o.approvalPolicy=t),n&&(o.sandboxMode=n)}else{let t=n===`plan`?`plan`:r.execution?.claude?.permissionMode??e.providerDefaults.execution?.claude?.permissionMode??void 0;t&&(o.permissionMode=t)}return{mode:n,model:a,sessionConfig:o,sessionTurnConfig:{mode:r.mode,model:r.model,reasoningEffort:r.reasoningEffort,execution:Xx(r.execution)}}}const rS=[],iS=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],aS=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],oS=Ni.options,sS=[`read-only`,`workspace-write`,`danger-full-access`],cS=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],lS=process.env.SESSION_FETCH_DEBUG===`1`||process.env.EXPO_PUBLIC_SESSION_FETCH_DEBUG===`1`;function uS(e){return e.lastHydratedExternalUpdatedAt||e.updatedAt||e.createdAt}function dS(e,t){lS&&(!e.startsWith(`config.get`)&&!e.endsWith(`.error`)||console.log(`[session-fetch][gateway] ${e}`,t))}function fS(e){return e?{sessionFound:!0,sessionId:e.id,nativeSessionId:e.nativeSessionId??null,sessionSource:e.source??null,sessionModel:e.model??null,sessionUpdatedAt:e.updatedAt,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt??null,sessionTurnConfigModel:e.sessionTurnConfig?.model??null,sessionTurnConfigReasoningEffort:e.sessionTurnConfig?.reasoningEffort??null,sessionTurnConfigApprovalPolicy:e.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,sessionTurnConfigSandboxMode:e.sessionTurnConfig?.execution?.codex?.sandboxMode??null,lastHydratedExternalUpdatedAt:e.lastHydratedExternalUpdatedAt??null,lastHydratedExternalConfigFreshnessAt:e.lastHydratedExternalConfigFreshnessAt??null}:{sessionFound:!1}}const pS={codex:[{version:`codex-mobile-v1`,defaults:{reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]},mS={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function hS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function gS(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function _S(e,t){let n=t?.trim().toLowerCase();return n?(pS[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function vS(e,t,n){return e.some(e=>e.id===t)?e.map(e=>({...e,isDefault:e.id===t})):[{id:t,label:t,isDefault:!0,...n===`codex`?{supportedReasoningEfforts:aS}:{}},...e.map(e=>({...e,isDefault:!1}))]}function yS(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function bS(e){let t=new Set;for(let n of e){let e=yS(n);e&&t.add(e)}return[...t]}function xS(e){return e?.trim()||void 0}function SS(e){let t=xS(e.runtimeModel);if(t)return t;let n=xS(e.discoveredModel);if(n)return n;let r=xS(e.existingModel),i=xS(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function CS(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,description:e.description,isDefault:e.isDefault,supportedReasoningEfforts:bS(e.supportedReasoningEfforts)}));return t.length===0?rS:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function wS(e){let t=Date.now();try{let n=CS(await My());return e?.info?.({provider:`codex`,durationMs:Date.now()-t,modelCount:n.length},`provider capabilities codex model load completed`),n}catch(n){return e?.warn?.({provider:`codex`,durationMs:Date.now()-t,err:n},`provider capabilities codex model load failed`),null}}async function TS(e){let t=Date.now();try{let n=await import(`@anthropic-ai/claude-agent-sdk`),r=n.query??n.default?.query;if(typeof r!=`function`)return null;let i=r,a=p.default.join(nc(),`claude-capability-probe`);await d.default.mkdir(a,{recursive:!0,mode:448});let o=i({prompt:`/clear`,options:{cwd:a,permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let n=await o.supportedModels(),r=[];for(let e of n){let t=typeof e.value==`string`?e.value:``;if(!t)continue;let n=Array.isArray(e.supportedEffortLevels)&&e.supportedEffortLevels.length>0,i=DS(e.description,e.displayName,t),a=e.supportsEffort===!1?[]:e.supportsEffort||n?bS(e.supportedEffortLevels??[]):i===`haiku`?[]:void 0;r.push({id:t,label:e.displayName||t,description:typeof e.description==`string`&&e.description.trim()?e.description.trim():void 0,isDefault:t===`default`,supportedReasoningEfforts:a})}return r.length===0?null:(r.some(e=>e.isDefault)||(r[0]={...r[0],isDefault:!0}),e?.info?.({provider:`claude`,durationMs:Date.now()-t,modelCount:r.length},`provider capabilities claude model load completed`),r)}finally{o.close()}}catch(n){return e?.warn?.({provider:`claude`,durationMs:Date.now()-t,err:n},`provider capabilities claude model load failed`),null}}function ES(e){let t=(e.find(e=>e.isDefault)??e[0])?.supportedReasoningEfforts??[];if(t.includes(`medium`))return`medium`;if(t.includes(`high`))return`high`;if(t.length>0)return t[0]}function DS(...e){for(let t of e){let e=t?.trim().toLowerCase();if(e){if(e.includes(`haiku`))return`haiku`;if(e.includes(`opus`))return`opus`;if(e.includes(`sonnet`)||e.includes(`sonnect`))return`sonnet`}}}var OS=class{sessions=new Map;providerCapabilitiesCache=new Map;providerCapabilitiesInFlight=new Map;nextRawSeqBySession=new Map;runtimeLifecycle;sweepTimer;lastRawEnvelopeTimestampMs=0;shuttingDown=!1;constructor(e){if(this.options=e,this.runtimeLifecycle={idleTtlMs:hS(e.runtimeLifecycle?.idleTtlMs,mS.idleTtlMs),sweepIntervalMs:gS(e.runtimeLifecycle?.sweepIntervalMs,mS.sweepIntervalMs),maxSessions:hS(e.runtimeLifecycle?.maxSessions,mS.maxSessions),maxCodexSessions:hS(e.runtimeLifecycle?.maxCodexSessions,mS.maxCodexSessions),maxClaudeSessions:hS(e.runtimeLifecycle?.maxClaudeSessions,mS.maxClaudeSessions)},this.runtimeLifecycle.sweepIntervalMs<=0){this.sweepTimer=null;return}this.sweepTimer=setInterval(()=>{this.sweepRuntimeSessions().catch(e=>{console.error(`[session-runtime] sweep failed: ${String(e)}`)})},this.runtimeLifecycle.sweepIntervalMs),this.sweepTimer.unref?.()}async shutdown(){this.shuttingDown=!0,this.sweepTimer&&clearInterval(this.sweepTimer);let e=[...this.sessions.keys()];this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown starting`),await Promise.allSettled(e.map(e=>this.closeRuntimeSession(e,`shutdown`))),await Pv(),this.options.logger?.info?.({sessionCount:e.length,sessionIds:e},`session manager shutdown completed`)}async listProjects(){let e=await this.options.projectStore.list(),t=this.buildProjectStatsMap();return e.map(e=>this.attachProjectStats(e,t))}async createProject(e){let t=await this.options.projectStore.upsertByPath(e.path,e.title);return this.attachProjectStats(t,this.buildProjectStatsMap())}async deleteProject(e){if(this.listProjectSessionsWithRuntime(e,`running`).length>0)throw t_(e);return this.options.projectStore.remove(e)}async restartCodexAppServer(){let e=this.listAllSessionsWithRuntime(`running`).length;if(e>0)throw n_(e);let t=[...this.sessions.values()].filter(e=>e.provider===`codex`).map(e=>e.id);return await Promise.allSettled(t.map(e=>this.closeRuntimeSession(e,`codex_restart`))),await Fv(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`codex.app_server.restart`,detail:{closedRuntimeSessionCount:t.length}}),{restarted:!0,closedRuntimeSessionCount:t.length}}async getProject(e){return this.options.projectStore.getById(e)}buildProjectStatsMap(){let e=new Map,t=this.listAllSessionsWithRuntime(`all`);for(let n of t){let t=e.get(n.projectId)??{runningCount:0,idleCount:0,totalCount:0,lastSessionAt:void 0};n.status===`running`?t.runningCount+=1:t.idleCount+=1,t.totalCount+=1;let r=n.updatedAt||n.createdAt;(!t.lastSessionAt||r>t.lastSessionAt)&&(t.lastSessionAt=r),e.set(n.projectId,t)}return e}attachProjectStats(e,t){let n=t.get(e.id),r=n?.idleCount??0;return{...e,lastSessionAt:n?.lastSessionAt,runningCount:n?.runningCount??0,idleCount:r,totalCount:n?.totalCount??0,endedCount:r}}async getProviderCapabilities(e,t,n){return(await this.resolveProviderCapabilities(e,t,n)).capabilities}async getAgentConfig(e,t){let n=await this.resolveProviderCapabilities(e,t?.projectId,t?.agentVersion);return{agent:{provider:e,requestedVersion:t?.agentVersion?.trim()||null,resolvedVersion:n.resolvedAgentVersion},capabilities:n.capabilities}}async warmStartupProviderCapabilities(){if(!this.options.preferNativeProviders||this.shuttingDown)return;let e=pS.claude.length>0?pS.claude.map(e=>e.version):[void 0];await Promise.allSettled(e.map(e=>this.resolveProviderCapabilities(`claude`,void 0,e)))}async resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw Qg(t);let r=_S(e,n),i=r?.version??`default`,a=`${e}::${i}`,o={provider:e,projectId:t??null,requestedAgentVersion:n?.trim()||null,resolvedAgentVersion:i},s=Date.now(),c=this.providerCapabilitiesCache.get(a);if(c){if(c.expiresAt>s)return this.options.logger?.info?.({...o,cacheStatus:`hit`,source:c.value.capabilities.source,modelCount:c.value.capabilities.models.length},`provider capabilities cache hit`),c.value;this.providerCapabilitiesCache.delete(a)}let l=this.providerCapabilitiesInFlight.get(a);if(l)return this.options.logger?.info?.({...o,cacheStatus:`in_flight`},`provider capabilities awaiting in-flight load`),l;let u=Date.now(),d=(async()=>{let t=Ab(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=Date.now(),a=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1;this.options.logger?.info?.({...o,cacheStatus:`miss`,nativeAvailable:a,durationMs:Date.now()-n},`provider capabilities native availability checked`);let s=a?`native`:`fallback`,c=e===`codex`&&a?await wS(this.options.logger)??rS:rS,l=e===`claude`&&a?await TS(this.options.logger)??iS:iS,d=bS(l.flatMap(e=>e.supportedReasoningEfforts??[])),f=e===`codex`?{provider:e,source:s,models:c,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:aS,approvalPolicies:oS,sandboxModes:sS,permissionModes:[]},defaults:{model:c.find(e=>e.isDefault)?.id??c[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:s,models:l,support:{reasoningEffort:d.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:d,approvalPolicies:[],sandboxModes:[],permissionModes:cS},defaults:{model:l.find(e=>e.isDefault)?.id??l[0]?.id,reasoningEffort:ES(l),permissionMode:`default`}};if(!r){let e={capabilities:f,resolvedAgentVersion:i};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:e.capabilities.source,modelCount:e.capabilities.models.length},`provider capabilities resolved`),e}let p={...f.defaults,...r.defaults},m=p.model?.trim(),h=s===`native`?f.models:m?vS(f.models,m,e):f.models,g={capabilities:{...f,models:h,defaults:p},resolvedAgentVersion:r.version};return this.options.logger?.info?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,source:g.capabilities.source,modelCount:g.capabilities.models.length},`provider capabilities resolved`),g})();this.providerCapabilitiesInFlight.set(a,d);try{let e=await d;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}catch(e){throw this.options.logger?.warn?.({...o,cacheStatus:`miss`,durationMs:Date.now()-u,err:e},`provider capabilities resolution failed`),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async getProviderDefaults(e,t,n){return Zx(e,await this.getProviderCapabilities(e,t,n))}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Qg(e);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){let n=this.options.historyStore.getProjectSession(e,t);return this.getRuntimeSessionSummary(e,t,n)||n}async getProjectSessionConfig(e,t){let n=this.options.historyStore.getProjectSession(e,t),r=this.getRuntimeSessionSummary(e,t,n);if(dS(`config.get.begin`,{projectId:e,sessionId:t,shouldHydrate:n?this.shouldHydrateCodexExternalSessionConfig(n):!1,persisted:fS(n),runtime:fS(r)}),r)return dS(`config.get.result`,{projectId:e,sessionId:t,resultSource:`runtime`,...fS(r)}),r;let i=await this.maybeHydrateCodexExternalSessionConfig(n);return dS(`config.get.result`,{projectId:e,sessionId:t,resultSource:i===n?`persisted`:`hydrated`,...fS(i)}),i}async syncProjectSessionHistory(e,t){let n=await this.options.projectStore.getById(e);if(!n)throw Qg(e);let r=this.options.historyStore.getProjectSession(e,t);if(!r&&this.options.preferNativeProviders&&(await this.syncCodexSessionsForProject(n),await this.syncClaudeSessionsForProject(n),r=this.options.historyStore.getProjectSession(e,t)),!r)throw $g(e,t);let i=await this.options.historyStore.getSessionRawEvents(r.id,2**53-1),a=await this.syncExternalRawHistory(r,e,i);return{session:this.options.historyStore.getProjectSession(e,r.id)??r,rawEvents:a}}async getProjectSessionRawEvents(e,t,n=300){let r=Date.now();if(!await this.options.projectStore.getById(e))throw Qg(e);let i=0,a=0,o,s=(s,c)=>{dS(`raw-events.read`,{projectId:e,sessionId:t,limit:n,provider:o?.provider,source:o?.source,providerMode:o?.providerMode,localReadDurationMs:i,finalCount:a,outcome:s,totalDurationMs:Date.now()-r,...c})},c=this.options.historyStore.getProjectSession(e,t);if(!c&&this.getRuntimeSessionSummary(e,t))return s(`runtime_session_empty`),[];if(!c)throw $g(e,t);o=c;let l=Date.now(),u=await this.options.historyStore.getSessionRawEvents(c.id,Math.max(n,300));return i=Date.now()-l,a=u.slice(-Math.max(1,n)).length,s(`local_only_cached`,{localEventCount:u.length}),u.slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300){let r=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsCompacted(r.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3){let i=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawEventsSinceSeq(i.id,n,r)}async getProjectSessionRawSeqRange(e,t){let n=await this.resolveProjectSessionForRawRead(e,t);return this.options.historyStore.getSessionRawSeqRange(n.id)}async resolveProjectSessionForRawRead(e,t){if(!await this.options.projectStore.getById(e))throw Qg(e);let n=this.options.historyStore.getProjectSession(e,t);if(!n)throw $g(e,t);return n}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${mg(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=Ab(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}),a=await this.getProviderDefaults(e.provider,t.id),o=e.sessionTurnConfig?$x(e.provider,e.sessionTurnConfig):tS({provider:e.provider,legacyModel:e.model,legacySessionConfig:e.sessionConfig}),s=nS({provider:e.provider,providerDefaults:a,currentSessionTurnConfig:o}),c=await i.createSession({sessionId:n,model:s.model,cwd:t.path,sessionConfig:s.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(e.provider,c,n),u=this.resolveNativeSessionId(e.provider,c,l),d=new Date().toISOString(),f=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:c.providerMode,model:s.model,title:void 0,sessionTurnConfig:o,sessionTurnConfigUpdatedAt:d,createdAt:d,updatedAt:d,status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(f),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:f.id,detail:{provider:e.provider,model:s.model,sessionConfig:e.sessionConfig,sessionTurnConfig:o,projectId:t.id,projectPath:t.path}}),{sessionId:f.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw e_(e);let a=await this.getProviderDefaults(i.provider,i.projectId),o=nS({provider:i.provider,providerDefaults:a,currentSessionTurnConfig:i.sessionTurnConfig,legacyModel:r?.model,legacySessionConfig:r?.sessionConfig,mode:r?.mode,config:r?.config});i.dispatchInFlight=!0,this.touchSession(i);try{if(await this.options.auditLogger.record({ts:new Date().toISOString(),action:`turn.input`,deviceId:n,sessionId:e,detail:{text:t,model:o.model,sessionConfig:r?.sessionConfig,mode:o.mode,config:r?.config,resolvedSessionConfig:o.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:o.model,sessionConfig:o.sessionConfig,mode:o.mode}),!i.title){let e=QS(t);e&&this.setSessionTitle(i,e)}let a=new Date().toISOString();i.sessionTurnConfig=$x(i.provider,o.sessionTurnConfig),i.sessionTurnConfigUpdatedAt=a,o.model&&i.model!==o.model&&(i.model=o.model),i.updatedAt=a,await this.persistSessionSnapshot(i)}finally{i.dispatchInFlight=!1,this.touchSession(i)}}async respondToolPermission(e,t,n,r,i){let a=this.mustGetSession(e);if(!a.pendingToolApprovals.has(t))throw Error(`Unknown tool approval request: ${t}`);if(typeof a.providerSession.respondToolPermission!=`function`){a.pendingToolApprovals.delete(t),a.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(a);return}await a.providerSession.respondToolPermission(t,n,r),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`tool.approval.respond`,deviceId:i,sessionId:e,detail:{requestId:t,decision:n,reason:r}})}async respondUserInput(e,t,n,r){let i=this.mustGetSession(e);if(!i.pendingUserInputs.has(t))throw Error(`Unknown user input request: ${t}`);if(typeof i.providerSession.respondUserInput!=`function`){i.pendingUserInputs.delete(t),i.updatedAt=new Date().toISOString(),await this.persistSessionSnapshot(i);return}await i.providerSession.respondUserInput(t,n),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`user.input.respond`,deviceId:r,sessionId:e,detail:{requestId:t,answeredCount:eC(n)}})}async interruptSession(e,t){let n=this.sessions.get(e);n&&await n.providerSession.interrupt(),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.interrupt`,deviceId:t,sessionId:e,detail:{runtimeSessionFound:!!n}})}async closeSession(e){throw Error(`session.close is deprecated. Use session.interrupt instead.`)}getSessionExecutionContext(e){let t=this.sessions.get(e);if(t)return{provider:t.provider,projectId:t.projectId,projectPath:t.projectPath};let n=this.options.historyStore.getSession(e);if(!n)throw e_(e);return{provider:n.provider,projectId:n.projectId,projectPath:n.projectPath}}async emitExternalEvent(e){let t=this.options.historyStore.getSession(e.sessionId),n={v:`1.0`,kind:`provider.raw`,rawSeq:await this.nextRawSeq(e.sessionId),provider:e.provider,sessionId:e.sessionId,projectId:e.projectId??t?.projectId,eventId:`raw_${mg(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:e.type,payload:{raw:{...e.raw,type:e.type}}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}async resumeSessionFromHistory(e){let t=this.options.historyStore.getSession(e);if(!t)return;let n=t.provider===`codex`&&this.options.requireNativeCodex,r=Ab(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=await this.getProviderDefaults(t.provider,t.projectId),a=$x(t.provider,t.sessionTurnConfig),o=nS({provider:t.provider,providerDefaults:i,currentSessionTurnConfig:a}),s=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,c=await r.createSession({sessionId:t.id,model:o.model??t.model,cwd:t.projectPath,resumeSessionId:s,sessionConfig:o.sessionConfig,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&c.providerMode!==`native`)throw await c.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let l=this.resolveCanonicalSessionId(t.provider,c,t.id),u=this.resolveNativeSessionId(t.provider,c,t.nativeSessionId),d=await this.attachRuntimeSession({id:l,nativeSessionId:u,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:c.providerMode,model:o.model??t.model,title:t.title,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:t.sessionTurnConfigUpdatedAt,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:c,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(d),d}async syncCodexSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await Oy(e.path)}catch{return}let n=new Set(t.filter(t=>t.cwd===e.path).map(e=>e.id)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`codex`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){if(n.cwd!==e.path)continue;let t=[...r.values()].find(e=>e.provider===`codex`&&(e.id===n.id||e.nativeSessionId===n.id)),i=t?.id??n.id,a=this.sessions.get(i)??this.sessions.get(n.id),o=tC(n.createdAt),s=tC(n.updatedAt),c=a?.status===`running`?`running`:`idle`,l=c===`running`?a?.pendingToolApprovals.size??0:0,u=c===`running`?a?.pendingUserInputs.size??0:0,d={id:i,nativeSessionId:n.id,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`codex`,providerMode:a?.providerMode??t?.providerMode??`native`,model:SS({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??QS(n.name??n.preview)??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??o,updatedAt:c===`running`?a?.updatedAt??s:s,status:c,pendingApprovals:l,pendingUserInputs:u,pendingActions:l+u};await this.options.historyStore.upsertSession(d),r.set(i,d)}}async syncClaudeSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await Pb(e.path)}catch{return}let n=new Set(t.map(e=>e.nativeSessionId)),r=new Map(this.options.historyStore.listProjectSessions(e.id,`all`).map(e=>[e.id,e])),i=[...r.values()].filter(e=>e.provider===`claude`&&e.source===`native_discovered`&&!this.sessions.has(e.id)&&!n.has(e.nativeSessionId??e.id)).map(e=>e.id);for(let e of i)await this.options.historyStore.removeSession(e),r.delete(e);for(let n of t){let t=[...r.values()].find(e=>e.provider===`claude`&&(e.id===n.nativeSessionId||e.nativeSessionId===n.nativeSessionId)),i=t?.id??n.nativeSessionId,a=this.sessions.get(i),o=a?.status===`running`?`running`:`idle`,s=o===`running`?a?.pendingToolApprovals.size??0:0,c=o===`running`?a?.pendingUserInputs.size??0:0,l={id:i,nativeSessionId:n.nativeSessionId,source:t?.source??`native_discovered`,projectId:e.id,projectPath:e.path,provider:`claude`,providerMode:a?.providerMode??t?.providerMode??`native`,model:a?.model??t?.model??n.model,title:a?.title??n.title??t?.title,sessionTurnConfig:a?.sessionTurnConfig??t?.sessionTurnConfig,sessionTurnConfigUpdatedAt:a?.sessionTurnConfigUpdatedAt??t?.sessionTurnConfigUpdatedAt,createdAt:t?.createdAt??n.createdAt,updatedAt:o===`running`?a?.updatedAt??n.updatedAt:n.updatedAt,status:o,pendingApprovals:s,pendingUserInputs:c,pendingActions:s+c};await this.options.historyStore.upsertSession(l),r.set(i,l)}}async maybeHydrateCodexExternalSessionConfig(e){if(!e||!this.shouldHydrateCodexExternalSessionConfig(e))return e;let t=uS(e),n=US([e.nativeSessionId,e.id]);for(let r of n)try{dS(`config.get.probe.begin`,{projectId:e.projectId,sessionId:e.id,threadId:r,...fS(e)});let n=await jy(r);if(!n){dS(`config.get.probe.empty`,{projectId:e.projectId,sessionId:e.id,threadId:r});continue}let i={...e,model:xS(n.model)??e.model,sessionTurnConfig:n.sessionTurnConfig??e.sessionTurnConfig,sessionTurnConfigUpdatedAt:n.sessionTurnConfigUpdatedAt,...t?{lastHydratedExternalConfigFreshnessAt:t}:{}};return await this.options.historyStore.upsertSession(i),dS(`config.get.probe.result`,{projectId:e.projectId,sessionId:e.id,threadId:r,snapshotModel:n.model??null,snapshotSessionTurnConfigModel:n.sessionTurnConfig?.model??null,snapshotReasoningEffort:n.sessionTurnConfig?.reasoningEffort??null,snapshotApprovalPolicy:n.sessionTurnConfig?.execution?.codex?.approvalPolicy??null,snapshotSandboxMode:n.sessionTurnConfig?.execution?.codex?.sandboxMode??null,snapshotUpdatedAt:n.sessionTurnConfigUpdatedAt,next:fS(i)}),this.options.historyStore.getProjectSession(e.projectId,e.id)??i}catch(t){dS(`config.get.probe.error`,{projectId:e.projectId,sessionId:e.id,threadId:r,error:String(t)})}return e}shouldHydrateCodexExternalSessionConfig(e){if(!this.options.preferNativeProviders||e.provider!==`codex`||e.source!==`native_discovered`||this.sessions.has(e.id)||e.nativeSessionId&&this.sessions.has(e.nativeSessionId))return!1;let t=uS(e),n=e.sessionTurnConfigUpdatedAt||``;if(!e.sessionTurnConfig||!xS(e.model)||!n)return!0;if(!t)return!1;let r=e.lastHydratedExternalConfigFreshnessAt;return r?t.localeCompare(r)>0:!0}async resolveProjectForSessionStart(e,t){if(!e&&!t)throw Error(`session.start requires projectId or cwd`);if(e&&t){let n=await this.options.projectStore.getById(e);if(!n)throw Qg(e);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await nC(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Qg(e);return await nC(t.path),t}return this.options.projectStore.upsertByPath(t)}async attachRuntimeSession(e){let t=this.sessions.get(e.id);t&&await this.closeRuntimeSession(t.id,`replaced`,{suppressAudit:!0});let n={...e,unsubscribe:()=>{}};return await this.initializeRawSeqCursor(n.id),n.unsubscribe=n.providerSession.onEvent(e=>{if(!n.streamReady){n.bufferedProviderEvents.push(e);return}this.handleProviderEvent(n,e)}),this.sessions.set(n.id,n),n}handleProviderEvent(e,t){let n=this.ensureProviderRequestId(t);if(this.emitRawEnvelope(e,n),this.maybePersistUpdatedNativeSessionId(e),e.updatedAt=new Date().toISOString(),this.touchSession(e),n.type===`thread.title.updated`){let t=$S(n.title);t&&this.setSessionTitle(e,t);return}if(n.type===`turn.started`){e.status=`running`,this.persistSessionSnapshot(e);return}if(n.type===`turn.completed`||n.type===`turn.failed`){e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`error.runtime`){let t=$S(n.message);e.status!==`idle`&&this.options.logger?.warn?.({sessionId:e.id,nativeSessionId:e.nativeSessionId,provider:e.provider,providerMode:e.providerMode,projectId:e.projectId,projectPath:e.projectPath,model:e.model,previousStatus:e.status,nextStatus:`idle`,eventType:n.type,errorMessage:t},`provider session forced idle after error event`),e.status=`idle`,this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingToolApprovals.add(t),this.persistSessionSnapshot(e);return}if(n.type===`tool.permission.resolved`&&typeof n.requestId==`string`){e.pendingToolApprovals.delete(n.requestId),this.persistSessionSnapshot(e);return}if(n.type===`user.input.requested`){let t=typeof n.requestId==`string`?n.requestId:``;if(!t)return;e.pendingUserInputs.add(t),this.persistSessionSnapshot(e);return}if(n.type===`user.input.resolved`&&typeof n.requestId==`string`){e.pendingUserInputs.delete(n.requestId),this.persistSessionSnapshot(e);return}}emitRawEnvelope(e,t){let n={v:`1.0`,kind:`provider.raw`,rawSeq:this.nextRawSeqSync(e.id),provider:e.provider,sessionId:e.id,projectId:e.projectId,eventId:`raw_${mg(12)}`,ts:this.nextRawEnvelopeTimestamp(),type:t.type,payload:{raw:t}};this.options.onEnvelope(n),this.options.historyStore.appendRawEvent(n).catch(e=>{console.error(`[session-history] append raw event failed: ${String(e)}`)})}nextRawEnvelopeTimestamp(){let e=Date.now(),t=e>this.lastRawEnvelopeTimestampMs?e:this.lastRawEnvelopeTimestampMs+1;return this.lastRawEnvelopeTimestampMs=t,new Date(t).toISOString()}async initializeRawSeqCursor(e){if(this.nextRawSeqBySession.has(e))return;let t=await this.options.historyStore.getSessionRawSeqRange(e),n=t?t.max+1:1;this.nextRawSeqBySession.set(e,n)}async nextRawSeq(e){return await this.initializeRawSeqCursor(e),this.nextRawSeqSync(e)}nextRawSeqSync(e){let t=this.nextRawSeqBySession.get(e)??1;return this.nextRawSeqBySession.set(e,t+1),t}touchSession(e){e.lastActiveAtMs=Date.now()}isSessionEvictable(e){return!(e.closing||e.status!==`idle`||e.pendingToolApprovals.size>0||e.pendingUserInputs.size>0||e.dispatchInFlight)}async closeRuntimeSession(e,t,n){let r=this.sessions.get(e);if(!r||r.closing)return!1;r.closing=!0;let i=Date.now();this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,statusBefore:r.status,projectId:r.projectId,projectPath:r.projectPath,model:r.model,pendingApprovalCount:r.pendingToolApprovals.size,pendingUserInputCount:r.pendingUserInputs.size,dispatchInFlight:r.dispatchInFlight},`provider runtime session close starting`);try{r.unsubscribe()}catch{}let a;try{await r.providerSession.close()}catch(n){a=n,console.error(`[session-runtime] failed closing session ${e}:`,n),this.options.logger?.error?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,error:String(n),err:n},`provider runtime session close failed`)}finally{r.status=`idle`,r.updatedAt=new Date().toISOString(),r.pendingToolApprovals.clear(),r.pendingUserInputs.clear();try{await this.persistSessionSnapshot(r)}catch(t){console.error(`[session-runtime] failed persisting closed session ${e}: ${String(t)}`)}this.sessions.delete(e),r.dispatchInFlight=!1,r.closing=!1}if(this.options.logger?.info?.({sessionId:e,nativeSessionId:r.nativeSessionId,provider:r.provider,providerMode:r.providerMode,reason:t,projectId:r.projectId,projectPath:r.projectPath,model:r.model,result:a?`error`:`success`,durationMs:Date.now()-i},`provider runtime session close completed`),!n?.suppressAudit)try{await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.runtime.close`,sessionId:e,detail:{reason:t,provider:r.provider}})}catch(e){console.error(`[session-runtime] failed to record runtime close audit log: ${String(e)}`)}return!0}async sweepRuntimeSessions(){if(this.shuttingDown||this.sessions.size===0)return;let e=Date.now(),t=this.runtimeLifecycle.idleTtlMs,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs);for(let r of n)e-r.lastActiveAtMs<t||await this.closeRuntimeSession(r.id,`idle_ttl`);await this.enforceProviderSessionCap(`codex`,this.runtimeLifecycle.maxCodexSessions),await this.enforceProviderSessionCap(`claude`,this.runtimeLifecycle.maxClaudeSessions),await this.enforceGlobalSessionCap(this.runtimeLifecycle.maxSessions)}async enforceProviderSessionCap(e,t){let n=[...this.sessions.values()].filter(t=>t.provider===e);if(n.length<=t)return;let r=n.length-t,i=n.filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),a=0;for(let e of i){if(a>=r)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(a+=1)}a<r&&console.warn(`[session-runtime] ${e} sessions exceed cap (${n.length}/${t}), no more idle sessions to evict`)}async enforceGlobalSessionCap(e){if(this.sessions.size<=e)return;let t=this.sessions.size-e,n=[...this.sessions.values()].filter(e=>this.isSessionEvictable(e)).sort((e,t)=>e.lastActiveAtMs-t.lastActiveAtMs),r=0;for(let e of n){if(r>=t)break;await this.closeRuntimeSession(e.id,`lru_cap`)&&(r+=1)}r<t&&console.warn(`[session-runtime] session count exceeds cap (${this.sessions.size}/${e}), no more idle sessions to evict`)}ensureProviderRequestId(e){return e.type===`tool.permission.requested`||e.type===`user.input.requested`?typeof e.requestId==`string`&&e.requestId.trim()?e:{...e,requestId:`req_${mg(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n)return t;let r=await this.options.historyStore.mergeSessionRawEvents(e.id,t),i=r[r.length-1]?.rawSeq;return typeof i==`number`&&Number.isFinite(i)&&i>0&&this.nextRawSeqBySession.set(e.id,i+1),r}async syncExternalRawHistory(e,t,n){if(e.provider===`claude`){let r=GS(e);if(!r)return n;try{let i=Date.now(),a=await Fb({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t}),o=Date.now(),s=await this.finalizeExternalRawHistorySync(e,n,a);return dS(`sync-external.claude`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,historyEventCount:a.length,resultEventCount:s.length,readHistoryDurationMs:o-i,finalizeDurationMs:Date.now()-o}),s}catch(r){return e.source===`native_discovered`&&WS(r)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),dS(`sync-external.claude.error`,{projectId:t,sessionId:e.id,source:e.source,localEventCount:n.length,error:r instanceof Error?r.message:String(r)}),n}}if(e.provider!==`codex`)return n;let r=US([e.nativeSessionId,e.id]);for(let i of r)try{let r=Date.now(),a=await Ay(i,!0),o=Date.now(),s=e.source===`gateway`&&n.length>0?YS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localEvents:n}):KS({thread:a,provider:e.provider,sessionId:e.id,projectId:t,localTerminalTurnStatusById:qS(n),localTurnLastEventTsById:JS(n)}),c=Date.now(),l=await this.finalizeExternalRawHistorySync(e,n,s,tC(a.updatedAt));return dS(`sync-external.codex`,{projectId:t,sessionId:e.id,source:e.source,threadId:i,localEventCount:n.length,historyEventCount:s.length,resultEventCount:l.length,readThreadDurationMs:o-r,buildHistoryDurationMs:c-o,finalizeDurationMs:Date.now()-c}),l}catch{}return n}async finalizeExternalRawHistorySync(e,t,n,r=e.updatedAt){let i=Date.now(),a=AS(e.provider,t,n),o=Date.now(),s=await this.maybePersistSyncedExternalRawEvents(e,a,!0);return await this.markExternalHistoryHydrated(e.id,r),dS(`sync-external.finalize`,{sessionId:e.id,provider:e.provider,source:e.source,localEventCount:t.length,historyEventCount:n.length,mergedEventCount:a.length,persistedEventCount:s.length,hydratedExternalUpdatedAt:r,mergeDurationMs:o-i,persistDurationMs:Date.now()-o}),s}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw e_(e);return t}markSessionStreamReady(e){if(e.streamReady||(e.streamReady=!0,e.bufferedProviderEvents.length===0))return;let t=[...e.bufferedProviderEvents];e.bufferedProviderEvents.length=0;for(let n of t)this.handleProviderEvent(e,n)}async persistSessionSnapshot(e){await this.options.historyStore.upsertSession(this.toSessionSummary(e))}listAllSessionsWithRuntime(e=`all`){let t=new Map(this.options.historyStore.listSessions(`all`).map(e=>[e.id,e]));for(let e of this.sessions.values())(!t.get(e.id)||e.status===`running`)&&t.set(e.id,this.toSessionSummary(e));return[...t.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessionsWithRuntime(e,t=`all`){return this.listAllSessionsWithRuntime(t).filter(t=>t.projectId===e)}getRuntimeSessionSummary(e,t,n){let r=this.sessions.get(t);if(!(!r||r.projectId!==e)&&!(r.status!==`running`&&n))return this.toSessionSummary(r)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,...e.source===`gateway`?{lastHydratedExternalUpdatedAt:e.updatedAt}:{},projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,sessionTurnConfig:e.sessionTurnConfig,sessionTurnConfigUpdatedAt:e.sessionTurnConfigUpdatedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.status,pendingApprovals:e.pendingToolApprovals.size,pendingUserInputs:e.pendingUserInputs.size,pendingActions:e.pendingToolApprovals.size+e.pendingUserInputs.size}}setSessionTitle(e,t){let n=ZS(t);!n||n===e.title||(e.title=n,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}resolveCanonicalSessionId(e,t,n){return e===`codex`&&t.getNativeSessionId?.()||n}resolveNativeSessionId(e,t,n){return e!==`codex`&&e!==`claude`?n:t.getNativeSessionId?.()||n}maybePersistUpdatedNativeSessionId(e){let t=this.resolveNativeSessionId(e.provider,e.providerSession,e.nativeSessionId);!t||t===e.nativeSessionId||this.shouldPersistNativeSessionId(e,t)&&(e.nativeSessionId=t,e.updatedAt=new Date().toISOString(),this.persistSessionSnapshot(e))}shouldPersistNativeSessionId(e,t){return e.source===`native_discovered`?!1:e.nativeSessionId?e.nativeSessionId===e.id&&e.id.startsWith(`sess_`)?t!==e.nativeSessionId:!1:!0}};const kS=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]);function AS(e,t,n){let r=new Map,i=new Set,a=jS(e),o=jS(e);for(let n of t){r.set(n.eventId,n);for(let t of MS(e,n,a))i.add(t)}for(let t of n){if(r.has(t.eventId))continue;let n=MS(e,t,o);if(!(n.length>0&&n.every(e=>i.has(e)))){r.set(t.eventId,t);for(let e of n)i.add(e)}}return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function jS(e){if(e===`codex`)return{codexTurnScopedItemOccurrences:new Map}}function MS(e,t,n){return e===`codex`?NS(t,n):e===`claude`?IS(t):[]}function NS(e,t){let n=zS(e.payload.raw),r=new Set,i=LS(e.type,n);if(i){let a=PS(e.type,n);a?r.add(FS(a,t)):r.add(i)}if(e.type!==`native.raw`||$(n.source)!==`codex.history.thread_read`)return[...r];let a=zS(n.message),o=$(a.scope);if(o===`thread`){let e=zS(a.thread),t=$(e.id);t&&r.add(RS(`thread.started`,{thread_id:t,thread:e}));let n=QS(BS(e.preview)??BS(e.name)??``);return n&&r.add(RS(`thread.title.updated`,{title:n,thread_id:t})),[...r]}if(o===`turn`){let e=zS(a.turn),t=$(e.status);return r.add(RS(`turn.started`,{turn:e})),t===`completed`?r.add(RS(`turn.completed`,{status:t,turn:e})):(t===`failed`||t===`interrupted`)&&r.add(RS(`turn.failed`,{status:t,turn:e})),[...r]}if(o===`item`){let e={turn_id:$(a.turn_id)??$(zS(a.item).turn_id),item:zS(a.item)},n=PS(`item.completed`,e);return n?r.add(FS(n,t)):r.add(RS(`item.completed`,e)),[...r]}return[...r]}function PS(e,t){if(!e.startsWith(`item.`))return;let n=zS(t.item),r=$(t.turn_id)??$(t.turnId)??$(n.turn_id)??$(n.turnId),i=$(n.type);if(!(!r||!i))return[`codex`,e,r,i,$(n.phase)??``,$(n.status)??``,$(n.command)??``,VS(n)??``].join(`|`)}function FS(e,t){let n=t?.codexTurnScopedItemOccurrences;if(!n)return e;let r=(n.get(e)??0)+1;return n.set(e,r),`${e}|${r}`}function IS(e){let t=zS(e.payload.raw),n=LS(e.type,t);if(n)return[n];if(e.type!==`native.raw`)return[];let r=$(t.source);if(!r||!kS.has(r))return[];let i=zS(t.message),a=$(t.native_type)??$(i.type),o=zS(i.message);if(a===`user`){let e=HS(o),t=$(i.uuid);return!e||!t?[]:[RS(`item.completed`,{item:{id:t,type:`user_message`,text:e}})]}if(a===`assistant`){let e=HS(o),t=$(o.id)??$(i.uuid);return!e||!t?[]:[RS(`item.completed`,{item:{id:t,type:`agent_message`,text:e}})]}return[]}function LS(e,t){switch(e){case`thread.started`:case`thread.title.updated`:case`turn.started`:case`turn.completed`:case`turn.failed`:case`item.started`:case`item.updated`:case`item.completed`:return RS(e,t);default:return}}function RS(e,t){let n=zS(t.item),r=zS(t.turn),i=zS(t.thread),a=$(n.id)??``,o=$(t.turn_id)??$(t.turnId)??$(r.id)??$(n.turn_id)??``,s=$(r.status)??$(t.status)??``,c=$(t.thread_id)??$(t.threadId)??$(i.id)??``,l=$(n.type)??``,u=$(n.phase)??``,d=$(n.status)??``,f=$(n.command)??``,p=VS(n),m=BS(t.message)??``,h=BS(t.title)??``;return e.startsWith(`item.`)?[e,a,l,u,d,f,p||m].join(`|`):e.startsWith(`turn.`)?[e,o,s].join(`|`):e===`thread.title.updated`?[e,c,h].join(`|`):[e,c,o,a,l,h||m].join(`|`)}function zS(e){return typeof e==`object`&&e?e:{}}function $(e){return typeof e==`string`&&e.trim()||void 0}function BS(e){if(typeof e==`string`)return e.length>0?e:void 0}function VS(e){let t=BS(e.text);if(t)return t;let n=Array.isArray(e.content)?e.content:[];if(n.length>0){let e=[];for(let t of n){let n=BS(zS(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
482
+ `)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>BS(e)).filter(e=>!!e);if(e.length>0)return e.join(`
483
+ `)}return``}function HS(e){let t=$(e.content);if(t)return t;let n=$(e.text)??$(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`){let t=e.trim();t&&i.push(t);continue}let t=zS(e),n=$(t.type);if(n&&n!==`text`)continue;let r=$(t.text)??$(t.content);r&&i.push(r)}if(i.length!==0)return i.join(`
484
+ `)}function US(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function WS(e){return String(e).includes(`returned no messages from getSessionMessages`)}function GS(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function KS(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,n+=1,new Date(n).toISOString()),a=t=>{let r=e.localTurnLastEventTsById?.get(t);typeof r==`number`&&Number.isFinite(r)&&(n=Math.max(n,r))},o=e=>String(e??``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``),s=t=>{let n=t.map(o).filter(e=>e.length>0);return n.length===0?`raw_hist_codex_${e.sessionId}_${r.toString().padStart(6,`0`)}`:`raw_hist_codex_${e.sessionId}_${n.join(`_`)}`},c=(n,r)=>{let a=t.length+1;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:s(r),ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};c({scope:`thread`,thread:{id:e.thread.id,preview:e.thread.preview,model_provider:e.thread.modelProvider,created_at:e.thread.createdAt,updated_at:e.thread.updatedAt,path:e.thread.path,cwd:e.thread.cwd,cli_version:e.thread.cliVersion,source:e.thread.source,git_info:e.thread.gitInfo}},[`thread`,e.thread.id,e.thread.updatedAt]);for(let t of e.thread.turns){if(e.localTerminalTurnStatusById?.get(t.id)===t.status&&XS(t.status)){a(t.id);continue}c({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}},[`turn`,t.id,t.status]);for(let n of t.items)c({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n},[`item`,t.id,$S(n.id)??null])}return t}function qS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=zS(n.payload.raw);if(n.type===`turn.completed`||n.type===`turn.failed`){let r=$(e.turn_id)??$(e.turnId)??$(zS(e.turn).id)??$(zS(e.item).turn_id)??$(zS(e.item).turnId),i=$(e.status)??(n.type===`turn.completed`?`completed`:`failed`);r&&t.set(r,i);continue}if(n.type!==`native.raw`||$(e.source)!==`codex.history.thread_read`)continue;let r=zS(e.message);if($(r.scope)===`turn`){let e=zS(r.turn),n=$(e.id),i=$(e.status);n&&i&&XS(i)&&t.set(n,i)}}return t}function JS(e){if(e.length===0)return new Map;let t=new Map;for(let n of e){let e=Date.parse(n.ts);if(!Number.isFinite(e))continue;let r=zS(n.payload.raw),i=$(r.turn_id)??$(r.turnId)??$(zS(r.turn).id);if(!i&&n.type===`native.raw`){if($(r.source)!==`codex.history.thread_read`)continue;let e=zS(r.message),t=$(e.scope);t===`turn`?i=$(zS(e.turn).id):t===`item`&&(i=$(e.turn_id)??$(e.turnId))}i&&t.set(i,Math.max(t.get(i)??0,e))}return t}function YS(e){let t=new Set,n=new Set,r=new Map,i=0,a=1;for(let o of e.localEvents){let e=Date.parse(o.ts);Number.isFinite(e)&&(i=Math.max(i,e)),a=Math.max(a,o.rawSeq+1);let s=zS(o.payload.raw);if(o.type===`item.started`||o.type===`item.updated`||o.type===`item.completed`){if(o.type===`item.completed`){let e=$(zS(s.item).id);e&&n.add(e)}}else if(o.type===`turn.started`){let e=$(s.turn_id)??$(zS(s.turn).id);e&&t.add(e);continue}if(o.type===`turn.completed`||o.type===`turn.failed`){let e=$(s.turn_id)??$(zS(s.turn).id);if(!e)continue;t.add(e);let n=$(s.status)??(o.type===`turn.completed`?`completed`:`failed`);r.set(e,n)}if(o.type!==`native.raw`||$(s.source)!==`codex.history.thread_read`)continue;let c=zS(s.message),l=$(c.scope);if(l===`turn`){let e=zS(c.turn),n=$(e.id);if(!n)continue;t.add(n);let i=$(e.status);i&&XS(i)&&r.set(n,i);continue}if(l===`item`){let e=$(zS(c.item).id);e&&n.add(e)}}let o=Math.max(i,e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now()),s=0,c=()=>(s+=1,new Date(o+s).toISOString()),l=[],u=(t,n)=>{let r=c();l.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_sync_codex_${e.sessionId}_${a.toString().padStart(6,`0`)}`,ts:r,type:t,payload:{raw:{...n,historyReplay:!0,replaySynthetic:!0,source:`codex.history.thread_read.incremental`}}}),a+=1};for(let i of e.thread.turns){let e=r.get(i.id);if(!(e===i.status&&XS(i.status))){t.has(i.id)||u(`turn.started`,{type:`turn.started`,turn:{id:i.id,status:i.status,items:[],error:i.error}});for(let e of i.items){let t=$(e.id);t&&n.has(t)||u(`item.completed`,{type:`item.completed`,turn_id:i.id,item:e})}if(XS(i.status)&&e!==i.status){if(i.status===`completed`){u(`turn.completed`,{type:`turn.completed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error}});continue}u(`turn.failed`,{type:`turn.failed`,status:i.status,turn:{id:i.id,status:i.status,items:[],error:i.error},...i.error?{error:i.error}:{}})}}}return l}function XS(e){return e===`completed`||e===`failed`||e===`interrupted`}function ZS(e){let t=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,``).replace(/\s+/g,` `).trim();if(t)return t}function QS(e,t=60){let n=ZS(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function $S(e){if(typeof e!=`string`)return;let t=ZS(e);if(t)return t}function eC(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function tC(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function nC(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var rC=class{indexPath;eventsDir;sessions=new Map;rawEventsCacheBySession=new Map;compactedRawEventsCacheBySession=new Map;pendingRawMutationsBySession=new Map;ready;writeQueue=Promise.resolve();constructor(e){this.baseDir=e,this.indexPath=p.default.join(e,`session-index.json`),this.eventsDir=p.default.join(e,`session-events`),this.ready=this.loadFromDisk()}async init(){await this.ready}async flushRawCompactions(e){await this.ready}async shutdown(){await this.ready}async upsertSession(e){await this.ready;let t=this.sessions.get(e.id);this.sessions.set(e.id,{...t,...e}),await this.enqueueWrite(async()=>{await this.persistIndex()})}async patchSession(e,t){await this.ready;let n=this.sessions.get(e);return n?(this.sessions.set(e,{...n,...t}),await this.enqueueWrite(async()=>{await this.persistIndex()}),!0):!1}async setSessionStatus(e,t,n){await this.ready;let r=this.sessions.get(e);r&&(this.sessions.set(e,{...r,status:t,updatedAt:n,pendingApprovals:t===`running`?r.pendingApprovals:0,pendingUserInputs:t===`running`?r.pendingUserInputs:0,pendingActions:t===`running`?r.pendingActions:0}),await this.enqueueWrite(async()=>{await this.persistIndex()}))}async removeSession(e){if(await this.ready,!this.sessions.has(e))return;this.sessions.delete(e),this.rawEventsCacheBySession.delete(e),this.compactedRawEventsCacheBySession.delete(e);let t=p.default.join(this.eventsDir,`${e}.jsonl`),n=p.default.join(this.eventsDir,`${e}.raw.jsonl`);await this.enqueueWrite(async()=>{await Promise.all([this.persistIndex(),d.default.rm(t,{force:!0}),d.default.rm(n,{force:!0})])})}hasSession(e){return this.sessions.has(e)}getSession(e){return this.sessions.get(e)}getProjectSession(e,t){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return n}listSessions(e=`all`){return[...this.sessions.values()].filter(t=>e===`all`||t.status===e).sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})}listProjectSessions(e,t=`all`){return this.listSessions(t).filter(t=>t.projectId===e)}async appendRawEvent(e){await this.ready,this.sessions.has(e.sessionId)&&await this.enqueueRawSessionWrite(e.sessionId,async()=>{if(mC(e)){let t=As([...await this.readSessionRawEventsLocked(e.sessionId),e]);await this.replaceRawEventFile(e.sessionId,t),this.rawEventsCacheBySession.set(e.sessionId,t),this.compactedRawEventsCacheBySession.set(e.sessionId,lC(t));return}await this.appendRawEventLine(e),this.appendRawEventToCache(e)})}async mergeSessionRawEvents(e,t){if(await this.ready,!this.sessions.has(e))return[];let n=t.filter(t=>t.sessionId===e),r=[];return await this.enqueueRawSessionWrite(e,async()=>{r=hC(await this.readSessionRawEventsLocked(e),n),await this.replaceRawEventFile(e,r),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.set(e,lC(r))}),r}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionRawEventsCompacted(e,t=300){if(await this.ready,!this.sessions.has(e))return[];let n=Math.max(1,t),r=this.readSessionRawEventsCompactedFromCache(e);if(r!==void 0)return r.slice(-n);let i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),i}async getSessionRawEventsSinceSeq(e,t,n=2e3){if(await this.ready,!this.sessions.has(e))return[];let r=Math.max(1,n),i=this.readSessionRawEventsFromCache(e);if(i!==void 0)return As(i.filter(e=>e.rawSeq>t)).slice(0,r);let a=[];return await this.enqueueWrite(async()=>{a=As((await this.readSessionRawEventsLocked(e)).filter(e=>e.rawSeq>t)).slice(0,r)}),a}async getSessionRawSeqRange(e){if(await this.ready,!this.sessions.has(e))return null;let t=this.readSessionRawEventsFromCache(e);if(t!==void 0)return sC(t);let n=null;return await this.enqueueWrite(async()=>{n=sC(await this.readSessionRawEventsLocked(e))}),n}async loadFromDisk(){await d.default.mkdir(this.eventsDir,{recursive:!0});try{let e=await d.default.readFile(this.indexPath,`utf8`),t=JSON.parse(e);if(t.v!==1||!Array.isArray(t.sessions))return;for(let e of t.sessions)e?.id&&e?.provider&&e?.createdAt&&e?.updatedAt&&e?.status&&e?.projectId&&e?.projectPath&&this.sessions.set(e.id,{...e,status:`idle`,pendingApprovals:0,pendingUserInputs:0,pendingActions:0})}catch(e){if(e.code!==`ENOENT`)throw e}}async persistIndex(){await d.default.mkdir(this.baseDir,{recursive:!0});let e={v:1,sessions:[...this.sessions.values()].sort((e,t)=>{let n=e.updatedAt||e.createdAt;return(t.updatedAt||t.createdAt).localeCompare(n)})};await d.default.writeFile(this.indexPath,`${JSON.stringify(e,null,2)}\n`,`utf8`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}async enqueueRawSessionWrite(e,t){this.incrementPendingRawMutation(e);try{let e;return await this.enqueueWrite(async()=>{e=await t()}),e}finally{this.decrementPendingRawMutation(e)}}async appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${oC(e)}\n`;await d.default.appendFile(t,n,`utf8`)}async replaceRawEventFile(e,t){let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r=t.map(e=>oC(e)).join(`
485
+ `);await cC(n,r?`${r}\n`:``)}appendRawEventToCache(e){let t=this.rawEventsCacheBySession.get(e.sessionId),n=t?.[t.length-1];t&&t.push(e);let r=this.compactedRawEventsCacheBySession.get(e.sessionId);if(r){if(pC(e)){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}if(n&&fC(e,n)<0){this.compactedRawEventsCacheBySession.delete(e.sessionId);return}dC(r,e)}}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return uC(t);let n=lC(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),uC(n)}async readSessionRawEventsLocked(e){let t=this.rawEventsCacheBySession.get(e);if(t)return t;let n=p.default.join(this.eventsDir,`${e}.raw.jsonl`),r;try{r=await d.default.readFile(n,`utf8`)}catch(t){if(t.code===`ENOENT`)return this.rawEventsCacheBySession.set(e,[]),[];throw t}let i=r.split(`
486
+ `).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!iC(t)||t.kind!==`provider.raw`)continue;let n=aC(t.rawSeq);a.push({value:t,...n===void 0?{}:{rawSeq:n}})}catch{}if(a.length===0)return this.rawEventsCacheBySession.set(e,[]),[];let o=a.some(e=>e.rawSeq===void 0),s=a.map((e,t)=>({...e.value,rawSeq:e.rawSeq??t+1})),c=[];for(let e of s){let t=fa.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>oC(e)).join(`
487
+ `),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}readSessionRawEventsFromCache(e){if(!this.hasPendingRawMutation(e))return this.rawEventsCacheBySession.get(e)}readSessionRawEventsCompactedFromCache(e){if(this.hasPendingRawMutation(e))return;let t=this.compactedRawEventsCacheBySession.get(e);if(t)return uC(t);let n=this.rawEventsCacheBySession.get(e);if(!n)return;let r=lC(n);return this.compactedRawEventsCacheBySession.set(e,r),uC(r)}incrementPendingRawMutation(e){this.pendingRawMutationsBySession.set(e,(this.pendingRawMutationsBySession.get(e)??0)+1)}decrementPendingRawMutation(e){let t=(this.pendingRawMutationsBySession.get(e)??0)-1;if(t>0){this.pendingRawMutationsBySession.set(e,t);return}this.pendingRawMutationsBySession.delete(e)}hasPendingRawMutation(e){return(this.pendingRawMutationsBySession.get(e)??0)>0}};function iC(e){return typeof e==`object`&&!!e}function aC(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function oC(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`bigint`)return n.toString();if(typeof n==`function`)return`[Function ${n.name||`anonymous`}]`;if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n})}function sC(e){if(e.length===0)return null;let t=e[0],n=e[e.length-1];return!t||!n?null:{min:t.rawSeq,max:n.rawSeq}}async function cC(e,t){await d.default.mkdir(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{await d.default.writeFile(n,t,`utf8`),await d.default.rename(n,e)}catch(e){try{await d.default.rm(n,{force:!0})}catch{}throw e}}function lC(e){let t=ks(e),n=t.map(e=>e),r=new Map;for(let[e,t]of n.entries()){let n=js(t);n&&r.set(n.key,e)}return{slots:n,indexByKey:r,dense:t}}function uC(e){return e.dense||=e.slots.filter(e=>e!==null),e.dense}function dC(e,t){let n=js(t);if(!n){e.slots.push(t),e.dense=null;return}let r=e.indexByKey.get(n.key);if(r===void 0){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let i=e.slots[r];if(!i){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}let a=Ms(i,t);if(!a){e.slots.push(t),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null;return}e.slots[r]=null,e.slots.push(a),e.indexByKey.set(n.key,e.slots.length-1),e.dense=null}function fC(e,t){let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n}function pC(e){if(e.type===`item.completed`)return!0;if(e.type!==`native.raw`)return!1;let t=iC(e.payload.raw)?e.payload.raw:{},n=iC(t.message)?t.message:{};return(typeof n.method==`string`?n.method:typeof t.method==`string`?t.method:``)===`item/completed`}function mC(e){return pC(e)}function hC(e,t){let n=new Map;for(let t of e)n.set(t.eventId,t);for(let e of t)n.set(e.eventId,e);return As([...n.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.eventId.localeCompare(t.eventId):n})).map((e,t)=>({...e,rawSeq:t+1}))}var gC=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${mg(10)}`;return this.clients.set(n,{id:n,deviceId:e,socket:t,subscriptionsBySessionId:new Map}),n}removeClient(e){let t=this.clients.get(e);t&&(this.removeClientFromSessionIndexes(e,t.subscriptionsBySessionId.keys()),this.removeClientDeliveryState(e),this.clients.delete(e))}replaceSubscriptions(e,t,n=!0){let r=this.clients.get(e);if(!r)return[];n&&(this.removeClientFromSessionIndexes(e,r.subscriptionsBySessionId.keys()),this.removeClientSessionDeliveryState(e,r.subscriptionsBySessionId.keys()),r.subscriptionsBySessionId.clear());let i=new Map;for(let e of t)i.set(e.sessionId,e);for(let[t,n]of i){r.subscriptionsBySessionId.set(t,n);let i=this.clientIdsBySessionId.get(t)??new Set;i.add(e),this.clientIdsBySessionId.set(t,i),this.ensureClientSessionDeliveryState(e,t)}return[...r.subscriptionsBySessionId.values()]}getSubscriptions(e){let t=this.clients.get(e);return t?[...t.subscriptionsBySessionId.values()]:[]}routeProviderRaw(e){let t=this.clientIdsBySessionId.get(e.sessionId);if(!t||t.size===0)return;let n=null;for(let r of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(r,e.sessionId));if(t?.paused){t.queued.push(e);continue}let i=this.clients.get(r);if(!(!i||i.socket.readyState!==i.socket.OPEN)){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}n??=JSON.stringify(e),i.socket.send(n)}}}pauseSession(e,t){let n=this.ensureClientSessionDeliveryState(e,t);n.paused=!0}resumeSession(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(!r||(r.paused=!1,r.queued.length===0))return;let i=this.clients.get(e);if(!i||i.socket.readyState!==i.socket.OPEN){r.queued=[];return}let a=[...r.queued].sort((e,t)=>e.rawSeq-t.rawSeq);r.queued=[];for(let e of a){if(i.socket.sendProviderRaw){i.socket.sendProviderRaw(e);continue}i.socket.send(JSON.stringify(e))}}sendStreamMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}sendSystemMessage(e,t){let n=this.clients.get(e);!n||n.socket.readyState!==n.socket.OPEN||n.socket.send(JSON.stringify(t))}broadcastSystemMessage(e){let t=JSON.stringify(e);for(let e of this.clients.values())e.socket.readyState===e.socket.OPEN&&e.socket.send(t)}count(){return this.clients.size}removeClientFromSessionIndexes(e,t){for(let n of t){let t=this.clientIdsBySessionId.get(n);t&&(t.delete(e),t.size===0&&this.clientIdsBySessionId.delete(n))}}clientSessionKey(e,t){return`${e}::${t}`}ensureClientSessionDeliveryState(e,t){let n=this.clientSessionKey(e,t),r=this.deliveryStateByClientSession.get(n);if(r)return r;let i={paused:!1,queued:[]};return this.deliveryStateByClientSession.set(n,i),i}removeClientSessionDeliveryState(e,t){for(let n of t)this.deliveryStateByClientSession.delete(this.clientSessionKey(e,n))}removeClientDeliveryState(e){let t=`${e}::`;for(let e of this.deliveryStateByClientSession.keys())e.startsWith(t)&&this.deliveryStateByClientSession.delete(e)}};async function _C(e,t={}){await nu(e.gatewayLogPath);let n=yC(e,t),r=vC(e,n.instance);await r.register(lg.default,{origin:!0}),await r.register(cg.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new c_(e);await s.init();let c=new m_(e.auditLogPath),l=new gC,u=new $_,d=new cv(e.projectStoreDir),f=new rC(e.sessionHistoryDir);await f.init();let m=new bx(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new sx({store:m});await h.init();let g,_=null,v=await qs(e.authStoreDir),y=new OS({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,logger:r.log,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}});y.warmStartupProviderCapabilities().catch(e=>{r.log.warn({err:e},`startup provider capability warmup failed`)});let b=new xl({packageName:P.packageName,currentVersion:P.version,sessionHub:l,logger:r.log,consoleWrite:e=>{console.log(e)},getRunningSessionCount:async()=>(await y.listProjects()).reduce((e,t)=>e+(t.runningCount??0),0),requestPreparedUpdate:t.onUpdatePrepared});r.addHook(`onClose`,async()=>{r.log.info({hasRelayClient:!!_},`gateway shutdown starting`);try{_?.close(),x.close(),await b.shutdown(),await y.shutdown(),await f.shutdown(),r.log.info(`gateway shutdown completed`)}catch(e){throw r.log.error({err:e},`gateway shutdown failed`),e}finally{n.close()}}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:N(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:il(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>$c({gatewayId:e.gatewayId,machineName:il(),relayBaseUrl:e.relayEnabled?fl({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:ul({protocol:e.httpsEnabled?`https`:`http`,host:e.host,port:e.httpsEnabled?e.httpsPort:e.port}),gatewayIdentity:v.identity})),r.post(`/api/pairing/start`,async(t,n)=>{if(!ee(t))return n.code(401).send({error:`Unauthorized`});try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);return await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`api`,ttlSeconds:e.pairingCodeTtlSeconds}}),t}catch(e){return r.log.error({err:e},`failed to generate pairing code via API`),n.code(500).send({error:`Failed to generate pairing code`,detail:String(e)})}}),r.post(`/api/pairing/claim`,async(e,t)=>{let n=xa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=fe(n.data.deviceName),t=await s.claimPairingCode(n.data.code,e,n.data.deviceIdentity);return await c.record({ts:new Date().toISOString(),action:`pairing.claim`,deviceId:t.deviceId,detail:{deviceName:e}}),kC(v,t,n.data.code,n.data.deviceIdentity)}catch(e){return t.code(400).send({error:String(e)})}}),r.post(`/api/auth/refresh`,async(e,t)=>{let n=wa.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await SC({authService:s,execute:()=>s.refreshAccessToken(n.data.refreshToken),logger:r.log,refreshToken:n.data.refreshToken,source:`direct_http`})}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(I(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(I(e,t))try{return await b.getOrCheckInfo(`mobile`)}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/gateway/update/apply`,async(e,t)=>{if(!I(e,t))return;let n=e.body,r=ja.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return Ia.parse(e)}catch(e){let n=String(e),r=n.includes(`already up to date`)||n.includes(`does not support self-update`)||n.includes(`requires idle runtime`)?409:500;return t.code(r).send({error:n})}}),r.post(`/api/codex/app-server/restart`,async(e,t)=>{if(I(e,t))try{return Da.parse(await y.restartCodexAppServer())}catch(e){let n=Kg(e)?e.status:500;return t.code(n).send({error:String(e)})}}),r.get(`/api/discovery/projects`,async(e,t)=>{if(I(e,t))try{return await h.getProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.post(`/api/discovery/projects/refresh`,async(e,t)=>{if(I(e,t))try{return await h.refreshProjects()}catch(e){return t.code(500).send({error:String(e)})}}),r.get(`/api/discovery/projects/sessions`,async(e,t)=>{if(!I(e,t))return;let n=e.query;if(typeof n.projectPath!=`string`||!n.projectPath.trim())return t.code(400).send({error:`projectPath is required and must be a non-empty string`});try{return await h.listProjectSessions(n.projectPath)}catch(e){let n=e instanceof Error?e.message:String(e);return Kg(e)&&e.code===`DISCOVERED_PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):NC(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!I(e,t))return;let n=e.query,r=Number(n.limit??200),i=Number.isFinite(r)?Math.min(500,Math.max(1,r)):200;try{return await u.listDirectoriesUnrestricted(typeof n.path==`string`?n.path:void 0,i)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/providers/:provider/capabilities`,async(e,t)=>{if(!I(e,t))return;let n=L(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return Kg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!I(e,t))return;let n=L(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return Kg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!I(e,t))return;let n=e.body;if(typeof n.path!=`string`||!n.path.trim())return t.code(400).send({error:`path is required and must be a non-empty string`});try{return{project:await y.createProject({path:n.path,title:typeof n.title==`string`?n.title:void 0})}}catch(e){return t.code(400).send({error:String(e)})}}),r.delete(`/api/projects/:projectId`,async(e,t)=>{if(!I(e,t))return;let n=e.params;try{return await y.deleteProject(n.projectId)?{removed:!0}:t.code(404).send({error:`Project not found`})}catch(e){return t.code(409).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=e.query,i=ae(r.status,t);if(!i)return;let a=oe(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return Kg(e)&&e.code===`PROJECT_NOT_FOUND`?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=await y.getProjectSessionSummary(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.get(`/api/projects/:projectId/sessions/:sessionId/config`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=await y.getProjectSessionConfig(n.projectId,n.sessionId);return r?{session:r}:t.code(404).send({error:`Session not found`})}),r.post(`/api/projects/:projectId/sessions/:sessionId/history-sync`,async(e,t)=>{if(!I(e,t))return;let n=e.params;try{let e=await y.syncProjectSessionHistory(n.projectId,n.sessionId);return{session:e.session,rawEventCount:e.rawEvents.length}}catch(e){return Kg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Session events endpoint is deprecated. Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/projects/:projectId/sessions/:sessionId/raw-events`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=e.query,i=(typeof r.limit==`string`?r.limit.trim().toLowerCase():``)===`all`?2**53-1:(()=>{let e=Number(r.limit??300);return Number.isFinite(e)?Math.min(2e3,Math.max(1,e)):300})();try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i)}}catch(e){return Kg(e)&&(e.code===`PROJECT_NOT_FOUND`||e.code===`PROJECT_SESSION_NOT_FOUND`)?t.code(e.status).send({error:String(e)}):t.code(500).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!I(e,t))return;let n=e.params,r=e.query,i=await y.getProject(n.projectId);if(!i)return t.code(404).send({error:`Project not found`});try{return await u.listTree(i.path,r.path??`.`)}catch(e){return t.code(400).send({error:String(e)})}}),r.get(`/api/sessions`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions`})),r.get(`/api/sessions/:sessionId`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId`})),r.get(`/api/sessions/:sessionId/events`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/sessions/:sessionId/raw-events`})),r.get(`/api/fs/tree`,async(e,t)=>t.code(410).send({error:`Use /api/projects/:projectId/fs/tree`})),r.get(`/api/devices`,async(e,t)=>ee(e)?{devices:s.listDevices()}:t.code(401).send({error:`Unauthorized`})),r.post(`/api/devices/:deviceId/revoke`,async(e,t)=>{if(!ee(e))return t.code(401).send({error:`Unauthorized`});let n=e.params;return await s.revokeDevice(n.deviceId)?(await c.record({ts:new Date().toISOString(),action:`device.revoke`,deviceId:n.deviceId}),{revoked:!0}):t.code(404).send({error:`Device not found`})}),r.get(`/ws`,{websocket:!0},(e,t)=>{let n=se(t.headers.authorization)??ce(t.url);if(!n){e.close(1008,`Missing access token`);return}let r;try{r=s.verifyAccessToken(n)}catch(t){e.close(1008,`Unauthorized: ${String(t)}`);return}let i=l.addClient(r.sub,e);e.on(`message`,async e=>{let t=e.toString(),n;try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e),await C(la(e),r.sub,i)}catch(e){await w({deviceId:r.sub,clientId:i,rawCommand:t,parsedInput:n,error:e})}}),e.on(`close`,()=>{l.removeClient(i)})});let x=new Nx({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=fe(e.deviceName);return kC(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await SC({authService:s,execute:()=>s.refreshAccessToken(t.refreshToken),logger:r.log,refreshToken:t.refreshToken,requestedDeviceId:t.deviceId,source:`relay_http_forward`});return xC(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>DC(e,{authService:s,logger:r.log,sessionManager:y,projectDiscoveryService:h,fsService:u,updateService:b,relayDeviceId:t.deviceId}),sendFrame:e=>_?.send(e)??!1,dispatchCommand:async(e,t,n)=>{try{await C(e,t,n)}catch(r){await w({deviceId:t,clientId:n,rawCommand:JSON.stringify(e),parsedInput:e,error:r})}}}),S=async(e,t,n)=>{switch(e.type){case`session.start`:{let r=await y.startSession({...e.payload,deviceId:t});l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:r});return}case`turn.input`:await y.sendInput(e.payload.sessionId,e.payload.text,t,{model:e.payload.model,sessionConfig:e.payload.sessionConfig,mode:e.payload.mode,config:e.payload.config});return;case`review.start`:throw Error(`review.start is not implemented yet.`);case`tool.approval.respond`:await y.respondToolPermission(e.payload.sessionId,e.payload.requestId,e.payload.decision,e.payload.reason,t);return;case`user.input.respond`:await y.respondUserInput(e.payload.sessionId,e.payload.requestId,e.payload.answers,t);return;case`session.interrupt`:await y.interruptSession(e.payload.sessionId,t);return;case`session.close`:throw Error(`session.close is deprecated. Use session.interrupt instead.`);case`session.stream.subscribe`:{let t=e.payload.sessions.map(e=>({sessionId:e.sessionId,projectId:e.projectId,cursor:e.cursor.kind===`raw_seq`?{kind:`raw_seq`,rawSeq:e.cursor.rawSeq}:{kind:`all`}}));await T(n,t,e.payload.replace),l.sendSystemMessage(n,{type:`command.ack`,commandType:e.type,commandId:e.commandId,payload:{replace:e.payload.replace,sessions:t.map(e=>e.sessionId)}});return}case`fs.read`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.readFile(t.projectPath,e.payload.path);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.changed`,raw:{path:n.path,content:n.content}});return}case`fs.diff`:{let t=y.getSessionExecutionContext(e.payload.sessionId),n=await u.diffFile(t.projectPath,e.payload.path,e.payload.baseContent??``);await y.emitExternalEvent({provider:t.provider,sessionId:e.payload.sessionId,projectId:t.projectId,type:`file.diff.ready`,raw:{path:n.path,diff:n.diff,currentContent:n.currentContent}});return}default:{let t=e;throw Error(`Unhandled command: ${JSON.stringify(t)}`)}}},C=async(e,t,n)=>{await S(e,t,n)},w=async e=>{r.log.warn({deviceId:e.deviceId,rawCommand:e.rawCommand,err:e.error},`ws command failed`);let t=typeof e.parsedInput?.commandId==`string`?e.parsedInput.commandId:void 0,n=typeof e.parsedInput?.type==`string`?e.parsedInput.type:void 0;l.sendSystemMessage(e.clientId,{type:`command.error`,commandId:t,commandType:n,message:String(e.error)}),await y.emitExternalEvent({provider:`codex`,sessionId:`system`,type:`error.runtime`,raw:{message:String(e.error),source:`ws.command`}})},T=async(e,t,n)=>{let r=E(t),i=new Set(r.map(e=>e.sessionId));for(let t of i)l.pauseSession(e,t);l.replaceSubscriptions(e,r,n);try{for(let t of r)await D(e,t)}finally{for(let t of i)l.resumeSession(e,t)}},E=e=>{let t=new Map;for(let n of e)t.set(n.sessionId,n);return[...t.values()]},D=async(e,t)=>{let n=await O(t);if(t.cursor.kind===`all`){await k(e,n,`cursor_all`);return}let r=await y.getProjectSessionRawSeqRange(n.projectId,n.sessionId);if(!r){await k(e,n,`empty_history_snapshot`);return}let i=t.cursor.rawSeq;if(i<Math.max(0,r.min-1)||i>r.max){await k(e,n,`cursor_out_of_range_snapshot`);return}let a=await y.getProjectSessionRawEventsSinceSeq(n.projectId,n.sessionId,i,2**53-1),o=a[a.length-1]?.rawSeq??i;l.sendStreamMessage(e,j({provider:n.provider,sessionId:n.sessionId,projectId:n.projectId,decision:`delta`,reason:n.status===`running`?`cursor_resumed_delta`:`session_idle_delta`,fromRawSeq:i,toRawSeq:o}));for(let t of a)l.sendStreamMessage(e,t)},O=async e=>{let t=e.sessionId;if(!t)throw Error(`session.stream.subscribe requires sessionId`);let n=e.projectId?.trim()??``;if(n){let e=await y.getProjectSessionSummary(n,t);if(!e)throw $g(n,t);return{sessionId:t,projectId:n,provider:e.provider,status:e.status}}let r=y.getSessionExecutionContext(t),i=await y.getProjectSessionSummary(r.projectId,t);return{sessionId:t,projectId:r.projectId,provider:i?.provider??r.provider,status:i?.status??`idle`}},k=async(e,t,n)=>{let r=`snap_${mg(12)}`,i=await y.getProjectSessionRawEventsCompacted(t.projectId,t.sessionId,2**53-1),a=i[i.length-1]?.rawSeq;l.sendStreamMessage(e,j({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,decision:`snapshot`,reason:n,snapshotId:r,...a===void 0?{}:{toRawSeq:a}}));let o=A(i,100),s=o.length;for(let n=0;n<o.length;n+=1){let i=o[n]??[];l.sendStreamMessage(e,M({provider:t.provider,sessionId:t.sessionId,projectId:t.projectId,snapshotId:r,chunkIndex:n,totalChunks:s,events:i}))}},A=(e,t)=>{if(e.length===0)return[[]];let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r},j=e=>({v:`1.0`,kind:`session.stream.sync`,type:`session.stream.sync`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_sync_${mg(12)}`,ts:new Date().toISOString(),payload:{raw:{decision:e.decision,reason:e.reason,snapshotId:e.snapshotId,fromRawSeq:e.fromRawSeq,toRawSeq:e.toRawSeq}}}),M=e=>({v:`1.0`,kind:`session.stream.snapshot.chunk`,type:`session.stream.snapshot.chunk`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`stream_snapshot_${e.snapshotId}_${e.chunkIndex}`,ts:new Date().toISOString(),payload:{raw:{snapshotId:e.snapshotId,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,events:e.events}}}),ee=t=>t.headers[`x-api-key`]===e.apiKey,N=e=>{if(e==null)return e;if(typeof e==`string`){let t=te(e);return t===void 0?ne(e,a):F(re(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=te(t);return n===void 0?ne(t,a):F(re(n))}return typeof e==`object`?F(re(e)):String(e)},te=e=>{try{return JSON.parse(e)}catch{return}},ne=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,re=e=>{if(Array.isArray(e))return e.map(e=>re(e));if(e&&typeof e==`object`){let t=e,n={};for(let[e,r]of Object.entries(t)){let t=e.toLowerCase();t.includes(`token`)||t.includes(`secret`)||t.includes(`password`)||t.includes(`authorization`)?n[e]=`[REDACTED]`:n[e]=re(r)}return n}return e},F=e=>{let t=ie(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:ne(t,a)}},ie=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},I=(e,t)=>{let n=se(e.headers.authorization);if(!n)return t.code(401).send({error:`Missing bearer token`}),null;try{return s.verifyAccessToken(n)}catch(e){return t.code(401).send({error:String(e)}),null}},ae=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},oe=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},L=(e,t)=>{let n=e.params,r=e.query,i=ji.safeParse(n.provider);return i.success?{provider:i.data,projectId:typeof r.projectId==`string`?r.projectId:void 0,agentVersion:typeof r.agentVersion==`string`?r.agentVersion:void 0}:(t.code(400).send({error:`Invalid provider`}),null)},se=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},ce=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},le=e.httpsEnabled?e.httpsPort:e.port,ue=e.httpsEnabled?`https`:`http`,de=il(),fe=e=>e?.trim()||de||`Gateway`;await r.listen({host:e.host,port:le});let pe=r.server.address(),me=typeof pe==`object`&&pe?pe.port:le;if(r.log.info({host:e.host,port:me,protocol:ue,machineName:de},bC(ue,e.host,me)),e.relayEnabled&&(_=new Hx({gatewayId:e.gatewayId,machineName:de,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>qx({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:ul({protocol:ue,host:e.host,port:me}),logger:r.log,onFrame:async e=>{await x.handleFrame(e)}}),_.start()),e.bootstrapPairingCodeOnStart)try{let t=await s.createPairingCode(e.pairingCodeTtlSeconds);g={code:t.code,expiresAt:t.expiresAt},await c.record({ts:new Date().toISOString(),action:`pairing.start`,detail:{expiresAt:t.expiresAt,source:`startup`,ttlSeconds:e.pairingCodeTtlSeconds}}),r.log.info({expiresAt:t.expiresAt},`startup pairing code generated`)}catch(e){r.log.error({err:e},`failed to generate startup pairing code`)}return await b.start(),{protocol:ue,listenPort:me,machineName:de,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),requestCodexAppServerRestart:async(e=`console`)=>y.restartCodexAppServer(),startupPairingCode:g}}function vC(e,t){let n=t;if(!e.httpsEnabled)return(0,ug.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,ug.default)({disableRequestLogging:!0,loggerInstance:n,https:{key:(0,u.readFileSync)(e.tlsKeyPath),cert:(0,u.readFileSync)(e.tlsCertPath),...e.tlsCaPath?{ca:(0,u.readFileSync)(e.tlsCaPath)}:{}}})}function yC(e,t){let n=process.env.NODE_ENV!==`production`,r=Wg.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?Wg.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,Wg.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function bC(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function xC(e,t){if(e&&e!==t)throw Zg()}async function SC(e){let t=CC(e.authService,e.refreshToken);e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:wC(t)},`auth refresh attempt`);try{let t=await e.execute(),n=CC(e.authService,e.refreshToken),r=CC(e.authService,t.refreshToken);return e.logger?.info?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshedDeviceId:t.deviceId,previousRefreshToken:wC(n),nextRefreshToken:wC(r)},`auth refresh succeeded`),t}catch(t){let n=CC(e.authService,e.refreshToken);throw e.logger?.warn?.({source:e.source,requestedDeviceId:e.requestedDeviceId??null,refreshToken:wC(n),error:TC(t)},`auth refresh failed`),t}}function CC(e,t){return e.inspectRefreshToken?.(t)??{tokenRecordState:`missing`}}function wC(e){return{claimDeviceId:e.claimDeviceId??null,claimExpAt:e.claimExpAt??null,claimIssuedAt:e.claimIssuedAt??null,claimJtiSuffix:EC(e.claimJti),claimType:e.claimType??null,latestActiveTokenCreatedAt:e.latestActiveTokenCreatedAt??null,latestActiveTokenJtiSuffix:EC(e.latestActiveTokenJti),tokenRecordCreatedAt:e.tokenRecordCreatedAt??null,tokenRecordDeviceId:e.tokenRecordDeviceId??null,tokenRecordRevokedAt:e.tokenRecordRevokedAt??null,tokenRecordState:e.tokenRecordState}}function TC(e){return Kg(e)?{code:e.code,message:String(e),status:e.status}:e instanceof Error?{message:e.message,name:e.name}:{message:String(e)}}function EC(e){return e?e.slice(-8):null}async function DC(e,t){try{let n=Oo.parse(e);switch(n.method){case`auth.refresh`:{let e=await SC({authService:t.authService,execute:()=>t.authService.refreshAccessToken(n.params.refreshToken),logger:t.logger,refreshToken:n.params.refreshToken,requestedDeviceId:n.params.deviceId??t.relayDeviceId,source:`relay_rpc`});return xC(n.params.deviceId??t.relayDeviceId,e.deviceId),ko.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return ko.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return ko.parse({method:n.method,result:e})}case`codex.appServer.restart`:{let e=await t.sessionManager.restartCodexAppServer();return ko.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return ko.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return ko.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return ko.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return ko.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw jC(n.method,`NOT_FOUND`,404,`Project not found`);return ko.parse({method:n.method,result:{removed:!0}});case`workspace.directories.list`:{let e=await t.fsService.listDirectoriesUnrestricted(n.params.path,n.params.limit??200);return ko.parse({method:n.method,result:e})}case`sessions.list`:{let e=await t.sessionManager.listProjectSessions(n.params.projectId,n.params.status??`all`,{syncExternal:n.params.syncExternal});return ko.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return ko.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw jC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.parse({method:n.method,result:{session:e}})}case`sessions.config.get`:{let e=await t.sessionManager.getProjectSessionConfig(n.params.projectId,n.params.sessionId);if(!e)throw jC(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return ko.parse({method:n.method,result:{session:e}})}case`sessions.history.sync`:{let e=await t.sessionManager.syncProjectSessionHistory(n.params.projectId,n.params.sessionId);return ko.parse({method:n.method,result:{session:e.session,rawEventCount:e.rawEvents.length}})}case`sessions.rawEvents.list`:{let e=await t.sessionManager.getProjectSessionRawEvents(n.params.projectId,n.params.sessionId,n.params.limit===`all`?2**53-1:n.params.limit);return ko.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=Date.now();t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null},`relay rpc provider capabilities request started`);try{let r=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0),i=r&&typeof r==`object`&&!Array.isArray(r)?r:null;return t.logger?.info?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,source:typeof i?.source==`string`?i.source:void 0,modelCount:Array.isArray(i?.models)?i.models.length:void 0},`relay rpc provider capabilities request completed`),ko.parse({method:n.method,result:{capabilities:r}})}catch(r){throw t.logger?.warn?.({relayDeviceId:t.relayDeviceId??null,rpcMethod:n.method,provider:n.params.provider,projectId:n.params.projectId??null,agentVersion:n.params.agentVersion??null,durationMs:Date.now()-e,err:r},`relay rpc provider capabilities request failed`),r}}case`agents.config.get`:{let e=await t.sessionManager.getAgentConfig(n.params.provider,{projectId:n.params.projectId??void 0,agentVersion:n.params.agentVersion??void 0});return ko.parse({method:n.method,result:e})}case`devices.list`:return ko.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw jC(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return ko.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw jC(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw OC(e)}}function OC(e){if(Kg(e))switch(e.code){case`REFRESH_TOKEN_REVOKED`:case`DEVICE_REVOKED`:case`REFRESH_TOKEN_DEVICE_MISMATCH`:return jC(`UNAUTHORIZED`,e.status,String(e),e.details);case`PROJECT_NOT_FOUND`:case`DISCOVERED_PROJECT_NOT_FOUND`:case`PROJECT_SESSION_NOT_FOUND`:case`SESSION_NOT_FOUND`:return jC(`NOT_FOUND`,e.status,String(e),e.details);case`PROJECT_DELETE_CONFLICT`:case`CODEX_APP_SERVER_RESTART_CONFLICT`:return jC(`BAD_REQUEST`,e.status,String(e),e.details);default:return jC(e.status>=500?`INTERNAL`:`BAD_REQUEST`,e.status,String(e),e.details)}let t=jo.safeParse(e);if(t.success)return t.data;let n=Ao.safeParse(e);if(n.success)return jC(void 0,n.data.code,n.data.status,n.data.message,n.data.details);if(e&&typeof e==`object`&&`code`in e&&`status`in e&&`message`in e&&typeof e.code==`string`&&typeof e.status==`number`&&typeof e.message==`string`){let t=e;return jC(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?jC(`BAD_REQUEST`,400,r):MC(e)?jC(`UNAUTHORIZED`,401,r):NC(r)?jC(`BAD_REQUEST`,400,r):jC(`INTERNAL`,500,r)}function kC(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:AC(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:Xs(e.identity,e.privateKeyPem,i)}}function AC(e){return e.replace(/\s+/gu,``).toUpperCase()}function jC(e,t,n,r,i){let a=typeof t==`string`,o=a?e:void 0,s=a?t:e,c=a?n:t,l=a?r:n,u=a?i:r;return jo.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function MC(e){return Kg(e)&&(e.code===`REFRESH_TOKEN_REVOKED`||e.code===`DEVICE_REVOKED`||e.code===`REFRESH_TOKEN_DEVICE_MISMATCH`)||s_(e)}function NC(e){let t=e.trim();return t===`Invalid provider`||t.startsWith(`Invalid provider:`)||t.startsWith(`Project path must be absolute:`)||t.startsWith(`Project path does not exist:`)||t.startsWith(`Project path is not a directory:`)||t.startsWith(`ZodError:`)}function PC(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:(0,y.inspect)(e,{depth:6,breakLength:120})}async function FC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await _C(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{LC({type:`worker.update.prepared`,payload:e})}});LC({type:`worker.ready`,payload:IC(n)});let r=null,i=e=>r||(r=Promise.resolve(n.close?.()).catch(e=>{console.error(`[gateway] worker shutdown failed: ${String(e)}`)}).finally(()=>{process.exit(e)}),r);process.on(`message`,e=>{let t=RC(e);if(t)switch(t.type){case`supervisor.request`:a(t);return;case`supervisor.shutdown`:i(0);return}}),process.on(`disconnect`,()=>{i(0)}),process.on(`SIGINT`,()=>{i(0)}),process.on(`SIGTERM`,()=>{i(0)}),process.on(`uncaughtException`,e=>{console.error(`[gateway] worker uncaught exception: ${PC(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${PC(e)}`),i(1)});async function a(e){try{switch(e.method){case`gateway.update.apply`:{if(!n.requestGatewayUpdate)throw Error(`gateway update is unavailable`);let t=await n.requestGatewayUpdate(e.requestedBy);LC({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}case`codex.appServer.restart`:{if(!n.requestCodexAppServerRestart)throw Error(`codex app-server restart is unavailable`);let t=await n.requestCodexAppServerRestart(e.requestedBy);LC({type:`worker.response`,id:e.id,method:e.method,ok:!0,result:t});return}}}catch(t){LC({type:`worker.response`,id:e.id,method:e.method,ok:!1,error:String(t)})}}await new Promise(()=>{})}function IC(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function LC(e){process.send&&process.send(e)}function RC(e){if(!zC(e)||typeof e.type!=`string`)return null;switch(e.type){case`supervisor.shutdown`:return e.reason!==`signal`&&e.reason!==`update`?null:{type:`supervisor.shutdown`,reason:e.reason};case`supervisor.request`:return typeof e.id!=`string`||e.method!==`gateway.update.apply`&&e.method!==`codex.appServer.restart`||e.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:e.method,requestedBy:e.requestedBy};default:return null}}function zC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}BC(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function BC(e){let t=ne(e);switch(t.command){case`help`:GC();return;case`version`:console.log(P.version);return;case`init`:await HC(t);return;case`doctor`:await UC(t);return;case`start`:await VC(t);return;case`__worker`:await WC(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function VC(e){let t=await ac({configPath:e.configPath,ensureConfigFile:!0});lc(t.config);let n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await Jl({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(ru(e,t.config))}Oc(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function HC(e){let t=await ic({configPath:e.configPath,overwrite:e.force});t.created?console.log(`[gateway] wrote config to ${t.configPath}`):(console.log(`[gateway] config already exists at ${t.configPath}`),console.log(`[gateway] rerun with --force to overwrite`));let n=await ac({configPath:t.configPath,ensureConfigFile:!1}),r=await Dc({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(kc(r))}async function UC(e){let t=await ac({configPath:rc(e.configPath),ensureConfigFile:!1,syncGatewayIdentityConfig:!1}),n=await Dc({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(kc(n)),Oc(n)&&(process.exitCode=1)}async function WC(e){try{await FC(e)}catch(t){let n=await ac({configPath:e.configPath,ensureConfigFile:!0});throw Error(ru(t,n.config))}}function GC(){console.log(`${P.cliName} ${P.version}`),console.log(``),console.log(`Usage:`),console.log(` ${P.cliName} [start] [--config <path>] [--log]`),console.log(` ${P.cliName} init [--config <path>] [--force]`),console.log(` ${P.cliName} doctor [--config <path>]`),console.log(` ${P.cliName} --version`)}exports.runCli=BC;