craby-gateway 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-sea/gateway.cjs +37 -37
- package/package.json +1 -1
package/dist-sea/gateway.cjs
CHANGED
|
@@ -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(`fs`);y=c(y);let b=require(`path`);b=c(b);let x=require(`module`),S=require(`child_process`),C=require(`@anthropic-ai/claude-agent-sdk`);var w={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.4.2`,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:`tsx watch src/index.ts`,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.71`,"@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`,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 T=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function E(e){let t=e.match(T);return t?t[0]:null}function D(e){return typeof e==`string`?E(e):null}function O(e,t){let n=A(e),r=A(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 k(e,t){return O(e,t)>=0}function A(e){let t=e.match(T);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const j=w,M=j.dependencies??{};function ee(e){return M[e]??``}const N={packageName:`craby-gateway`,cliName:`craby-gateway`,version:j.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:ee(`@anthropic-ai/claude-agent-sdk`),minimumVersion:D(ee(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function te(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=P(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 P(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})),ne=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=ne();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(`fs`);y=c(y);let b=require(`path`);b=c(b);let x=require(`module`),S=require(`child_process`),C=require(`@anthropic-ai/claude-agent-sdk`);var w={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.4.3`,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:`tsx watch src/index.ts`,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.71`,"@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`,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 T=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function E(e){let t=e.match(T);return t?t[0]:null}function D(e){return typeof e==`string`?E(e):null}function O(e,t){let n=A(e),r=A(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 k(e,t){return O(e,t)>=0}function A(e){let t=e.match(T);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const j=w,M=j.dependencies??{};function ee(e){return M[e]??``}const N={packageName:`craby-gateway`,cliName:`craby-gateway`,version:j.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:ee(`@anthropic-ai/claude-agent-sdk`),minimumVersion:D(ee(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function te(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=P(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 P(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})),ne=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=ne();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})),re=o((e=>{var t=F(),n=ne();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})),L=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})),ie=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})),ae=o((e=>{var t=L(),n=F(),r=ie();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}}})),R=o((e=>{var t=re(),n=ne(),r=F(),i=ae(),a=ie(),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})),oe=o((e=>{var t=F(),n=ae(),r=ie();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})),se=o((e=>{var t=R(),n=F(),r=oe();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})),ce=o((e=>{var t=se(),n=F(),r=ae();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})),le=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
|
`)?`
|
|
@@ -117,20 +117,20 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
117
117
|
- `)}`)}async function wt(e,t){if(!t)return null;if(Pt(t))return t;let n={...t.gateway??{},gatewayId:Ft()},r={...t,gateway:n};return await St(e,r),r}function Tt(e){let t=p.default.dirname(e);return{homeDir:t,workspaceRoot:f.default.homedir(),auditLogPath:p.default.join(t,`logs`,`audit.log`),gatewayLogPath:p.default.join(t,`logs`,`gateway.log`),sessionHistoryDir:p.default.join(t,`logs`,`sessions-v2`),projectStoreDir:p.default.join(t,`logs`,`projects`),authStoreDir:p.default.join(t,`logs`,`auth`)}}function Et(e,t,n){return e?.trim()||t?.trim()||n}function Dt(e,t,n){let r=e?.trim().toLowerCase();return r===`true`||r===`1`?!0:r===`false`||r===`0`?!1:typeof t==`boolean`?t:n}function Ot(e,t,n){let r=Nt(e);return r===null?Number.isFinite(t)?Math.max(1,Math.trunc(t)):n:Math.max(1,r)}function kt(e,t,n){let r=Nt(e);return r===null?Number.isFinite(t)?Math.max(0,Math.trunc(t)):n:Math.max(0,r)}function At(e,t,n){return jt(e,t)??p.default.resolve(Mt(n))}function jt(e,t){let n=e?.trim()||t?.trim();return n?p.default.resolve(Mt(n)):null}function Mt(e){return e===`~`?f.default.homedir():e.startsWith(`~/`)||e.startsWith(`~\\`)?p.default.join(f.default.homedir(),e.slice(2)):e}function Nt(e){if(typeof e!=`string`||!e.trim())return null;let t=Number(e);return Number.isFinite(t)?Math.trunc(t):null}function Pt(e){return Et(void 0,e.gateway?.gatewayId??e.gateway?.relayGatewayId??e.gatewayId??e.relayGatewayId,``)}function Ft(){return`craby-gw-${(0,l.randomBytes)(6).toString(`hex`)}`}function It(e){return(0,l.randomBytes)(e).toString(`hex`)}async function Lt(e,t){try{await d.default.chmod(e,t)}catch{}}async function Rt(e){try{return await d.default.access(e,u.constants.F_OK),!0}catch{return!1}}const zt=(0,h.createRequire)(require(`url`).pathToFileURL(__filename).href),Bt=(0,g.fileURLToPath)(require(`url`).pathToFileURL(__filename).href);async function Vt(e,t=Wt){let n=N.providerRequirements.map(e=>Gt(e,t));return{gatewayVersion:N.version,configPath:e.configPath,configExists:e.configExists,configSummary:e.config?{httpsEnabled:e.config.httpsEnabled,port:e.config.httpsEnabled?e.config.httpsPort:e.config.port,enableNativeProviders:e.config.enableNativeProviders,workspaceRoot:e.config.workspaceRoot}:null,checks:n}}function Ht(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)}function Ut(e){let t=[`[gateway] version ${e.gatewayVersion}`,`[gateway] config ${e.configExists?`found`:`missing`}: ${e.configPath}`];e.configSummary&&(t.push(`[gateway] runtime https=${String(e.configSummary.httpsEnabled)} port=${e.configSummary.port} nativeProviders=${String(e.configSummary.enableNativeProviders)}`),t.push(`[gateway] workspaceRoot ${e.configSummary.workspaceRoot}`));for(let n of e.checks){let e=[`[doctor] ${n.id}`];n.minimumVersion&&e.push(`required>=${n.minimumVersion}`),n.dependencyName&&n.bundledStatus&&e.push(`bundled=${Jt(n.bundledDependencyVersion)}(${n.bundledStatus})`),e.push(`system=${Jt(n.systemToolVersion)}(${n.systemStatus})`),t.push(e.join(` `));for(let e of n.notes)t.push(`[doctor] ${n.id} note: ${e}`)}return t.join(`
|
|
118
118
|
`)}const Wt={readInstalledPackageVersion:Kt,readSystemToolVersion:qt};function Gt(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&&!k(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&&!k(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 Kt(e){try{let t=Yt(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 qt(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?E(r):null}catch{return null}}function Jt(e){return e??`missing`}function Yt(e){try{return zt.resolve(`${e}/package.json`)}catch{}try{let t=zt.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(Bt),process.cwd()]){let n=Xt(t,e);if(n)return n}return null}function Xt(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 Zt(e,t){let n=[e];return t.configPath&&n.push(`--config`,t.configPath),t.logToConsole&&n.push(`--log`),n}function Qt(e,t,n){let r=Zt(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 $t(e,t,n,r){if(!e.binPath)throw Error(`gateway launch command is unavailable`);return{command:e.binPath,args:Zt(t,n),cwd:r}}var en;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(en||={});var tn;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(tn||={});const V=en.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),nn=e=>{switch(typeof e){case`undefined`:return V.undefined;case`string`:return V.string;case`number`:return Number.isNaN(e)?V.nan:V.number;case`boolean`:return V.boolean;case`function`:return V.function;case`bigint`:return V.bigint;case`symbol`:return V.symbol;case`object`:return Array.isArray(e)?V.array:e===null?V.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?V.promise:typeof Map<`u`&&e instanceof Map?V.map:typeof Set<`u`&&e instanceof Set?V.set:typeof Date<`u`&&e instanceof Date?V.date:V.object;default:return V.unknown}},H=en.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var rn=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,en.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};rn.create=e=>new rn(e);const an=(e,t)=>{let n;switch(e.code){case H.invalid_type:n=e.received===V.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case H.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,en.jsonStringifyReplacer)}`;break;case H.unrecognized_keys:n=`Unrecognized key(s) in object: ${en.joinValues(e.keys,`, `)}`;break;case H.invalid_union:n=`Invalid input`;break;case H.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${en.joinValues(e.options)}`;break;case H.invalid_enum_value:n=`Invalid enum value. Expected ${en.joinValues(e.options)}, received '${e.received}'`;break;case H.invalid_arguments:n=`Invalid function arguments`;break;case H.invalid_return_type:n=`Invalid function return type`;break;case H.invalid_date:n=`Invalid date`;break;case H.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:en.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case H.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case H.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case H.custom:n=`Invalid input`;break;case H.invalid_intersection_types:n=`Intersection results could not be merged`;break;case H.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case H.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,en.assertNever(e)}return{message:n}};let on=an;function sn(){return on}const cn=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function U(e,t){let n=sn(),r=cn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===an?void 0:an].filter(e=>!!e)});e.common.issues.push(r)}var ln=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return W;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return W;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const W=Object.freeze({status:`aborted`}),un=e=>({status:`dirty`,value:e}),dn=e=>({status:`valid`,value:e}),fn=e=>e.status===`aborted`,pn=e=>e.status===`dirty`,mn=e=>e.status===`valid`,hn=e=>typeof Promise<`u`&&e instanceof Promise;var G;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(G||={});var gn=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const _n=(e,t)=>{if(mn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new rn(e.common.issues),this._error}}};function K(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var q=class{get description(){return this._def.description}_getType(e){return nn(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:nn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ln,ctx:{common:e.parent.common,data:e.data,parsedType:nn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(hn(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nn(e)};return _n(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nn(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return mn(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>mn(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nn(e)},r=this._parse({data:e,path:n.path,parent:n});return _n(n,await(hn(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:H.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new yr({schema:this,typeName:J.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return br.create(this,this._def)}nullable(){return xr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return er.create(this)}promise(){return vr.create(this,this._def)}or(e){return rr.create([this,e],this._def)}and(e){return sr.create(this,e,this._def)}transform(e){return new yr({...K(this._def),schema:this,typeName:J.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Sr({...K(this._def),innerType:this,defaultValue:t,typeName:J.ZodDefault})}brand(){return new Tr({typeName:J.ZodBranded,type:this,...K(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Cr({...K(this._def),innerType:this,catchValue:t,typeName:J.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Er.create(this,e)}readonly(){return Dr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const vn=/^c[^\s-]{8,}$/i,yn=/^[0-9a-z]+$/,bn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Sn=/^[a-z0-9_-]{21}$/i,Cn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Tn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let En;const Dn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,On=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,kn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,An=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Mn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nn=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Pn=RegExp(`^${Nn}$`);function Fn(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function In(e){return RegExp(`^${Fn(e)}$`)}function Ln(e){let t=`${Nn}T${Fn(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Rn(e,t){return!!((t===`v4`||!t)&&Dn.test(e)||(t===`v6`||!t)&&kn.test(e))}function zn(e,t){if(!Cn.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Bn(e,t){return!!((t===`v4`||!t)&&On.test(e)||(t===`v6`||!t)&&An.test(e))}var Vn=class e extends q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.string,received:t.parsedType}),W}let t=new ln,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),U(n,{code:H.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),U(n,{code:H.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?U(n,{code:H.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&U(n,{code:H.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Tn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`email`,code:H.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)En||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),En.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`emoji`,code:H.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)xn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`uuid`,code:H.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Sn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`nanoid`,code:H.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)vn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`cuid`,code:H.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)yn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`cuid2`,code:H.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)bn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`ulid`,code:H.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),U(n,{validation:`url`,code:H.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`regex`,code:H.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),U(n,{code:H.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),U(n,{code:H.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),U(n,{code:H.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ln(r).test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{code:H.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Pn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{code:H.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?In(r).test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{code:H.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?wn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`duration`,code:H.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Rn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`ip`,code:H.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?zn(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`jwt`,code:H.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Bn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`cidr`,code:H.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?jn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`base64`,code:H.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Mn.test(e.data)||(n=this._getOrReturnCtx(e,n),U(n,{validation:`base64url`,code:H.invalid_string,message:r.message}),t.dirty()):en.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:H.invalid_string,...G.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...G.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...G.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...G.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...G.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...G.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...G.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...G.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...G.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...G.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...G.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...G.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...G.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...G.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...G.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...G.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...G.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...G.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...G.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...G.errToObj(t)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Vn.create=e=>new Vn({checks:[],typeName:J.ZodString,coerce:e?.coerce??!1,...K(e)});function Hn(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Un=class e extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==V.number){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.number,received:t.parsedType}),W}let t,n=new ln;for(let r of this._def.checks)r.kind===`int`?en.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{code:H.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),U(t,{code:H.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),U(t,{code:H.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Hn(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),U(t,{code:H.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),U(t,{code:H.not_finite,message:r.message}),n.dirty()):en.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,G.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,G.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,G.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,G.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:G.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:G.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:G.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:G.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:G.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:G.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&en.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Un.create=e=>new Un({checks:[],typeName:J.ZodNumber,coerce:e?.coerce||!1,...K(e)});var Wn=class e extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==V.bigint)return this._getInvalidInput(e);let t,n=new ln;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),U(t,{code:H.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),U(t,{code:H.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),U(t,{code:H.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):en.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.bigint,received:t.parsedType}),W}gte(e,t){return this.setLimit(`min`,e,!0,G.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,G.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,G.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,G.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:G.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:G.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Wn.create=e=>new Wn({checks:[],typeName:J.ZodBigInt,coerce:e?.coerce??!1,...K(e)});var Gn=class extends q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.boolean,received:t.parsedType}),W}return dn(e.data)}};Gn.create=e=>new Gn({typeName:J.ZodBoolean,coerce:e?.coerce||!1,...K(e)});var Kn=class e extends q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.date,received:t.parsedType}),W}if(Number.isNaN(e.data.getTime()))return U(this._getOrReturnCtx(e),{code:H.invalid_date}),W;let t=new ln,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),U(n,{code:H.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),U(n,{code:H.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):en.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:G.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:G.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Kn.create=e=>new Kn({checks:[],coerce:e?.coerce||!1,typeName:J.ZodDate,...K(e)});var qn=class extends q{_parse(e){if(this._getType(e)!==V.symbol){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.symbol,received:t.parsedType}),W}return dn(e.data)}};qn.create=e=>new qn({typeName:J.ZodSymbol,...K(e)});var Jn=class extends q{_parse(e){if(this._getType(e)!==V.undefined){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.undefined,received:t.parsedType}),W}return dn(e.data)}};Jn.create=e=>new Jn({typeName:J.ZodUndefined,...K(e)});var Yn=class extends q{_parse(e){if(this._getType(e)!==V.null){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.null,received:t.parsedType}),W}return dn(e.data)}};Yn.create=e=>new Yn({typeName:J.ZodNull,...K(e)});var Xn=class extends q{constructor(){super(...arguments),this._any=!0}_parse(e){return dn(e.data)}};Xn.create=e=>new Xn({typeName:J.ZodAny,...K(e)});var Zn=class extends q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return dn(e.data)}};Zn.create=e=>new Zn({typeName:J.ZodUnknown,...K(e)});var Qn=class extends q{_parse(e){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.never,received:t.parsedType}),W}};Qn.create=e=>new Qn({typeName:J.ZodNever,...K(e)});var $n=class extends q{_parse(e){if(this._getType(e)!==V.undefined){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.void,received:t.parsedType}),W}return dn(e.data)}};$n.create=e=>new $n({typeName:J.ZodVoid,...K(e)});var er=class e extends q{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==V.array)return U(t,{code:H.invalid_type,expected:V.array,received:t.parsedType}),W;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(U(t,{code:e?H.too_big:H.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(U(t,{code:H.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(U(t,{code:H.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new gn(t,e,t.path,n)))).then(e=>ln.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new gn(t,e,t.path,n)));return ln.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:G.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:G.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:G.toString(n)}})}nonempty(e){return this.min(1,e)}};er.create=(e,t)=>new er({type:e,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...K(t)});function tr(e){if(e instanceof nr){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=br.create(tr(r))}return new nr({...e._def,shape:()=>t})}else if(e instanceof er)return new er({...e._def,type:tr(e.element)});else if(e instanceof br)return br.create(tr(e.unwrap()));else if(e instanceof xr)return xr.create(tr(e.unwrap()));else if(e instanceof cr)return cr.create(e.items.map(e=>tr(e)));else return e}var nr=class e extends q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:en.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==V.object){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.object,received:t.parsedType}),W}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Qn&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new gn(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Qn){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(U(n,{code:H.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new gn(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>ln.mergeObjectSync(t,e)):ln.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return G.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:G.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:J.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of en.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of en.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return tr(this)}partial(t){let n={};for(let e of en.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of en.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof br;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return hr(en.objectKeys(this.shape))}};nr.create=(e,t)=>new nr({shape:()=>e,unknownKeys:`strip`,catchall:Qn.create(),typeName:J.ZodObject,...K(t)}),nr.strictCreate=(e,t)=>new nr({shape:()=>e,unknownKeys:`strict`,catchall:Qn.create(),typeName:J.ZodObject,...K(t)}),nr.lazycreate=(e,t)=>new nr({shape:e,unknownKeys:`strip`,catchall:Qn.create(),typeName:J.ZodObject,...K(t)});var rr=class extends q{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new rn(e.ctx.common.issues));return U(t,{code:H.invalid_union,unionErrors:n}),W}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new rn(e));return U(t,{code:H.invalid_union,unionErrors:i}),W}}get options(){return this._def.options}};rr.create=(e,t)=>new rr({options:e,typeName:J.ZodUnion,...K(t)});const ir=e=>e instanceof pr?ir(e.schema):e instanceof yr?ir(e.innerType()):e instanceof mr?[e.value]:e instanceof gr?e.options:e instanceof _r?en.objectValues(e.enum):e instanceof Sr?ir(e._def.innerType):e instanceof Jn?[void 0]:e instanceof Yn?[null]:e instanceof br?[void 0,...ir(e.unwrap())]:e instanceof xr?[null,...ir(e.unwrap())]:e instanceof Tr||e instanceof Dr?ir(e.unwrap()):e instanceof Cr?ir(e._def.innerType):[];var ar=class e extends q{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==V.object)return U(t,{code:H.invalid_type,expected:V.object,received:t.parsedType}),W;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(U(t,{code:H.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=ir(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:J.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...K(r)})}};function or(e,t){let n=nn(e),r=nn(t);if(e===t)return{valid:!0,data:e};if(n===V.object&&r===V.object){let n=en.objectKeys(t),r=en.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=or(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===V.array&&r===V.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=or(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===V.date&&r===V.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var sr=class extends q{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(fn(e)||fn(r))return W;let i=or(e.value,r.value);return i.valid?((pn(e)||pn(r))&&t.dirty(),{status:t.value,value:i.data}):(U(n,{code:H.invalid_intersection_types}),W)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};sr.create=(e,t,n)=>new sr({left:e,right:t,typeName:J.ZodIntersection,...K(n)});var cr=class e extends q{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.array)return U(n,{code:H.invalid_type,expected:V.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return U(n,{code:H.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),W;!this._def.rest&&n.data.length>this._def.items.length&&(U(n,{code:H.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new gn(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>ln.mergeArray(t,e)):ln.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};cr.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new cr({items:e,typeName:J.ZodTuple,rest:null,...K(t)})};var lr=class e extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.object)return U(n,{code:H.invalid_type,expected:V.object,received:n.parsedType}),W;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new gn(n,e,n.path,e)),value:a._parse(new gn(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?ln.mergeObjectAsync(t,r):ln.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof q?new e({keyType:t,valueType:n,typeName:J.ZodRecord,...K(r)}):new e({keyType:Vn.create(),valueType:t,typeName:J.ZodRecord,...K(n)})}},ur=class extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.map)return U(n,{code:H.invalid_type,expected:V.map,received:n.parsedType}),W;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new gn(n,e,n.path,[a,`key`])),value:i._parse(new gn(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return W;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return W;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ur.create=(e,t,n)=>new ur({valueType:t,keyType:e,typeName:J.ZodMap,...K(n)});var dr=class e extends q{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.set)return U(n,{code:H.invalid_type,expected:V.set,received:n.parsedType}),W;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(U(n,{code:H.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(U(n,{code:H.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return W;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new gn(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:G.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:G.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};dr.create=(e,t)=>new dr({valueType:e,minSize:null,maxSize:null,typeName:J.ZodSet,...K(t)});var fr=class e extends q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==V.function)return U(t,{code:H.invalid_type,expected:V.function,received:t.parsedType}),W;function n(e,n){return cn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,sn(),an].filter(e=>!!e),issueData:{code:H.invalid_arguments,argumentsError:n}})}function r(e,n){return cn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,sn(),an].filter(e=>!!e),issueData:{code:H.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof vr){let e=this;return dn(async function(...t){let o=new rn([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return dn(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new rn([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new rn([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:cr.create(t).rest(Zn.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||cr.create([]).rest(Zn.create()),returns:n||Zn.create(),typeName:J.ZodFunction,...K(r)})}},pr=class extends q{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};pr.create=(e,t)=>new pr({getter:e,typeName:J.ZodLazy,...K(t)});var mr=class extends q{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return U(t,{received:t.data,code:H.invalid_literal,expected:this._def.value}),W}return{status:`valid`,value:e.data}}get value(){return this._def.value}};mr.create=(e,t)=>new mr({value:e,typeName:J.ZodLiteral,...K(t)});function hr(e,t){return new gr({values:e,typeName:J.ZodEnum,...K(t)})}var gr=class e extends q{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return U(t,{expected:en.joinValues(n),received:t.parsedType,code:H.invalid_type}),W}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return U(t,{received:t.data,code:H.invalid_enum_value,options:n}),W}return dn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};gr.create=hr;var _r=class extends q{_parse(e){let t=en.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==V.string&&n.parsedType!==V.number){let e=en.objectValues(t);return U(n,{expected:en.joinValues(e),received:n.parsedType,code:H.invalid_type}),W}if(this._cache||=new Set(en.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=en.objectValues(t);return U(n,{received:n.data,code:H.invalid_enum_value,options:e}),W}return dn(e.data)}get enum(){return this._def.values}};_r.create=(e,t)=>new _r({values:e,typeName:J.ZodNativeEnum,...K(t)});var vr=class extends q{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==V.promise&&t.common.async===!1?(U(t,{code:H.invalid_type,expected:V.promise,received:t.parsedType}),W):dn((t.parsedType===V.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};vr.create=(e,t)=>new vr({type:e,typeName:J.ZodPromise,...K(t)});var yr=class extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{U(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return W;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?W:r.status===`dirty`||t.value===`dirty`?un(r.value):r});{if(t.value===`aborted`)return W;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?W:r.status===`dirty`||t.value===`dirty`?un(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?W:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?W:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!mn(e))return W;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>mn(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):W);en.assertNever(r)}};yr.create=(e,t,n)=>new yr({schema:e,typeName:J.ZodEffects,effect:t,...K(n)}),yr.createWithPreprocess=(e,t,n)=>new yr({schema:t,effect:{type:`preprocess`,transform:e},typeName:J.ZodEffects,...K(n)});var br=class extends q{_parse(e){return this._getType(e)===V.undefined?dn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};br.create=(e,t)=>new br({innerType:e,typeName:J.ZodOptional,...K(t)});var xr=class extends q{_parse(e){return this._getType(e)===V.null?dn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xr.create=(e,t)=>new xr({innerType:e,typeName:J.ZodNullable,...K(t)});var Sr=class extends q{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Sr.create=(e,t)=>new Sr({innerType:e,typeName:J.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...K(t)});var Cr=class extends q{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return hn(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new rn(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new rn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Cr.create=(e,t)=>new Cr({innerType:e,typeName:J.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...K(t)});var wr=class extends q{_parse(e){if(this._getType(e)!==V.nan){let t=this._getOrReturnCtx(e);return U(t,{code:H.invalid_type,expected:V.nan,received:t.parsedType}),W}return{status:`valid`,value:e.data}}};wr.create=e=>new wr({typeName:J.ZodNaN,...K(e)});var Tr=class extends q{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Er=class e extends q{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?W:e.status===`dirty`?(t.dirty(),un(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?W:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:J.ZodPipeline})}},Dr=class extends q{_parse(e){let t=this._def.innerType._parse(e),n=e=>(mn(e)&&(e.value=Object.freeze(e.value)),e);return hn(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Dr.create=(e,t)=>new Dr({innerType:e,typeName:J.ZodReadonly,...K(t)}),nr.lazycreate;var J;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(J||={});const Y=Vn.create,Or=Un.create;wr.create,Wn.create;const kr=Gn.create;Kn.create,qn.create,Jn.create,Yn.create,Xn.create;const Ar=Zn.create;Qn.create,$n.create;const jr=er.create,X=nr.create;nr.strictCreate;const Mr=rr.create,Nr=ar.create;sr.create,cr.create;const Pr=lr.create;ur.create,dr.create,fr.create,pr.create;const Z=mr.create,Fr=gr.create;_r.create,vr.create,yr.create,br.create,xr.create;const Ir=yr.createWithPreprocess;Er.create;function Lr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function Rr(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got `+e)}function zr(e,...t){if(!Lr(e))throw Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function Br(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.createHasher`);Rr(e.outputLen),Rr(e.blockLen)}function Vr(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function Hr(e,t){zr(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least `+n)}function Ur(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Wr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Gr(e,t){return e<<32-t|e>>>t}new Uint8Array(new Uint32Array([287454020]).buffer)[0],typeof Uint8Array.from([]).toHex==`function`&&Uint8Array.fromHex;function Kr(e){if(typeof e!=`string`)throw Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function qr(e){return typeof e==`string`&&(e=Kr(e)),zr(e),e}var Jr=class{};function Yr(e){let t=t=>e().update(qr(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}var Xr=class extends Jr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Br(e);let n=qr(t);if(this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),Ur(i)}update(e){return Vr(this),this.iHash.update(e),this}digestInto(e){Vr(this),zr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Zr=(e,t,n)=>new Xr(e,t).update(n).digest();Zr.create=(e,t)=>new Xr(e,t);function Qr(e,t,n){return Br(e),n===void 0&&(n=new Uint8Array(e.outputLen)),Zr(e,qr(n),qr(t))}const $r=Uint8Array.from([0]),ei=Uint8Array.of();function ti(e,t,n,r=32){Br(e),Rr(r);let i=e.outputLen;if(r>255*i)throw Error(`Length should be <= 255*HashLen`);let a=Math.ceil(r/i);n===void 0&&(n=ei);let o=new Uint8Array(a*i),s=Zr.create(e,t),c=s._cloneInto(),l=new Uint8Array(s.outputLen);for(let e=0;e<a;e++)$r[0]=e+1,c.update(e===0?ei:l).update(n).update($r).digestInto(l),o.set(l,i*e),s._cloneInto(c);return s.destroy(),c.destroy(),Ur(l,$r),o.slice(0,r)}const ni=(e,t,n,r,i)=>ti(e,Qr(e,t,n),r,i);function ri(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}function ii(e,t,n){return e&t^~e&n}function ai(e,t,n){return e&t^e&n^t&n}var oi=class extends Jr{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Wr(this.buffer)}update(e){Vr(this),e=qr(e),zr(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=Wr(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Vr(this),Hr(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,Ur(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;ri(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=Wr(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const si=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ci=BigInt(2**32-1),li=BigInt(32);function ui(e,t=!1){return t?{h:Number(e&ci),l:Number(e>>li&ci)}:{h:Number(e>>li&ci)|0,l:Number(e&ci)|0}}function di(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=ui(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}const fi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pi=new Uint32Array(64);var mi=class extends oi{constructor(e=32){super(64,e,8,!1),this.A=si[0]|0,this.B=si[1]|0,this.C=si[2]|0,this.D=si[3]|0,this.E=si[4]|0,this.F=si[5]|0,this.G=si[6]|0,this.H=si[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)pi[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=pi[e-15],n=pi[e-2],r=Gr(t,7)^Gr(t,18)^t>>>3;pi[e]=(Gr(n,17)^Gr(n,19)^n>>>10)+pi[e-7]+r+pi[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=Gr(o,6)^Gr(o,11)^Gr(o,25),u=l+t+ii(o,s,c)+fi[e]+pi[e]|0,d=(Gr(n,2)^Gr(n,13)^Gr(n,22))+ai(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){Ur(pi)}destroy(){this.set(0,0,0,0,0,0,0,0),Ur(this.buffer)}};const hi=di(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e)));hi[0],hi[1];const gi=Yr(()=>new mi);var _i=Fr([`codex`,`claude`]),vi=Fr([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),yi=Fr([`untrusted`,`on-failure`,`on-request`,`never`]),bi=Fr([`read-only`,`workspace-write`,`danger-full-access`]),xi=Fr([`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`]),Si=X({reasoningEffort:vi.optional(),approvalPolicy:yi.optional(),sandboxMode:bi.optional(),permissionMode:xi.optional()}),Ci=Fr([`native`,`fallback`]),wi=X({provider:_i,models:jr(X({id:Y().min(1),label:Y().min(1),isDefault:kr().optional(),supportedReasoningEfforts:jr(vi).optional()})),support:X({reasoningEffort:kr(),approvalPolicy:kr(),sandboxMode:kr(),permissionMode:kr().optional()}),options:X({reasoningEfforts:jr(vi),approvalPolicies:jr(yi),sandboxModes:jr(bi),permissionModes:jr(xi).optional()}),defaults:X({model:Y().min(1).optional(),reasoningEffort:vi.optional(),approvalPolicy:yi.optional(),sandboxMode:bi.optional(),permissionMode:xi.optional()}),source:Ci}),Ti=Y().min(1).regex(/^[A-Za-z0-9+/=]+$/u),Ei=X({v:Z(`1.0`),provider:_i,sessionId:Y().min(1),projectId:Y().min(1).optional(),eventId:Y().min(1),ts:Y().datetime(),type:Y().min(1),payload:X({raw:Ar()}).passthrough()}).passthrough(),Di=X({commandId:Y().min(1).optional()}),Oi=Di.extend({type:Z(`session.start`),payload:X({provider:_i,model:Y().min(1).optional(),projectId:Y().min(1).optional(),cwd:Y().min(1).optional(),sessionConfig:Si.optional(),metadata:Pr(Ar()).optional()})}),ki=Di.extend({type:Z(`turn.input`),payload:X({sessionId:Y().min(1),text:Y().min(1),model:Y().min(1).optional(),sessionConfig:Si.optional()})}),Ai=Di.extend({type:Z(`tool.approval.respond`),payload:X({sessionId:Y().min(1),requestId:Y().min(1),decision:Fr([`allow`,`deny`]),reason:Y().min(1).optional()})}),ji=Di.extend({type:Z(`user.input.respond`),payload:X({sessionId:Y().min(1),requestId:Y().min(1),answers:Pr(jr(Y()))})}),Mi=Di.extend({type:Z(`session.interrupt`),payload:X({sessionId:Y().min(1)})}),Ni=Di.extend({type:Z(`session.close`),payload:X({sessionId:Y().min(1)})}),Pi=Nr(`kind`,[X({kind:Z(`all`)}),X({kind:Z(`raw_seq`),rawSeq:Or().int().nonnegative()})]),Fi=X({sessionId:Y().min(1),projectId:Y().min(1).optional(),cursor:Pi}),Ii=Nr(`type`,[Oi,ki,Ai,ji,Mi,Ni,Di.extend({type:Z(`session.stream.subscribe`),payload:X({replace:kr().default(!0),sessions:jr(Fi)})}),Di.extend({type:Z(`fs.read`),payload:X({sessionId:Y().min(1),path:Y().min(1)})}),Di.extend({type:Z(`fs.diff`),payload:X({sessionId:Y().min(1),path:Y().min(1),baseContent:Y().optional()})})]);function Li(e){let t=Ii.parse(e);if(t.type===`session.start`&&!t.payload.projectId&&!t.payload.cwd)throw Error(`session.start requires at least one of projectId or cwd`);return t}var Ri=Fr([`session.started`,`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`,`tool.permission.requested`,`tool.permission.resolved`,`user.input.requested`,`user.input.resolved`,`file.changed`,`file.diff.ready`,`status.progress`,`error`,`error.runtime`]),zi=Ei.extend({type:Ri}),Bi=Ei.extend({kind:Z(`provider.raw`),rawSeq:Or().int().positive(),type:Y().min(1)});zi.extend({kind:Z(`gateway.control`).optional(),derivedFrom:Y().min(1).optional()});var Vi=Mr([Bi,Ei.extend({kind:Z(`session.stream.sync`),type:Z(`session.stream.sync`),payload:X({raw:X({decision:Fr([`delta`,`snapshot`]),reason:Y().min(1),snapshotId:Y().min(1).optional(),fromRawSeq:Or().int().nonnegative().optional(),toRawSeq:Or().int().nonnegative().optional()}).passthrough()}).passthrough()}),Ei.extend({kind:Z(`session.stream.snapshot.chunk`),type:Z(`session.stream.snapshot.chunk`),payload:X({raw:X({snapshotId:Y().min(1),chunkIndex:Or().int().nonnegative(),totalChunks:Or().int().positive(),events:jr(Bi)}).passthrough()}).passthrough()})]),Hi=X({algorithm:Fr([`ed25519`]),publicKey:Ti,publicKeyFingerprint:Y().min(1),keyVersion:Or().int().min(1),createdAt:Y().datetime()});X({code:Y().min(4),expiresAt:Y().datetime()});var Ui=Fr([`ed25519`]),Wi=Fr([`active`,`revoked`,`rotating`,`unknown`]),Gi=X({algorithm:Ui,publicKey:Ti,publicKeyFingerprint:Y().min(1)}),Ki=X({pairingCode:Y().min(4),signedAt:Y().datetime()}),qi=X({gatewayId:Y().min(1),deviceId:Y().min(1),mobilePublicKey:Ti,pairingContext:Ki}),Ji=X({algorithm:Z(`ed25519`),gatewayPublicKeyFingerprint:Y().min(1),payload:qi,signature:Ti}),Yi=X({code:Y().min(4),deviceName:Ir(e=>{if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:void 0},Y().min(1).optional()),deviceIdentity:Gi.optional()}),Xi=X({accessToken:Y().min(1),refreshToken:Y().min(1),expiresInSeconds:Or().int().positive()}),Zi=Xi.extend({gatewayId:Y().min(1),deviceId:Y().min(1),gatewayIdentity:Hi.optional(),deviceIdentityFingerprint:Y().min(1).optional(),deviceIdentityStatus:Wi.optional(),pairingConfirmation:Ji.optional()}),Qi=X({refreshToken:Y().min(1)}),$i=Xi.extend({deviceId:Y().min(1),deviceIdentityFingerprint:Y().min(1).optional(),deviceIdentityStatus:Wi.optional()});function ea(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var ta=Fr([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),na=Fr([`npm`,`pnpm`,`yarn`,`unknown`]),ra=Fr([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),ia=Fr([`console`,`mobile`,`system`]),aa=X({manager:na,installType:ra,packageName:Y().min(1),packageRoot:Y().min(1).optional(),binPath:Y().min(1).optional(),canSelfUpdate:kr(),reason:Y().min(1).optional()}),oa=X({id:Y().min(1),targetVersion:Y().min(1),requestedBy:ia,requestedAt:Y().datetime(),startedAt:Y().datetime().optional()}),sa=X({packageName:Y().min(1),currentVersion:Y().min(1),latestVersion:Y().min(1).optional(),available:kr(),canApply:kr(),status:ta,checkedAt:Y().datetime().optional(),install:aa,job:oa.optional(),lastError:Y().min(1).optional()}),ca=X({type:Z(`gateway.update.status`),payload:sa}),la=X({started:kr(),update:sa}),ua=Ir(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},Y().trim().min(1)),da=X({id:Y().min(1),title:Y().min(1),path:Y().min(1),createdAt:Y().datetime(),updatedAt:Y().datetime(),lastSessionAt:Y().datetime().optional(),runningCount:Or().int().nonnegative(),idleCount:Or().int().nonnegative().optional(),totalCount:Or().int().nonnegative().optional(),endedCount:Or().int().nonnegative()}),fa=X({name:Y().min(1),path:Y().min(1)}),pa=X({rootPath:Y().min(1),currentPath:Y().min(1),parentPath:Y().min(1).nullable(),directories:jr(fa)}),ma=Fr([`running`,`idle`]),ha=Fr([`running`,`idle`,`all`]),ga=X({id:Y().min(1),nativeSessionId:Y().min(1).optional(),source:Fr([`gateway`,`native_discovered`]).optional(),projectId:Y().min(1),projectPath:Y().min(1),provider:_i,providerMode:Fr([`native`,`mock`]).optional(),model:Y().min(1).optional(),title:Y().min(1).optional(),createdAt:Y().datetime(),updatedAt:Y().datetime(),status:ma,pendingApprovals:Or().int().nonnegative(),pendingUserInputs:Or().int().nonnegative(),pendingActions:Or().int().nonnegative()}),_a=X({id:Y().min(1),name:Y().min(1),createdAt:Y().datetime(),revokedAt:Y().datetime().optional(),identityAlgorithm:Fr([`ed25519`]).optional(),publicKeyFingerprint:Y().min(1).optional(),identityStatus:Wi.optional(),lastVerifiedAt:Y().datetime().optional()}),va=X({agent:X({provider:_i,requestedVersion:Y().min(1).nullable(),resolvedVersion:Y().min(1)}),capabilities:wi}),ya=X({scannedAt:Y().datetime(),sessionCount:Or().int().nonnegative(),status:Fr([`ready`,`partial`,`failed`]),error:Y().min(1).optional()}),ba=X({codex:ya.optional(),claude:ya.optional()}),xa=X({key:Y().min(1),path:Y().min(1),title:Y().min(1),lastSessionAt:Y().datetime().optional(),sessionCount:Or().int().nonnegative(),providerCounts:X({codex:Or().int().nonnegative(),claude:Or().int().nonnegative()}),lastDiscoveryAt:Y().datetime()}),Sa=X({provider:_i,nativeSessionId:Y().min(1),title:Y().min(1).optional(),model:Y().min(1).optional(),createdAt:Y().datetime().optional(),updatedAt:Y().datetime()}),Ca=X({generatedAt:Y().datetime(),source:Fr([`cache`,`fresh_scan`]),providers:ba,projects:jr(xa)}),wa=X({canonicalProjectPath:Y().min(1),project:xa,providers:ba,sessions:jr(Sa)}),Ta=Fr([`auth.refresh`,`gateway.update.get`,`gateway.update.apply`,`projects.list`,`projects.discovery.get`,`projects.discovery.refresh`,`projects.create`,`projects.delete`,`workspace.directories.list`,`sessions.list`,`sessions.discovery.list`,`sessions.get`,`sessions.rawEvents.list`,`providers.capabilities.get`,`agents.config.get`,`devices.list`,`devices.revoke`]),Ea=X({}).strict(),Da=Nr(`method`,[X({method:Z(`auth.refresh`),params:Qi.extend({deviceId:Y().min(1).optional()})}),X({method:Z(`gateway.update.get`),params:Ea}),X({method:Z(`gateway.update.apply`),params:X({requestedBy:ia.optional()})}),X({method:Z(`projects.list`),params:Ea}),X({method:Z(`projects.discovery.get`),params:Ea}),X({method:Z(`projects.discovery.refresh`),params:Ea}),X({method:Z(`projects.create`),params:X({path:ua,title:Y().min(1).optional()})}),X({method:Z(`projects.delete`),params:X({projectId:Y().min(1)})}),X({method:Z(`workspace.directories.list`),params:X({path:Y().min(1).optional(),limit:Or().int().positive().max(500).optional()})}),X({method:Z(`sessions.list`),params:X({projectId:Y().min(1),status:ha.optional(),syncExternal:kr().optional()})}),X({method:Z(`sessions.discovery.list`),params:X({projectPath:ua})}),X({method:Z(`sessions.get`),params:X({projectId:Y().min(1),sessionId:Y().min(1)})}),X({method:Z(`sessions.rawEvents.list`),params:X({projectId:Y().min(1),sessionId:Y().min(1),limit:Mr([Or().int().positive().max(2e3),Z(`all`)]).optional(),syncExternal:kr().optional()})}),X({method:Z(`providers.capabilities.get`),params:X({provider:_i,projectId:Y().min(1).optional(),agentVersion:Y().min(1).optional()})}),X({method:Z(`agents.config.get`),params:X({provider:_i,projectId:Y().min(1).optional(),agentVersion:Y().min(1).optional()})}),X({method:Z(`devices.list`),params:Ea}),X({method:Z(`devices.revoke`),params:X({deviceId:Y().min(1)})})]),Oa=Nr(`method`,[X({method:Z(`auth.refresh`),result:$i.extend({relayToken:Y().min(1).optional()})}),X({method:Z(`gateway.update.get`),result:sa}),X({method:Z(`gateway.update.apply`),result:la}),X({method:Z(`projects.list`),result:X({projects:jr(da)})}),X({method:Z(`projects.discovery.get`),result:Ca}),X({method:Z(`projects.discovery.refresh`),result:Ca}),X({method:Z(`projects.create`),result:X({project:da})}),X({method:Z(`projects.delete`),result:X({removed:Z(!0)})}),X({method:Z(`workspace.directories.list`),result:pa}),X({method:Z(`sessions.list`),result:X({sessions:jr(ga)})}),X({method:Z(`sessions.discovery.list`),result:wa}),X({method:Z(`sessions.get`),result:X({session:ga})}),X({method:Z(`sessions.rawEvents.list`),result:X({events:jr(Ar())})}),X({method:Z(`providers.capabilities.get`),result:X({capabilities:wi})}),X({method:Z(`agents.config.get`),result:va}),X({method:Z(`devices.list`),result:X({devices:jr(_a)})}),X({method:Z(`devices.revoke`),result:X({revoked:Z(!0)})})]),ka=`craby-`,Aa=`gw-`,ja=Y().url(),Ma=Mr([ja,Z(``)]),Na=Y().min(1).regex(/^[A-Za-z0-9_-]+$/u),Pa=Fr([`plaintext-relay`,`e2ee-relay`]),Fa=Fr([`plain`,`crypt`]);function Ia(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function La(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=Ia(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function Ra(e){let t=e.trim();return t.startsWith(`${ka}${Aa}`)?t.slice(ka.length):t}var za=Fr([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),Ba=Or().int().positive();Or().int().min(0).max(2**53-1);var Va=Fr([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`unsupported_version`]),Ha=Fr([`guest`,`account`,`self_hosted`]);X({type:Z(`relay.gateway`),grantType:Ha,gatewayId:Y().min(1),subjectId:Y().min(1),gatewayIdentityFingerprint:Y().min(1).optional(),jti:Y().min(1),iss:Y().min(1),aud:Y().min(1),iat:Or().int().nonnegative(),exp:Or().int().positive()}),X({type:Z(`relay.mobile`),gatewayId:Y().min(1),deviceId:Y().min(1),iat:Or().int().nonnegative(),exp:Or().int().positive()});var Ua=X({v:Z(1),gw:Y().min(1),name:Y().min(1),relay:Ma.optional(),direct:jr(ja).default([]),pc:Y().min(1),tsl:Fa.optional(),gatewayIdentity:Hi.optional()});Ir(La,Ua);var Wa=Ir(La,Ua.omit({pc:!0}));Ir(La,X({v:Z(1),gw:Y().min(1),relay:Ma.optional(),direct:Ma.optional(),pc:Y().min(1),tsl:Fa.optional(),gatewayIdentity:Hi.optional()}));var Ga=Ir(La,X({v:Z(1),gw:Y().min(1),relay:Ma.optional(),direct:ja,pc:Y().min(1),pkf:Na,tsl:Fa.optional()})),Ka=X({name:Y().min(1),relayBaseUrl:Ma.optional(),directBaseUrls:jr(ja).default([]),transportSecurityLevel:Pa.default(`plaintext-relay`),gatewayIdentity:Hi.optional(),gatewayAccessToken:Y().min(1).optional(),connectedAt:Y().datetime().optional()}),qa=X({gatewayId:Y().min(1),deviceId:Y().min(1),connectedAt:Y().datetime().optional()}),Ja=X({version:Z(1),securityLevel:Z(`e2ee-relay`),cipherSuite:za,deviceId:Y().min(1),deviceIdentity:Gi,clientNonce:Ti}),Ya=X({version:Z(1),securityLevel:Z(`e2ee-relay`),cipherSuite:za,gatewayId:Y().min(1),deviceId:Y().min(1),clientNonce:Ti,gatewayNonce:Ti,gatewayPublicKeyFingerprint:Y().min(1),gatewayEphemeralPublicKey:Ti,signatureAlgorithm:Z(`ed25519`),signature:Ti}),Xa=X({version:Z(1),gatewayId:Y().min(1),deviceId:Y().min(1),deviceIdentityFingerprint:Y().min(1),clientEphemeralPublicKey:Ti,signatureAlgorithm:Z(`ed25519`),signature:Ti}),Za=X({version:Z(1),securityLevel:Z(`e2ee-relay`),cipherSuite:za,gatewayId:Y().min(1),deviceId:Y().min(1),keyEpoch:Ba,deviceIdentityFingerprint:Y().min(1),deviceIdentityStatus:Wi}),Qa=Fr([`gateway_restarted`,`gateway_available`]),$a=X({version:Z(1),gatewayId:Y().min(1),deviceId:Y().min(1),reason:Qa,retryable:Z(!0)}),eo=X({version:Z(1),gatewayId:Y().min(1),deviceId:Y().min(1).optional(),code:Va,message:Y().min(1),retryable:kr().optional()}),to=Da,no=Oa,ro=X({code:Fr([`BAD_REQUEST`,`NOT_FOUND`,`UNAUTHORIZED`,`TIMEOUT`,`INTERNAL`,`GATEWAY_OFFLINE`,`TOKEN_INVALID`,`TOKEN_EXPIRED`,`GATEWAY_MISMATCH`,`GATEWAY_REVOKED`]),message:Y().min(1),status:Or().int().min(400).max(599),details:Ar().optional()}),io=ro.extend({method:Ta.optional()}),ao=Yi.extend({gatewayId:Y().min(1)}),oo=Zi.extend({relayToken:Y().min(1).optional()}),so=Qi.extend({gatewayId:Y().min(1),deviceId:Y().min(1).optional()}),co=$i.extend({gatewayId:Y().min(1),relayToken:Y().min(1).optional()}),lo=X({gatewayId:Y().min(1),gatewayIdentity:Hi,requestedAt:Y().datetime()});X({grantType:Z(`guest`),payload:lo,signatureAlgorithm:Z(`ed25519`),signature:Ti});var uo=X({grantType:Ha,token:Y().min(1),expiresInSeconds:Or().int().positive()}),fo=Fr([`rpc`,`command`,`event`,`system`]),po=X({gatewayId:Y().min(1),mobileId:Y().min(1).optional(),messageType:fo,requestId:Y().min(1).optional()}),mo=Fr([`fresh_connect`,`gateway_replay`]),ho=X({deviceId:Y().min(1),deliveryMode:mo,gatewayAvailableAtConnect:kr()}),go=X({deviceId:Y().min(1)}),_o=Mr([Vi,ca,X({type:Z(`command.ack`),commandType:Y().min(1),commandId:Y().min(1).optional(),payload:Ar().optional()}),X({type:Z(`command.error`),commandType:Y().min(1).optional(),commandId:Y().min(1).optional(),message:Y().min(1)}),X({type:Z(`relay.error`),error:ro})]),vo=Nr(`type`,[po.extend({type:Z(`gateway.hello`),messageType:Z(`system`),payload:Ka}),po.extend({type:Z(`mobile.hello`),messageType:Z(`system`),payload:qa}),po.extend({type:Z(`secure.client_hello`),messageType:Z(`system`),payload:Ja}),po.extend({type:Z(`secure.gateway_hello`),mobileId:Y().min(1),messageType:Z(`system`),payload:Ya}),po.extend({type:Z(`secure.client_auth`),messageType:Z(`system`),payload:Xa}),po.extend({type:Z(`secure.ready`),mobileId:Y().min(1),messageType:Z(`system`),payload:Za}),po.extend({type:Z(`secure.handshake_required`),mobileId:Y().min(1),messageType:Z(`system`),payload:$a}),po.extend({type:Z(`secure.error`),mobileId:Y().min(1),messageType:Z(`system`),payload:eo}),po.extend({type:Z(`mobile.connected`),messageType:Z(`system`),payload:ho}),po.extend({type:Z(`mobile.disconnected`),messageType:Z(`system`),payload:go}),po.extend({type:Z(`from_mobile`),messageType:Z(`command`),mobileId:Y().min(1),payload:Ii}),po.extend({type:Z(`to_mobile`),messageType:Z(`event`),mobileId:Y().min(1),payload:_o}),po.extend({type:Z(`broadcast`),messageType:Z(`event`),payload:Vi}),po.extend({type:Z(`rpc.request`),messageType:Z(`rpc`),requestId:Y().min(1),mobileId:Y().min(1),payload:to}),po.extend({type:Z(`rpc.response`),messageType:Z(`rpc`),requestId:Y().min(1),mobileId:Y().min(1),payload:no}),po.extend({type:Z(`rpc.error`),messageType:Z(`rpc`),requestId:Y().min(1),mobileId:Y().min(1),payload:io}),po.extend({type:Z(`pairing.claim.forward`),messageType:Z(`system`),requestId:Y().min(1),payload:ao}),po.extend({type:Z(`pairing.claim.result`),messageType:Z(`system`),requestId:Y().min(1),payload:oo}),po.extend({type:Z(`auth.refresh.forward`),messageType:Z(`system`),requestId:Y().min(1),payload:so}),po.extend({type:Z(`auth.refresh.result`),messageType:Z(`system`),requestId:Y().min(1),payload:co}),po.extend({type:Z(`relay.error`),messageType:Z(`system`),payload:ro})]);function yo(e){return JSON.stringify([`relay-gateway-guest-token-v1`,e.gatewayId,e.gatewayIdentity.algorithm,e.gatewayIdentity.publicKey,e.gatewayIdentity.publicKeyFingerprint,e.gatewayIdentity.keyVersion,e.gatewayIdentity.createdAt,e.requestedAt])}function bo(e){return JSON.stringify([e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey])}function xo(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,bo(e)])}function So(e){return JSON.stringify([`relay-secure-client-auth-v1`,bo(e),e.clientAuth.clientEphemeralPublicKey])}function Co(e){let t=Ba.parse(e.keyEpoch??1);return JSON.stringify([`relay-secure-session-v1`,e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey,e.clientAuth.clientEphemeralPublicKey,t])}function wo(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=Ba.parse(e.keyEpoch??1),r=jo(No(Co({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=jo(Mo(No(`relay-secure-hkdf-salt-v1`),r)),a=No(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=Ao(e.sharedSecret,i,a,72);return{keyEpoch:n,cipherSuite:t,transcriptHash:r,clientToGatewayKey:o.slice(0,32),gatewayToClientKey:o.slice(32,64),clientToGatewayNoncePrefix:o.slice(64,68),gatewayToClientNoncePrefix:o.slice(68,72)}}function To(e){return e.role===`client`?{role:`client`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.clientToGatewayKey,inboundKey:e.keySchedule.gatewayToClientKey,outboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,inboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,outboundCounter:0,highestInboundCounter:null}:{role:`gateway`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.gatewayToClientKey,inboundKey:e.keySchedule.clientToGatewayKey,outboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,inboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,outboundCounter:0,highestInboundCounter:null}}function Eo(e){let t=globalThis.Buffer;if(t)return t.from(e).toString(`base64`);let n=``;for(let t of e)n+=String.fromCharCode(t);if(typeof btoa!=`function`)throw Error(`base64 encoder unavailable`);return btoa(n)}function Do(e){let t=globalThis.Buffer;if(t)return new Uint8Array(t.from(e,`base64`));if(typeof atob!=`function`)throw Error(`base64 decoder unavailable`);let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}function Oo(e){return Eo(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function ko(e){return Do(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function Ao(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(ni(gi,e,t.length>0?t:new Uint8Array(32),n,r))}function jo(e){return new Uint8Array(gi(e))}function Mo(...e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function No(e){return new TextEncoder().encode(e)}function Po(e){return Oo(gi(Do(e)).subarray(0,16))}function Fo(e){if(e.type!==`native.raw`)return null;let t=Vo(e.payload.raw),n=Vo(t.message),r=Vo(n.params),i=Vo(r.msg),a=Ho(n.method)??Ho(t.method);if(!a)return null;let o=Ho(i.type)??``;if(!zo(a)&&!Bo(o))return null;let s=Ro(t);if(!s||!s.delta)return null;let c=Ho(r.conversationId)??Ho(r.conversation_id)??``,l=Ho(i.thread_id)??Ho(i.threadId)??Ho(r.threadId)??Ho(r.thread_id)??``,u=Ho(i.turn_id)??Ho(i.turnId)??Ho(r.turnId)??Ho(r.turn_id)??``,d=Ho(i.item_id)??Ho(i.itemId)??Ho(r.itemId)??Ho(r.item_id)??``,f=Ho(t.source)??``,p=Uo(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=Uo(i.contentIndex??i.content_index??r.contentIndex??r.content_index);return{key:[e.sessionId,f,a,c,l,u,d,o,p,m].join(`|`),delta:s.delta,method:a}}function Io(e,t){let n=Fo(e),r=Fo(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=Vo(t.payload.raw),o=Ro(a)?.location??Ro(Vo(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Lo(a,o,i)}}:null}function Lo(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=Vo(e.message),i=Vo(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=Vo(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Ro(e){let t=Vo(Vo(e.message).params),n=Vo(t.msg);return typeof n.delta==`string`?{delta:n.delta,location:`msg.delta`}:typeof t.delta==`string`?{delta:t.delta,location:`params.delta`}:typeof e.delta==`string`?{delta:e.delta,location:`raw.delta`}:null}function zo(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Bo(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function Vo(e){return typeof e==`object`&&e?e:{}}function Ho(e){return typeof e==`string`&&e.trim()||void 0}function Uo(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Ho(e)??``}function Wo(e){let t=Xo(e),n=[],r=new Map;for(let e of t){let t=Ko(e);if(!t){n.push(e);continue}let i=r.get(t.key);if(i===void 0){n.push(e),r.set(t.key,n.length-1);continue}let a=n[i];if(!a){n.push(e),r.set(t.key,n.length-1);continue}let o=Go(a,e);if(!o){n.push(e),r.set(t.key,n.length-1);continue}n[i]=null,n.push(o),r.set(t.key,n.length-1)}return n.filter(e=>e!==null)}function Go(e,t){let n=Ko(e),r=Ko(t);if(!n||!r||n.key!==r.key)return null;if(n.envelopeType===`native.raw`&&r.envelopeType===`native.raw`)return Io(e,t);if(n.envelopeType!==`item.updated`||r.envelopeType!==`item.updated`)return null;let i=n.location===`native.raw`?null:n.location,a=(r.location===`native.raw`?null:r.location)??i;if(!a)return null;let o=$o(t.payload.raw),s=`${n.delta}${r.delta}`;return{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Yo(o,a,s)}}}function Ko(e){let t=Fo(e);return t?{...t,envelopeType:`native.raw`,location:`native.raw`,key:`native.raw|${t.key}`}:qo(e)}function qo(e){if(e.type!==`item.updated`)return null;let t=$o(e.payload.raw),n=$o(t.item),r=$o(n.payload),i=es(n.original_method)??es(n.originalMethod)??``,a=es(n.type)??``,o=Jo(n,r,i);if(!o)return null;let s=es(n.id)??es(n.item_id)??es(n.itemId)??es(r.item_id)??es(r.itemId)??``,c=es(n.turn_id)??es(n.turnId)??es(r.turn_id)??es(r.turnId)??es(t.turn_id)??es(t.turnId)??``,l=ts(r.summaryIndex??r.summary_index??n.summaryIndex??n.summary_index??t.summaryIndex??t.summary_index),u=ts(r.contentIndex??r.content_index??n.contentIndex??n.content_index??t.contentIndex??t.content_index);return{envelopeType:`item.updated`,location:o.location,key:[`item.updated`,e.sessionId,s,a,c,i,l,u].join(`|`),delta:o.delta,method:i||`item.updated`}}function Jo(e,t,n){return typeof t.delta==`string`&&t.delta.length>0?{delta:t.delta,location:`item.payload.delta`}:typeof t.output_delta==`string`&&t.output_delta.length>0?{delta:t.output_delta,location:`item.payload.output_delta`}:typeof t.outputDelta==`string`&&t.outputDelta.length>0?{delta:t.outputDelta,location:`item.payload.outputDelta`}:typeof e.output_delta==`string`&&e.output_delta.length>0?{delta:e.output_delta,location:`item.output_delta`}:typeof e.outputDelta==`string`&&e.outputDelta.length>0?{delta:e.outputDelta,location:`item.outputDelta`}:(Zo(n)||Qo(n))&&typeof e.text==`string`&&e.text.length>0?{delta:e.text,location:`item.text`}:null}function Yo(e,t,n){let r=$o(e.item),i=$o(r.payload);return t===`item.payload.delta`?{...e,item:{...r,payload:{...i,delta:n}}}:t===`item.payload.output_delta`?{...e,item:{...r,payload:{...i,output_delta:n}}}:t===`item.payload.outputDelta`?{...e,item:{...r,payload:{...i,outputDelta:n}}}:t===`item.output_delta`?{...e,item:{...r,output_delta:n}}:t===`item.outputDelta`?{...e,item:{...r,outputDelta:n}}:{...e,item:{...r,text:n}}}function Xo(e){let t=new Map;for(let[n,r]of e.entries()){let e=t.get(r.eventId);if(e){e.event=r;continue}t.set(r.eventId,{event:r,index:n})}return[...t.values()].sort((e,t)=>{let n=e.event.ts.localeCompare(t.event.ts);return n===0?e.index-t.index:n}).map(e=>e.event)}function Zo(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Qo(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function $o(e){return typeof e==`object`&&e?e:{}}function es(e){return typeof e==`string`&&e.trim()||void 0}function ts(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():es(e)??``}var ns=o(((e,t)=>{t.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}})),rs=o(((e,t)=>{var n=ns();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})),is=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})),as=o(((e,t)=>{var n=is();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})),os=o(((e,t)=>{t.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}})),ss=o(((e,t)=>{var n=ns(),r=as(),i=is(),a=os(),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})),cs=o(((e,t)=>{t.exports={L:1,M:0,Q:3,H:2}})),ls=o(((e,t)=>{var n=cs();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})),us=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})),ds=c(o(((e,t)=>{var n=rs(),r=ss(),i=as(),a=ls(),o=us();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),fs=c(cs(),1);const ps={renderQr:_s};function ms(e){return Ga.parse({v:1,gw:Ra(e.gatewayId),relay:e.relayBaseUrl,direct:e.bootstrapDirectBaseUrl,pc:e.pairingCode,pkf:Po(e.gatewayIdentityPublicKey)})}function hs(e){return Wa.parse({v:1,gw:Ra(e.gatewayId),name:e.machineName,relay:e.relayBaseUrl,direct:e.directBaseUrls,gatewayIdentity:e.gatewayIdentity})}function gs(e,t=ps){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(`
|
|
119
119
|
`)}function _s(e){let t=new ds.default(-1,fs.default.L);t.addData(e),t.make();let n=t.getModuleCount(),r=t.modules.slice(),i=n%2==1;i&&r.push(vs(n,!1));let a={whiteAll:`█`,whiteBlack:`▀`,blackWhite:`▄`,blackAll:` `},o=a.blackWhite.repeat(n+3),s=a.whiteBlack.repeat(n+3),c=`${o}\n`;for(let e=0;e<n;e+=2){c+=a.whiteAll;for(let t=0;t<n;t+=1)r[e][t]===!1&&r[e+1][t]===!1?c+=a.whiteAll:r[e][t]===!1&&r[e+1][t]===!0?c+=a.whiteBlack:r[e][t]===!0&&r[e+1][t]===!1?c+=a.blackWhite:c+=a.blackAll;c+=`${a.whiteAll}\n`}return i||(c+=s),c.trimEnd()}function vs(e,t){return Array.from({length:e},()=>t)}function ys(){return f.default.hostname()}const bs={networkInterfaces:()=>f.default.networkInterfaces()};function xs(e,t=bs){if(!Ss(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||!Cs(t.family)||n.add(t.address);return[...n]}function Ss(e){return e===`0.0.0.0`||e===`::`||e===`[::]`}function Cs(e){return e===`IPv4`||e===4}const ws={listGatewayListenHosts:xs,renderQr:_s};function Ts(e,t=ws){return t.listGatewayListenHosts(e.host).map(t=>`${e.protocol}://${As(t)}:${e.port}`)}function Es(e){return e.find(e=>!js(e))??e[0]??``}function Ds(e,t=ws){let n=e.relayUrl.trim();if(!n)return``;let r;try{r=new URL(n)}catch{return n}if(!Ms(r.hostname))return n;let i=t.listGatewayListenHosts(e.gatewayHost).find(e=>!Ms(e));return i?(r.hostname=i,r.toString().replace(/\/$/,``)):n}function Os(e,t=ws){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: ${Ds({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t)}`:`[gateway] relay disabled`),n.push(`[gateway] available URLs:`);let r=Ts({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(gs({descriptor:ms({gatewayId:e.config.gatewayId,bootstrapDirectBaseUrl:Es(r),pairingCode:e.startedServer.startupPairingCode.code,gatewayIdentityPublicKey:e.startedServer.gatewayIdentity.publicKey,relayBaseUrl:e.config.relayEnabled?Ds({relayUrl:e.config.relayUrl,gatewayHost:e.config.host},t):void 0}),expiresAt:e.startedServer.startupPairingCode.expiresAt},{renderQr:t.renderQr??_s})),n.push(...ks(e.doctorReport)),n.join(`
|
|
120
|
-
`)}function ks(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function As(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function js(e){try{let t=new URL(e).hostname;return Ms(t)}catch{return!1}}function Ms(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const Ns={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 Ps(){return p.default.join(gt(),`update-state.json`)}function Fs(e){return ca.parse({type:`gateway.update.status`,payload:e})}var Is=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??Ps(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??Ns,this.state=sa.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 sa.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=Bs({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=zs(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=O(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 la.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:Ys(t.install,{cwd:i.cwd,argv:[...i.argv]}),requestedBy:e,requestedAt:a.requestedAt}};await Zs(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});try{await this.requestPreparedUpdate?.({stateFilePath:this.stateFilePath,targetVersion:r,requestedBy:e})}catch(e){let t=sa.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await Zs(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(Fs(t)),e}return la.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=sa.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(Fs(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await Xs(this.stateFilePath);if(!e)return;let t=Bs({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=O(this.currentVersion,n)>=0,i=sa.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 Zs(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=sa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Ls(e,t={}){let n=t.runtime??Ns,r=t.waitForProcessExit??Qs,i=await Xs(e);if(!i?.helper)throw Error(`gateway update helper state is missing`);await r(i.helper.originalPid);let a=Rs(i.helper.manager,i.helper.packageName,i.helper.targetVersion),o=n.runCommand(a.command,a.args,{cwd:i.helper.restart.cwd});if(o.status!==0){let t={...i,update:{...i.update,status:`failed`,lastError:tc(a.command,a.args,o)},helper:void 0};return await Zs(e,t),{updated:!1,update:sa.parse(t.update)}}let s={...i,update:{...i.update,status:`restarting`,lastError:void 0},helper:void 0};return await Zs(e,s),{updated:!0,update:sa.parse(s.update)}}function Rs(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 zs(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 Bs(e){let t=Ws(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?aa.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?Vs(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Hs(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Us(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||aa.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`}):aa.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function Vs(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=Ks(c);if(!Gs(l,t,n))return null;let d=Ks(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),Js(r.platform)),m=qs(l,d)?`global_registry`:`global_file`;return aa.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 Hs(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=Ks(c);if(!Gs(l,t,n))return null;let d=qs(l,Ks(p.default.dirname(o)))?`global_registry`:`global_file`;return aa.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,Js(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Us(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=Ks(c);return Gs(l,t,n)?aa.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,Js(r.platform)),canSelfUpdate:!0}):null}function Ws(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 Gs(e,t,n){let r=Ks(e),i=t?Ks(t):null,a=Ks(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function Ks(e){try{return u.default.realpathSync(e)}catch{return e}}function qs(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function Js(e=v.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function Ys(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function Xs(e){try{let t=await d.default.readFile(e,`utf8`);return nc(JSON.parse(t))}catch{return null}}async function Zs(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 Qs(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!$s(e))return;await ec(500)}}function $s(e){try{return v.default.kill(e,0),!0}catch{return!1}}function ec(e){return new Promise(t=>setTimeout(t,e))}function tc(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 nc(e){if(!ac(e)||e.version!==1)return null;let t=sa.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=rc(e.helper);return n?{version:1,update:t.data,helper:n}:null}function rc(e){if(!ac(e))return null;let t=na.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=ia.safeParse(e.requestedBy);if(!n.success||!oc(e.packageName)||!oc(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!sc(e.requestedAt))return null;let r=ic(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 ic(e){return!ac(e)||!oc(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!oc(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function ac(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oc(e){return typeof e==`string`&&e.trim().length>0}function sc(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}async function cc(e){let t=uc(),n=new Map,r=0,i=null,a=!1,o=null,s=null,c=!1,l=null,u=null,d=null,f=new Promise((e,t)=>{o=e,s=t}),p=()=>{d&&=(clearTimeout(d),null)},h=()=>{u&&=(clearTimeout(u),null)},g=lc({enabled:v.default.stdin.isTTY&&v.default.stdout.isTTY,onUpdate:async()=>{if(!(!i||c))try{let e=await T(`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)}`)}}}),_=e=>{for(let t of n.values())t.reject(e);n.clear()},y=e=>{h(),p(),g(),_(Error(`gateway supervisor shutting down`)),v.default.exit(e)},b=e=>{if(i){try{i.send?.({type:`supervisor.shutdown`,reason:e})}catch{i.kill(`SIGTERM`)}p(),d=setTimeout(()=>{i?.kill(`SIGTERM`)},1e4)}},x=async n=>{console.log(`[gateway] applying update to ${n.targetVersion}...`);let r=await Ls(n.stateFilePath),i=r.updated&&r.update.install.binPath?$t(r.update.install,`__worker`,e.args,t.cwd):Qt(t,`__worker`,e.args);!r.updated&&r.update.lastError&&console.error(`[gateway] update failed: ${r.update.lastError}`),r.updated?console.log(`[gateway] update installed; restarting worker...`):console.log(`[gateway] relaunching current worker after failed update.`),l=null,w(i)},S=(e,t)=>{if(p(),h(),i=null,l){_(Error(`gateway worker restarting for update`)),x(l).catch(e=>{console.error(`[gateway] update handoff failed: ${String(e)}`),y(1)});return}if(c){y(0);return}if(_(Error(`gateway worker exited`)),!a){s?.(Error(`gateway worker exited before signaling ready (code=${String(e)}, signal=${String(t)})`)),s=null,o=null;return}t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),y(e??1)},C=t=>{switch(t.type){case`worker.ready`:if(!a){a=!0,console.log(Os({configPath:e.loaded.configPath,createdDefaultConfig:e.loaded.createdDefaultConfig,config:e.loaded.config,doctorReport:e.doctorReport,startedServer:t.payload,logToConsole:e.args.logToConsole})),o?.(),o=null,s=null;return}console.log(`[gateway] worker ready after update.`);return;case`worker.response`:{let e=n.get(t.id);if(!e)return;n.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,h(),u=setTimeout(()=>{b(`update`)},250);return}},w=e=>{let t=(0,m.spawn)(e.command,e.args,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0});i=t,t.stdout&&t.stdout.pipe(v.default.stdout),t.stderr&&t.stderr.pipe(v.default.stderr),t.on(`message`,e=>{let t=dc(e);t&&C(t)}),t.on(`exit`,(e,n)=>{t.stdout&&t.stdout.unpipe(v.default.stdout),t.stderr&&t.stderr.unpipe(v.default.stderr),S(e,n)}),t.on(`error`,e=>{if(console.error(`[gateway] failed to launch worker: ${String(e)}`),!a){s?.(e instanceof Error?e:Error(String(e))),s=null,o=null;return}y(1)})},T=e=>{let t=i;if(!t?.send)throw Error(`gateway worker is unavailable`);let a=`worker_req_${r+=1}`;return new Promise((r,i)=>{n.set(a,{resolve:r,reject:i});try{t.send?.({type:`supervisor.request`,id:a,method:`gateway.update.apply`,requestedBy:e})}catch(e){n.delete(a),i(e instanceof Error?e:Error(String(e)))}})},E=e=>{if(!c){if(c=!0,console.log(`[gateway] received ${e}; shutting down...`),!i){y(0);return}b(`signal`)}};v.default.on(`SIGINT`,E),v.default.on(`SIGTERM`,E),w(Qt(t,`__worker`,e.args)),await f}function lc(e){if(!e.enabled)return()=>{};let t=_.default.createInterface({input:v.default.stdin,output:v.default.stdout,terminal:!0});return t.on(`line`,t=>{t.trim().toLowerCase()===`update`&&e.onUpdate()}),()=>{t.close()}}function uc(){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 dc(e){if(!fc(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return fc(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||typeof e.ok!=`boolean`?null:e.ok?{type:`worker.response`,id:e.id,ok:!0,result:e.result}:typeof e.error==`string`?{type:`worker.response`,id:e.id,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!fc(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 fc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function pc(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function mc(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 hc=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})),gc=o(((e,t)=>{var n=hc();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})),_c=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})),vc=o(((e,t)=>{let{createError:n}=_c();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`)}})),yc=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`)}})),bc=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=yc();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}})),xc=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),Sc=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}})),Cc=o(((e,t)=>{let{kPluginMeta:n}=yc();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
|
|
121
|
-
`).slice(0,2).map(e=>e.trim()).join(` -- `)}t.exports={getPluginName:r}})),wc=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}t.exports={isPromiseLike:n}})),Tc=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{inherits:r}=require(`node:util`),{debug:i}=xc(),{createPromise:a}=Sc(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:o}=vc(),{getPluginName:s}=Cc(),{isPromiseLike:c}=wc();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}})),Ec=o(((e,t)=>{let{AVV_ERR_PLUGIN_NOT_VALID:n}=vc();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}})),Dc=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.default==`function`}t.exports={isBundledOrTypescriptPlugin:n}})),Oc=o(((e,t)=>{let{debug:n}=xc(),{kThenifyDoNotWrap:r}=yc();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}})),kc=o(((e,t)=>{let{isPromiseLike:n}=wc(),{kAvvio:r}=yc();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}})),Ac=o(((e,t)=>{let n=gc(),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}=vc(),{kAvvio:u,kIsOnCloseHandler:d}=yc(),{TimeTree:f}=bc(),{Plugin:p}=Tc(),{debug:m}=xc(),{validatePlugin:h}=Ec(),{isBundledOrTypescriptPlugin:g}=Dc(),{isPromiseLike:_}=wc(),{thenify:v}=Oc(),{executeWithThenable:y}=kc();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})),jc=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`)}})),Mc=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})),Nc=o(((e,t)=>{let{createWarning:n}=Mc();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})}})),Pc=o(((e,t)=>{let n=_c(),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}})),Fc=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}=Pc(),{kChildren:f,kHooks:p,kRequestPayloadStream:m}=jc();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}})),Ic=o(((e,t)=>{t.exports=function(){return{[Symbol.iterator]:function*(){},add(){},delete(){},has(){return!0}}}})),Lc=o(((e,t)=>{let{kTestInternals:n}=jc();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}}})),Rc=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}=jc(),{FSTWRN003:d}=Nc(),{onListenHookRunner:f}=Fc(),{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}=Pc(),_=Ic(),v=Lc();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()}}})),zc=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}}})),Bc=o(((e,t)=>{let{kReplyHasStatusCode:n}=jc();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}})),Vc=o(((e,t)=>{let{kReplyIsError:n,kReplyHijacked:r}=jc(),{setErrorStatusCode:i}=Bc(),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})),Hc=o(((e,t)=>{let{kSchemaHeaders:n,kSchemaParams:r,kSchemaQuerystring:i,kSchemaBody:a,kSchemaResponse:o}=jc(),s=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:c}=Pc(),{FSTWRN001:l}=Nc();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}})),Uc=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=zc(),i=Vc(),{validate:a}=Hc(),{preValidationHookRunner:o,preHandlerHookRunner:s}=Fc(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:c}=Pc(),{setErrorStatusCode:l}=Bc(),{kReplyIsError:u,kRouteContext:d,kFourOhFourContext:f,kSupportedHTTPMethods:p}=jc(),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}})),Wc=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)}})})),Gc=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+`
|
|
120
|
+
`)}function ks(e){return e.checks.some(e=>e.bundledStatus===`fail`||e.systemStatus===`fail`)?["[doctor] runtime checks failed; run `craby-gateway doctor` for details."]:[]}function As(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function js(e){try{let t=new URL(e).hostname;return Ms(t)}catch{return!1}}function Ms(e){return e===`127.0.0.1`||e===`::1`||e===`localhost`}const Ns={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 Ps(){return p.default.join(gt(),`update-state.json`)}function Fs(e){return ca.parse({type:`gateway.update.status`,payload:e})}var Is=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??Ps(),this.checkIntervalMs=e.checkIntervalMs??216e5,this.runtime=e.runtime??Ns,this.state=sa.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 sa.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=Bs({packageName:this.packageName,currentScriptPath:this.runtime.currentContext().scriptPath,runtime:this.runtime});this.patchState({status:`checking`,install:n});let r=zs(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=O(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 la.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:Ys(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 Zs(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=sa.parse({...this.getInfo(),status:`failed`,job:void 0,lastError:`failed to schedule gateway update: ${String(e)}`});throw await Zs(this.stateFilePath,{version:1,update:t}),this.state=t,this.logger.error?.({update:t},`gateway update scheduling failed`),this.sessionHub.broadcastSystemMessage(Fs(t)),e}return la.parse({started:!0,update:this.getInfo()})})().finally(()=>{this.applyPromise=null}),this.applyPromise}patchState(e){let t=sa.parse({...this.state,...e});this.state=t,this.logger.info?.({update:t},`gateway update status changed`),this.sessionHub.broadcastSystemMessage(Fs(t))}scheduleRecurringChecks(){this.recurringCheckTimer||=setInterval(()=>{this.checkForUpdates(`system`)},this.checkIntervalMs)}async reconcilePersistedState(){let e=await Xs(this.stateFilePath);if(!e)return;let t=Bs({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=O(this.currentVersion,n)>=0,i=sa.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 Zs(this.stateFilePath,{version:1,update:i}),this.state=i;return}this.state=sa.parse({...e.update,packageName:this.packageName,currentVersion:this.currentVersion,install:t,canApply:e.update.available&&t.canSelfUpdate})}};async function Ls(e,t={}){let n=t.runtime??Ns,r=t.waitForProcessExit??Qs,i=t.logger,a=await Xs(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=$s(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=Rs(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:tc(l.command,l.args,d)},helper:void 0};return await Zs(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:sa.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 Zs(e,p),i?.info?.({stateFilePath:e,targetVersion:a.helper.targetVersion},`gateway update apply completed; worker restart may proceed`),{updated:!0,update:sa.parse(p.update)}}function Rs(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 zs(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 Bs(e){let t=Ws(e.currentScriptPath);return t.packageName===`@remote-agent/desktop-gateway`?aa.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?Vs(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Hs(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||Us(e.packageName,t.packageRoot,e.currentScriptPath,e.runtime)||aa.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`}):aa.parse({manager:`unknown`,installType:`standalone_binary`,packageName:e.packageName,canSelfUpdate:!1,reason:`standalone gateway binary does not support package-manager self-update`})}function Vs(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=Ks(c);if(!Gs(l,t,n))return null;let d=Ks(o),f=p.default.join(r.platform===`win32`?s:p.default.join(s,`bin`),Js(r.platform)),m=qs(l,d)?`global_registry`:`global_file`;return aa.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 Hs(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=Ks(c);if(!Gs(l,t,n))return null;let d=qs(l,Ks(p.default.dirname(o)))?`global_registry`:`global_file`;return aa.parse({manager:`pnpm`,installType:d,packageName:e,packageRoot:l,binPath:p.default.join(s,Js(r.platform)),canSelfUpdate:d===`global_registry`,...d===`global_registry`?{}:{reason:`pnpm file-linked global install is not supported`}})}function Us(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=Ks(c);return Gs(l,t,n)?aa.parse({manager:`yarn`,installType:`global_registry`,packageName:e,packageRoot:l,binPath:p.default.join(s,Js(r.platform)),canSelfUpdate:!0}):null}function Ws(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 Gs(e,t,n){let r=Ks(e),i=t?Ks(t):null,a=Ks(n);return r===i||a===r||a.startsWith(`${r}${p.default.sep}`)}function Ks(e){try{return u.default.realpathSync(e)}catch{return e}}function qs(e,t){let n=p.default.relative(t,e);return!!n&&!n.startsWith(`..`)&&!p.default.isAbsolute(n)}function Js(e=v.default.platform){return e===`win32`?`craby-gateway.cmd`:`craby-gateway`}function Ys(e,t){if(!e.binPath)throw Error(`gateway restart command is unavailable`);return{binPath:e.binPath,args:[...t.argv],cwd:t.cwd}}async function Xs(e){try{let t=await d.default.readFile(e,`utf8`);return nc(JSON.parse(t))}catch{return null}}async function Zs(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 Qs(e){let t=Date.now();for(;Date.now()-t<6e4;){if(!$s(e))return;await ec(500)}}function $s(e){try{return v.default.kill(e,0),!0}catch{return!1}}function ec(e){return new Promise(t=>setTimeout(t,e))}function tc(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 nc(e){if(!ac(e)||e.version!==1)return null;let t=sa.safeParse(e.update);if(!t.success)return null;if(e.helper===void 0)return{version:1,update:t.data};let n=rc(e.helper);return n?{version:1,update:t.data,helper:n}:null}function rc(e){if(!ac(e))return null;let t=na.safeParse(e.manager);if(!t.success||t.data===`unknown`)return null;let n=ia.safeParse(e.requestedBy);if(!n.success||!oc(e.packageName)||!oc(e.targetVersion)||typeof e.originalPid!=`number`||!Number.isInteger(e.originalPid)||e.originalPid<=0||!sc(e.requestedAt))return null;let r=ic(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 ic(e){return!ac(e)||!oc(e.binPath)||!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`)||!oc(e.cwd)?null:{binPath:e.binPath,args:[...e.args],cwd:e.cwd}}function ac(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oc(e){return typeof e==`string`&&e.trim().length>0}function sc(e){return typeof e==`string`&&!Number.isNaN(Date.parse(e))}async function cc(e){let t=uc(),n=pc(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=new Promise((e,t)=>{s=e,c=t}),h=()=>{f&&=(clearTimeout(f),null)},g=()=>{d&&=(clearTimeout(d),null)},_=lc({enabled:v.default.stdin.isTTY&&v.default.stdout.isTTY,onUpdate:async()=>{if(!(!a||l))try{let e=await E(`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)}`)}}}),y=e=>{for(let t of r.values())t.reject(e);r.clear()},b=e=>{g(),h(),_(),y(Error(`gateway supervisor shutting down`)),n.close(),v.default.exit(e)},x=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`)}h(),f=setTimeout(()=>{a?.kill(`SIGTERM`)},1e4)}},S=async r=>{n.info(r,`gateway supervisor continuing prepared update`),console.log(`[gateway] applying update to ${r.targetVersion}...`);let i=await Ls(r.stateFilePath,{logger:n}),a=i.updated&&i.update.install.binPath?$t(i.update.install,`__worker`,e.args,t.cwd):Qt(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,T(a)},C=(e,t)=>{if(h(),g(),n.info({workerPid:a?.pid??void 0,code:e,signal:t,preparedUpdate:u,shuttingDown:l},`gateway supervisor observed worker exit`),a=null,u){y(Error(`gateway worker restarting for update`)),S(u).catch(e=>{n.error({error:e,preparedUpdate:u},`gateway update handoff failed`),console.error(`[gateway] update handoff failed: ${String(e)}`),b(1)});return}if(l){b(0);return}if(y(Error(`gateway worker exited`)),!o){c?.(Error(`gateway worker exited before signaling ready (code=${String(e)}, signal=${String(t)})`)),c=null,s=null;return}t?console.error(`[gateway] worker exited from signal ${t}`):console.error(`[gateway] worker exited with code ${String(e??1)}`),b(e??1)},w=t=>{switch(t.type){case`worker.ready`:if(!o){o=!0,n.info(t.payload,`gateway supervisor received initial worker ready`),console.log(Os({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`),g(),d=setTimeout(()=>{x(`update`)},250);return}},T=e=>{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=dc(e);t&&w(t)}),t.on(`exit`,(e,n)=>{t.stdout&&t.stdout.unpipe(v.default.stdout),t.stderr&&t.stderr.unpipe(v.default.stderr),C(e,n)}),t.on(`error`,t=>{if(n.error({error:t,invocation:e},`gateway supervisor failed to launch worker`),console.error(`[gateway] failed to launch worker: ${String(t)}`),!o){c?.(t instanceof Error?t:Error(String(t))),c=null,s=null;return}b(1)})},E=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:i,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)))}})},D=e=>{if(!l){if(l=!0,n.info({signal:e},`gateway supervisor received shutdown signal`),console.log(`[gateway] received ${e}; shutting down...`),!a){b(0);return}x(`signal`)}};v.default.on(`SIGINT`,D),v.default.on(`SIGTERM`,D),T(Qt(t,`__worker`,e.args)),await p}function lc(e){if(!e.enabled)return()=>{};let t=_.default.createInterface({input:v.default.stdin,output:v.default.stdout,terminal:!0});return t.on(`line`,t=>{t.trim().toLowerCase()===`update`&&e.onUpdate()}),()=>{t.close()}}function uc(){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 dc(e){if(!fc(e)||typeof e.type!=`string`)return null;switch(e.type){case`worker.ready`:return fc(e.payload)?{type:`worker.ready`,payload:e.payload}:null;case`worker.response`:return typeof e.id!=`string`||typeof e.ok!=`boolean`?null:e.ok?{type:`worker.response`,id:e.id,ok:!0,result:e.result}:typeof e.error==`string`?{type:`worker.response`,id:e.id,ok:!1,error:e.error}:null;case`worker.update.prepared`:return!fc(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 fc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pc(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,...mc(r),msg:i??``};try{u.default.appendFileSync(e,`${JSON.stringify(a,hc)}\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 mc(e){return fc(e)?e:{detail:e}}function hc(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t==`bigint`?t.toString():t}async function gc(e){let t=p.default.dirname(e);await d.default.mkdir(t,{recursive:!0}),await(await d.default.open(e,`a`,384)).close()}function _c(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 vc=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})),yc=o(((e,t)=>{var n=vc();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})),bc=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})),xc=o(((e,t)=>{let{createError:n}=bc();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`)}})),Sc=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`)}})),Cc=o(((e,t)=>{let{kUntrackNode:n,kTrackNode:r,kGetParent:i,kGetNode:a,kAddNode:o}=Sc();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}})),wc=o(((e,t)=>{let{debuglog:n}=require(`node:util`);t.exports={debug:n(`avvio`)}})),Tc=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}})),Ec=o(((e,t)=>{let{kPluginMeta:n}=Sc();function r(e,t){return e[n]?.name?e[n].name:t?.name?t.name:e.name?e.name:e.toString().split(`
|
|
121
|
+
`).slice(0,2).map(e=>e.trim()).join(` -- `)}t.exports={getPluginName:r}})),Dc=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}t.exports={isPromiseLike:n}})),Oc=o(((e,t)=>{let{EventEmitter:n}=require(`node:events`),{inherits:r}=require(`node:util`),{debug:i}=wc(),{createPromise:a}=Tc(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:o}=xc(),{getPluginName:s}=Ec(),{isPromiseLike:c}=Dc();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}})),kc=o(((e,t)=>{let{AVV_ERR_PLUGIN_NOT_VALID:n}=xc();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}})),Ac=o(((e,t)=>{function n(e){return typeof e==`object`&&!!e&&typeof e.default==`function`}t.exports={isBundledOrTypescriptPlugin:n}})),jc=o(((e,t)=>{let{debug:n}=wc(),{kThenifyDoNotWrap:r}=Sc();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}})),Mc=o(((e,t)=>{let{isPromiseLike:n}=Dc(),{kAvvio:r}=Sc();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}})),Nc=o(((e,t)=>{let n=yc(),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}=xc(),{kAvvio:u,kIsOnCloseHandler:d}=Sc(),{TimeTree:f}=Cc(),{Plugin:p}=Oc(),{debug:m}=wc(),{validatePlugin:h}=kc(),{isBundledOrTypescriptPlugin:g}=Ac(),{isPromiseLike:_}=Dc(),{thenify:v}=jc(),{executeWithThenable:y}=Mc();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})),Pc=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`)}})),Fc=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})),Ic=o(((e,t)=>{let{createWarning:n}=Fc();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})}})),Lc=o(((e,t)=>{let n=bc(),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}})),Rc=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}=Lc(),{kChildren:f,kHooks:p,kRequestPayloadStream:m}=Pc();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}})),zc=o(((e,t)=>{t.exports=function(){return{[Symbol.iterator]:function*(){},add(){},delete(){},has(){return!0}}}})),Bc=o(((e,t)=>{let{kTestInternals:n}=Pc();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}}})),Vc=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}=Pc(),{FSTWRN003:d}=Ic(),{onListenHookRunner:f}=Rc(),{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}=Lc(),_=zc(),v=Bc();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()}}})),Hc=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}}})),Uc=o(((e,t)=>{let{kReplyHasStatusCode:n}=Pc();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}})),Wc=o(((e,t)=>{let{kReplyIsError:n,kReplyHijacked:r}=Pc(),{setErrorStatusCode:i}=Uc(),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})),Gc=o(((e,t)=>{let{kSchemaHeaders:n,kSchemaParams:r,kSchemaQuerystring:i,kSchemaBody:a,kSchemaResponse:o}=Pc(),s=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:c}=Lc(),{FSTWRN001:l}=Ic();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}})),Kc=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=Hc(),i=Wc(),{validate:a}=Gc(),{preValidationHookRunner:o,preHandlerHookRunner:s}=Rc(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:c}=Lc(),{setErrorStatusCode:l}=Uc(),{kReplyIsError:u,kRouteContext:d,kFourOhFourContext:f,kSupportedHTTPMethods:p}=Pc(),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}})),qc=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)}})})),Jc=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+`
|
|
122
122
|
causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
|
|
123
|
-
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)}})),Kc=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}}})),qc=o(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=Gc(),{pinoErrProto:a,pinoErrorSymbols:o}=Kc(),{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}})),Jc=o(((e,t)=>{t.exports=s;let{isErrorLike:n}=Gc(),{pinoErrProto:r,pinoErrorSymbols:i}=Kc(),{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}})),Yc=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)}}})),Xc=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)}}})),Zc=o(((e,t)=>{let n=qc(),r=Jc(),i=Yc(),a=Xc();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))}}}})),Qc=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}})),$c=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})),el=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}})),tl=o(((e,t)=>{let n=$c(),{redactFmtSym:r,wildcardFirstSym:i}=el(),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})),nl=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"`}}})),rl=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)}})),il=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}})),al=o(((e,t)=>{let n=require(`fs`),r=require(`events`),i=require(`util`).inherits,a=require(`path`),o=il(),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})),ol=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}})),sl=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`}})),cl=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}})),ll=o(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),ul=o(((e,t)=>{let{version:n}=sl(),{EventEmitter:r}=require(`events`),{Worker:i}=require(`worker_threads`),{join:a}=require(`path`),{pathToFileURL:o}=require(`url`),{wait:s}=cl(),{WRITE_INDEX:c,READ_INDEX:l}=ll(),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})),dl=o(((e,t)=>{let{createRequire:n}=require(`module`),{existsSync:r}=require(`node:fs`),i=Qc(),{join:a,isAbsolute:o,sep:s}=require(`node:path`),{fileURLToPath:c}=require(`node:url`),l=il(),u=ol(),d=ul();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})),fl=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=rl(),{mapHttpRequest:i,mapHttpResponse:a}=Zc(),o=al(),s=ol(),{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}=el(),{isMainThread:w}=require(`worker_threads`),T=dl(),[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,F),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 F(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function ne(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 I(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 re(e,t,n){return{level:e,bindings:t,log:n}}function L(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:ne,stringify:I,buildFormatters:re,normalizeDestFileDescriptor:L}})),pl=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`}}})),ml=o(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=el(),{noop:l,genLog:u}=fl(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=pl(),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}})),hl=o(((e,t)=>{t.exports={version:`10.3.1`}})),gl=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}=el(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:ee}=ml(),{asChindings:N,asJson:te,buildFormatters:P,stringify:F,noop:ne}=fl(),{version:I}=hl(),re=tl(),L={constructor:class{},child:ae,bindings:R,setBindings:oe,flush:le,isLevelEnabled:k,version:I,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]:ce,[l]:te,[o]:D,[a]:O};Object.setPrototypeOf(L,n.prototype),t.exports=function(){return Object.create(L)};let ie=e=>e;function ae(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!==ie&&(i[g]=P(r.level,ie,r.log)),i[s]=N(i,e),this.onChild!==ne&&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||ie,a||r.log)}else i[g]=P(r.level,ie,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=re(i.redact,F),n={stringify:e[x]};i[S]=F,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 R(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function oe(e){this[s]=N(this,e)}function se(e,t){return Object.assign(t,e)}function ce(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||se,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 le(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||ne):e&&e()}})),_l=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}})),vl=o(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=pl(),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})),yl=o(((e,t)=>{let n=require(`node:os`),r=Zc(),i=Qc(),a=tl(),o=nl(),s=gl(),c=el(),{configure:l}=_l(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=ml(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=pl(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=fl(),{version:w}=hl(),{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:F,errorKeySym:ne,nestedKeySym:I,mixinSym:re,levelCompSym:L,useOnlyCustomLevelsSym:ie,formattersSym:ae,hooksSym:R,nestedKeyStrSym:oe,mixinMergeStrategySym:se,msgPrefixSym:ce}=c,{epochTime:le,nullTime:ue}=o,{pid:de}=process,z=n.hostname(),fe=r.err,pe=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:de,hostname:z},serializers:Object.assign(Object.create(null),{err:fe}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:le,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),me=Object.assign(Object.create(null),r);function he(...e){let t={},{opts:n,stream:r}=pe(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:de,name:z,level:fe,customLevels:me,levelComparison:he,mixin:ge,mixinMergeStrategy:_e,useOnlyCustomLevels:ve,formatters:ye,hooks:be,depthLimit:xe,edgeLimit:Se,onChild:Ce,msgPrefix:we}=n,Te=l({maximumDepth:xe,maximumBreadth:Se}),Ee=b(ye.level,ye.bindings,ye.log),De=x.bind({[M]:Te}),Oe=o?a(o,De):{},ke=o?{stringify:Oe[E]}:{stringify:De},Ae=`}`+(c?`\r
|
|
123
|
+
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)}})),Yc=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}}})),Xc=o(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=Jc(),{pinoErrProto:a,pinoErrorSymbols:o}=Yc(),{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}})),Zc=o(((e,t)=>{t.exports=s;let{isErrorLike:n}=Jc(),{pinoErrProto:r,pinoErrorSymbols:i}=Yc(),{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}})),Qc=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)}}})),$c=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)}}})),el=o(((e,t)=>{let n=Xc(),r=Zc(),i=Qc(),a=$c();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))}}}})),tl=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}})),nl=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})),rl=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}})),il=o(((e,t)=>{let n=nl(),{redactFmtSym:r,wildcardFirstSym:i}=rl(),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})),al=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"`}}})),ol=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)}})),sl=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}})),cl=o(((e,t)=>{let n=require(`fs`),r=require(`events`),i=require(`util`).inherits,a=require(`path`),o=sl(),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})),ll=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}})),ul=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`}})),dl=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}})),fl=o(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),pl=o(((e,t)=>{let{version:n}=ul(),{EventEmitter:r}=require(`events`),{Worker:i}=require(`worker_threads`),{join:a}=require(`path`),{pathToFileURL:o}=require(`url`),{wait:s}=dl(),{WRITE_INDEX:c,READ_INDEX:l}=fl(),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})),ml=o(((e,t)=>{let{createRequire:n}=require(`module`),{existsSync:r}=require(`node:fs`),i=tl(),{join:a,isAbsolute:o,sep:s}=require(`node:path`),{fileURLToPath:c}=require(`node:url`),l=sl(),u=ll(),d=pl();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})),hl=o(((e,t)=>{let n=require(`node:diagnostics_channel`),r=ol(),{mapHttpRequest:i,mapHttpResponse:a}=el(),o=cl(),s=ll(),{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}=rl(),{isMainThread:w}=require(`worker_threads`),T=ml(),[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,F),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 F(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function ne(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 I(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 re(e,t,n){return{level:e,bindings:t,log:n}}function L(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:ne,stringify:I,buildFormatters:re,normalizeDestFileDescriptor:L}})),gl=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`}}})),_l=o(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=rl(),{noop:l,genLog:u}=hl(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=gl(),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}})),vl=o(((e,t)=>{t.exports={version:`10.3.1`}})),yl=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}=rl(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:ee}=_l(),{asChindings:N,asJson:te,buildFormatters:P,stringify:F,noop:ne}=hl(),{version:I}=vl(),re=il(),L={constructor:class{},child:ae,bindings:R,setBindings:oe,flush:le,isLevelEnabled:k,version:I,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]:ce,[l]:te,[o]:D,[a]:O};Object.setPrototypeOf(L,n.prototype),t.exports=function(){return Object.create(L)};let ie=e=>e;function ae(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!==ie&&(i[g]=P(r.level,ie,r.log)),i[s]=N(i,e),this.onChild!==ne&&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||ie,a||r.log)}else i[g]=P(r.level,ie,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=re(i.redact,F),n={stringify:e[x]};i[S]=F,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 R(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function oe(e){this[s]=N(this,e)}function se(e,t){return Object.assign(t,e)}function ce(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||se,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 le(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||ne):e&&e()}})),bl=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}})),xl=o(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=gl(),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})),Sl=o(((e,t)=>{let n=require(`node:os`),r=el(),i=tl(),a=il(),o=al(),s=yl(),c=rl(),{configure:l}=bl(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=_l(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=gl(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=hl(),{version:w}=vl(),{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:F,errorKeySym:ne,nestedKeySym:I,mixinSym:re,levelCompSym:L,useOnlyCustomLevelsSym:ie,formattersSym:ae,hooksSym:R,nestedKeyStrSym:oe,mixinMergeStrategySym:se,msgPrefixSym:ce}=c,{epochTime:le,nullTime:ue}=o,{pid:de}=process,z=n.hostname(),fe=r.err,pe=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:de,hostname:z},serializers:Object.assign(Object.create(null),{err:fe}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:le,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),me=Object.assign(Object.create(null),r);function he(...e){let t={},{opts:n,stream:r}=pe(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:de,name:z,level:fe,customLevels:me,levelComparison:he,mixin:ge,mixinMergeStrategy:_e,useOnlyCustomLevels:ve,formatters:ye,hooks:be,depthLimit:xe,edgeLimit:Se,onChild:Ce,msgPrefix:we}=n,Te=l({maximumDepth:xe,maximumBreadth:Se}),Ee=b(ye.level,ye.bindings,ye.log),De=x.bind({[M]:Te}),Oe=o?a(o,De):{},ke=o?{stringify:Oe[E]}:{stringify:De},Ae=`}`+(c?`\r
|
|
124
124
|
`:`
|
|
125
|
-
`),je=v.bind(null,{[T]:``,[D]:g,[ee]:Oe,[j]:x,[M]:Te,[ae]:Ee}),Me=``;de!==null&&(Me=je(z===void 0?de:Object.assign({},de,{name:z})));let Ne=_ instanceof Function?_:_?le:ue,Pe=Ne().indexOf(`:`)+1;if(ve&&!me)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(ge&&typeof ge!=`function`)throw Error(`Unknown mixin type "${typeof ge}" - expected "function"`);if(we&&typeof we!=`string`)throw Error(`Unknown msgPrefix type "${typeof we}" - expected "string"`);u(fe,me,ve);let Fe=d(me,ve);typeof r.emit==`function`&&r.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Fe,messageKey:y,errorKey:S}}),m(he);let Ie=p(he);return Object.assign(t,{levels:Fe,[L]:Ie,[ie]:ve,[A]:r,[O]:Ne,[k]:Pe,[j]:x,[M]:Te,[ee]:Oe,[te]:Ae,[P]:ke,[F]:y,[ne]:S,[I]:w,[oe]:w?`,${JSON.stringify(w)}:{`:``,[D]:g,[re]:ge,[se]:_e,[T]:Me,[ae]:Ee,[R]:be,silent:C,onChild:Ce,[ce]:we}),Object.setPrototypeOf(t,s()),f(t),t[N](fe),t}t.exports=he,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=dl(),t.exports.multistream=vl(),t.exports.levels=d(),t.exports.stdSerializers=me,t.exports.stdTimeFunctions=Object.assign({},o),t.exports.symbols=c,t.exports.version=w,t.exports.default=he,t.exports.pino=he})),bl=o(((e,t)=>{let n=yl(),{serializersSym:r}=n.symbols,{FST_ERR_LOG_INVALID_DESTINATION:i}=Pc();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}})),xl=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}=Pc();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=Wc();return e.child=()=>e,{logger:e,hasLogger:!1}}let{createPinoLogger:t,serializers:a}=bl();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}})),Sl=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}}})),Cl=o(((e,t)=>{let n=Sl()({circles:!1,proto:!0}),{kSchemaVisited:r,kSchemaResponse:i}=jc(),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}=Pc(),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}})),wl=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)}}})),Tl=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,wl().restoreFromState({mode:`standalone`}))})),El=o(((e,t)=>{let n=require(`node:http`).STATUS_CODES,r=Vc(),{setErrorStatusCode:i}=Bc(),{kReplyHeaders:a,kReplyNextErrorHandler:o,kReplyIsRunningOnErrorHook:s,kRouteContext:c,kDisableRequestLogging:l}=jc(),{FST_ERR_REP_INVALID_PAYLOAD_TYPE:u,FST_ERR_FAILED_ERROR_SERIALIZATION:d}=Pc(),{getSchemaSerializer:f}=Cl(),p=Tl(),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}})),Dl=o(((e,t)=>{let{kReply:n,kRequest:r,kState:i,kHasBeenDecorated:a}=jc(),{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}=Pc();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}})),Ol=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}=jc(),{onSendHookRunner:S,onResponseHookRunner:C,preHandlerHookRunner:w,preSerializationHookRunner:T}=Fc(),E=Uc()[Symbol.for(`internals`)],D=xl().now,{handleError:O}=El(),{getSchemaSerializer:k}=Cl(),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:F,FST_ERR_BAD_TRAILER_VALUE:ne,FST_ERR_MISSING_SERIALIZATION_FN:I,FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:re,FST_ERR_DEC_UNDECLARED:L}=Pc(),ie=Dl(),ae=Object.prototype.toString;function R(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}R.props=[],Object.defineProperties(R.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}}}),R.prototype.writeEarlyHints=function(e,t){return this.raw.writeEarlyHints(e,t),this},R.prototype.hijack=function(){return this[a]=!0,this},R.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,ve(this,e,ue),this;if(e===void 0)return ue(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`||ae.call(e)===`[object Response]`)return ue(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 ue(this,t),this}if(!n&&typeof e==`string`)return this[d][`content-type`]=A.PLAIN,ue(this,e),this}if(this[c]!==null){if(typeof e!=`string`)return se(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 se(this,e),this}return ue(this,e),this},R.prototype.getHeader=function(e){e=e.toLowerCase();let t=this[d][e];return t===void 0?this.raw.getHeader(e):t},R.prototype.getHeaders=function(){return{...this.raw.getHeaders(),...this[d]}},R.prototype.hasHeader=function(e){return e=e.toLowerCase(),this[d][e]!==void 0||this.raw.hasHeader(e)},R.prototype.removeHeader=function(e){return delete this[d][e.toLowerCase()],this},R.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},R.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 oe=new Set([`transfer-encoding`,`content-length`,`host`,`cache-control`,`max-forwards`,`te`,`authorization`,`set-cookie`,`content-encoding`,`content-type`,`content-range`,`trailer`]);R.prototype.trailer=function(e,t){if(e=e.toLowerCase(),oe.has(e))throw new F(e);if(typeof t!=`function`)throw new ne(e,typeof t);return this[f]===null&&(this[f]={}),this[f][e]=t,this},R.prototype.hasTrailer=function(e){return this[f]?.[e.toLowerCase()]!==void 0},R.prototype.removeTrailer=function(e){return this[f]===null||(this[f][e.toLowerCase()]=void 0),this},R.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},R.prototype.status=R.prototype.code,R.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},R.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},R.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 re(n,r):new I(n)}else a=this[x][v]?.has(t)?this[x][v].get(t):this.compileSerializationSchema(t,n,r);return a(e)},R.prototype.serialize=function(e){return this[c]===null?this[x]&&this[x][l]?this[x][l](e,this.raw.statusCode):Ce(this[x],e,this.raw.statusCode):this[c](e)},R.prototype.serializer=function(e){return this[c]=e,this},R.prototype.type=function(e){return this[d][`content-type`]=e,this},R.prototype.redirect=function(e,t){return t||=this[p]?this.raw.statusCode:302,this.header(`location`,e).code(t).send()},R.prototype.callNotFound=function(){return Se(this),this},R.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()})},R.prototype.getDecorator=function(e){if(!ie.hasKey(this,e)&&!ie.exist(this,e))throw new L(e,`reply`);let t=this[e];return typeof t==`function`?t.bind(this):t};function se(e,t){e[x].preSerialization===null?ce(null,void 0,e,t):T(e[x].preSerialization,e.request,e,t,ce)}function ce(e,t,n,r){if(e!=null){ve(n,e);return}try{r=n[c]===null?n[x]&&n[x][l]?n[x][l](r,n.raw.statusCode):Ce(n[x],r,n.raw.statusCode,n[d][`content-type`]):n[c](r)}catch(e){le(e,n),ve(n,e);return}ue(n,r)}function le(e,t){e.serialization=t[x].config}function ue(e,t){e[x].onSend===null?fe(e,t):S(e[x].onSend,e.request,e,t,de)}function de(e,t,n,r){e==null?fe(n,r):ve(n,e)}function z(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 fe(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(ae.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`),z(e,i),ge(t,n,e);return}if(i>=100&&i<200||i===204){e.removeHeader(`content-type`),e.removeHeader(`content-length`),z(e,i),ge(void 0,n,e),typeof t.resume==`function`&&(t.on(`error`,we),t.resume());return}if(typeof t.pipe==`function`){he(t,n,e);return}if(typeof t.getReader==`function`){me(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))}z(e,i),n.write(t),ge(t,n,e)}function pe(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 me(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,pe(r.log,e,t)),s.cancel().catch(we))}),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,ge(null,t,r);return}if(t.destroyed){i=!1,s.cancel().catch(we);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,pe(r.log,e,r)),t.destroy()):ve(r,e)}s.read().then(c,u)}function he(e,t,r){let i=!0,a=!1;if(_e(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,pe(r.log,e,r)),t.destroy()):ve(r,e))}),n(t,function(n){i&&(n!=null&&t.headersSent&&!a&&(a=!0,pe(r.log,n,t)),typeof e.destroy==`function`?e.destroy():typeof e.close==`function`?e.close(we):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 ge(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 _e(e,t,n){n[f]!==null&&e.on(`end`,()=>ge(null,t,n))}function ve(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 ye(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,be):be(n,e.request,e)};e.raw.on(`finish`,t),e.raw.on(`error`,t)}function be(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 xe(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 Se(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 Ce(e,t,n,r){let i=k(e,n,r);return i?i(t):JSON.stringify(t)}function we(){}t.exports=R,t.exports.buildReply=xe,t.exports.setupResponseListeners=ye})),kl=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})),Al=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)})),jl=o(((e,t)=>{t.exports=m,t.exports.default=m,t.exports.proxyaddr=m,t.exports.all=c,t.exports.compile=l;let n=kl(),r=Al(),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)}}})),Ml=o(((e,t)=>{let n=jl(),{kHasBeenDecorated:r,kSchemaBody:i,kSchemaHeaders:a,kSchemaParams:o,kSchemaQuerystring:s,kSchemaController:c,kOptions:l,kRequestCacheValidateFns:u,kRouteContext:d,kRequestOriginalUrl:f}=jc(),{FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:p,FST_ERR_DEC_UNDECLARED:m}=Pc(),h=Dl(),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})),Nl=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}=jc();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})),Pl=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})),Fl=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})),Il=o(((e,t)=>{let{AsyncResource:n}=require(`node:async_hooks`),{FifoMap:r}=Pl(),{parse:i}=Fl(),a=zc(),{kDefaultJsonParse:o,kContentTypeParser:s,kBodyLimit:c,kRequestPayloadStream:l,kState:u,kTestInternals:d,kReplyIsError:f,kRouteContext:p}=jc(),{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}=Pc(),{FSTSEC001:T}=Nc();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}})),Ll=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})),Rl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Ll();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}}})),Q=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=Ll(),n=Rl();var r=Ll();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=Rl();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?`
|
|
126
|
-
`:``},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._)`!${F(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._)`${F(n)} ${e} ${F(r)}`}function F(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),$=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=Q(),n=Ll();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})),zl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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`)}})),Bl=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=Q(),n=$(),r=zl();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])}})),Vl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Bl(),n=Q(),r=zl(),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)}})),Hl=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})),Ul=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})),Wl=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=Hl(),n=Ul(),r=Bl(),i=Q(),a=$();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
|
|
125
|
+
`),je=v.bind(null,{[T]:``,[D]:g,[ee]:Oe,[j]:x,[M]:Te,[ae]:Ee}),Me=``;de!==null&&(Me=je(z===void 0?de:Object.assign({},de,{name:z})));let Ne=_ instanceof Function?_:_?le:ue,Pe=Ne().indexOf(`:`)+1;if(ve&&!me)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(ge&&typeof ge!=`function`)throw Error(`Unknown mixin type "${typeof ge}" - expected "function"`);if(we&&typeof we!=`string`)throw Error(`Unknown msgPrefix type "${typeof we}" - expected "string"`);u(fe,me,ve);let Fe=d(me,ve);typeof r.emit==`function`&&r.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Fe,messageKey:y,errorKey:S}}),m(he);let Ie=p(he);return Object.assign(t,{levels:Fe,[L]:Ie,[ie]:ve,[A]:r,[O]:Ne,[k]:Pe,[j]:x,[M]:Te,[ee]:Oe,[te]:Ae,[P]:ke,[F]:y,[ne]:S,[I]:w,[oe]:w?`,${JSON.stringify(w)}:{`:``,[D]:g,[re]:ge,[se]:_e,[T]:Me,[ae]:Ee,[R]:be,silent:C,onChild:Ce,[ce]:we}),Object.setPrototypeOf(t,s()),f(t),t[N](fe),t}t.exports=he,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=ml(),t.exports.multistream=xl(),t.exports.levels=d(),t.exports.stdSerializers=me,t.exports.stdTimeFunctions=Object.assign({},o),t.exports.symbols=c,t.exports.version=w,t.exports.default=he,t.exports.pino=he})),Cl=o(((e,t)=>{let n=Sl(),{serializersSym:r}=n.symbols,{FST_ERR_LOG_INVALID_DESTINATION:i}=Lc();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}})),wl=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}=Lc();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=qc();return e.child=()=>e,{logger:e,hasLogger:!1}}let{createPinoLogger:t,serializers:a}=Cl();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}})),Tl=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}}})),El=o(((e,t)=>{let n=Tl()({circles:!1,proto:!0}),{kSchemaVisited:r,kSchemaResponse:i}=Pc(),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}=Lc(),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}})),Dl=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)}}})),Ol=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,Dl().restoreFromState({mode:`standalone`}))})),kl=o(((e,t)=>{let n=require(`node:http`).STATUS_CODES,r=Wc(),{setErrorStatusCode:i}=Uc(),{kReplyHeaders:a,kReplyNextErrorHandler:o,kReplyIsRunningOnErrorHook:s,kRouteContext:c,kDisableRequestLogging:l}=Pc(),{FST_ERR_REP_INVALID_PAYLOAD_TYPE:u,FST_ERR_FAILED_ERROR_SERIALIZATION:d}=Lc(),{getSchemaSerializer:f}=El(),p=Ol(),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}})),Al=o(((e,t)=>{let{kReply:n,kRequest:r,kState:i,kHasBeenDecorated:a}=Pc(),{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}=Lc();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}})),jl=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}=Pc(),{onSendHookRunner:S,onResponseHookRunner:C,preHandlerHookRunner:w,preSerializationHookRunner:T}=Rc(),E=Kc()[Symbol.for(`internals`)],D=wl().now,{handleError:O}=kl(),{getSchemaSerializer:k}=El(),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:F,FST_ERR_BAD_TRAILER_VALUE:ne,FST_ERR_MISSING_SERIALIZATION_FN:I,FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:re,FST_ERR_DEC_UNDECLARED:L}=Lc(),ie=Al(),ae=Object.prototype.toString;function R(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}R.props=[],Object.defineProperties(R.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}}}),R.prototype.writeEarlyHints=function(e,t){return this.raw.writeEarlyHints(e,t),this},R.prototype.hijack=function(){return this[a]=!0,this},R.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,ve(this,e,ue),this;if(e===void 0)return ue(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`||ae.call(e)===`[object Response]`)return ue(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 ue(this,t),this}if(!n&&typeof e==`string`)return this[d][`content-type`]=A.PLAIN,ue(this,e),this}if(this[c]!==null){if(typeof e!=`string`)return se(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 se(this,e),this}return ue(this,e),this},R.prototype.getHeader=function(e){e=e.toLowerCase();let t=this[d][e];return t===void 0?this.raw.getHeader(e):t},R.prototype.getHeaders=function(){return{...this.raw.getHeaders(),...this[d]}},R.prototype.hasHeader=function(e){return e=e.toLowerCase(),this[d][e]!==void 0||this.raw.hasHeader(e)},R.prototype.removeHeader=function(e){return delete this[d][e.toLowerCase()],this},R.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},R.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 oe=new Set([`transfer-encoding`,`content-length`,`host`,`cache-control`,`max-forwards`,`te`,`authorization`,`set-cookie`,`content-encoding`,`content-type`,`content-range`,`trailer`]);R.prototype.trailer=function(e,t){if(e=e.toLowerCase(),oe.has(e))throw new F(e);if(typeof t!=`function`)throw new ne(e,typeof t);return this[f]===null&&(this[f]={}),this[f][e]=t,this},R.prototype.hasTrailer=function(e){return this[f]?.[e.toLowerCase()]!==void 0},R.prototype.removeTrailer=function(e){return this[f]===null||(this[f][e.toLowerCase()]=void 0),this},R.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},R.prototype.status=R.prototype.code,R.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},R.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},R.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 re(n,r):new I(n)}else a=this[x][v]?.has(t)?this[x][v].get(t):this.compileSerializationSchema(t,n,r);return a(e)},R.prototype.serialize=function(e){return this[c]===null?this[x]&&this[x][l]?this[x][l](e,this.raw.statusCode):Ce(this[x],e,this.raw.statusCode):this[c](e)},R.prototype.serializer=function(e){return this[c]=e,this},R.prototype.type=function(e){return this[d][`content-type`]=e,this},R.prototype.redirect=function(e,t){return t||=this[p]?this.raw.statusCode:302,this.header(`location`,e).code(t).send()},R.prototype.callNotFound=function(){return Se(this),this},R.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()})},R.prototype.getDecorator=function(e){if(!ie.hasKey(this,e)&&!ie.exist(this,e))throw new L(e,`reply`);let t=this[e];return typeof t==`function`?t.bind(this):t};function se(e,t){e[x].preSerialization===null?ce(null,void 0,e,t):T(e[x].preSerialization,e.request,e,t,ce)}function ce(e,t,n,r){if(e!=null){ve(n,e);return}try{r=n[c]===null?n[x]&&n[x][l]?n[x][l](r,n.raw.statusCode):Ce(n[x],r,n.raw.statusCode,n[d][`content-type`]):n[c](r)}catch(e){le(e,n),ve(n,e);return}ue(n,r)}function le(e,t){e.serialization=t[x].config}function ue(e,t){e[x].onSend===null?fe(e,t):S(e[x].onSend,e.request,e,t,de)}function de(e,t,n,r){e==null?fe(n,r):ve(n,e)}function z(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 fe(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(ae.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`),z(e,i),ge(t,n,e);return}if(i>=100&&i<200||i===204){e.removeHeader(`content-type`),e.removeHeader(`content-length`),z(e,i),ge(void 0,n,e),typeof t.resume==`function`&&(t.on(`error`,we),t.resume());return}if(typeof t.pipe==`function`){he(t,n,e);return}if(typeof t.getReader==`function`){me(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))}z(e,i),n.write(t),ge(t,n,e)}function pe(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 me(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,pe(r.log,e,t)),s.cancel().catch(we))}),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,ge(null,t,r);return}if(t.destroyed){i=!1,s.cancel().catch(we);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,pe(r.log,e,r)),t.destroy()):ve(r,e)}s.read().then(c,u)}function he(e,t,r){let i=!0,a=!1;if(_e(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,pe(r.log,e,r)),t.destroy()):ve(r,e))}),n(t,function(n){i&&(n!=null&&t.headersSent&&!a&&(a=!0,pe(r.log,n,t)),typeof e.destroy==`function`?e.destroy():typeof e.close==`function`?e.close(we):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 ge(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 _e(e,t,n){n[f]!==null&&e.on(`end`,()=>ge(null,t,n))}function ve(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 ye(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,be):be(n,e.request,e)};e.raw.on(`finish`,t),e.raw.on(`error`,t)}function be(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 xe(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 Se(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 Ce(e,t,n,r){let i=k(e,n,r);return i?i(t):JSON.stringify(t)}function we(){}t.exports=R,t.exports.buildReply=xe,t.exports.setupResponseListeners=ye})),Ml=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})),Nl=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)})),Pl=o(((e,t)=>{t.exports=m,t.exports.default=m,t.exports.proxyaddr=m,t.exports.all=c,t.exports.compile=l;let n=Ml(),r=Nl(),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)}}})),Fl=o(((e,t)=>{let n=Pl(),{kHasBeenDecorated:r,kSchemaBody:i,kSchemaHeaders:a,kSchemaParams:o,kSchemaQuerystring:s,kSchemaController:c,kOptions:l,kRequestCacheValidateFns:u,kRouteContext:d,kRequestOriginalUrl:f}=Pc(),{FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:p,FST_ERR_DEC_UNDECLARED:m}=Lc(),h=Al(),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})),Il=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}=Pc();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})),Ll=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})),Rl=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})),zl=o(((e,t)=>{let{AsyncResource:n}=require(`node:async_hooks`),{FifoMap:r}=Ll(),{parse:i}=Rl(),a=Hc(),{kDefaultJsonParse:o,kContentTypeParser:s,kBodyLimit:c,kRequestPayloadStream:l,kState:u,kTestInternals:d,kReplyIsError:f,kRouteContext:p}=Pc(),{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}=Lc(),{FSTSEC001:T}=Ic();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}})),Bl=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})),Vl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Bl();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}}})),Q=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=Bl(),n=Vl();var r=Bl();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=Vl();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?`
|
|
126
|
+
`:``},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._)`!${F(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._)`${F(n)} ${e} ${F(r)}`}function F(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),$=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=Q(),n=Bl();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})),Hl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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`)}})),Ul=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=Q(),n=$(),r=Hl();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])}})),Wl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Ul(),n=Q(),r=Hl(),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)}})),Gl=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})),Kl=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})),ql=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=Gl(),n=Kl(),r=Ul(),i=Q(),a=$();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
|
|
127
127
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
|
|
128
128
|
|| (${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"
|
|
129
|
-
|| ${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}}})),Gl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=Q(),n=$();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)}`)}})),Kl=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=Q(),n=$(),r=zl(),i=$();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})),ql=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Q(),n=zl(),r=Kl(),i=Bl();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})),Jl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Q(),n=$();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})),Yl=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}})),Xl=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`)}})),Zl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=$(),n=Yl(),r=Xl(),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})),Ql=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Vl(),n=Wl(),r=Ul(),i=Wl(),a=Gl(),o=ql(),s=Jl(),c=Q(),l=zl(),u=Zl(),d=$(),f=Bl();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(()=>R(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)&&R(e,n.keyword,n.definition,t.type)})}function te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P(e,t),e.opts.allowUnionTypes||F(e,t),ne(e,e.dataTypes))}function P(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{re(e.dataTypes,t)||ie(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),L(e,t)}}function F(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ie(e,`use allowUnionTypes to allow union type keyword`)}function ne(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=>I(t,e))&&ie(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function I(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function re(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function L(e,t){let n=[];for(let r of e.dataTypes)re(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ie(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ae=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`,ce(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=ae;function R(e,t,n,r){let i=new ae(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 oe=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ce(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!oe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=se.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=ce})),$l=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}}})),eu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Zl();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))}}})),tu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Q(),n=$l(),r=zl(),i=Zl(),a=$(),o=Ql();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}})),nu=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}})),ru=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}})),iu=o(((e,t)=>{let{isUUID:n}=ru(),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}})),au=o(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=ru(),{SCHEMES:c,getSchemeHandler:l}=iu();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=_})),ou=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=au();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),su=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=Ql();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Q();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=$l(),i=eu(),a=Hl(),o=tu(),s=Q(),c=Zl(),l=Wl(),u=$(),d=nu(),f=ou(),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]}}})),cu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),lu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=eu(),n=Kl(),r=Q(),i=zl(),a=tu(),o=$(),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})),uu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=cu(),n=lu();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),du=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),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})`)}}})),fu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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}))`)}}})),pu=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`})),mu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=pu();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}`)}}})),hu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kl(),n=$(),r=Q();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})`)}}}})),gu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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}`)}}})),_u=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kl(),n=Q(),r=$();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)}}}})),vu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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}`)}}})),yu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Yl();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),bu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Wl(),n=Q(),r=$(),i=yu();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)})))}}}})),xu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=yu();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}`)}}})),Su=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=yu();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}`}}}})),Cu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=du(),n=fu(),r=mu(),i=hu(),a=gu(),o=_u(),s=vu(),c=bu(),l=xu(),u=Su();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]})),wu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=Q(),n=$(),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})),Tu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=Q(),n=$(),r=Kl(),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})),Eu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Tu();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Du=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=Kl(),i=wu();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)))}}})),Ou=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$();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)))}}}})),ku=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Q(),n=$(),r=Kl();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},
|
|
129
|
+
|| ${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}}})),Jl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=Q(),n=$();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)}`)}})),Yl=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=Q(),n=$(),r=Hl(),i=$();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})),Xl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Q(),n=Hl(),r=Yl(),i=Ul();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})),Zl=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Q(),n=$();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})),Ql=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}})),$l=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`)}})),eu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=$(),n=Ql(),r=$l(),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})),tu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Wl(),n=ql(),r=Kl(),i=ql(),a=Jl(),o=Xl(),s=Zl(),c=Q(),l=Hl(),u=eu(),d=$(),f=Ul();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(()=>R(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)&&R(e,n.keyword,n.definition,t.type)})}function te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(P(e,t),e.opts.allowUnionTypes||F(e,t),ne(e,e.dataTypes))}function P(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{re(e.dataTypes,t)||ie(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),L(e,t)}}function F(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ie(e,`use allowUnionTypes to allow union type keyword`)}function ne(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=>I(t,e))&&ie(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function I(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function re(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function L(e,t){let n=[];for(let r of e.dataTypes)re(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ie(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ae=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`,ce(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=ae;function R(e,t,n,r){let i=new ae(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 oe=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ce(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!oe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=se.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=ce})),nu=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}}})),ru=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=eu();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))}}})),iu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Q(),n=nu(),r=Hl(),i=eu(),a=$(),o=tu();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}})),au=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}})),ou=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}})),su=o(((e,t)=>{let{isUUID:n}=ou(),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}})),cu=o(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=ou(),{SCHEMES:c,getSchemeHandler:l}=su();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=_})),lu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=cu();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),uu=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=tu();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Q();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=nu(),i=ru(),a=Gl(),o=iu(),s=Q(),c=eu(),l=ql(),u=$(),d=au(),f=lu(),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]}}})),du=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),fu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=ru(),n=Yl(),r=Q(),i=Hl(),a=iu(),o=$(),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})),pu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=du(),n=fu();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),mu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),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})`)}}})),hu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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}))`)}}})),gu=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`})),_u=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=gu();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}`)}}})),vu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Yl(),n=$(),r=Q();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})`)}}}})),yu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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}`)}}})),bu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Yl(),n=Q(),r=$();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)}}}})),xu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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}`)}}})),Su=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ql();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),Cu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ql(),n=Q(),r=$(),i=Su();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)})))}}}})),wu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=Su();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}`)}}})),Tu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=Su();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}`}}}})),Eu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=mu(),n=hu(),r=_u(),i=vu(),a=yu(),o=bu(),s=xu(),c=Cu(),l=wu(),u=Tu();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]})),Du=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=Q(),n=$(),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})),Ou=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=Q(),n=$(),r=Yl(),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})),ku=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ou();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Au=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),r=Yl(),i=Du();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)))}}})),ju=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$();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)))}}}})),Mu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Q(),n=$(),r=Yl();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},
|
|
130
130
|
missingProperty: ${i},
|
|
131
131
|
depsCount: ${n},
|
|
132
|
-
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})),Au=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$();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)}}})),ju=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kl(),n=Q(),r=zl(),i=$();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)}}}})),Mu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ql(),n=Kl(),r=$(),i=ju();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)}}}})),Nu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kl(),n=Q(),r=$(),i=$();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())})})}}}})),Pu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$();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`}}})),Fu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Kl().validateUnion,error:{message:`must match a schema in anyOf`}}})),Iu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$();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)})})}}}})),Lu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$();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)})}}})),Ru=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),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})),zu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$();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`)}}})),Bu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wu(),n=Eu(),r=Tu(),i=Du(),a=Ou(),o=ku(),s=Au(),c=ju(),l=Mu(),u=Nu(),d=Pu(),f=Fu(),p=Iu(),m=Lu(),h=Ru(),g=zu();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=_})),Vu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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})`}}}}})),Hu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Vu().default]})),Uu=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`]})),Wu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=uu(),n=Cu(),r=Bu(),i=Hu(),a=Uu();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Gu=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={}))})),Ku=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Gu(),r=tu(),i=eu(),a=$();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}}}}})),qu=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}})),Ju=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=su(),r=Wu(),i=Ku(),a=qu(),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=Ql();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Q();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=$l();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=eu();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Yu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkMetadata=void 0;let t=$(),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})),Xu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hasRef=void 0;let t=tu(),n=Q(),r=eu(),i=zl(),a=lu(),o=Yu(),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})),Zu=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`})),Qu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.typeErrorParams=e.typeErrorMessage=e.typeError=void 0;let t=Q();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})),$u=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.intRange=void 0;let t=Q(),n=Zu(),r=$(),i=Yu(),a=Qu();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)}}})),ed=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkNullableObject=e.checkNullable=void 0;let t=Q();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})),td=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Yu(),r=ed();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()))}}}})),nd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$(),n=Kl(),r=Q(),i=Yu(),a=ed();e.default={keyword:`elements`,schemaType:`object`,error:(0,Qu().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)}}})),rd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateProperties=e.error=void 0;let t=Kl(),n=$(),r=Q(),i=Yu(),a=ed(),o=Qu();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})),id=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=rd();e.default={keyword:`optionalProperties`,schemaType:`object`,error:t.error,code(e){e.parentSchema.properties||(0,t.validateProperties)(e)}}})),ad=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Yu(),r=ed(),i=Qu(),a=Gu();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}}}})),od=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$(),n=Q(),r=Yu(),i=ed();e.default={keyword:`values`,schemaType:`object`,error:(0,Qu().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)})}}}}})),sd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`union`,schemaType:`array`,trackErrors:!0,code:Kl().validateUnion,error:{message:`must match a schema in union`}}})),cd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Xu(),n=$u(),r=td(),i=nd(),a=rd(),o=id(),s=ad(),c=od(),l=sd(),u=Yu();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`}]})),ld=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)}})),ud=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.jtdForms=void 0,e.jtdForms=[`elements`,`values`,`discriminator`,`properties`,`optionalProperties`,`enum`,`type`,`ref`]})),dd=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`})),fd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ud(),n=tu(),r=Q(),i=eu(),a=zl(),o=Kl(),s=Xu(),c=$(),l=dd(),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)`,`)}})),pd=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:`
|
|
133
|
-
`,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`})),md=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ud(),n=tu(),r=Q(),i=eu(),a=zl(),o=Kl(),s=Xu(),c=$u(),l=pd(),u=$(),d=Zu(),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),L(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)),ae(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,ae));function v(e,t){let{gen:n,schema:r,data:i}=e;if(!r.nullable)return t(e);re(e,`null`,t,()=>n.assign(i,null))}function y(e){let{gen:t,schema:n,data:i}=e;I(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;I(e,`{`),t.assign(i,(0,r._)`{}`),x(e,`}`,()=>C(e,n.values))}function x(e,t,n){S(e,t,n),I(e,t)}function S(e,t,n){let{gen:i}=e;i.for((0,r._)`;${a.default.jsonPos}<${a.default.jsonLen} && ${ie(1)}!==${t};`,()=>{n(),re(e,`,`,()=>i.break(),o)});function o(){re(e,t,()=>{},ae)}}function C(e,t){let{gen:n}=e,r=n.let(`key`);A({...e,data:r}),I(e,`:`),O(e,r,t)}function w(e){let{gen:t,data:n,schema:i}=e,{discriminator:o,mapping:s}=i;I(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}),I(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`),R(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(),R(e,(0,r.str)`discriminator value not in schema`),t.endIf()}function T(e){let{gen:t,data:n}=e;I(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}),I(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}]`}):R(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),()=>R(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,()=>R(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`,()=>R(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}`,()=>R(e,(0,r.str)`integer out of range`))}}}}function A(e){I(e,`"`),F(e,l.parseJsonString)}function j(e){let{gen:t,data:n,schema:i}=e,o=i.enum;I(e,`"`),t.if(!1);for(let e of o){let i=JSON.stringify(e).slice(1);t.elseIf((0,r._)`${ie(i.length)} === ${i}`),t.assign(n,(0,r.str)`${e}`),t.add(a.default.jsonPos,i.length)}t.else(),ae(e),t.endIf()}function M(e,t){let{gen:n}=e;L(e),n.if((0,r._)`"-0123456789".indexOf(${ie(1)}) < 0`,()=>ae(e),()=>F(e,l.parseJsonNumber,t))}function ee(e,t){return n=>{let{gen:r,data:i}=n;re(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;ne(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){F(e,l.parseJson)}function F(e,t,n){ne(e,(0,u.useFunc)(e.gen,t),n)}function ne(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`,()=>R(e,(0,r._)`${t}.message`))}function I(e,t){re(e,t,ae)}function re(e,t,n,i){let{gen:o}=e,s=t.length;L(e),o.if((0,r._)`${ie(s)} === ${t}`,()=>{o.add(a.default.jsonPos,s),i?.(e)},()=>n(e))}function L({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 ie(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 ae(e){R(e,(0,r._)`"unexpected token " + ${a.default.json}[${a.default.jsonPos}]`)}function R({gen:e,parseName:t},n){e.assign((0,r._)`${t}.message`,n),e.assign((0,r._)`${t}.position`,a.default.jsonPos),e.return(m)}})),hd=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=su(),r=cd(),i=ld(),a=fd(),o=md(),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=Ql();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Q();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=$l();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=eu();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),gd=o(((e,t)=>{let n=au();t.exports=Object.freeze({coerceTypes:`array`,useDefaults:!0,removeAdditional:!0,uriResolver:n,addUsedSchema:!1,allErrors:!1})})),_d=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}}})),vd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Ju(),n=Q(),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)})),yd=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=_d(),r=vd(),i=Q(),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})),bd=o(((e,t)=>{let n=Ju().default,r=hd(),i=gd();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&&yd()(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)}}})),xd=o(((e,t)=>{let n=hd(),r=gd();t.exports=class{constructor(e,t){this.ajv=new n(Object.assign({},r,t))}buildSerializerFunction({schema:e}){return this.ajv.compileSerializer(e)}}})),Sd=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Rl(),r=Ll();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})),Cd=o(((e,t)=>{let n=wd(),r=Sd().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})),wd=o(((e,t)=>{let n=Symbol.for(`fastify.ajv-compiler.reference`),r=bd(),i=xd();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=Cd()})),Td=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})),Ed=o(((e,t)=>{let{dequal:n}=Td(),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}})),Dd=o(((e,t)=>{let n=Ju(),r=au(),i=yd(),a=Sl()({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}}})),Od=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}}})),kd=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=_d().fullFormats.uri,o=_d().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=yu().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}})),Ad=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}".`}}}})),jd=o(((e,t)=>{let{dequal:n}=Td(),{MergeError:r}=Ad();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}})),Md=o(((e,t)=>{let{dequal:n}=Td(),r=jd(),i=Ad(),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}})),Nd=o(((e,t)=>{let{mergeSchemas:n}=Md();function r(e){return n(e,{onConflict:`skip`})}t.exports=r})),Pd=o(((e,t)=>{function n(e,t,n,r){let i=``;t.validatorSchemasIds.size>0?(i+=`const Validator = require('fast-json-stringify/lib/validator')
|
|
132
|
+
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})),Nu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$();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)}}})),Pu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Yl(),n=Q(),r=Hl(),i=$();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)}}}})),Fu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=tu(),n=Yl(),r=$(),i=Pu();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)}}}})),Iu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Yl(),n=Q(),r=$(),i=$();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())})})}}}})),Lu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$();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`}}})),Ru=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Yl().validateUnion,error:{message:`must match a schema in anyOf`}}})),zu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$();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)})})}}}})),Bu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$();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)})}}})),Vu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=$(),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})),Hu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$();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`)}}})),Uu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Du(),n=ku(),r=Ou(),i=Au(),a=ju(),o=Mu(),s=Nu(),c=Pu(),l=Fu(),u=Iu(),d=Lu(),f=Ru(),p=zu(),m=Bu(),h=Vu(),g=Hu();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=_})),Wu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q();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})`}}}}})),Gu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Wu().default]})),Ku=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`]})),qu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=pu(),n=Eu(),r=Uu(),i=Gu(),a=Ku();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Ju=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={}))})),Yu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Ju(),r=iu(),i=ru(),a=$();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}}}}})),Xu=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}})),Zu=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=uu(),r=qu(),i=Yu(),a=Xu(),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=tu();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Q();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=nu();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=ru();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Qu=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkMetadata=void 0;let t=$(),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})),$u=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hasRef=void 0;let t=iu(),n=Q(),r=ru(),i=Hl(),a=fu(),o=Qu(),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})),ed=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`})),td=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.typeErrorParams=e.typeErrorMessage=e.typeError=void 0;let t=Q();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})),nd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.intRange=void 0;let t=Q(),n=ed(),r=$(),i=Qu(),a=td();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)}}})),rd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkNullableObject=e.checkNullable=void 0;let t=Q();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})),id=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Qu(),r=rd();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()))}}}})),ad=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$(),n=Yl(),r=Q(),i=Qu(),a=rd();e.default={keyword:`elements`,schemaType:`object`,error:(0,td().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)}}})),od=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateProperties=e.error=void 0;let t=Yl(),n=$(),r=Q(),i=Qu(),a=rd(),o=td();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})),sd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=od();e.default={keyword:`optionalProperties`,schemaType:`object`,error:t.error,code(e){e.parentSchema.properties||(0,t.validateProperties)(e)}}})),cd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Q(),n=Qu(),r=rd(),i=td(),a=Ju();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}}}})),ld=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$(),n=Q(),r=Qu(),i=rd();e.default={keyword:`values`,schemaType:`object`,error:(0,td().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)})}}}}})),ud=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`union`,schemaType:`array`,trackErrors:!0,code:Yl().validateUnion,error:{message:`must match a schema in union`}}})),dd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$u(),n=nd(),r=id(),i=ad(),a=od(),o=sd(),s=cd(),c=ld(),l=ud(),u=Qu();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`}]})),fd=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)}})),pd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.jtdForms=void 0,e.jtdForms=[`elements`,`values`,`discriminator`,`properties`,`optionalProperties`,`enum`,`type`,`ref`]})),md=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`})),hd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=pd(),n=iu(),r=Q(),i=ru(),a=Hl(),o=Yl(),s=$u(),c=$(),l=md(),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)`,`)}})),gd=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:`
|
|
133
|
+
`,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`})),_d=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=pd(),n=iu(),r=Q(),i=ru(),a=Hl(),o=Yl(),s=$u(),c=nd(),l=gd(),u=$(),d=ed(),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),L(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)),ae(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,ae));function v(e,t){let{gen:n,schema:r,data:i}=e;if(!r.nullable)return t(e);re(e,`null`,t,()=>n.assign(i,null))}function y(e){let{gen:t,schema:n,data:i}=e;I(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;I(e,`{`),t.assign(i,(0,r._)`{}`),x(e,`}`,()=>C(e,n.values))}function x(e,t,n){S(e,t,n),I(e,t)}function S(e,t,n){let{gen:i}=e;i.for((0,r._)`;${a.default.jsonPos}<${a.default.jsonLen} && ${ie(1)}!==${t};`,()=>{n(),re(e,`,`,()=>i.break(),o)});function o(){re(e,t,()=>{},ae)}}function C(e,t){let{gen:n}=e,r=n.let(`key`);A({...e,data:r}),I(e,`:`),O(e,r,t)}function w(e){let{gen:t,data:n,schema:i}=e,{discriminator:o,mapping:s}=i;I(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}),I(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`),R(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(),R(e,(0,r.str)`discriminator value not in schema`),t.endIf()}function T(e){let{gen:t,data:n}=e;I(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}),I(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}]`}):R(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),()=>R(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,()=>R(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`,()=>R(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}`,()=>R(e,(0,r.str)`integer out of range`))}}}}function A(e){I(e,`"`),F(e,l.parseJsonString)}function j(e){let{gen:t,data:n,schema:i}=e,o=i.enum;I(e,`"`),t.if(!1);for(let e of o){let i=JSON.stringify(e).slice(1);t.elseIf((0,r._)`${ie(i.length)} === ${i}`),t.assign(n,(0,r.str)`${e}`),t.add(a.default.jsonPos,i.length)}t.else(),ae(e),t.endIf()}function M(e,t){let{gen:n}=e;L(e),n.if((0,r._)`"-0123456789".indexOf(${ie(1)}) < 0`,()=>ae(e),()=>F(e,l.parseJsonNumber,t))}function ee(e,t){return n=>{let{gen:r,data:i}=n;re(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;ne(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){F(e,l.parseJson)}function F(e,t,n){ne(e,(0,u.useFunc)(e.gen,t),n)}function ne(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`,()=>R(e,(0,r._)`${t}.message`))}function I(e,t){re(e,t,ae)}function re(e,t,n,i){let{gen:o}=e,s=t.length;L(e),o.if((0,r._)`${ie(s)} === ${t}`,()=>{o.add(a.default.jsonPos,s),i?.(e)},()=>n(e))}function L({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 ie(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 ae(e){R(e,(0,r._)`"unexpected token " + ${a.default.json}[${a.default.jsonPos}]`)}function R({gen:e,parseName:t},n){e.assign((0,r._)`${t}.message`,n),e.assign((0,r._)`${t}.position`,a.default.jsonPos),e.return(m)}})),vd=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=uu(),r=dd(),i=fd(),a=hd(),o=_d(),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=tu();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Q();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=nu();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=ru();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),yd=o(((e,t)=>{let n=cu();t.exports=Object.freeze({coerceTypes:`array`,useDefaults:!0,removeAdditional:!0,uriResolver:n,addUsedSchema:!1,allErrors:!1})})),bd=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}}})),xd=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Zu(),n=Q(),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)})),Sd=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=bd(),r=xd(),i=Q(),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})),Cd=o(((e,t)=>{let n=Zu().default,r=vd(),i=yd();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&&Sd()(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)}}})),wd=o(((e,t)=>{let n=vd(),r=yd();t.exports=class{constructor(e,t){this.ajv=new n(Object.assign({},r,t))}buildSerializerFunction({schema:e}){return this.ajv.compileSerializer(e)}}})),Td=o(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Vl(),r=Bl();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})),Ed=o(((e,t)=>{let n=Dd(),r=Td().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})),Dd=o(((e,t)=>{let n=Symbol.for(`fastify.ajv-compiler.reference`),r=Cd(),i=wd();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=Ed()})),Od=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})),kd=o(((e,t)=>{let{dequal:n}=Od(),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}})),Ad=o(((e,t)=>{let n=Zu(),r=cu(),i=Sd(),a=Tl()({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}}})),jd=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}}})),Md=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=bd().fullFormats.uri,o=bd().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=Su().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}})),Nd=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}".`}}}})),Pd=o(((e,t)=>{let{dequal:n}=Od(),{MergeError:r}=Nd();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}})),Fd=o(((e,t)=>{let{dequal:n}=Od(),r=Pd(),i=Nd(),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}})),Id=o(((e,t)=>{let{mergeSchemas:n}=Fd();function r(e){return n(e,{onConflict:`skip`})}t.exports=r})),Ld=o(((e,t)=>{function n(e,t,n,r){let i=``;t.validatorSchemasIds.size>0?(i+=`const Validator = require('fast-json-stringify/lib/validator')
|
|
134
134
|
`,i+=`const validatorState = ${JSON.stringify(r.getState())}\n`,i+=`const validator = Validator.restoreFromState(validatorState)
|
|
135
135
|
`):i+=`const validator = null
|
|
136
136
|
`;let{schema:a,...o}=n.getState();return`
|
|
@@ -142,7 +142,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
142
142
|
|
|
143
143
|
${i}
|
|
144
144
|
|
|
145
|
-
module.exports = ${e.toString()}(validator, serializer)`}t.exports=n,t.exports.dependencies={Serializer:
|
|
145
|
+
module.exports = ${e.toString()}(validator, serializer)`}t.exports=n,t.exports.dependencies={Serializer:Dl(),Validator:Ad()}})),Rd=o(((e,t)=>{let{RefResolver:n}=kd(),r=Dl(),i=Ad(),a=jd(),o=Md(),s=Id(),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=L(o,c,`input`),g=`
|
|
146
146
|
|
|
147
147
|
const {
|
|
148
148
|
asString,
|
|
@@ -182,7 +182,7 @@ const asInteger = serializer.asInteger.bind(serializer)
|
|
|
182
182
|
${o.functions.join(`
|
|
183
183
|
`)}
|
|
184
184
|
return main
|
|
185
|
-
`;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`?
|
|
185
|
+
`;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`?Ld()(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=`
|
|
186
186
|
for (const key of Object.keys(${r})) {
|
|
187
187
|
if (
|
|
188
188
|
${a.length>0?a.map(e=>`key === ${JSON.stringify(e)}`).join(` || `)+` ||`:``}
|
|
@@ -424,11 +424,11 @@ const asInteger = serializer.asInteger.bind(serializer)
|
|
|
424
424
|
} else {
|
|
425
425
|
`),r.const===void 0?Array.isArray(a)?i+=N(e,t,n):i+=te(e,t,n):i+=F(t,n),o&&(i+=`
|
|
426
426
|
}
|
|
427
|
-
`),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])}})),Id=o(((e,t)=>{let n=Fd();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})),Ld=o(((e,t)=>{let{SerializerSelector:n,StandaloneSerializer:r}=Id();t.exports=n,t.exports.default=n,t.exports.SerializerSelector=n,t.exports.StandaloneSerializer=r})),Rd=o(((e,t)=>{let{buildSchemas:n}=Cl();function r(e,t){if(e)return new i(e,t);let r=Object.assign({buildValidator:null,buildSerializer:null},t?.compilersFactory);return r.buildValidator||=wd()(),r.buildSerializer||=Ld()(),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})),zd=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}})),Bd=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):()=>{}})),Vd=o(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=zd(),a=Bd();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*$`)})),Hd=o(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),Ud=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)}})),Wd=o(((e,t)=>{let n=Bd(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=zd(),{safeRe:a,t:o}=Vd(),s=Hd(),{compareIdentifiers:c}=Ud();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}}})),Gd=o(((e,t)=>{let n=Wd();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}}})),Kd=o(((e,t)=>{let n=Gd();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),qd=o(((e,t)=>{let n=Gd();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),Jd=o(((e,t)=>{let n=Wd();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}}})),Yd=o(((e,t)=>{let n=Gd();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`}})),Xd=o(((e,t)=>{let n=Wd();t.exports=(e,t)=>new n(e,t).major})),Zd=o(((e,t)=>{let n=Wd();t.exports=(e,t)=>new n(e,t).minor})),Qd=o(((e,t)=>{let n=Wd();t.exports=(e,t)=>new n(e,t).patch})),$d=o(((e,t)=>{let n=Gd();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),ef=o(((e,t)=>{let n=Wd();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),tf=o(((e,t)=>{let n=ef();t.exports=(e,t,r)=>n(t,e,r)})),nf=o(((e,t)=>{let n=ef();t.exports=(e,t)=>n(e,t,!0)})),rf=o(((e,t)=>{let n=Wd();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),af=o(((e,t)=>{let n=rf();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),of=o(((e,t)=>{let n=rf();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),sf=o(((e,t)=>{let n=ef();t.exports=(e,t,r)=>n(e,t,r)>0})),cf=o(((e,t)=>{let n=ef();t.exports=(e,t,r)=>n(e,t,r)<0})),lf=o(((e,t)=>{let n=ef();t.exports=(e,t,r)=>n(e,t,r)===0})),uf=o(((e,t)=>{let n=ef();t.exports=(e,t,r)=>n(e,t,r)!==0})),df=o(((e,t)=>{let n=ef();t.exports=(e,t,r)=>n(e,t,r)>=0})),ff=o(((e,t)=>{let n=ef();t.exports=(e,t,r)=>n(e,t,r)<=0})),pf=o(((e,t)=>{let n=lf(),r=uf(),i=sf(),a=df(),o=cf(),s=ff();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}`)}}})),mf=o(((e,t)=>{let n=Wd(),r=Gd(),{safeRe:i,t:a}=Vd();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)}})),hf=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}}})),gf=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(hf()),i=Hd(),a=_f(),o=Bd(),s=Wd(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=Vd(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=zd(),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}})),_f=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=Hd(),{safeRe:i,t:a}=Vd(),o=pf(),s=Bd(),c=Wd(),l=gf()})),vf=o(((e,t)=>{let n=gf();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),yf=o(((e,t)=>{let n=gf();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),bf=o(((e,t)=>{let n=Wd(),r=gf();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}})),xf=o(((e,t)=>{let n=Wd(),r=gf();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}})),Sf=o(((e,t)=>{let n=Wd(),r=gf(),i=sf();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}})),Cf=o(((e,t)=>{let n=gf();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),wf=o(((e,t)=>{let n=Wd(),r=_f(),{ANY:i}=r,a=gf(),o=vf(),s=sf(),c=cf(),l=ff(),u=df();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}})),Tf=o(((e,t)=>{let n=wf();t.exports=(e,t,r)=>n(e,t,`>`,r)})),Ef=o(((e,t)=>{let n=wf();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Df=o(((e,t)=>{let n=gf();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),Of=o(((e,t)=>{let n=vf(),r=ef();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}})),kf=o(((e,t)=>{let n=gf(),r=_f(),{ANY:i}=r,a=vf(),o=ef(),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})),Af=o(((e,t)=>{let n=Vd(),r=zd(),i=Wd(),a=Ud();t.exports={parse:Gd(),valid:Kd(),clean:qd(),inc:Jd(),diff:Yd(),major:Xd(),minor:Zd(),patch:Qd(),prerelease:$d(),compare:ef(),rcompare:tf(),compareLoose:nf(),compareBuild:rf(),sort:af(),rsort:of(),gt:sf(),lt:cf(),eq:lf(),neq:uf(),gte:df(),lte:ff(),cmp:pf(),coerce:mf(),Comparator:_f(),Range:gf(),satisfies:vf(),toComparators:yf(),maxSatisfying:bf(),minSatisfying:xf(),minVersion:Sf(),validRange:Cf(),outside:wf(),gtr:Tf(),ltr:Ef(),intersects:Df(),simplifyRange:Of(),subset:kf(),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}})),jf=o(((e,t)=>{let n=Af(),r=require(`node:assert`),i=Symbol.for(`registered-plugin`),{kTestInternals:a}=jc(),{exist:o,existReply:s,existRequest:c}=Dl(),{FST_ERR_PLUGIN_VERSION_MISMATCH:l,FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:u,FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:d}=Pc(),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(`
|
|
428
|
-
`,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}})),Mf=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}})),Nf=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})),Pf=o(((e,t)=>{let n=Nf(),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})),Ff=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}})),If=o(((e,t)=>{let{encodeString:n}=Ff();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})),Lf=o(((e,t)=>{let n=Pf(),r=If(),i={parse:n,stringify:r};t.exports=i,t.exports.default=i,t.exports.parse=n,t.exports.stringify=r})),Rf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),zf=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||={})})),Bf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),Vf=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(Rf(),e),n(zf(),e),n(Bf(),e)})),Hf=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=Vf(),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})})),Uf=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=Vf(),a=r(Hf());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`)}})),Wf=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(Uf()),a=Vf(),o=r(Hf()),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)}}}}})),Gf=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(Hf()),a=Vf();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)})),Kf=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=Vf(),a=r(Gf());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)}})),qf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconstruct=void 0;let t=Vf(),n=Kf(),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}`)}}})),Jf=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=Vf();Object.defineProperty(e,`types`,{enumerable:!0,get:function(){return i.types}}),r(Wf(),e),r(qf(),e);let a=Wf(),o=qf();r(Vf(),e),e.default=a.tokenizer,t.exports=a.tokenizer,t.exports.types=i.types,t.exports.reconstruct=o.reconstruct})),Yf=o(((e,t)=>{let n=Jf(),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})),Xf=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}})),Zf=o(((e,t)=>{let n=Yl(),r=Xf(),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(`
|
|
427
|
+
`),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])}})),zd=o(((e,t)=>{let n=Rd();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})),Bd=o(((e,t)=>{let{SerializerSelector:n,StandaloneSerializer:r}=zd();t.exports=n,t.exports.default=n,t.exports.SerializerSelector=n,t.exports.StandaloneSerializer=r})),Vd=o(((e,t)=>{let{buildSchemas:n}=El();function r(e,t){if(e)return new i(e,t);let r=Object.assign({buildValidator:null,buildSerializer:null},t?.compilersFactory);return r.buildValidator||=Dd()(),r.buildSerializer||=Bd()(),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})),Hd=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}})),Ud=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):()=>{}})),Wd=o(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=Hd(),a=Ud();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*$`)})),Gd=o(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),Kd=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)}})),qd=o(((e,t)=>{let n=Ud(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=Hd(),{safeRe:a,t:o}=Wd(),s=Gd(),{compareIdentifiers:c}=Kd();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}}})),Jd=o(((e,t)=>{let n=qd();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}}})),Yd=o(((e,t)=>{let n=Jd();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),Xd=o(((e,t)=>{let n=Jd();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),Zd=o(((e,t)=>{let n=qd();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}}})),Qd=o(((e,t)=>{let n=Jd();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`}})),$d=o(((e,t)=>{let n=qd();t.exports=(e,t)=>new n(e,t).major})),ef=o(((e,t)=>{let n=qd();t.exports=(e,t)=>new n(e,t).minor})),tf=o(((e,t)=>{let n=qd();t.exports=(e,t)=>new n(e,t).patch})),nf=o(((e,t)=>{let n=Jd();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),rf=o(((e,t)=>{let n=qd();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),af=o(((e,t)=>{let n=rf();t.exports=(e,t,r)=>n(t,e,r)})),of=o(((e,t)=>{let n=rf();t.exports=(e,t)=>n(e,t,!0)})),sf=o(((e,t)=>{let n=qd();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),cf=o(((e,t)=>{let n=sf();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),lf=o(((e,t)=>{let n=sf();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),uf=o(((e,t)=>{let n=rf();t.exports=(e,t,r)=>n(e,t,r)>0})),df=o(((e,t)=>{let n=rf();t.exports=(e,t,r)=>n(e,t,r)<0})),ff=o(((e,t)=>{let n=rf();t.exports=(e,t,r)=>n(e,t,r)===0})),pf=o(((e,t)=>{let n=rf();t.exports=(e,t,r)=>n(e,t,r)!==0})),mf=o(((e,t)=>{let n=rf();t.exports=(e,t,r)=>n(e,t,r)>=0})),hf=o(((e,t)=>{let n=rf();t.exports=(e,t,r)=>n(e,t,r)<=0})),gf=o(((e,t)=>{let n=ff(),r=pf(),i=uf(),a=mf(),o=df(),s=hf();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}`)}}})),_f=o(((e,t)=>{let n=qd(),r=Jd(),{safeRe:i,t:a}=Wd();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)}})),vf=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}}})),yf=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(vf()),i=Gd(),a=bf(),o=Ud(),s=qd(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=Wd(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=Hd(),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}})),bf=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=Gd(),{safeRe:i,t:a}=Wd(),o=gf(),s=Ud(),c=qd(),l=yf()})),xf=o(((e,t)=>{let n=yf();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),Sf=o(((e,t)=>{let n=yf();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),Cf=o(((e,t)=>{let n=qd(),r=yf();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}})),wf=o(((e,t)=>{let n=qd(),r=yf();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}})),Tf=o(((e,t)=>{let n=qd(),r=yf(),i=uf();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}})),Ef=o(((e,t)=>{let n=yf();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),Df=o(((e,t)=>{let n=qd(),r=bf(),{ANY:i}=r,a=yf(),o=xf(),s=uf(),c=df(),l=hf(),u=mf();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}})),Of=o(((e,t)=>{let n=Df();t.exports=(e,t,r)=>n(e,t,`>`,r)})),kf=o(((e,t)=>{let n=Df();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Af=o(((e,t)=>{let n=yf();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),jf=o(((e,t)=>{let n=xf(),r=rf();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}})),Mf=o(((e,t)=>{let n=yf(),r=bf(),{ANY:i}=r,a=xf(),o=rf(),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})),Nf=o(((e,t)=>{let n=Wd(),r=Hd(),i=qd(),a=Kd();t.exports={parse:Jd(),valid:Yd(),clean:Xd(),inc:Zd(),diff:Qd(),major:$d(),minor:ef(),patch:tf(),prerelease:nf(),compare:rf(),rcompare:af(),compareLoose:of(),compareBuild:sf(),sort:cf(),rsort:lf(),gt:uf(),lt:df(),eq:ff(),neq:pf(),gte:mf(),lte:hf(),cmp:gf(),coerce:_f(),Comparator:bf(),Range:yf(),satisfies:xf(),toComparators:Sf(),maxSatisfying:Cf(),minSatisfying:wf(),minVersion:Tf(),validRange:Ef(),outside:Df(),gtr:Of(),ltr:kf(),intersects:Af(),simplifyRange:jf(),subset:Mf(),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}})),Pf=o(((e,t)=>{let n=Nf(),r=require(`node:assert`),i=Symbol.for(`registered-plugin`),{kTestInternals:a}=Pc(),{exist:o,existReply:s,existRequest:c}=Al(),{FST_ERR_PLUGIN_VERSION_MISMATCH:l,FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:u,FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:d}=Lc(),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(`
|
|
428
|
+
`,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}})),Ff=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}})),If=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})),Lf=o(((e,t)=>{let n=If(),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})),Rf=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}})),zf=o(((e,t)=>{let{encodeString:n}=Rf();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})),Bf=o(((e,t)=>{let n=Lf(),r=zf(),i={parse:n,stringify:r};t.exports=i,t.exports.default=i,t.exports.parse=n,t.exports.stringify=r})),Vf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),Hf=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||={})})),Uf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0})})),Wf=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(Vf(),e),n(Hf(),e),n(Uf(),e)})),Gf=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=Wf(),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})})),Kf=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=Wf(),a=r(Gf());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`)}})),qf=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(Kf()),a=Wf(),o=r(Gf()),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)}}}}})),Jf=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(Gf()),a=Wf();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)})),Yf=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=Wf(),a=r(Jf());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)}})),Xf=o((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconstruct=void 0;let t=Wf(),n=Yf(),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}`)}}})),Zf=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=Wf();Object.defineProperty(e,`types`,{enumerable:!0,get:function(){return i.types}}),r(qf(),e),r(Xf(),e);let a=qf(),o=Xf();r(Wf(),e),e.default=a.tokenizer,t.exports=a.tokenizer,t.exports.types=i.types,t.exports.reconstruct=o.reconstruct})),Qf=o(((e,t)=>{let n=Zf(),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})),$f=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}})),ep=o(((e,t)=>{let n=Ql(),r=$f(),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(`
|
|
429
429
|
`,`
|
|
430
430
|
`+t+d);n+=t+u+s+f+`
|
|
431
|
-
`,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}})),
|
|
431
|
+
`,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}})),tp=o(((e,t)=>{let n=function(){};n.prototype=Object.create(null),t.exports={NullObject:n}})),np=o(((e,t)=>{let{NullObject:n}=tp(),r=$f();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(`
|
|
432
432
|
`))(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(`
|
|
433
433
|
let candidates = ${(1<<this.handlers.length)-1}
|
|
434
434
|
let mask, matches
|
|
@@ -444,41 +444,41 @@ const asInteger = serializer.asInteger.bind(serializer)
|
|
|
444
444
|
}
|
|
445
445
|
if (candidates === 0) return null;
|
|
446
446
|
`)}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(`
|
|
447
|
-
`))}}})),
|
|
448
|
-
`)).bind(this)}}})),ip=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(`.`)})),ap=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}})),op=o(((e,t)=>{let n=require(`node:assert`),r=Lf(),i=Yf(),a=Yl(),{prettyPrintTree:o}=Zf(),{StaticNode:s,NODE_TYPES:c}=ep(),l=rp(),u=ip(),d=Xf(),{safeDecodeURI:f,safeDecodeURIComponent:p}=ap(),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)}})),sp=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}})),cp=o(((e,t)=>{let n=op(),r=Nl(),i=Uc(),{onRequestAbortHookRunner:a,lifecycleHooks:o,preParsingHookRunner:s,onTimeoutHookRunner:c,onRequestHookRunner:l}=Fc(),{normalizeSchema:u}=Cl(),{parseHeadOnSendHandlers:d}=sp(),{compileSchemasForValidation:f,compileSchemasForSerialization:p}=Hc(),{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}=Pc(),{kRoutePrefix:O,kSupportedHTTPMethods:k,kLogLevel:A,kLogSerializers:j,kHooks:M,kSchemaController:ee,kOptions:N,kReplySerializerDefault:te,kReplyIsError:P,kRequestPayloadStream:F,kDisableRequestLogging:ne,kSchemaErrorFormatter:I,kErrorHandler:re,kHasBeenDecorated:L,kRequestAcceptVersion:ie,kRouteByFastify:ae,kRouteContext:R}=jc(),{buildErrorHandler:oe}=El(),{createChildLogger:se}=xl(),{getGenReqId:ce}=Mf(),{FSTDEP022:le}=Nc(),ue=[`allowUnsafeRegex`,`buildPrettyMeta`,`caseSensitive`,`constraints`,`defaultRoute`,`ignoreDuplicateSlashes`,`ignoreTrailingSlash`,`maxParamLength`,`onBadUrl`,`querystringParser`,`useSemicolonDelimiter`];function de(e){let t=n(e),i,s,c,C,w,T,E,k,P,F,R,le,ue,de=!1;return{setup(e,t){i=t.avvio,s=t.fourOhFour,c=e.logger,C=t.hasLogger,w=t.setupResponseListeners,T=t.throwIfAlreadyStarted,le=e.exposeHeadRoutes,E=e.disableRequestLogging,typeof E==`function`&&(k=e.disableRequestLogging),P=e.routerOptions.ignoreTrailingSlash,F=e.routerOptions.ignoreDuplicateSlashes,R=Object.hasOwn(e,`return503OnClosing`)?e.return503OnClosing:!0,ue=t.keepAliveConnections},routing:t.lookup.bind(t),route:we,hasRoute:Se,prepareRoute:xe,routeHandler:Te,closeRoutes:()=>{de=!0},printRoutes:t.prettyPrint.bind(t),addConstraintStrategy:_e,hasConstraintStrategy:ye,isAsyncConstraint:be,findRoute:Ce};function _e(e){return T(`Cannot add constraint strategy!`),t.addConstraintStrategy(e)}function ye(e){return t.hasConstraintStrategy(e)}function be(){return t.constrainer.asyncStrategiesInUse.size>0}function xe({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}),we.call(this,{options:n,isFastify:i})}function Se({options:e}){let n=e.method?.toUpperCase()??``;return t.hasRoute(n,e.url||``,e.constraints)}function Ce(e){let n=t.find(e.method,e.url||``,e.constraints);return n?{handler:n.handler,params:n.params,searchParams:n.searchParams}:null}function we({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);he(a.bodyLimit);let l=a.exposeHeadRoute??le,_=!1,y=!1;if(Array.isArray(a.method))for(let e=0;e<a.method.length;++e)a.method[e]=pe.call(this,a.method[e]),me.call(this,a.method[e],c,a.schema),_=a.method.includes(`GET`),y=a.method.includes(`HEAD`);else a.method=pe.call(this,a.method),me.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&&(F!==!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},Te,T)}catch(e){if(!T[ae])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?oe(this[re],a.errorHandler):this[re],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[I]||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[L]&&T.Request.parent;)T.Request=T.Request.parent;for(;!T.Reply[L]&&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);xe.call(this,{method:`HEAD`,url:e,options:{...b,onSend:t},isFastify:!0})}}}function Te(e,t,n,r,i){let o=ce(r.server,e),s={level:r.logLevel};r.logSerializers&&(s.serializers=r.logSerializers);let u=se(r,c,e,o,s);if(u[ne]=k?!1:E,de===!0&&(e.httpVersionMajor!==2&&t.setHeader(`Connection`,`close`),R)){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`&&ue.has(e.socket)===!1&&(ue.add(e.socket),e.socket.on(`close`,ve.bind({keepAliveConnections:ue,socket:e.socket}))),e.headers[ie]!==void 0&&(e.headers[`accept-version`]=e.headers[ie],e.headers[ie]=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[ne]=p,p===!1&&u.info({req:d},`incoming request`),(C===!0||r.onResponse!==null)&&w(f),r.onRequest===null?ge(null,d,f):l(r.onRequest,d,f,ge),r.onRequestAbort!==null&&e.on(`close`,()=>{e.aborted&&a(r.onRequestAbort,d,z.bind(null,f))}),r.onTimeout!==null&&(d.raw.socket._meta||d.raw.socket.on(`timeout`,fe),d.raw.socket._meta={context:r,request:d,reply:f})}}function z(e,t){t&&e.log.error({err:t},`onRequestAborted hook failed`)}function fe(){let{context:e,request:t,reply:n}=this._meta;c(e.onTimeout,t,n,ye)}function pe(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 me(e,t,n){if(this[k].bodyless.has(e)&&n?.body)throw new T(e,t)}function he(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw new E(e)}function ge(e,t,n){if(n.sent!==!0){if(e!=null){n[P]=!0,n.send(e);return}t[F]=t.raw,t[R].preParsing===null?i.call(t.server,null,t,n):s(t[R].preParsing,t,n,i.bind(t.server))}}function _e(e,t){let n=e.routerOptions||Object.create(null),r=ue.filter(t=>Object.hasOwn(e,t));r.length>0&&le(r.join(`, `));for(let r of ue)Object.hasOwn(n,r)||(n[r]=e[r]??t[r]);return n}function ve(){this.keepAliveConnections.delete(this.socket)}function ye(){}t.exports={buildRouting:de,validateBodyLimitOption:he,buildRouterOptions:_e}})),lp=o(((e,t)=>{let n=op(),r=Ol(),i=Ml(),a=Nl(),{kRoutePrefix:o,kCanSetNotFoundHandler:s,kFourOhFourLevelInstance:c,kFourOhFourContext:l,kHooks:u,kErrorHandler:d}=jc(),{lifecycleHooks:f}=Fc(),{buildErrorHandler:p}=El(),{FST_ERR_NOT_FOUND:m}=Pc(),{createChildLogger:h}=xl(),{getGenReqId:g}=Mf();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=_})),up=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}}})),dp=o(((e,t)=>{let n=up(),r=Sl()({circles:!0,proto:!1}),{FST_ERR_INIT_OPTS_INVALID:i}=Pc();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}})),fp=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}=jc(),h=Ol(),g=Ml(),_=Rd(),v=Il(),{buildHooks:y}=Fc(),b=jf();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}})),pp=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]`}})),mp=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})),hp=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}})),gp=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
|
|
449
|
-
`),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})),_p=o(((e,t)=>{let{Readable:n,addAbortSignal:r}=require(`node:stream`),i=require(`node:util`),a=pp(),o=require(`node:assert`),{createDeprecation:s}=mp(),c=hp(),{isFormDataLike:l,formDataToStream:u}=gp(),{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})),vp=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})),yp=o(((e,t)=>{let n=require(`node:http`),{Writable:r,Readable:i,addAbortSignal:a}=require(`node:stream`),o=require(`node:util`),s=vp();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})),bp=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}})),xp=o(((e,t)=>{let n=require(`node:assert`),r=_p(),i=yp(),a=`The dispatch function has already been invoked`,o=bp();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})),Sp=o(((e,t)=>{let n=Ac(),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}=jc(),{createServer:j}=Rc(),M=Ol(),ee=Ml(),N=Nl(),te=Dl(),P=Il(),F=Rd(),{Hooks:ne,hookRunnerApplication:I,supportedHooks:re}=Fc(),{createChildLogger:L,defaultChildLoggerFactory:ie,createLogger:ae}=xl(),R=jf(),{getGenReqId:oe,reqIdGenFactory:se}=Mf(),{buildRouting:ce,validateBodyLimitOption:le,buildRouterOptions:ue}=cp(),de=lp(),z=dp(),fe=fp(),{appendStackTrace:pe,AVVIO_ERRORS_MAP:me,...he}=Pc(),ge=Lc(),{defaultInitOptions:_e}=z,{FST_ERR_ASYNC_CONSTRAINT:ve,FST_ERR_BAD_URL:ye,FST_ERR_OPTIONS_NOT_OBJ:be,FST_ERR_QSP_NOT_FN:xe,FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:Se,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:Ce,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:we,FST_ERR_INSTANCE_ALREADY_LISTENING:Te,FST_ERR_REOPENED_CLOSE_SERVER:Ee,FST_ERR_ROUTE_REWRITE_NOT_STR:De,FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:Oe,FST_ERR_ERROR_HANDLER_NOT_FN:ke,FST_ERR_ERROR_HANDLER_ALREADY_SET:Ae,FST_ERR_ROUTE_METHOD_INVALID:je}=he,{buildErrorHandler:Me}=El(),{FSTWRN004:Ne}=Nc(),Pe=i.channel(`fastify.initialization`);function Fe(e){let{options:t,genReqId:i,disableRequestLogging:ae,hasLogger:le,initialConfig:ue}=Ie(e,Xe,Ze),z=ce(t.routerOptions),be=de(t),xe=ct(z,t),{server:Se,listen:Ce,forceCloseConnections:we,serverHasCloseAllConnections:Oe,serverHasCloseHttp2Sessions:Fe,keepAliveConnections:Le}=j(t,xe),Re=M.setupResponseListeners,Be=F.buildSchemaController(null,t.schemaController),B={[S]:{listening:!1,closing:!1,started:!1,ready:!1,booting:!1,aborted:!1,readyResolver:null},[D]:Le,[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 ne,[h]:Be,[T]:null,[E]:Me(),[A]:!1,[O]:t.childLoggerFactory||ie,[_]:null,[v]:new P(t.bodyLimit,t.onProtoPoisoning||_e.onProtoPoisoning,t.onConstructorPoisoning||_e.onConstructorPoisoning),[y]:M.buildReply(M),[b]:ee.buildRequest(ee,t.trustProxy),[x]:be,[R.kRegisteredPlugins]:[],[w]:[`fastify`],[o]:null,[k]:i,routing:xe,delete:function(e,t,n){return z.prepareRoute.call(this,{method:`DELETE`,url:e,options:t,handler:n})},get:function(e,t,n){return z.prepareRoute.call(this,{method:`GET`,url:e,options:t,handler:n})},head:function(e,t,n){return z.prepareRoute.call(this,{method:`HEAD`,url:e,options:t,handler:n})},trace:function(e,t,n){return z.prepareRoute.call(this,{method:`TRACE`,url:e,options:t,handler:n})},patch:function(e,t,n){return z.prepareRoute.call(this,{method:`PATCH`,url:e,options:t,handler:n})},post:function(e,t,n){return z.prepareRoute.call(this,{method:`POST`,url:e,options:t,handler:n})},put:function(e,t,n){return z.prepareRoute.call(this,{method:`PUT`,url:e,options:t,handler:n})},options:function(e,t,n){return z.prepareRoute.call(this,{method:`OPTIONS`,url:e,options:t,handler:n})},all:function(e,t,n){return z.prepareRoute.call(this,{method:this.supportedMethods,url:e,options:t,handler:n})},route:function(e){return z.route.call(this,{options:e})},hasRoute:function(e){return z.hasRoute.call(this,{options:e})},findRoute:function(e){return z.findRoute(e)},log:t.logger,withTypeProvider:qe,addHook:Je,addSchema:Ye,getSchema:Be.getSchema.bind(Be),getSchemas:Be.getSchemas.bind(Be),setValidatorCompiler:et,setSerializerCompiler:nt,setSchemaController:rt,setReplySerializer:it,setSchemaErrorFormatter:tt,setGenReqId:lt,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[R.kRegisteredPlugins].includes(e)||this[w].includes(e)},listen:Ce,server:Se,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:ut,inject:Ge,printRoutes:st,setNotFoundHandler:$e,setErrorHandler:at,setChildLoggerFactory:ot,initialConfig:ue,addConstraintStrategy:z.addConstraintStrategy.bind(z),hasConstraintStrategy:z.hasConstraintStrategy.bind(z)};Object.defineProperties(B,{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&&(ze(t.schemaErrorFormatter),B[T]=t.schemaErrorFormatter.bind(B));let Ve=Number(t.pluginTimeout),He=n(B,{autostart:!1,timeout:isNaN(Ve)===!1?Ve:_e.pluginTimeout,expose:{use:`register`}});He.override=fe,He.on(`start`,()=>B[S].started=!0),B[o]=B.ready,B.ready=Ke,B.printPlugins=He.prettyPrint.bind(He),He.once(`preReady`,()=>{B.onClose((e,n)=>{B[S].closing=!0,z.closeRoutes(),I(`preClose`,B[o],B,function(){if(B[S].listening){if(we===`idle`)e.server.closeIdleConnections();else if(Oe&&we)e.server.closeAllConnections();else if(we===!0)for(let e of B[D])e.destroy(),B[D].delete(e)}Fe&&e.server.closeHttp2Sessions(),!t.serverFactory||B[S].listening?e.server.close(function(e){e&&e.code!==`ERR_SERVER_NOT_RUNNING`?n(null):n()}):process.nextTick(n,null)})})});let Ue=new N({server:B,config:{}});return B.setNotFoundHandler(),be.arrange404(B),z.setup(t,{avvio:He,fourOhFour:be,hasLogger:le,setupResponseListeners:Re,throwIfAlreadyStarted:We,keepAliveConnections:Le}),Se.on(`clientError`,t.clientErrorHandler.bind(B)),Pe.hasSubscribers&&Pe.publish({fastify:B}),`asyncDispose`in Symbol&&(B[Symbol.asyncDispose]=function(){return B.close()}),B;function We(e){if(B[S].started)throw new Te(e)}function Ge(e,t){if(a===void 0&&(a=xp()),B[S].started){if(B[S].closing){let e=new Ee;if(t){t(e);return}else return Promise.reject(e)}return a(xe,e,t)}if(t)this.ready(n=>{n?t(n,null):a(xe,e,t)});else return a((e,t)=>{this.ready(function(n){if(n){t.emit(`error`,n);return}xe(e,t)})},e)}function Ke(e){if(this[S].readyResolver!==null){if(e!=null){this[S].readyResolver.promise.then(()=>e(null,B),e);return}return this[S].readyResolver.promise}if(process.nextTick(t),this[S].readyResolver=ge.withResolvers(),e)this[S].readyResolver.promise.then(()=>e(null,B),e);else return this[S].readyResolver.promise;function t(){B[o]((e,t)=>{e||B[S].started||B[S].ready||B[S].booting?n(e):(B[S].booting=!0,I(`onReady`,B[o],B,n)),t()})}function n(e){if(e=e!=null&&me[e.code]!=null?pe(e,new me[e.code](e.message)):e,e)return B[S].readyResolver.reject(e);B[S].readyResolver.resolve(B),B[S].booting=!1,B[S].ready=!0,B[S].readyResolver=null}}function qe(){return this}function Je(e,t){if(We(`Cannot call "addHook"!`),t==null)throw new he.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 he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onReady`||e===`onListen`){if(t.constructor.name===`AsyncFunction`&&t.length!==0)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new he.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 Ye(e){return We(`Cannot call "addSchema"!`),this[h].add(e),this[s].forEach(t=>t.addSchema(e)),this}function Xe(e,t){e.headers[`accept-version`]!==void 0&&(e.headers[g]=e.headers[`accept-version`],e.headers[`accept-version`]=void 0),be.router.lookup(e,t)}function Ze(e,n,r){if(t.frameworkErrors){let i=oe(Ue.server,n),a=L(Ue,t.logger,n,i),o=new ee(i,null,n,null,a,Ue),s=new M(r,o,a);return(typeof ae==`function`?ae(n):ae)===!1&&a.info({req:o},`incoming request`),t.frameworkErrors(new ye(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 Qe(e,n,r){if(e!==!1)return function(e){if(e){if(t.frameworkErrors){let e=oe(Ue.server,n),i=L(Ue,t.logger,n,e),a=new ee(e,null,n,null,i,Ue),o=new M(r,a,i);return(typeof ae==`function`?ae(n):ae)===!1&&i.info({req:a},`incoming request`),t.frameworkErrors(new ve,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 $e(e,t){return We(`Cannot call "setNotFoundHandler"!`),be.setNotFoundHandler.call(this,e,t,He,z.routeHandler),this}function et(e){return We(`Cannot call "setValidatorCompiler"!`),this[h].setValidatorCompiler(e),this}function tt(e){return We(`Cannot call "setSchemaErrorFormatter"!`),ze(e),this[T]=e.bind(this),this}function nt(e){return We(`Cannot call "setSerializerCompiler"!`),this[h].setSerializerCompiler(e),this}function rt(e){We(`Cannot call "setSchemaController"!`);let t=this[h],n=F.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 it(e){return We(`Cannot call "setReplySerializer"!`),this[_]=e,this}function at(e){if(We(`Cannot call "setErrorHandler"!`),typeof e!=`function`)throw new ke;if(!t.allowErrorHandlerOverride&&this[A])throw new Ae;return this[A]&&Ne(`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]=Me(this[E],e.bind(this)),this}function ot(e){return We(`Cannot call "setChildLoggerFactory"!`),this[O]=e,this}function st(e={}){return e.includeMeta=e.includeHooks?e.includeMeta?re.concat(e.includeMeta):re:e.includeMeta,z.printRoutes(e)}function ct(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(B,n);if(typeof e==`string`)n.url=e;else{let t=new De(n.url,typeof e);n.destroy(t)}}e.routing(n,i,Qe(r,n,i))}}function lt(e){return We(`Cannot call "setGenReqId"!`),this[k]=se(this[C].requestIdHeader,e),this}function ut(e,{hasBody:t=!1}={}){if(typeof e!=`string`||r.METHODS.indexOf(e)===-1)throw new je;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 z.prepareRoute.call(this,{method:e,url:t,options:n,handler:r})}),this}}function Ie(e,t,n){if(e&&typeof e!=`object`)throw new be;if(e=Object.assign({},e),e.querystringParser&&typeof e.querystringParser!=`function`||e.routerOptions?.querystringParser&&typeof e.routerOptions.querystringParser!=`function`)throw new xe(typeof(e.querystringParser??e.routerOptions.querystringParser));if(e.schemaController&&e.schemaController.bucket&&typeof e.schemaController.bucket!=`function`)throw new Se(typeof e.schemaController.bucket);le(e.bodyLimit);let r=typeof e.requestIdHeader==`string`&&e.requestIdHeader.length!==0?e.requestIdHeader.toLowerCase():e.requestIdHeader===!0&&`request-id`,i=se(r,e.genReqId),a=e.requestIdLogLabel||`reqId`;e.bodyLimit=e.bodyLimit||_e.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 Ce(typeof s.customOptions);if(!s.plugins||!Array.isArray(s.plugins))throw new we(typeof s.plugins);let{logger:c,hasLogger:l}=ae(e);e.connectionTimeout=e.connectionTimeout||_e.connectionTimeout,e.keepAliveTimeout=e.keepAliveTimeout||_e.keepAliveTimeout,e.maxRequestsPerSocket=e.maxRequestsPerSocket||_e.maxRequestsPerSocket,e.requestTimeout=e.requestTimeout||_e.requestTimeout,e.logger=c,e.requestIdHeader=r,e.requestIdLogLabel=a,e.disableRequestLogging=o,e.ajv=s,e.clientErrorHandler=e.clientErrorHandler||Re,e.allowErrorHandlerOverride=e.allowErrorHandlerOverride??_e.allowErrorHandlerOverride;let u=z(e);return e.exposeHeadRoutes=u.exposeHeadRoutes,e.http2SessionTimeout=u.http2SessionTimeout,e.routerOptions=ue(e,{defaultRoute:t,onBadUrl:n,ignoreTrailingSlash:_e.ignoreTrailingSlash,ignoreDuplicateSlashes:_e.ignoreDuplicateSlashes,maxParamLength:_e.maxParamLength,allowUnsafeRegex:_e.allowUnsafeRegex,buildPrettyMeta:Le,useSemicolonDelimiter:_e.useSemicolonDelimiter}),{options:e,genReqId:i,disableRequestLogging:o,hasLogger:l,initialConfig:u}}function Le(e){let t={};return[`errorHandler`,`logLevel`,`logSerializers`].concat(re).forEach(n=>{t[n]=e.store[n]}),Object.assign({},t)}function Re(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 ze(e){if(typeof e!=`function`)throw new Oe(typeof e);if(e.constructor.name===`AsyncFunction`)throw new Oe(`AsyncFunction`)}t.exports=Fe,t.exports.errorCodes=he,t.exports.fastify=Fe,t.exports.default=Fe})),Cp=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})),wp=o(((e,t)=>{t.exports=function(e){return e[0]===`@`&&(e=e.slice(1).replace(`/`,`-`)),e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}})),Tp=o(((e,t)=>{let n=Cp(),r=wp(),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})),Ep=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})),Dp=o((e=>{e.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<`u`,e.SYMBOL_SUPPORT=typeof Symbol<`u`})),Op=o(((e,t)=>{var n=Dp(),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)}})),kp=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}})),Ap=o((e=>{var t=Op(),n=kp();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})),jp=o(((e,t)=>{var n=Ep(),r=Op(),i=kp(),a=Ap();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})),Mp=o(((e,t)=>{let n=jp(),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})),Np=o(((e,t)=>{let n=Tp(),{addAccessControlRequestHeadersToVaryHeader:r,addOriginToVaryHeader:i}=Mp(),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})),Pp=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:()=>{}}})),Fp=o(((e,t)=>{let{EMPTY_BUFFER:n}=Pp(),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{}})),Ip=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])}}}})),Lp=o(((e,t)=>{let n=require(`zlib`),r=Fp(),i=Ip(),{kStatusCode:a}=Pp(),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)}})),Rp=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=Pp(),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{}})),zp=o(((e,t)=>{let{Writable:n}=require(`stream`),r=Lp(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Pp(),{concat:c,toArrayBuffer:l,unmask:u}=Fp(),{isValidStatusCode:d,isValidUTF8:f}=Rp(),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}}})),Bp=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=Lp(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Pp(),{isBlob:c,isValidStatusCode:l}=Rp(),{mask:u,toBuffer:d}=Fp(),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)}})),Vp=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Pp(),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)}})),Hp=o(((e,t)=>{let{tokenChars:n}=Rp();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}})),Up=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=Lp(),p=zp(),m=Bp(),{isBlob:h}=Rp(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=Pp(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Vp(),{format:D,parse:O}=Hp(),{toBuffer:k}=Fp(),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`,L),i.on(`drain`,ie),i.on(`error`,ae),i.on(`message`,oe),i.on(`ping`,se),i.on(`pong`,ce),a.onerror=ue,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,z),t.on(`data`,fe),t.on(`end`,pe),t.on(`error`,me),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){I(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())}),de(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){re(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){re(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){re(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){I(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?ne:F),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`,()=>{I(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){I(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)||I(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`){I(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(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){I(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{I(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 F(e){return e.path=e.socketPath,a.connect(e)}function ne(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function I(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),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 re(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 L(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,fe),process.nextTick(le,n._socket),e===1005?n.close():n.close(e,t))}function ie(){let e=this[C];e.isPaused||e._socket.resume()}function ae(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,fe),process.nextTick(le,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function R(){this[C].emitClose()}function oe(e,t){this[C].emit(`message`,e,t)}function se(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ce(e){this[C].emit(`pong`,e)}function le(e){e.resume()}function ue(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function z(){let e=this[C];if(this.removeListener(`close`,z),this.removeListener(`data`,fe),this.removeListener(`end`,pe),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`,R),e._receiver.on(`finish`,R))}function fe(e){this[C]._receiver.write(e)||this.pause()}function pe(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function me(){let e=this[C];this.removeListener(`error`,me),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),Wp=o(((e,t)=>{Up();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})),Gp=o(((e,t)=>{let{tokenChars:n}=Rp();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}})),Kp=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Hp(),s=Lp(),c=Gp(),l=Up(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=Pp(),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
|
|
447
|
+
`))}}})),rp=o(((e,t)=>{let n=np(),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}})),ip=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`)}}})),ap=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`)}}})),op=o(((e,t)=>{let n=ip(),r=ap(),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(`
|
|
448
|
+
`)).bind(this)}}})),sp=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(`.`)})),cp=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}})),lp=o(((e,t)=>{let n=require(`node:assert`),r=Bf(),i=Qf(),a=Ql(),{prettyPrintTree:o}=ep(),{StaticNode:s,NODE_TYPES:c}=rp(),l=op(),u=sp(),d=$f(),{safeDecodeURI:f,safeDecodeURIComponent:p}=cp(),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)}})),up=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}})),dp=o(((e,t)=>{let n=lp(),r=Il(),i=Kc(),{onRequestAbortHookRunner:a,lifecycleHooks:o,preParsingHookRunner:s,onTimeoutHookRunner:c,onRequestHookRunner:l}=Rc(),{normalizeSchema:u}=El(),{parseHeadOnSendHandlers:d}=up(),{compileSchemasForValidation:f,compileSchemasForSerialization:p}=Gc(),{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}=Lc(),{kRoutePrefix:O,kSupportedHTTPMethods:k,kLogLevel:A,kLogSerializers:j,kHooks:M,kSchemaController:ee,kOptions:N,kReplySerializerDefault:te,kReplyIsError:P,kRequestPayloadStream:F,kDisableRequestLogging:ne,kSchemaErrorFormatter:I,kErrorHandler:re,kHasBeenDecorated:L,kRequestAcceptVersion:ie,kRouteByFastify:ae,kRouteContext:R}=Pc(),{buildErrorHandler:oe}=kl(),{createChildLogger:se}=wl(),{getGenReqId:ce}=Ff(),{FSTDEP022:le}=Ic(),ue=[`allowUnsafeRegex`,`buildPrettyMeta`,`caseSensitive`,`constraints`,`defaultRoute`,`ignoreDuplicateSlashes`,`ignoreTrailingSlash`,`maxParamLength`,`onBadUrl`,`querystringParser`,`useSemicolonDelimiter`];function de(e){let t=n(e),i,s,c,C,w,T,E,k,P,F,R,le,ue,de=!1;return{setup(e,t){i=t.avvio,s=t.fourOhFour,c=e.logger,C=t.hasLogger,w=t.setupResponseListeners,T=t.throwIfAlreadyStarted,le=e.exposeHeadRoutes,E=e.disableRequestLogging,typeof E==`function`&&(k=e.disableRequestLogging),P=e.routerOptions.ignoreTrailingSlash,F=e.routerOptions.ignoreDuplicateSlashes,R=Object.hasOwn(e,`return503OnClosing`)?e.return503OnClosing:!0,ue=t.keepAliveConnections},routing:t.lookup.bind(t),route:we,hasRoute:Se,prepareRoute:xe,routeHandler:Te,closeRoutes:()=>{de=!0},printRoutes:t.prettyPrint.bind(t),addConstraintStrategy:_e,hasConstraintStrategy:ye,isAsyncConstraint:be,findRoute:Ce};function _e(e){return T(`Cannot add constraint strategy!`),t.addConstraintStrategy(e)}function ye(e){return t.hasConstraintStrategy(e)}function be(){return t.constrainer.asyncStrategiesInUse.size>0}function xe({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}),we.call(this,{options:n,isFastify:i})}function Se({options:e}){let n=e.method?.toUpperCase()??``;return t.hasRoute(n,e.url||``,e.constraints)}function Ce(e){let n=t.find(e.method,e.url||``,e.constraints);return n?{handler:n.handler,params:n.params,searchParams:n.searchParams}:null}function we({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);he(a.bodyLimit);let l=a.exposeHeadRoute??le,_=!1,y=!1;if(Array.isArray(a.method))for(let e=0;e<a.method.length;++e)a.method[e]=pe.call(this,a.method[e]),me.call(this,a.method[e],c,a.schema),_=a.method.includes(`GET`),y=a.method.includes(`HEAD`);else a.method=pe.call(this,a.method),me.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&&(F!==!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},Te,T)}catch(e){if(!T[ae])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?oe(this[re],a.errorHandler):this[re],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[I]||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[L]&&T.Request.parent;)T.Request=T.Request.parent;for(;!T.Reply[L]&&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);xe.call(this,{method:`HEAD`,url:e,options:{...b,onSend:t},isFastify:!0})}}}function Te(e,t,n,r,i){let o=ce(r.server,e),s={level:r.logLevel};r.logSerializers&&(s.serializers=r.logSerializers);let u=se(r,c,e,o,s);if(u[ne]=k?!1:E,de===!0&&(e.httpVersionMajor!==2&&t.setHeader(`Connection`,`close`),R)){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`&&ue.has(e.socket)===!1&&(ue.add(e.socket),e.socket.on(`close`,ve.bind({keepAliveConnections:ue,socket:e.socket}))),e.headers[ie]!==void 0&&(e.headers[`accept-version`]=e.headers[ie],e.headers[ie]=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[ne]=p,p===!1&&u.info({req:d},`incoming request`),(C===!0||r.onResponse!==null)&&w(f),r.onRequest===null?ge(null,d,f):l(r.onRequest,d,f,ge),r.onRequestAbort!==null&&e.on(`close`,()=>{e.aborted&&a(r.onRequestAbort,d,z.bind(null,f))}),r.onTimeout!==null&&(d.raw.socket._meta||d.raw.socket.on(`timeout`,fe),d.raw.socket._meta={context:r,request:d,reply:f})}}function z(e,t){t&&e.log.error({err:t},`onRequestAborted hook failed`)}function fe(){let{context:e,request:t,reply:n}=this._meta;c(e.onTimeout,t,n,ye)}function pe(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 me(e,t,n){if(this[k].bodyless.has(e)&&n?.body)throw new T(e,t)}function he(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw new E(e)}function ge(e,t,n){if(n.sent!==!0){if(e!=null){n[P]=!0,n.send(e);return}t[F]=t.raw,t[R].preParsing===null?i.call(t.server,null,t,n):s(t[R].preParsing,t,n,i.bind(t.server))}}function _e(e,t){let n=e.routerOptions||Object.create(null),r=ue.filter(t=>Object.hasOwn(e,t));r.length>0&&le(r.join(`, `));for(let r of ue)Object.hasOwn(n,r)||(n[r]=e[r]??t[r]);return n}function ve(){this.keepAliveConnections.delete(this.socket)}function ye(){}t.exports={buildRouting:de,validateBodyLimitOption:he,buildRouterOptions:_e}})),fp=o(((e,t)=>{let n=lp(),r=jl(),i=Fl(),a=Il(),{kRoutePrefix:o,kCanSetNotFoundHandler:s,kFourOhFourLevelInstance:c,kFourOhFourContext:l,kHooks:u,kErrorHandler:d}=Pc(),{lifecycleHooks:f}=Rc(),{buildErrorHandler:p}=kl(),{FST_ERR_NOT_FOUND:m}=Lc(),{createChildLogger:h}=wl(),{getGenReqId:g}=Ff();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=_})),pp=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}}})),mp=o(((e,t)=>{let n=pp(),r=Tl()({circles:!0,proto:!1}),{FST_ERR_INIT_OPTS_INVALID:i}=Lc();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}})),hp=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}=Pc(),h=jl(),g=Fl(),_=Vd(),v=zl(),{buildHooks:y}=Rc(),b=Pf();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}})),gp=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]`}})),_p=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})),vp=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}})),yp=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
|
|
449
|
+
`),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})),bp=o(((e,t)=>{let{Readable:n,addAbortSignal:r}=require(`node:stream`),i=require(`node:util`),a=gp(),o=require(`node:assert`),{createDeprecation:s}=_p(),c=vp(),{isFormDataLike:l,formDataToStream:u}=yp(),{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})),xp=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})),Sp=o(((e,t)=>{let n=require(`node:http`),{Writable:r,Readable:i,addAbortSignal:a}=require(`node:stream`),o=require(`node:util`),s=xp();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})),Cp=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}})),wp=o(((e,t)=>{let n=require(`node:assert`),r=bp(),i=Sp(),a=`The dispatch function has already been invoked`,o=Cp();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})),Tp=o(((e,t)=>{let n=Nc(),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}=Pc(),{createServer:j}=Vc(),M=jl(),ee=Fl(),N=Il(),te=Al(),P=zl(),F=Vd(),{Hooks:ne,hookRunnerApplication:I,supportedHooks:re}=Rc(),{createChildLogger:L,defaultChildLoggerFactory:ie,createLogger:ae}=wl(),R=Pf(),{getGenReqId:oe,reqIdGenFactory:se}=Ff(),{buildRouting:ce,validateBodyLimitOption:le,buildRouterOptions:ue}=dp(),de=fp(),z=mp(),fe=hp(),{appendStackTrace:pe,AVVIO_ERRORS_MAP:me,...he}=Lc(),ge=Bc(),{defaultInitOptions:_e}=z,{FST_ERR_ASYNC_CONSTRAINT:ve,FST_ERR_BAD_URL:ye,FST_ERR_OPTIONS_NOT_OBJ:be,FST_ERR_QSP_NOT_FN:xe,FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:Se,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:Ce,FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:we,FST_ERR_INSTANCE_ALREADY_LISTENING:Te,FST_ERR_REOPENED_CLOSE_SERVER:Ee,FST_ERR_ROUTE_REWRITE_NOT_STR:De,FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:Oe,FST_ERR_ERROR_HANDLER_NOT_FN:ke,FST_ERR_ERROR_HANDLER_ALREADY_SET:Ae,FST_ERR_ROUTE_METHOD_INVALID:je}=he,{buildErrorHandler:Me}=kl(),{FSTWRN004:Ne}=Ic(),Pe=i.channel(`fastify.initialization`);function Fe(e){let{options:t,genReqId:i,disableRequestLogging:ae,hasLogger:le,initialConfig:ue}=Ie(e,Xe,Ze),z=ce(t.routerOptions),be=de(t),xe=ct(z,t),{server:Se,listen:Ce,forceCloseConnections:we,serverHasCloseAllConnections:Oe,serverHasCloseHttp2Sessions:Fe,keepAliveConnections:Le}=j(t,xe),Re=M.setupResponseListeners,Be=F.buildSchemaController(null,t.schemaController),B={[S]:{listening:!1,closing:!1,started:!1,ready:!1,booting:!1,aborted:!1,readyResolver:null},[D]:Le,[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 ne,[h]:Be,[T]:null,[E]:Me(),[A]:!1,[O]:t.childLoggerFactory||ie,[_]:null,[v]:new P(t.bodyLimit,t.onProtoPoisoning||_e.onProtoPoisoning,t.onConstructorPoisoning||_e.onConstructorPoisoning),[y]:M.buildReply(M),[b]:ee.buildRequest(ee,t.trustProxy),[x]:be,[R.kRegisteredPlugins]:[],[w]:[`fastify`],[o]:null,[k]:i,routing:xe,delete:function(e,t,n){return z.prepareRoute.call(this,{method:`DELETE`,url:e,options:t,handler:n})},get:function(e,t,n){return z.prepareRoute.call(this,{method:`GET`,url:e,options:t,handler:n})},head:function(e,t,n){return z.prepareRoute.call(this,{method:`HEAD`,url:e,options:t,handler:n})},trace:function(e,t,n){return z.prepareRoute.call(this,{method:`TRACE`,url:e,options:t,handler:n})},patch:function(e,t,n){return z.prepareRoute.call(this,{method:`PATCH`,url:e,options:t,handler:n})},post:function(e,t,n){return z.prepareRoute.call(this,{method:`POST`,url:e,options:t,handler:n})},put:function(e,t,n){return z.prepareRoute.call(this,{method:`PUT`,url:e,options:t,handler:n})},options:function(e,t,n){return z.prepareRoute.call(this,{method:`OPTIONS`,url:e,options:t,handler:n})},all:function(e,t,n){return z.prepareRoute.call(this,{method:this.supportedMethods,url:e,options:t,handler:n})},route:function(e){return z.route.call(this,{options:e})},hasRoute:function(e){return z.hasRoute.call(this,{options:e})},findRoute:function(e){return z.findRoute(e)},log:t.logger,withTypeProvider:qe,addHook:Je,addSchema:Ye,getSchema:Be.getSchema.bind(Be),getSchemas:Be.getSchemas.bind(Be),setValidatorCompiler:et,setSerializerCompiler:nt,setSchemaController:rt,setReplySerializer:it,setSchemaErrorFormatter:tt,setGenReqId:lt,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[R.kRegisteredPlugins].includes(e)||this[w].includes(e)},listen:Ce,server:Se,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:ut,inject:Ge,printRoutes:st,setNotFoundHandler:$e,setErrorHandler:at,setChildLoggerFactory:ot,initialConfig:ue,addConstraintStrategy:z.addConstraintStrategy.bind(z),hasConstraintStrategy:z.hasConstraintStrategy.bind(z)};Object.defineProperties(B,{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&&(ze(t.schemaErrorFormatter),B[T]=t.schemaErrorFormatter.bind(B));let Ve=Number(t.pluginTimeout),He=n(B,{autostart:!1,timeout:isNaN(Ve)===!1?Ve:_e.pluginTimeout,expose:{use:`register`}});He.override=fe,He.on(`start`,()=>B[S].started=!0),B[o]=B.ready,B.ready=Ke,B.printPlugins=He.prettyPrint.bind(He),He.once(`preReady`,()=>{B.onClose((e,n)=>{B[S].closing=!0,z.closeRoutes(),I(`preClose`,B[o],B,function(){if(B[S].listening){if(we===`idle`)e.server.closeIdleConnections();else if(Oe&&we)e.server.closeAllConnections();else if(we===!0)for(let e of B[D])e.destroy(),B[D].delete(e)}Fe&&e.server.closeHttp2Sessions(),!t.serverFactory||B[S].listening?e.server.close(function(e){e&&e.code!==`ERR_SERVER_NOT_RUNNING`?n(null):n()}):process.nextTick(n,null)})})});let Ue=new N({server:B,config:{}});return B.setNotFoundHandler(),be.arrange404(B),z.setup(t,{avvio:He,fourOhFour:be,hasLogger:le,setupResponseListeners:Re,throwIfAlreadyStarted:We,keepAliveConnections:Le}),Se.on(`clientError`,t.clientErrorHandler.bind(B)),Pe.hasSubscribers&&Pe.publish({fastify:B}),`asyncDispose`in Symbol&&(B[Symbol.asyncDispose]=function(){return B.close()}),B;function We(e){if(B[S].started)throw new Te(e)}function Ge(e,t){if(a===void 0&&(a=wp()),B[S].started){if(B[S].closing){let e=new Ee;if(t){t(e);return}else return Promise.reject(e)}return a(xe,e,t)}if(t)this.ready(n=>{n?t(n,null):a(xe,e,t)});else return a((e,t)=>{this.ready(function(n){if(n){t.emit(`error`,n);return}xe(e,t)})},e)}function Ke(e){if(this[S].readyResolver!==null){if(e!=null){this[S].readyResolver.promise.then(()=>e(null,B),e);return}return this[S].readyResolver.promise}if(process.nextTick(t),this[S].readyResolver=ge.withResolvers(),e)this[S].readyResolver.promise.then(()=>e(null,B),e);else return this[S].readyResolver.promise;function t(){B[o]((e,t)=>{e||B[S].started||B[S].ready||B[S].booting?n(e):(B[S].booting=!0,I(`onReady`,B[o],B,n)),t()})}function n(e){if(e=e!=null&&me[e.code]!=null?pe(e,new me[e.code](e.message)):e,e)return B[S].readyResolver.reject(e);B[S].readyResolver.resolve(B),B[S].booting=!1,B[S].ready=!0,B[S].readyResolver=null}}function qe(){return this}function Je(e,t){if(We(`Cannot call "addHook"!`),t==null)throw new he.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 he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onReady`||e===`onListen`){if(t.constructor.name===`AsyncFunction`&&t.length!==0)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(e===`onRequestAbort`){if(t.constructor.name===`AsyncFunction`&&t.length!==1)throw new he.FST_ERR_HOOK_INVALID_ASYNC_HANDLER}else if(t.constructor.name===`AsyncFunction`&&t.length===3)throw new he.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 Ye(e){return We(`Cannot call "addSchema"!`),this[h].add(e),this[s].forEach(t=>t.addSchema(e)),this}function Xe(e,t){e.headers[`accept-version`]!==void 0&&(e.headers[g]=e.headers[`accept-version`],e.headers[`accept-version`]=void 0),be.router.lookup(e,t)}function Ze(e,n,r){if(t.frameworkErrors){let i=oe(Ue.server,n),a=L(Ue,t.logger,n,i),o=new ee(i,null,n,null,a,Ue),s=new M(r,o,a);return(typeof ae==`function`?ae(n):ae)===!1&&a.info({req:o},`incoming request`),t.frameworkErrors(new ye(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 Qe(e,n,r){if(e!==!1)return function(e){if(e){if(t.frameworkErrors){let e=oe(Ue.server,n),i=L(Ue,t.logger,n,e),a=new ee(e,null,n,null,i,Ue),o=new M(r,a,i);return(typeof ae==`function`?ae(n):ae)===!1&&i.info({req:a},`incoming request`),t.frameworkErrors(new ve,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 $e(e,t){return We(`Cannot call "setNotFoundHandler"!`),be.setNotFoundHandler.call(this,e,t,He,z.routeHandler),this}function et(e){return We(`Cannot call "setValidatorCompiler"!`),this[h].setValidatorCompiler(e),this}function tt(e){return We(`Cannot call "setSchemaErrorFormatter"!`),ze(e),this[T]=e.bind(this),this}function nt(e){return We(`Cannot call "setSerializerCompiler"!`),this[h].setSerializerCompiler(e),this}function rt(e){We(`Cannot call "setSchemaController"!`);let t=this[h],n=F.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 it(e){return We(`Cannot call "setReplySerializer"!`),this[_]=e,this}function at(e){if(We(`Cannot call "setErrorHandler"!`),typeof e!=`function`)throw new ke;if(!t.allowErrorHandlerOverride&&this[A])throw new Ae;return this[A]&&Ne(`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]=Me(this[E],e.bind(this)),this}function ot(e){return We(`Cannot call "setChildLoggerFactory"!`),this[O]=e,this}function st(e={}){return e.includeMeta=e.includeHooks?e.includeMeta?re.concat(e.includeMeta):re:e.includeMeta,z.printRoutes(e)}function ct(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(B,n);if(typeof e==`string`)n.url=e;else{let t=new De(n.url,typeof e);n.destroy(t)}}e.routing(n,i,Qe(r,n,i))}}function lt(e){return We(`Cannot call "setGenReqId"!`),this[k]=se(this[C].requestIdHeader,e),this}function ut(e,{hasBody:t=!1}={}){if(typeof e!=`string`||r.METHODS.indexOf(e)===-1)throw new je;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 z.prepareRoute.call(this,{method:e,url:t,options:n,handler:r})}),this}}function Ie(e,t,n){if(e&&typeof e!=`object`)throw new be;if(e=Object.assign({},e),e.querystringParser&&typeof e.querystringParser!=`function`||e.routerOptions?.querystringParser&&typeof e.routerOptions.querystringParser!=`function`)throw new xe(typeof(e.querystringParser??e.routerOptions.querystringParser));if(e.schemaController&&e.schemaController.bucket&&typeof e.schemaController.bucket!=`function`)throw new Se(typeof e.schemaController.bucket);le(e.bodyLimit);let r=typeof e.requestIdHeader==`string`&&e.requestIdHeader.length!==0?e.requestIdHeader.toLowerCase():e.requestIdHeader===!0&&`request-id`,i=se(r,e.genReqId),a=e.requestIdLogLabel||`reqId`;e.bodyLimit=e.bodyLimit||_e.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 Ce(typeof s.customOptions);if(!s.plugins||!Array.isArray(s.plugins))throw new we(typeof s.plugins);let{logger:c,hasLogger:l}=ae(e);e.connectionTimeout=e.connectionTimeout||_e.connectionTimeout,e.keepAliveTimeout=e.keepAliveTimeout||_e.keepAliveTimeout,e.maxRequestsPerSocket=e.maxRequestsPerSocket||_e.maxRequestsPerSocket,e.requestTimeout=e.requestTimeout||_e.requestTimeout,e.logger=c,e.requestIdHeader=r,e.requestIdLogLabel=a,e.disableRequestLogging=o,e.ajv=s,e.clientErrorHandler=e.clientErrorHandler||Re,e.allowErrorHandlerOverride=e.allowErrorHandlerOverride??_e.allowErrorHandlerOverride;let u=z(e);return e.exposeHeadRoutes=u.exposeHeadRoutes,e.http2SessionTimeout=u.http2SessionTimeout,e.routerOptions=ue(e,{defaultRoute:t,onBadUrl:n,ignoreTrailingSlash:_e.ignoreTrailingSlash,ignoreDuplicateSlashes:_e.ignoreDuplicateSlashes,maxParamLength:_e.maxParamLength,allowUnsafeRegex:_e.allowUnsafeRegex,buildPrettyMeta:Le,useSemicolonDelimiter:_e.useSemicolonDelimiter}),{options:e,genReqId:i,disableRequestLogging:o,hasLogger:l,initialConfig:u}}function Le(e){let t={};return[`errorHandler`,`logLevel`,`logSerializers`].concat(re).forEach(n=>{t[n]=e.store[n]}),Object.assign({},t)}function Re(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 ze(e){if(typeof e!=`function`)throw new Oe(typeof e);if(e.constructor.name===`AsyncFunction`)throw new Oe(`AsyncFunction`)}t.exports=Fe,t.exports.errorCodes=he,t.exports.fastify=Fe,t.exports.default=Fe})),Ep=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})),Dp=o(((e,t)=>{t.exports=function(e){return e[0]===`@`&&(e=e.slice(1).replace(`/`,`-`)),e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}})),Op=o(((e,t)=>{let n=Ep(),r=Dp(),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})),kp=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})),Ap=o((e=>{e.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<`u`,e.SYMBOL_SUPPORT=typeof Symbol<`u`})),jp=o(((e,t)=>{var n=Ap(),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)}})),Mp=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}})),Np=o((e=>{var t=jp(),n=Mp();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})),Pp=o(((e,t)=>{var n=kp(),r=jp(),i=Mp(),a=Np();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})),Fp=o(((e,t)=>{let n=Pp(),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})),Ip=o(((e,t)=>{let n=Op(),{addAccessControlRequestHeadersToVaryHeader:r,addOriginToVaryHeader:i}=Fp(),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})),Lp=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:()=>{}}})),Rp=o(((e,t)=>{let{EMPTY_BUFFER:n}=Lp(),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{}})),zp=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])}}}})),Bp=o(((e,t)=>{let n=require(`zlib`),r=Rp(),i=zp(),{kStatusCode:a}=Lp(),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)}})),Vp=o(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=Lp(),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{}})),Hp=o(((e,t)=>{let{Writable:n}=require(`stream`),r=Bp(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Lp(),{concat:c,toArrayBuffer:l,unmask:u}=Rp(),{isValidStatusCode:d,isValidUTF8:f}=Vp(),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}}})),Up=o(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=Bp(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Lp(),{isBlob:c,isValidStatusCode:l}=Vp(),{mask:u,toBuffer:d}=Rp(),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)}})),Wp=o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Lp(),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)}})),Gp=o(((e,t)=>{let{tokenChars:n}=Vp();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}})),Kp=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=Bp(),p=Hp(),m=Up(),{isBlob:h}=Vp(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=Lp(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Wp(),{format:D,parse:O}=Gp(),{toBuffer:k}=Rp(),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`,L),i.on(`drain`,ie),i.on(`error`,ae),i.on(`message`,oe),i.on(`ping`,se),i.on(`pong`,ce),a.onerror=ue,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,z),t.on(`data`,fe),t.on(`end`,pe),t.on(`error`,me),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){I(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())}),de(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){re(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){re(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){re(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){I(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?ne:F),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`,()=>{I(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){I(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)||I(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`){I(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(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){I(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{I(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 F(e){return e.path=e.socketPath,a.connect(e)}function ne(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function I(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),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 re(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 L(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,fe),process.nextTick(le,n._socket),e===1005?n.close():n.close(e,t))}function ie(){let e=this[C];e.isPaused||e._socket.resume()}function ae(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,fe),process.nextTick(le,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function R(){this[C].emitClose()}function oe(e,t){this[C].emit(`message`,e,t)}function se(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ce(e){this[C].emit(`pong`,e)}function le(e){e.resume()}function ue(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function z(){let e=this[C];if(this.removeListener(`close`,z),this.removeListener(`data`,fe),this.removeListener(`end`,pe),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`,R),e._receiver.on(`finish`,R))}function fe(e){this[C]._receiver.write(e)||this.pause()}function pe(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function me(){let e=this[C];this.removeListener(`error`,me),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),qp=o(((e,t)=>{Kp();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})),Jp=o(((e,t)=>{let{tokenChars:n}=Vp();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}})),Yp=o(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Gp(),s=Bp(),c=Jp(),l=Kp(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=Lp(),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
450
|
`).join(`\r
|
|
451
451
|
`)),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
|
|
452
452
|
`)+`\r
|
|
453
453
|
\r
|
|
454
|
-
`+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)}})),qp=o(((e,t)=>{let n=Up();n.createWebSocketStream=Wp(),n.Server=Kp(),n.Receiver=zp(),n.Sender=Bp(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})),Jp=o(((e,t)=>{t.exports=require(`stream`)})),Yp=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}()})),Xp=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}})),Zp=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})),Qp=o(((e,t)=>{var n=Zp().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}})),$p=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}}})),em=o(((e,t)=>{try{var n=require(`util`);if(typeof n.inherits!=`function`)throw``;t.exports=n.inherits}catch{t.exports=$p()}})),tm=o(((e,t)=>{t.exports=require(`util`).deprecate})),nm=o(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ie(t,e)}}var r;T.WritableState=C;var i={deprecate:tm()},a=Jp(),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=Xp(),d=Qp().getHighWaterMark,f=Zp().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;em()(T,a);function S(){}function C(e,t,i){r||=rm(),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||=rm();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(re,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),re(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=F(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(),re(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||L(this,r,n),this},Object.defineProperty(T.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function F(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function ne(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),re(e,t)})}function I(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(ne,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function re(e,t){var n=F(t);if(n&&(I(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 L(e,t,n){t.ending=!0,re(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ie(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)}})),rm=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=lm(),i=nm();em()(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)}})})),im=o(((e,t)=>{
|
|
454
|
+
`+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)}})),Xp=o(((e,t)=>{let n=Kp();n.createWebSocketStream=qp(),n.Server=Yp(),n.Receiver=Hp(),n.Sender=Up(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})),Zp=o(((e,t)=>{t.exports=require(`stream`)})),Qp=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}()})),$p=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}})),em=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})),tm=o(((e,t)=>{var n=em().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}})),nm=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}}})),rm=o(((e,t)=>{try{var n=require(`util`);if(typeof n.inherits!=`function`)throw``;t.exports=n.inherits}catch{t.exports=nm()}})),im=o(((e,t)=>{t.exports=require(`util`).deprecate})),am=o(((e,t)=>{t.exports=T;function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ie(t,e)}}var r;T.WritableState=C;var i={deprecate:im()},a=Zp(),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=$p(),d=tm().getHighWaterMark,f=em().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;rm()(T,a);function S(){}function C(e,t,i){r||=om(),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||=om();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(re,e,t),e._writableState.errorEmitted=!0,x(e,r)):(i(r),e._writableState.errorEmitted=!0,x(e,r),re(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=F(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(),re(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||L(this,r,n),this},Object.defineProperty(T.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function F(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function ne(e,t){e._final(function(n){t.pendingcb--,n&&x(e,n),t.prefinished=!0,e.emit(`prefinish`),re(e,t)})}function I(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(ne,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function re(e,t){var n=F(t);if(n&&(I(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 L(e,t,n){t.ending=!0,re(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ie(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)}})),om=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=fm(),i=am();rm()(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)}})})),sm=o(((e,t)=>{
|
|
455
455
|
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
456
|
-
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)}})),am=o((e=>{var t=im().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):``}})),om=o(((e,t)=>{var n=Zp().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})),sm=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=om(),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}})),cm=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=Zp().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})),lm=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=Jp(),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=Yp(),f=Xp(),p=Qp().getHighWaterMark,m=Zp().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;em()(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||=rm(),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||=am().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=rm(),!(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||=am().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?oe(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&oe(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?R(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&&oe(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,ae(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(F,e,t))}function F(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=ne(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&&ce(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 ne(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,ae(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=ce(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(re,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(I,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(I,this),t};function I(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 re(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,L(this,e)),e.paused=!1,this};function L(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ie,e,t))}function ie(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),ae(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 ae(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=sm()),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=R,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function R(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 oe(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(se,t,e))}function se(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=cm()),x(E,e,t)});function ce(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),um=o(((e,t)=>{t.exports=l;var n=Zp().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=rm();em()(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)}})),dm=o(((e,t)=>{t.exports=r;var n=um();em()(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)}})),fm=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=Zp().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=om()),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})),pm=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=lm(),e.Stream=n||e,e.Readable=e,e.Writable=nm(),e.Duplex=rm(),e.Transform=um(),e.PassThrough=dm(),e.finished=om(),e.pipeline=fm())})),mm=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}}})),hm=o(((e,t)=>{var n=mm();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}})),gm=o(((e,t)=>{var n=hm(),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})),_m=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}})),vm=o(((e,t)=>{var n=pm(),r=gm(),i=em(),a=_m(),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})),ym=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=Tp(),o=qp(),s=vm(),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),bm=c(Np(),1),xm=c(Sp(),1);let Sm,Cm;function wm(e){!Sm||Sm.length<e?(Sm=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(Sm),Cm=0):Cm+e>Sm.length&&(l.webcrypto.getRandomValues(Sm),Cm=0),Cm+=e}function Tm(e=21){wm(e|=0);let t=``;for(let n=Cm-e;n<Cm;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[Sm[n]&63];return t}var Em=o(((e,t)=>{var n=im().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})),Dm=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})),Om=o(((e,t)=>{var n=im().Buffer,r=Dm(),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}})),km=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}})),Am=o(((e,t)=>{var n=im().Buffer,r=require(`crypto`),i=Om(),a=require(`util`),o=`"%s" is not a valid algorithm.
|
|
456
|
+
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)}})),cm=o((e=>{var t=sm().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):``}})),lm=o(((e,t)=>{var n=em().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})),um=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=lm(),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}})),dm=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=em().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})),fm=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=Zp(),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=Qp(),f=$p(),p=tm().getHighWaterMark,m=em().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;rm()(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||=om(),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||=cm().StringDecoder,this.decoder=new y(e.encoding),this.encoding=e.encoding)}function E(e){if(n||=om(),!(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||=cm().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?oe(this):N(this),null;if(e=M(e,t),e===0&&t.ended)return t.length===0&&oe(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?R(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&&oe(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,ae(e)}function P(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(F,e,t))}function F(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=ne(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&&ce(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 ne(e){return function(){var t=e._readableState;u(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&r(e,`data`)&&(t.flowing=!0,ae(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=ce(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(re,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(I,this),n},E.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(I,this),t};function I(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 re(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,L(this,e)),e.paused=!1,this};function L(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ie,e,t))}function ie(e,t){u(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),ae(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 ae(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=um()),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=R,Object.defineProperty(E.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function R(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 oe(e){var t=e._readableState;u(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(se,t,e))}function se(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=dm()),x(E,e,t)});function ce(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),pm=o(((e,t)=>{t.exports=l;var n=em().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=om();rm()(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)}})),mm=o(((e,t)=>{t.exports=r;var n=pm();rm()(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)}})),hm=o(((e,t)=>{var n;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=em().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=lm()),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})),gm=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=fm(),e.Stream=n||e,e.Readable=e,e.Writable=am(),e.Duplex=om(),e.Transform=pm(),e.PassThrough=mm(),e.finished=lm(),e.pipeline=hm())})),_m=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}}})),vm=o(((e,t)=>{var n=_m();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}})),ym=o(((e,t)=>{var n=vm(),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})),bm=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}})),xm=o(((e,t)=>{var n=gm(),r=ym(),i=rm(),a=bm(),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})),Sm=c(o(((e,t)=>{let{ServerResponse:n}=require(`node:http`),{PassThrough:r}=require(`node:stream`),{randomBytes:i}=require(`node:crypto`),a=Op(),o=Xp(),s=xm(),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),Cm=c(Ip(),1),wm=c(Tp(),1);let Tm,Em;function Dm(e){!Tm||Tm.length<e?(Tm=Buffer.allocUnsafe(e*128),l.webcrypto.getRandomValues(Tm),Em=0):Em+e>Tm.length&&(l.webcrypto.getRandomValues(Tm),Em=0),Em+=e}function Om(e=21){Dm(e|=0);let t=``;for(let n=Em-e;n<Em;n++)t+=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`[Tm[n]&63];return t}var km=o(((e,t)=>{var n=sm().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})),Am=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})),jm=o(((e,t)=>{var n=sm().Buffer,r=Am(),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}})),Mm=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}})),Nm=o(((e,t)=>{var n=sm().Buffer,r=require(`crypto`),i=jm(),a=require(`util`),o=`"%s" is not a valid algorithm.
|
|
457
457
|
Supported algorithms are:
|
|
458
|
-
"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||=km(),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)}}})),jm=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)}})),Mm=o(((e,t)=>{var n=im().Buffer,r=Em(),i=Am(),a=require(`stream`),o=jm(),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})),Nm=o(((e,t)=>{var n=im().Buffer,r=Em(),i=Am(),a=require(`stream`),o=jm(),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})),Pm=o((e=>{var t=Mm(),n=Nm();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)}})),Fm=o(((e,t)=>{var n=Pm();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}})),Im=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})),Lm=o(((e,t)=>{var n=Im(),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})),Rm=o(((e,t)=>{var n=Im(),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})),zm=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`:``)}})),Bm=o(((e,t)=>{var n=zm();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}})),Vm=o(((e,t)=>{t.exports=Af().satisfies(process.version,`>=15.7.0`)})),Hm=o(((e,t)=>{t.exports=Af().satisfies(process.version,`>=16.9.0`)})),Um=o(((e,t)=>{let n=Vm(),r=Hm(),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}}})),Wm=o(((e,t)=>{t.exports=Af().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Gm=o(((e,t)=>{let n=Im(),r=Lm(),i=Rm(),a=Fm(),o=Bm(),s=Um(),c=Wm(),l=Pm(),{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)})}})),Km=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=F(e)?e:ue(e),n=n&&!r?se(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),ae(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return ne(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function F(e){return e!=null&&re(e.length)&&!I(e)}function ne(e){return ie(e)&&F(e)}function I(e){var t=L(e)?E.call(e):``;return t==s||t==c}function re(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function L(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ie(e){return!!e&&typeof e==`object`}function ae(e){return typeof e==`string`||!P(e)&&ie(e)&&E.call(e)==l}function R(e){return typeof e==`symbol`||ie(e)&&E.call(e)==u}function oe(e){return e?(e=ce(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function se(e){var t=oe(e),n=t%1;return t===t?n?t-n:t:0}function ce(e){if(typeof e==`number`)return e;if(R(e))return a;if(L(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=L(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 le(e){return F(e)?A(e):j(e)}function ue(e){return e?S(e,le(e)):[]}t.exports=N})),qm=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})),Jm=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})),Ym=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})),Xm=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})),Zm=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})),Qm=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})),$m=o(((e,t)=>{let n=Bm(),r=Wm(),i=Um(),a=Pm(),o=Km(),s=qm(),c=Jm(),l=Ym(),u=Xm(),d=Zm(),f=Qm(),{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}}})),eh=o(((e,t)=>{t.exports={decode:Fm(),verify:Gm(),sign:$m(),JsonWebTokenError:Im(),NotBeforeError:Lm(),TokenExpiredError:Rm()}})),th=c(yl(),1),nh=c(eh(),1),rh=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=ih(),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 Error(`Invalid pairing code`);if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),Error(`Pairing code expired`);this.pairingCodes.delete(e);let i=`dev_${Tm(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=nh.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 Error(`Refresh token revoked`);let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Error(`Device revoked`);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=nh.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 Error(`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 Error(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw Error(`Device identity not registered`);if(!oh(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw Error(`Device identity mismatch`);if(n.identityStatus!==`active`)throw Error(`Device identity not active: ${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)}issueTokenPair(e){let t=nh.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${Tm(14)}`,r=nh.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=nh.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=nh.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 ch(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await ch(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await ch(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:ah(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 sh(this.pairingCodes,e),sh(this.devices,t),sh(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 ih(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function ah(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function oh(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function sh(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function ch(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var lh=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 uh(){}uh.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(dh(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(dh(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 dh(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 uh;function fh(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 ph(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 mh(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 hh(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 gh(e,t){return mh(e,t,``)}function _h(e,t){return hh(e,t,``)}function vh(e,t){return t.slice(0,yh(e,t))}function yh(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 bh=`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}`,xh=RegExp(`[${bh}]+|\\s+|[^${bh}]`,`ug`),Sh=new uh;Sh.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},Sh.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(xh)||[];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},Sh.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},Sh.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)&&Ch(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Ch(n,i,r,null),e};function Ch(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=fh(i,o);e.value=hh(e.value,o,c),t.value=gh(t.value,c),n.value=gh(n.value,c)}if(r){var l=ph(a,s);r.value=mh(r.value,s,l),t.value=_h(t.value,l),n.value=_h(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=fh(u,d);t.value=gh(t.value,p);var m=ph(gh(u,p),f);t.value=_h(t.value,m),r.value=mh(r.value,u,m),e.value=hh(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],_=vh(g,h);t.value=_h(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=vh(v,y);t.value=gh(t.value,b)}}var wh=new uh;wh.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${bh}]+|[^\\S\\n\\r]+|[^${bh}]`,`ug`);return e.match(t)||[]};var Th=new uh;Th.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
459
|
-
`));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},
|
|
458
|
+
"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||=Mm(),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)}}})),Pm=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)}})),Fm=o(((e,t)=>{var n=sm().Buffer,r=km(),i=Nm(),a=require(`stream`),o=Pm(),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})),Im=o(((e,t)=>{var n=sm().Buffer,r=km(),i=Nm(),a=require(`stream`),o=Pm(),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})),Lm=o((e=>{var t=Fm(),n=Im();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)}})),Rm=o(((e,t)=>{var n=Lm();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}})),zm=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})),Bm=o(((e,t)=>{var n=zm(),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})),Vm=o(((e,t)=>{var n=zm(),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})),Hm=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`:``)}})),Um=o(((e,t)=>{var n=Hm();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}})),Wm=o(((e,t)=>{t.exports=Nf().satisfies(process.version,`>=15.7.0`)})),Gm=o(((e,t)=>{t.exports=Nf().satisfies(process.version,`>=16.9.0`)})),Km=o(((e,t)=>{let n=Wm(),r=Gm(),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}}})),qm=o(((e,t)=>{t.exports=Nf().satisfies(process.version,`^6.12.0 || >=8.0.0`)})),Jm=o(((e,t)=>{let n=zm(),r=Bm(),i=Vm(),a=Rm(),o=Um(),s=Km(),c=qm(),l=Lm(),{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)})}})),Ym=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=F(e)?e:ue(e),n=n&&!r?se(n):0;var i=e.length;return n<0&&(n=k(i+n,0)),ae(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&y(e,t,n)>-1}function te(e){return ne(e)&&T.call(e,`callee`)&&(!D.call(e,`callee`)||E.call(e)==o)}var P=Array.isArray;function F(e){return e!=null&&re(e.length)&&!I(e)}function ne(e){return ie(e)&&F(e)}function I(e){var t=L(e)?E.call(e):``;return t==s||t==c}function re(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=r}function L(e){var t=typeof e;return!!e&&(t==`object`||t==`function`)}function ie(e){return!!e&&typeof e==`object`}function ae(e){return typeof e==`string`||!P(e)&&ie(e)&&E.call(e)==l}function R(e){return typeof e==`symbol`||ie(e)&&E.call(e)==u}function oe(e){return e?(e=ce(e),e===n||e===-n?(e<0?-1:1)*i:e===e?e:0):e===0?e:0}function se(e){var t=oe(e),n=t%1;return t===t?n?t-n:t:0}function ce(e){if(typeof e==`number`)return e;if(R(e))return a;if(L(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=L(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 le(e){return F(e)?A(e):j(e)}function ue(e){return e?S(e,le(e)):[]}t.exports=N})),Xm=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})),Zm=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})),Qm=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})),$m=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})),eh=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})),th=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})),nh=o(((e,t)=>{let n=Um(),r=qm(),i=Km(),a=Lm(),o=Ym(),s=Xm(),c=Zm(),l=Qm(),u=$m(),d=eh(),f=th(),{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}}})),rh=o(((e,t)=>{t.exports={decode:Rm(),verify:Jm(),sign:nh(),JsonWebTokenError:zm(),NotBeforeError:Bm(),TokenExpiredError:Vm()}})),ih=c(Sl(),1),ah=c(rh(),1),oh=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=sh(),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 Error(`Invalid pairing code`);if(r.expiresAtMs<Date.now())throw this.pairingCodes.delete(e),await this.persistState(),Error(`Pairing code expired`);this.pairingCodes.delete(e);let i=`dev_${Om(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=ah.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 Error(`Refresh token revoked`);let r=this.devices.get(t.sub);if(!r||r.revokedAt)throw Error(`Device revoked`);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=ah.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 Error(`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 Error(`Device revoked or not found`);if(!n.publicKey||!n.publicKeyFingerprint)throw Error(`Device identity not registered`);if(!lh(n.publicKey,t.publicKey)||n.publicKeyFingerprint!==t.publicKeyFingerprint)throw Error(`Device identity mismatch`);if(n.identityStatus!==`active`)throw Error(`Device identity not active: ${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)}issueTokenPair(e){let t=ah.default.sign({sub:e,type:`access`},this.config.accessSecret,{expiresIn:this.config.accessTtl}),n=`rt_${Om(14)}`,r=ah.default.sign({sub:e,type:`refresh`,jti:n},this.config.refreshSecret,{expiresIn:this.config.refreshTtl}),i=ah.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=ah.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 dh(this.indexPath),r=!0;else{let a=null;try{a=JSON.parse(i)}catch{await dh(this.indexPath),r=!0}if(a)if(a.v!==1||!Array.isArray(a.pairingCodes)||!Array.isArray(a.devices)||!Array.isArray(a.refreshTokens))await dh(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:ch(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 uh(this.pairingCodes,e),uh(this.devices,t),uh(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 sh(){let e=``;for(let t=0;t<6;t+=1)e+=`ABCDEFGHJKLMNPQRSTUVWXYZ23456789`[Math.floor(Math.random()*32)];return e}function ch(e){return e===`active`||e===`revoked`||e===`rotating`||e===`unknown`}function lh(e,t){let n=Buffer.from(e,`base64`),r=Buffer.from(t,`base64`);return n.length===r.length&&n.equals(r)}function uh(e,t){e.clear();for(let[n,r]of t.entries())e.set(n,r)}async function dh(e){let t=`${e}.corrupt-${Date.now()}`;try{await d.default.rename(e,t)}catch(e){if(e.code!==`ENOENT`)throw e}}var fh=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 ph(){}ph.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(mh(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(mh(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 mh(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 ph;function hh(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 gh(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 _h(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 vh(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 yh(e,t){return _h(e,t,``)}function bh(e,t){return vh(e,t,``)}function xh(e,t){return t.slice(0,Sh(e,t))}function Sh(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 Ch=`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}`,wh=RegExp(`[${Ch}]+|\\s+|[^${Ch}]`,`ug`),Th=new ph;Th.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},Th.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(wh)||[];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},Th.join=function(e){return e.map(function(e,t){return t==0?e:e.replace(/^\s+/,``)}).join(``)},Th.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)&&Eh(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Eh(n,i,r,null),e};function Eh(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=hh(i,o);e.value=vh(e.value,o,c),t.value=yh(t.value,c),n.value=yh(n.value,c)}if(r){var l=gh(a,s);r.value=_h(r.value,s,l),t.value=bh(t.value,l),n.value=bh(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=hh(u,d);t.value=yh(t.value,p);var m=gh(yh(u,p),f);t.value=bh(t.value,m),r.value=_h(r.value,u,m),e.value=vh(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],_=xh(g,h);t.value=bh(t.value,_)}else if(e){var v=e.value.match(/\s*$/)[0],y=t.value.match(/^\s*/)[0],b=xh(v,y);t.value=yh(t.value,b)}}var Dh=new ph;Dh.tokenize=function(e){var t=RegExp(`(\\r?\\n)|[${Ch}]+|[^\\S\\n\\r]+|[^${Ch}]`,`ug`);return e.match(t)||[]};var Oh=new ph;Oh.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
459
|
+
`));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},Oh.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
460
460
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
461
461
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
462
462
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
463
|
-
`)&&(t=t.slice(0,-1))),
|
|
464
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
465
|
-
`)?_.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
|
|
463
|
+
`)&&(t=t.slice(0,-1))),ph.prototype.equals.call(this,e,t,n)};function kh(e,t,n){return Oh.diff(e,t,n)}var Ah=new ph;Ah.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var jh=new ph;jh.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Mh(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 Nh(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Mh(Object(n),!0).forEach(function(t){Lh(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Mh(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Ph(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 Fh(e){var t=Ph(e,`string`);return typeof t==`symbol`?t:t+``}function Ih(e){"@babel/helpers - typeof";return Ih=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},Ih(e)}function Lh(e,t,n){return t=Fh(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Rh(e){return zh(e)||Bh(e)||Vh(e)||Uh()}function zh(e){if(Array.isArray(e))return Hh(e)}function Bh(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function Vh(e,t){if(e){if(typeof e==`string`)return Hh(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 Hh(e,t)}}function Hh(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 Uh(){throw TypeError(`Invalid attempt to spread non-iterable instance.
|
|
464
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Wh=new ph;Wh.useLongestToken=!0,Wh.tokenize=Oh.tokenize,Wh.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(Gh(e,null,null,i),i,` `)},Wh.equals=function(e,t,n){return ph.prototype.equals.call(Wh,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)};function Gh(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]=Gh(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),Ih(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]=Gh(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var Kh=new ph;Kh.tokenize=function(e){return e.slice()},Kh.join=Kh.removeEmpty=function(e){return e};function qh(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;kh(n,r,Nh(Nh({},o),{},{callback:function(e){s(c(e))}}))}else return c(kh(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||Xh(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,Rh(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,Rh(r(t)))}else{var h,g=Math.min(t.length,o.context);(h=u).push.apply(h,Rh(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(`
|
|
465
|
+
`)?_.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 Jh(e){if(Array.isArray(e))return e.map(Jh).join(`
|
|
466
466
|
`);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(`
|
|
467
467
|
`)+`
|
|
468
|
-
`}function
|
|
468
|
+
`}function Yh(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;qh(e,t,n,r,i,a,Nh(Nh({},o),{},{callback:function(e){e?c(Jh(e)):c()}}))}else{var l=qh(e,t,n,r,i,a,o);return l?Jh(l):void 0}}function Xh(e){var t=e.endsWith(`
|
|
469
469
|
`),n=e.split(`
|
|
470
470
|
`).map(function(e){return e+`
|
|
471
|
-
`});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var Jh=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return ng(r,await eg(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await tg(e,n),i=p.default.parse(r).root;return ng(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await Yh(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 Yh(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:Kh(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=Xh(t),a=await Zh(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 Yh(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=Xh(t),i=await Zh(n,r),a=await d.default.realpath(i);return Qh(n,a,r),{absolutePath:a,normalizedPath:r}}function Xh(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function Zh(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 Qh(e,n,t),n}function Qh(e,t,n){let r=$h(e),i=$h(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function $h(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function eg(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;Qh(e,r,n??`.`);let i=await d.default.realpath(r);if(Qh(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function tg(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 ng(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}}async function rg(e){let t=p.default.join(e,`gateway-identity.json`);await d.default.mkdir(e,{recursive:!0,mode:448});try{let e=await d.default.readFile(t,`utf8`),n=JSON.parse(e);return{identity:n.identity,privateKeyPem:n.privateKeyPem,path:t,created:!1}}catch(e){if(!sg(e))throw e}let n=ig(),r={v:1,identity:n.identity,privateKeyPem:n.privateKeyPem};return await d.default.writeFile(t,`${JSON.stringify(r,null,2)}\n`,{encoding:`utf8`,mode:384}),{...n,path:t,created:!0}}function ig(){let{publicKey:e,privateKey:t}=(0,l.generateKeyPairSync)(`ed25519`),n=e.export({format:`der`,type:`spki`}),r=t.export({format:`pem`,type:`pkcs8`}).toString(),i=new Date().toISOString();return{identity:{algorithm:`ed25519`,publicKey:n.toString(`base64`),publicKeyFingerprint:ag(n),keyVersion:1,createdAt:i},privateKeyPem:r}}function ag(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`)}function og(e,t,n){let r=(0,l.createPrivateKey)(t),i=(0,l.sign)(null,Buffer.from(ea(n),`utf8`),r).toString(`base64`);return{algorithm:`ed25519`,gatewayPublicKeyFingerprint:e.publicKeyFingerprint,payload:n,signature:i}}function sg(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}var cg=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 ug(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=lg(t)??(p.default.basename(n)||n),o=r?{...r,title:lg(t)??r.title,updatedAt:i}:{id:`proj_${Tm(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 ug(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 lg(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function ug(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)}var dg=120,fg=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_${Tm(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 pg(dg);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 pg(e){return new Promise(t=>setTimeout(t,e))}var mg=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new fg(this.provider,e)}};function hg(e){let t=yg(_g(e)),n=bg(t.type);return n&&(t.type=gg(n)),t}function gg(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 vg(e)}}function _g(e){if(Array.isArray(e))return e.map(e=>_g(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[vg(n)]=_g(r);return t}return e}function vg(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function yg(e){return typeof e==`object`&&e?e:{}}function bg(e){if(typeof e==`string`)return e}function xg(e){return typeof e==`string`||typeof e==`number`?String(e):``}var Sg=[...`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}`)],Cg=[b.default.join(b.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),b.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function wg(e,t){let n=Tg(e);if(!n)return null;let r=JSON.parse(y.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:b.default.resolve(b.default.dirname(n),i)}function Tg(e){for(let t of Cg)try{return(0,x.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}function Eg(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 Dg(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var Og=3e4,kg=5e3,Ag=1e3,jg=2e3,Mg=1e3,Ng={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Pg=class e{constructor(e,t,n,r,i,a){this.process=t,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.closeInterruptTimeoutMs=r,this.closeGraceTimeoutMs=i,this.forceKillTimeoutMs=a,this.processExitPromise=new Promise(e=>{this.resolveProcessExit=e}),this.bindProcess()}id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;stdoutBuffer=``;stderrTail=``;closeInterruptTimeoutMs;closeGraceTimeoutMs;forceKillTimeoutMs;processExitPromise;resolveProcessExit=null;closePromise=null;static async create(t,n={}){let r=new e(t,n.spawnProcess?.()??Ig(),n.requestTimeoutMs??Og,n.closeInterruptTimeoutMs??Ag,n.closeGraceTimeoutMs??jg,n.forceKillTimeoutMs??Mg);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}onEvent(e){return this.listeners.add(e),()=>{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=Eg(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=zg(this.activeSessionConfig.reasoningEffort),o;try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a})}catch(e){if(!(a===`minimal`&&Bg(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`})}let s=bg(o.turn?.id);s&&(this.activeTurnId=s)}catch(e){throw this.turnInProgress=!1,e}}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}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 tool approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;if(r.method===`item/commandExecution/requestApproval`||r.method===`execCommandApproval`){let e={decision:i};this.sendResponse(r.rpcId,e)}else{let e={decision:i};this.sendResponse(r.rpcId,e)}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=Hg(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:Dg(r),inputMethod:n.method})}async bootstrap(){let e={clientInfo:Ng,capabilities:{experimentalApi:!1,optOutNotificationMethods:Sg}};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 bg((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 bg((await this.sendRequest(`thread/resume`,i)).thread?.id)}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.consumeStderrChunk(String(e))}),this.process.on(`error`,e=>{this.handleProcessFailure(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.resolveProcessExit?.(),this.resolveProcessExit=null,this.closed)return;let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.handleProcessFailure(`Codex app-server exited unexpectedly (${i})${r}`)})}async closeInternal(){this.closed||(await this.tryInterruptTurnForClose(),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.pendingApprovals.clear(),this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.endProcessStdin(),!await this.waitForProcessExit(this.closeGraceTimeoutMs)&&(this.tryKillProcess(`SIGTERM`),!await this.waitForProcessExit(this.forceKillTimeoutMs)&&(this.tryKillProcess(`SIGKILL`),await this.waitForProcessExit(this.forceKillTimeoutMs))))}async tryInterruptTurnForClose(){if(!(!this.threadId||!this.activeTurnId))try{await Ug(this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:this.activeTurnId}),this.closeInterruptTimeoutMs,`Codex app-server turn/interrupt timed out during close`)}catch{}}endProcessStdin(){if(!(this.process.stdin.destroyed||this.process.stdin.writableEnded))try{this.process.stdin.end()}catch{}}async waitForProcessExit(e){if(this.process.exitCode!==null)return!0;if(!Number.isFinite(e)||e<=0)return await this.processExitPromise,!0;let t;try{await Promise.race([this.processExitPromise,new Promise(n=>{t=setTimeout(n,e)})])}finally{t&&clearTimeout(t)}return this.process.exitCode!==null}tryKillProcess(e){if(this.process.exitCode===null)try{this.process.kill(e)}catch{}}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
472
|
-
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t&&this.handleIncomingLine(t)}}consumeStderrChunk(e){this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}handleIncomingLine(e){let t;try{t=JSON.parse(e)}catch{this.emit({type:`native.raw`,source:`codex.app_server`,parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON line from codex app-server`,line:e});return}this.emit({type:`native.raw`,source:`codex.app_server`,message:t});let n=
|
|
473
|
-
`)}emit(e){for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=
|
|
471
|
+
`});return t?n.pop():n.push(n.pop().slice(0,-1)),n}var Zh=class{async listDirectories(e,t,n=200){let r=await d.default.realpath(p.default.resolve(e));return ag(r,await rg(r,t),n)}async listDirectoriesUnrestricted(e,t=200,n=f.default.homedir()){let r=await ig(e,n),i=p.default.parse(r).root;return ag(i,r,t)}async readFile(e,t){let{absolutePath:n,normalizedPath:r}=await Qh(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 Qh(e,t),a=await d.default.readFile(r,`utf8`);return{path:i,absolutePath:r,diff:Yh(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=$h(t),a=await eg(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 Qh(e,t){let n=await d.default.realpath(p.default.resolve(e)),r=$h(t),i=await eg(n,r),a=await d.default.realpath(i);return tg(n,a,r),{absolutePath:a,normalizedPath:r}}function $h(e){let t=e.trim();if(!t)throw Error(`Path is required`);return t}async function eg(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 tg(e,n,t),n}function tg(e,t,n){let r=ng(e),i=ng(t);if(t!==e&&!i.startsWith(r))throw Error(`Path outside project root is not allowed: ${n}`)}function ng(e){return e.endsWith(p.default.sep)?e:`${e}${p.default.sep}`}async function rg(e,t){let n=t?.trim(),r=n?p.default.isAbsolute(n)?p.default.resolve(n):p.default.resolve(e,n):e;tg(e,r,n??`.`);let i=await d.default.realpath(r);if(tg(e,i,n??`.`),!(await d.default.stat(i)).isDirectory())throw Error(`Path is not a directory: ${i}`);return i}async function ig(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 ag(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}}async function og(e){let t=p.default.join(e,`gateway-identity.json`);await d.default.mkdir(e,{recursive:!0,mode:448});try{let e=await d.default.readFile(t,`utf8`),n=JSON.parse(e);return{identity:n.identity,privateKeyPem:n.privateKeyPem,path:t,created:!1}}catch(e){if(!ug(e))throw e}let n=sg(),r={v:1,identity:n.identity,privateKeyPem:n.privateKeyPem};return await d.default.writeFile(t,`${JSON.stringify(r,null,2)}\n`,{encoding:`utf8`,mode:384}),{...n,path:t,created:!0}}function sg(){let{publicKey:e,privateKey:t}=(0,l.generateKeyPairSync)(`ed25519`),n=e.export({format:`der`,type:`spki`}),r=t.export({format:`pem`,type:`pkcs8`}).toString(),i=new Date().toISOString();return{identity:{algorithm:`ed25519`,publicKey:n.toString(`base64`),publicKeyFingerprint:cg(n),keyVersion:1,createdAt:i},privateKeyPem:r}}function cg(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`)}function lg(e,t,n){let r=(0,l.createPrivateKey)(t),i=(0,l.sign)(null,Buffer.from(ea(n),`utf8`),r).toString(`base64`);return{algorithm:`ed25519`,gatewayPublicKeyFingerprint:e.publicKeyFingerprint,payload:n,signature:i}}function ug(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}var dg=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 pg(e),r=this.projectByPath.get(n),i=new Date().toISOString(),a=fg(t)??(p.default.basename(n)||n),o=r?{...r,title:fg(t)??r.title,updatedAt:i}:{id:`proj_${Om(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 pg(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 fg(e){if(typeof e==`string`)return e.replace(/\s+/g,` `).trim()||void 0}async function pg(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)}var mg=120,hg=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_${Om(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 gg(mg);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 gg(e){return new Promise(t=>setTimeout(t,e))}var _g=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new hg(this.provider,e)}};function vg(e){let t=Sg(bg(e)),n=Cg(t.type);return n&&(t.type=yg(n)),t}function yg(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 xg(e)}}function bg(e){if(Array.isArray(e))return e.map(e=>bg(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[xg(n)]=bg(r);return t}return e}function xg(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function Sg(e){return typeof e==`object`&&e?e:{}}function Cg(e){if(typeof e==`string`)return e}function wg(e){return typeof e==`string`||typeof e==`number`?String(e):``}var Tg=[...`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}`)],Eg=[b.default.join(b.default.dirname(process.execPath),`__remote_agent_runtime__.cjs`),b.default.join(process.cwd(),`__remote_agent_runtime__.cjs`)];function Dg(e,t){let n=Og(e);if(!n)return null;let r=JSON.parse(y.default.readFileSync(n,`utf8`)),i=typeof r.bin==`string`?r.bin:r.bin?.[t];return typeof i!=`string`||!i.trim()?null:b.default.resolve(b.default.dirname(n),i)}function Og(e){for(let t of Eg)try{return(0,x.createRequire)(t).resolve(`${e}/package.json`)}catch{continue}return null}function kg(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 Ag(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var jg=3e4,Mg=5e3,Ng=1e3,Pg=2e3,Fg=1e3,Ig={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Lg=class e{constructor(e,t,n,r,i,a){this.process=t,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.logger=e.logger,this.requestTimeoutMs=n,this.closeInterruptTimeoutMs=r,this.closeGraceTimeoutMs=i,this.forceKillTimeoutMs=a,this.processExitPromise=new Promise(e=>{this.resolveProcessExit=e}),this.bindProcess()}id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;listeners=new Set;pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;requestTimeoutMs;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;titleReadInFlight=!1;stdoutBuffer=``;stderrTail=``;closeInterruptTimeoutMs;closeGraceTimeoutMs;forceKillTimeoutMs;processExitPromise;resolveProcessExit=null;closePromise=null;static async create(t,n={}){let r=new e(t,n.spawnProcess?.()??zg(),n.requestTimeoutMs??jg,n.closeInterruptTimeoutMs??Ng,n.closeGraceTimeoutMs??Pg,n.forceKillTimeoutMs??Fg);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}onEvent(e){return this.listeners.add(e),()=>{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=kg(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=Hg(this.activeSessionConfig.reasoningEffort),o;try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a})}catch(e){if(!(a===`minimal`&&Ug(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`})}let s=Cg(o.turn?.id);s&&(this.activeTurnId=s)}catch(e){throw this.turnInProgress=!1,e}}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}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 tool approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;if(r.method===`item/commandExecution/requestApproval`||r.method===`execCommandApproval`){let e={decision:i};this.sendResponse(r.rpcId,e)}else{let e={decision:i};this.sendResponse(r.rpcId,e)}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=Gg(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:Ag(r),inputMethod:n.method})}async bootstrap(){let e={clientInfo:Ig,capabilities:{experimentalApi:!1,optOutNotificationMethods:Tg}};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 Cg((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 Cg((await this.sendRequest(`thread/resume`,i)).thread?.id)}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.consumeStderrChunk(String(e))}),this.process.on(`error`,e=>{this.handleProcessFailure(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.resolveProcessExit?.(),this.resolveProcessExit=null,this.closed){this.log(`info`,`codex app-server process exited during shutdown`,{exitCode:e,signal:t});return}let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.handleProcessFailure(`Codex app-server exited unexpectedly (${i})${r}`)})}async closeInternal(){if(this.closed)return;let e=Date.now(),t={threadId:this.threadId,activeTurnId:this.activeTurnId};this.log(`info`,`codex app-server shutdown starting`,{...t,turnInProgress:this.turnInProgress,pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,closeInterruptTimeoutMs:this.closeInterruptTimeoutMs,closeGraceTimeoutMs:this.closeGraceTimeoutMs,forceKillTimeoutMs:this.forceKillTimeoutMs});let n=await this.tryInterruptTurnForClose();this.log(n.result===`failed`?`warn`:`info`,`codex app-server shutdown turn interrupt completed`,{...t,interrupt:n}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.pendingApprovals.clear(),this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.endProcessStdin();let r=Date.now();if(await this.waitForProcessExit(this.closeGraceTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`graceful_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r});return}this.log(`warn`,`codex app-server shutdown grace period elapsed; sending SIGTERM`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r}),this.tryKillProcess(`SIGTERM`);let i=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigterm_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i});return}this.log(`warn`,`codex app-server shutdown SIGTERM grace elapsed; sending SIGKILL`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i}),this.tryKillProcess(`SIGKILL`);let a=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigkill_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a});return}this.log(`error`,`codex app-server shutdown did not observe process exit after SIGKILL`,{...t,result:`sigkill_timeout`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a})}async tryInterruptTurnForClose(){let e=Date.now();if(!this.threadId||!this.activeTurnId)return{attempted:!1,result:`skipped`,durationMs:Date.now()-e,reason:this.threadId?`missing_active_turn_id`:`missing_thread_id`};try{return await Kg(this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:this.activeTurnId}),this.closeInterruptTimeoutMs,`Codex app-server turn/interrupt timed out during close`),{attempted:!0,result:`submitted`,durationMs:Date.now()-e}}catch(t){return{attempted:!0,result:`failed`,durationMs:Date.now()-e,error:String(t)}}}endProcessStdin(){if(!(this.process.stdin.destroyed||this.process.stdin.writableEnded))try{this.process.stdin.end()}catch{}}async waitForProcessExit(e){if(this.process.exitCode!==null)return!0;if(!Number.isFinite(e)||e<=0)return await this.processExitPromise,!0;let t;try{await Promise.race([this.processExitPromise,new Promise(n=>{t=setTimeout(n,e)})])}finally{t&&clearTimeout(t)}return this.process.exitCode!==null}tryKillProcess(e){if(this.process.exitCode===null)try{this.process.kill(e)}catch{}}log(e,t,n={}){let r=this.logger?.[e];r&&r({provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,processPid:this.process.pid??void 0,model:this.activeModel??this.model,cwd:this.cwd,...n},t)}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
472
|
+
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t&&this.handleIncomingLine(t)}}consumeStderrChunk(e){this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}handleIncomingLine(e){let t;try{t=JSON.parse(e)}catch{this.emit({type:`native.raw`,source:`codex.app_server`,parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON line from codex app-server`,line:e});return}this.emit({type:`native.raw`,source:`codex.app_server`,message:t});let n=Cg(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let e={method:n,id:t.id,params:t.params};this.handleServerRequest(e);return}if(n){let e={method:n,params:t.params};this.handleNotification(e);return}r&&this.handleResponse(t)}handleResponse(e){let t=wg(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=Sg(e.error),r=Cg(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}`);return}}registerApprovalRequest(e,t,n,r){let i=`req_${Om(8)}`;this.pendingApprovals.set(i,{rpcId:e,method:t,kind:n});let a=Sg(r),o=Cg(a.threadId);o&&(this.threadId=o),this.emit({type:`tool.permission.requested`,requestId:i,toolName:n===`command`?`command_execution`:`file_change`,reason:Cg(a.reason),threadId:o,turnId:Cg(a.turnId),itemId:Cg(a.itemId),approvalMethod:t,rawParams:bg(a)})}registerUserInputRequest(e,t,n){let r=`req_${Om(8)}`;this.pendingUserInputs.set(r,{rpcId:e,method:t});let i=Cg(n.threadId);i&&(this.threadId=i);let a=Array.isArray(n.questions)?n.questions.map(Wg).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:r,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:bg(n)})}handleNotification(e){switch(e.method){case`thread/started`:{let t=e.params,n=Cg(t.thread?.id);n&&(this.threadId=n),this.emitThreadTitleUpdated(Cg(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:bg(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Cg(t.threadId);n&&(this.threadId=n),this.emitThreadTitleUpdated(Cg(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params,n=Cg(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.emit({type:`turn.started`,turn:bg(t.turn)});return}case`turn/completed`:{let t=e.params,n=Cg(t.turn?.status);if(this.turnInProgress=!1,this.activeTurnId=void 0,n===`failed`){this.emit({type:`turn.failed`,status:n,turn:bg(t.turn),error:bg(t.turn?.error??{})});return}this.emit({type:`turn.completed`,status:n,turn:bg(t.turn)}),this.tryEmitTitleFromThreadRead();return}case`item/started`:{let t=e.params;this.emit({type:`item.started`,item:vg(t.item)});return}case`item/completed`:{let t=e.params;this.emit({type:`item.completed`,item:vg(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;this.emit({type:`item.updated`,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;this.emit({type:`item.updated`,item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;this.emit({type:`item.updated`,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=Sg(e.params);this.emit({type:`item.updated`,item:{id:Cg(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Cg(t.delta)??Cg(t.text)??``,original_method:e.method,payload:bg(t)}});return}case`error`:{let t=e.params;this.emit({type:`error`,message:Cg(t.error?.message)??`Codex app-server error`,error:bg(t.error),thread_id:Cg(t.threadId),turn_id:Cg(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=wg(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(),this.process.stdin.write(`${JSON.stringify(e)}
|
|
473
|
+
`)}emit(e){for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=Vg(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(Cg(e.thread?.preview),`codex.thread_read_preview`,{thread_id:this.threadId})}catch{}finally{this.titleReadInFlight=!1}}}handleProcessFailure(e){if(!this.closed){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`,message:e})}}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};async function Rg(e=Mg){let t=Bg();return new Promise(n=>{let r=!1,i=(0,S.spawn)(t.command,[...t.args,`app-server`,`--help`],{stdio:[`ignore`,`ignore`,`ignore`],windowsHide:!0}),a=e=>{r||(r=!0,clearTimeout(o),n(e))},o=setTimeout(()=>{!i.killed&&i.exitCode===null&&i.kill(),a(!1)},e);i.on(`error`,()=>{a(!1)}),i.on(`exit`,e=>{a(e===0)})})}function zg(){let e=Bg();return(0,S.spawn)(e.command,[...e.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function Bg(){let e=process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(e)return{command:process.execPath,args:[b.default.resolve(e)]};try{let e=Dg(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}function Vg(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function Hg(e){return e?e===`max`?`xhigh`:e:null}function Ug(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function Wg(e){let t=Sg(e),n=Cg(t.id),r=Cg(t.header),i=Cg(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=Sg(e),n=Cg(t.label),r=Cg(t.description);return!n||!r?null:{label:n,description:r}}).filter(e=>e!==null):null;return{id:n,header:r,question:i,isOther:t.isOther===!0,isSecret:t.isSecret===!0,options:o}}function Gg(e){let t={};for(let[n,r]of Object.entries(e??{}))n&&(t[n]=Array.isArray(r)?r.map(e=>String(e)):[]);return t}async function Kg(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)}}var qg=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new _g(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await Rg()}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??Lg.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)}}},Jg=15e3,Yg={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},Xg=class{constructor(e,t={}){this.process=e,this.requestTimeoutMs=t.requestTimeoutMs??Jg,this.bindProcess()}pendingRequests=new Map;requestTimeoutMs;stdoutBuffer=``;stderrTail=``;nextRequestId=1;closed=!1;async bootstrap(){let e={clientInfo:Yg,capabilities:{experimentalApi:!1,optOutNotificationMethods:Tg}};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.process.stdin.destroyed||this.process.stdin.end(),!this.process.killed&&this.process.exitCode===null&&this.process.kill())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=wg(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}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.process.stdin.write(`${JSON.stringify(e)}
|
|
474
474
|
`)}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}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.handleProcessFailure(`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.handleProcessFailure(`Codex app-server exited unexpectedly (${i})${r}`)})}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
475
|
-
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t&&this.handleIncomingLine(t)}}handleIncomingLine(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=bg(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=xg(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=yg(e.error),r=bg(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleProcessFailure(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 Jg(e,t={}){let n=new qg(t.spawnProcess?.()??Yg(t.codexBinOverride),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}function Yg(e){let t=Xg(e);return(0,S.spawn)(t.command,[...t.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function Xg(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[b.default.resolve(t)]};try{let e=wg(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}async function Zg(e){let t=[],n=null;do{let r=await Qg({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function Qg(e){return Jg(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>t_(e)),nextCursor:n.nextCursor}})}async function $g(e,t=!0){return Jg(async n=>t_((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function e_(){let e=[],t=null;do{let n=await Jg(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>n_(e))),t=n.nextCursor}while(t);return e}function t_(e){let t=bg(yg(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:i_(e.source),gitInfo:e.gitInfo?yg(_g(e.gitInfo)):null,turns:e.turns.map(e=>r_(e))}}function n_(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 r_(e){return{id:e.id,status:e.status,error:e.error?yg(_g(e.error)):null,items:e.items.map(e=>hg(e))}}function i_(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`}var a_=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;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.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=Eg(this.activeSessionConfig,t?.sessionConfig);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=u_(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:Dg(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=g_(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:__(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)=>s_(e,t)?this.requestUserInput(e,t,n):o_(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${Tm(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=c_(t),i=`req_${Tm(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=g_(e),n=__(t.session_id)??__(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_${Tm(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=x_(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=__(e.tool_id)??__(e.tool_use_id)??y_(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=__(e.uuid);if(n)return this.activeToolItemId=n,n;let r=S_(__(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=g_(e),n=__(t.type);if(n===`user`){let e=f_(g_(t.message));return e?[{type:`item.completed`,item:{id:__(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:e,turn_id:this.activeTurnId,source_event_type:__(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.activeAssistantItemId,n=this.ensureAssistantItemId(t);e&&e!==n&&(this.assistantStarted=!1,this.assistantCompleted=!1);let r=d_(t),i=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(i.push({type:`item.started`,item:{id:n,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),i.push({type:`item.completed`,item:{id:n,type:`agent_message`,text:r,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,i}if(n===`stream_event`){let e=g_(t.event);if(__(e.type)===`message_start`){let t=x_(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=p_(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||__(t.subtype)?.startsWith(`error_`)===!0){let n=m_(t);return[...e,{type:`turn.failed`,error:{message:n},usage:h_(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:h_(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=__(t.summary)??`tool summary`,i=__(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=__(t.tool_name)??`tool`,i=__(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=__(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(__(t.session_id)??__(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:__(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=__(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}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 o_(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 s_(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function c_(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,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=l_(n.options);return{id:r,header:i,question:a,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function l_(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;return n?{label:n,description:r}:null}).filter(e=>e!==null);return t.length>0?t:null}function u_(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function d_(e){return f_(g_(e.message))||(v_(e.result)??``)}function f_(e){let t=v_(e.content);if(t)return t;let n=v_(e.text)??v_(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=g_(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
|
|
476
|
-
`)}function p_(e){let t=g_(g_(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text;if(typeof t.partial_json==`string`&&t.partial_json.length>0)return t.partial_json}function m_(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):__(e.subtype)||`Claude turn failed`}function h_(e){let t=g_(e);return{input_tokens:b_(t.input_tokens)??b_(t.inputTokens)??0,cached_input_tokens:b_(t.cached_input_tokens)??b_(t.cache_read_input_tokens)??b_(t.cacheReadInputTokens)??0,output_tokens:b_(t.output_tokens)??b_(t.outputTokens)??0}}function g_(e){return typeof e==`object`&&e?e:{}}function __(e){if(typeof e==`string`&&e.trim())return e}function v_(e){if(typeof e==`string`&&e.length>0)return e}function y_(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function b_(e){if(typeof e==`number`&&Number.isFinite(e))return e}function x_(e){let t=__(g_(e.message).id);if(t)return t;let n=__(g_(g_(e.event).message).id);if(n)return n}function S_(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var C_=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=w_(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 w_(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var T_=`@anthropic-ai/claude-agent-sdk`,E_=`claude-sonnet-4-6`,D_=1e4,O_=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(T_),!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(T_),n=await k_(A_(t,e),D_,`Claude native query session creation timed out`);if(n)return n;let r=await k_(j_(t,e),D_,`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 k_(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 A_(e,t){let n=M_(e);if(!n)return null;let r=t.model??E_;return new a_(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=N_(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 j_(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 C_(`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 C_(`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 C_(`claude`,t.sessionId,t.model,n)}return null}function M_(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function N_(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 P_(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new Wg(n,r):new O_(n,r)}const F_=p.default.join(`.claude`,`projects`);async function I_(e){return(await(0,C.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>U_(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function L_(e,t){let n=V_(e,t?.homeDir),r;try{r=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),a=await X_(t);if(!q_(a))continue;let o=await d.default.stat(t),s=K_(a,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});i.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}return i.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function R_(e){let t=await Z_(e.nativeSessionId,e.projectPath),n=await Q_(e.projectPath,e.nativeSessionId,e.homeDir);return W_({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}async function z_(e){let t=await Z_(e.nativeSessionId,e.projectPath),n=await Q_(e.projectPath,e.nativeSessionId,e.homeDir);return G_({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function B_(e,t,n){return p.default.join(V_(e,n),`${t}.jsonl`)}function V_(e,t){let n=t??f.default.homedir();return p.default.join(n,F_,H_(e))}function H_(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function U_(e){let t=J_(e.customTitle)??J_(e.summary)??J_(e.firstPrompt),n=Y_(e.lastModified);return{nativeSessionId:e.sessionId,cwd:J_(e.cwd),title:t,createdAt:n,updatedAt:n}}function W_(e){let t=[],n=K_(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=0,s,c=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()},l=(n,r,a)=>{i+=1,t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`,ts:c(a),type:n,payload:{raw:r}})},u=(e,t)=>s||(o+=1,s={id:`claude_hist_turn_${o}`,terminal:!1,failed:!1},l(`turn.started`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s),d=(e,t)=>{if(!s||s.terminal){s=void 0;return}s.terminal=!0,l(`turn.completed`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s=void 0},f=(e,t,n)=>{let r=u(t,n);r.terminal||(r.terminal=!0,r.failed=!0,l(`turn.failed`,{turn_id:r.id,source_event_type:`claude.history`,source_line:n,error:{message:e}},t),s=void 0)};l(`thread.started`,{thread_id:e.nativeSessionId,source:`claude.history.getSessionMessages`},n.createdAt),n.title&&l(`thread.title.updated`,{title:n.title,source:`claude.history.first_user_message`,thread_id:e.nativeSessionId},n.createdAt);for(let t of e.rows){let e=t.type;if(!e||e===`queue-operation`)continue;if(e===`user`){let e=av(t.raw.message),n=nv(e),r=tv(e);if(n){d(t.timestamp,t.line);let e=u(t.timestamp,t.line);l(`item.completed`,{item:{id:ov(t.raw.uuid)??`claude_user_${t.line}`,type:`user_message`,text:n,turn_id:e.id,source_event_type:`claude.user`},source_line:t.line},t.timestamp)}for(let e=0;e<r.length;e+=1){let n=r[e],i=u(t.timestamp,t.line);l(`item.completed`,{item:{id:n.toolUseId??`claude_tool_result_${t.line}_${e+1}`,type:`tool_status`,status:n.isError?`failed`:`completed`,tool_name:n.toolName??`tool`,text:n.text,turn_id:i.id,source_event_type:`claude.tool_result`},source_line:t.line},t.timestamp)}continue}if(e!==`assistant`)continue;let n=av(t.raw.message),r=u(t.timestamp,t.line),i=ev(n);for(let e=0;e<i.length;e+=1){let n=i[e];l(`item.started`,{item:{id:n.id??`claude_tool_use_${t.line}_${e+1}`,type:`tool_status`,status:`running`,tool_name:n.name,text:n.summary,command:n.command,turn_id:r.id,source_event_type:`claude.tool_use`},source_line:t.line},t.timestamp)}let a=nv(n);a&&l(`item.completed`,{item:{id:ov(n.id)??ov(t.raw.uuid)??`claude_assistant_${t.line}`,type:`agent_message`,text:a,turn_id:r.id,source_event_type:`claude.assistant`},source_line:t.line},t.timestamp);let o=ov(t.raw.error);o&&f(o,t.timestamp,t.line)}return d(n.updatedAt),t}function G_(e){let t=[],n=K_(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 K_(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=iv(nv(av(t.raw.message)))),!n&&t.type===`assistant`&&(n=ov(av(t.raw.message).model));let o=i??cv(t.createdAtFallbackMs)??0,s=a??cv(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function q_(e){for(let t of e){if(t.type===`user`){let e=av(t.raw.message);if(nv(e)||tv(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=av(t.raw.message);if(nv(e)||ev(e).length>0||ov(t.raw.error))return!0}return!1}function J_(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Y_(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function X_(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
|
477
|
-
`),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=
|
|
478
|
-
`)}function rv(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=av(e),r=ov(t.text)??ov(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function iv(e,t=60){if(!e)return;let n=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 av(e){return typeof e==`object`&&e?e:{}}function ov(e){return typeof e==`string`&&e.trim()||void 0}function sv(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function cv(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var lv=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}=dv(r,[t,n]);if(fv(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=mv(await this.refreshProjects()),r=!0);let i=await pv(n.projects,t);if(!i)throw Error(`Discovered project not found: ${t}`);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=mv(await this.refreshProjects()),i=await pv(n.projects,t),!i)throw Error(`Discovered project not found: ${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 Qg({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 uv({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>_v(e.cwd),mapSession:e=>{let t=vv(e.createdAt),n=vv(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:_v(e.name)??_v(e.preview),model:_v(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 uv({sessions:await I_(),canonicalPathCache:e,getRawPath:e=>_v(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:_v(e.title),model:_v(e.model),createdAt:_v(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 uv(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 hv(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function dv(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:gv(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=yv(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(xv)})).sort((e,t)=>bv(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function fv(e){return Object.values(e).some(e=>e?.status===`failed`)}async function pv(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await ug(t);return e.find(e=>e.path===r)}function mv(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function hv(e,t){let n=t.get(e);return n||(n=ug(e),t.set(e,n)),n}function gv(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function _v(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function vv(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function yv(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function bv(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 xv(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Sv=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 Cv(this.getProjectPath(e),Ev);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 wv(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 wv(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 Cv(this.indexPath,Tv)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Cv(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 wv(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 Tv(e){return!Dv(e)||e.v!==1||typeof e.generatedAt!=`string`||!ba.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>xa.safeParse(e).success)}function Ev(e){return!Dv(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!xa.safeParse(e.project).success||!ba.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Sa.safeParse(e).success)}function Dv(e){return typeof e==`object`&&!!e}const Ov=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function kv(e){let t=Ja.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=Eo(ko(Nv(i.export({format:`jwk`})))),o=xo({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:Ya.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 Av(e){let t=Ja.parse(e.clientHello),n=Ya.parse(e.gatewayHello),r=Xa.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!za.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([Ov,Do(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(So({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,Do(r.signature)))throw Error(`transcript_invalid`)}function jv(e){let t=Ya.parse(e.gatewayHello),n=Xa.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:Oo(Do(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return To({role:`gateway`,keySchedule:wo({gatewayId:e.gatewayId,clientHello:Ja.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function Mv(e){return eo.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function Nv(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var Pv=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}close(){this.readyState=3}},Fv=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.mobileId,e.payload);return;case`rpc.request`:await this.handleRpcRequest(e.mobileId,e.requestId,e.payload);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(vo.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,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile 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`||!n.clientId){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}await this.dependencies.dispatchCommand(t,n.deviceId,n.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(vo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Lv(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(vo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Lv(t,`auth.refresh`)})}}async handleRpcRequest(e,t,n){let r=this.mobileConnections.get(e);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,requestId:t,messageType:`rpc`,payload:{...Iv(`BAD_REQUEST`,400,`Unknown mobile ${e}`),method:n.method}});return}if(r.handshake.status!==`ready`){this.sendSecureError(e,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}try{let i=await this.dependencies.handleRpcRequest(n,{mobileId:e,deviceId:r.deviceId});this.dependencies.sendFrame(vo.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:e,requestId:t,messageType:`rpc`,payload:i}))}catch(r){let i=io.safeParse(r);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,requestId:t,messageType:`rpc`,payload:{...i.success?i.data:Iv(`INTERNAL`,500,String(r)),method:n.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=kv({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(vo.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{Av({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Rv(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=jv({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(vo.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,zv(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new Pv(t=>{let n=vo.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,payload:t});this.dependencies.sendFrame(n)}),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:Mv({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`})})}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:Iv(e.code,e.status,e.message)})}};function Iv(e,t,n){return io.parse({code:e,status:t,message:n})}function Lv(e,t){let n=String(e);return t===`pairing.claim`&&(n.includes(`Invalid pairing code`)||n.includes(`Pairing code expired`))?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(n.includes(`Refresh token revoked`)||n.includes(`Device revoked`)||n.includes(`Refresh token device mismatch`)||n.includes(`TokenExpiredError:`)||n.includes(`JsonWebTokenError:`)||n.includes(`NotBeforeError:`))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Rv(e){let t=String(e);return t.includes(`identity_mismatch`)?`identity_mismatch`:t.includes(`counter_replay`)?`counter_replay`:t.includes(`unsupported_version`)?`unsupported_version`:`transcript_invalid`}function zv(e){let t=String(e);return t.includes(`revoked`)?`device_revoked`:t.includes(`mismatch`)||t.includes(`not registered`)?`identity_mismatch`:`transcript_invalid`}var Bv=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;webSocketFactory;socket;reconnectTimer;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.webSocketFactory=e.webSocketFactory??Uv}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;this.socket=void 0,e?.close(1e3,`Gateway shutting down`)}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=vo.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=Vv(this.options.relayUrl,t);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.addEventListener(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,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.addEventListener(`message`,e=>{if(this.socket===r)try{let t=vo.parse(JSON.parse(Hv(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.addEventListener(`error`,e=>{this.socket===r&&this.logger.warn?.({event:e},`relay websocket emitted error`)}),r.addEventListener(`close`,e=>{if(this.socket===r){if(this.socket=void 0,this.stopped){this.state=`stopped`;return}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)}};function Vv(e,t){let n=new URL(e);return n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`),n.pathname=`/ws/gateway`,n.searchParams.set(`gatewayAccessToken`,t),n.toString()}function Hv(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`data`in e){let t=e.data;return typeof t==`string`?t:t instanceof ArrayBuffer?Buffer.from(t).toString(`utf8`):ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString(`utf8`):String(t)}return String(e)}function Uv(e){let t=globalThis.WebSocket;if(!t)throw Error(`Global WebSocket is not available in this runtime`);return new t(e)}function Wv(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 Gv(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(Kv(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(Wv({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 uo.parse(JSON.parse(r)).token}function Kv(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()}const qv=[{id:`gpt-5.3-codex`,label:`GPT-5.3 Codex`,isDefault:!0,supportedReasoningEfforts:[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]}],Jv=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],Yv=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],Xv=yi.options,Zv=[`read-only`,`workspace-write`,`danger-full-access`],Qv=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],$v={codex:[{version:`codex-mobile-v1`,defaults:{model:`gpt-5.3-codex`,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{model:`gpt-5.3-codex`,reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]},ey={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function ty(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function ny(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function ry(e,t){let n=t?.trim().toLowerCase();return n?($v[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function iy(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:Yv}:{}},...e.map(e=>({...e,isDefault:!1}))]}function ay(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function oy(e){let t=new Set;for(let n of e){let e=ay(n);e&&t.add(e)}return[...t]}function sy(e){return e?.trim()||void 0}function cy(e){let t=sy(e.runtimeModel);if(t)return t;let n=sy(e.discoveredModel);if(n)return n;let r=sy(e.existingModel),i=sy(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function ly(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,isDefault:e.isDefault,supportedReasoningEfforts:oy(e.supportedReasoningEfforts)}));return t.length===0?qv:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function uy(){try{return ly(await e_())}catch{return null}}async function dy(){try{let e=await import(`@anthropic-ai/claude-agent-sdk`),t=e.query??e.default?.query;if(typeof t!=`function`)return null;let n=t({prompt:`Model capability probe`,options:{permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let e=await n.supportedModels(),t=[];for(let n of e){let e=typeof n.value==`string`?n.value:``;if(!e)continue;let r=n.supportsEffort?oy(n.supportedEffortLevels??[]):void 0;t.push({id:e,label:n.displayName||e,isDefault:e===`default`,supportedReasoningEfforts:r})}return t.length===0?null:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}finally{n.close()}}catch{return null}}function fy(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]}var py=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:ty(e.runtimeLifecycle?.idleTtlMs,ey.idleTtlMs),sweepIntervalMs:ny(e.runtimeLifecycle?.sweepIntervalMs,ey.sweepIntervalMs),maxSessions:ty(e.runtimeLifecycle?.maxSessions,ey.maxSessions),maxCodexSessions:ty(e.runtimeLifecycle?.maxCodexSessions,ey.maxCodexSessions),maxClaudeSessions:ty(e.runtimeLifecycle?.maxClaudeSessions,ey.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()];await Promise.allSettled(e.map(e=>this.closeRuntimeSession(e,`shutdown`)))}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 Error(`Cannot delete project ${e} while sessions are running`);return this.options.projectStore.remove(e)}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 resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw Error(`Project not found: ${t}`);let r=ry(e,n),i=r?.version??`default`,a=`${e}::${i}`,o=Date.now(),s=this.providerCapabilitiesCache.get(a);if(s){if(s.expiresAt>o)return s.value;this.providerCapabilitiesCache.delete(a)}let c=this.providerCapabilitiesInFlight.get(a);if(c)return c;let l=(async()=>{let t=P_(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1,a=n?`native`:`fallback`,o=e===`codex`&&n?await uy()??qv:qv,s=e===`claude`&&n?await dy()??Jv:Jv,c=oy(s.flatMap(e=>e.supportedReasoningEfforts??[])),l=e===`codex`?{provider:e,source:a,models:o,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:Yv,approvalPolicies:Xv,sandboxModes:Zv,permissionModes:[]},defaults:{model:o.find(e=>e.isDefault)?.id??o[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:a,models:s,support:{reasoningEffort:c.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:c,approvalPolicies:[],sandboxModes:[],permissionModes:Qv},defaults:{model:s.find(e=>e.isDefault)?.id??s[0]?.id,reasoningEffort:fy(s),permissionMode:`default`}};if(!r)return{capabilities:l,resolvedAgentVersion:i};let u={...l.defaults,...r.defaults},d=u.model?.trim(),f=d?iy(l.models,d,e):l.models;return{capabilities:{...l,models:f,defaults:u},resolvedAgentVersion:r.version}})();this.providerCapabilitiesInFlight.set(a,l);try{let e=await l;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Error(`Project not found: ${e}`);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){return this.getRuntimeSessionSummary(e,t)||this.options.historyStore.getProjectSession(e,t)}async getProjectSessionEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Error(`Project not found: ${e}`);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Error(`Session ${t} not found in project ${e}`);let s=await this.options.historyStore.getSessionEvents(t,Math.max(n,300));if(o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0)return s.slice(-Math.max(1,n));if(o.provider===`claude`){let t=Ey(o);if(!t)return s.slice(-Math.max(1,n));try{let r=await R_({projectPath:o.projectPath,nativeSessionId:t,provider:o.provider,sessionId:o.id,projectId:e});return o.source===`native_discovered`?gy(r,s.filter(e=>!hy.has(e.type)),n):vy(s,r,hy,n)}catch{return s.slice(-Math.max(1,n))}}if(o.provider!==`codex`)return s.slice(-Math.max(1,n));let c=wy([o.nativeSessionId,o.id]);for(let t of c)try{return vy(s,Dy({thread:await $g(t,!0),provider:o.provider,sessionId:o.id,projectId:e}),my,n)}catch{}return s.slice(-Math.max(1,n))}async getProjectSessionRawEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Error(`Project not found: ${e}`);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Error(`Session ${t} not found in project ${e}`);let s=await this.options.historyStore.getSessionRawEvents(o.id,Math.max(n,300));return o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0?s.slice(-Math.max(1,n)):(a?await this.syncExternalRawHistory(o,e,s):s).slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300,r){let i=await this.resolveProjectSessionForRawRead(e,t,r);return this.options.historyStore.getSessionRawEventsCompacted(i.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3,i){let a=await this.resolveProjectSessionForRawRead(e,t,i);return this.options.historyStore.getSessionRawEventsSinceSeq(a.id,n,r)}async getProjectSessionRawSeqRange(e,t,n){let r=await this.resolveProjectSessionForRawRead(e,t,n);return this.options.historyStore.getSessionRawSeqRange(r.id)}async resolveProjectSessionForRawRead(e,t,n){let r=await this.options.projectStore.getById(e);if(!r)throw Error(`Project not found: ${e}`);let i=n?.syncExternal===!0,a=this.options.historyStore.getProjectSession(e,t);if(!a&&i&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)):a?.provider===`codex`&&i?(await this.syncCodexSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a):a?.provider===`claude`&&i&&(await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a),!a)throw Error(`Session ${t} not found in project ${e}`);return a}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${Tm(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=await P_(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}).createSession({sessionId:n,model:e.model,cwd:t.path,sessionConfig:e.sessionConfig,metadata:e.metadata});if(r&&i.providerMode!==`native`)throw await i.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let a=this.resolveCanonicalSessionId(e.provider,i,n),o=this.resolveNativeSessionId(e.provider,i,a),s=new Date().toISOString(),c=await this.attachRuntimeSession({id:a,nativeSessionId:o,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:i.providerMode,model:e.model,title:void 0,createdAt:s,updatedAt:s,status:`idle`,providerSession:i,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(c),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:c.id,detail:{provider:e.provider,model:e.model,sessionConfig:e.sessionConfig,projectId:t.id,projectPath:t.path}}),{sessionId:c.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw Error(`Session not found: ${e}`);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:r?.model,sessionConfig:r?.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:r?.model,sessionConfig:r?.sessionConfig}),!i.title){let e=Ay(t);e&&this.setSessionTitle(i,e)}if(typeof r?.model==`string`&&r.model.trim()){let e=r.model.trim();i.model!==e&&(i.model=e,i.updatedAt=new Date().toISOString(),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:My(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 Error(`Session not found: ${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_${Tm(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=P_(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,a=await r.createSession({sessionId:t.id,model:t.model,cwd:t.projectPath,resumeSessionId:i,metadata:{resumeFromHistory:!0}});if(n&&a.providerMode!==`native`)throw await a.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let o=this.resolveCanonicalSessionId(t.provider,a,t.id),s=this.resolveNativeSessionId(t.provider,a,t.nativeSessionId),c=await this.attachRuntimeSession({id:o,nativeSessionId:s,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:a.providerMode,model:t.model,title:t.title,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:a,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(c),c}async syncCodexSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await Zg(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=Ny(n.createdAt),s=Ny(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:cy({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??Ay(n.preview)??t?.title,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 L_(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??t?.title??n.title,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 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 Error(`Project not found: ${e}`);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await Py(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Error(`Project not found: ${e}`);return await Py(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=jy(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===`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_${Tm(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;try{r.unsubscribe()}catch{}try{await r.providerSession.close()}catch(t){console.error(`[session-runtime] failed closing session ${e}: ${String(t)}`)}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(!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_${Tm(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n||e.source!==`native_discovered`)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=Ey(e);if(!r)return n;try{let i=await z_({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,i)}catch(t){return e.source===`native_discovered`&&Ty(t)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),n}}if(e.provider!==`codex`)return n;let r=wy([e.nativeSessionId,e.id]);for(let i of r)try{let r=Oy({thread:await $g(i,!0),provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,r)}catch{}return n}async finalizeExternalRawHistorySync(e,t,n){let r=_y(t,n),i=await this.maybePersistSyncedExternalRawEvents(e,r,!0);return e.source===`native_discovered`&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),i}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw Error(`Session not found: ${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.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){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return this.toSessionSummary(n)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,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=ky(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 my=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]),hy=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]);function gy(e,t,n){let r=new Map;for(let t of e)r.set(t.eventId,t);for(let e of t)r.set(e.eventId,e);return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,n))}function _y(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[...n.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function vy(e,t,n,r){let i=new Map,a=new Map;for(let t of e)if(i.set(t.eventId,t),n.has(t.type)){let e=yy(t);a.set(e,(a.get(e)??0)+1)}for(let e of t){if(!n.has(e.type))continue;let t=yy(e),r=a.get(t)??0;if(r>0){r===1?a.delete(t):a.set(t,r-1);continue}i.set(e.eventId,e)}return[...i.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,r))}function yy(e){let t=by(e.payload.raw),n=by(t.item),r=by(t.turn),i=xy(t.turn_id)??xy(t.turnId)??xy(r.id)??``,a=xy(r.status)??xy(t.status)??``,o=xy(t.thread_id)??xy(t.threadId)??``,s=xy(n.type)??``,c=xy(n.phase)??``,l=xy(n.status)??``,u=xy(n.command)??``,d=Cy(n),f=Sy(t.message)??``,p=Sy(t.title)??``;return e.type.startsWith(`item.`)?[e.type,s,c,l,u,d||f].join(`|`):e.type.startsWith(`turn.`)?[e.type,i,a].join(`|`):e.type===`thread.title.updated`?[e.type,p].join(`|`):[e.type,o,i,s,p||f].join(`|`)}function by(e){return typeof e==`object`&&e?e:{}}function xy(e){return typeof e==`string`&&e.trim()||void 0}function Sy(e){if(typeof e==`string`)return e.length>0?e:void 0}function Cy(e){let t=Sy(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=Sy(by(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
479
|
-
`)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>
|
|
480
|
-
`)}return``}function
|
|
475
|
+
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t&&this.handleIncomingLine(t)}}handleIncomingLine(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=Cg(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=wg(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=Sg(e.error),r=Cg(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleProcessFailure(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 Zg(e,t={}){let n=new Xg(t.spawnProcess?.()??Qg(t.codexBinOverride),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}function Qg(e){let t=$g(e);return(0,S.spawn)(t.command,[...t.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function $g(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();if(t)return{command:process.execPath,args:[b.default.resolve(t)]};try{let e=Dg(`@openai/codex`,`codex`);if(e)return{command:process.execPath,args:[e]}}catch{}return{command:`codex`,args:[]}}async function e_(e){let t=[],n=null;do{let r=await t_({cwd:e,archived:!1,cursor:n,limit:100});t.push(...r.threads),n=r.nextCursor}while(n);return t}async function t_(e){return Zg(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>i_(e)),nextCursor:n.nextCursor}})}async function n_(e,t=!0){return Zg(async n=>i_((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function r_(){let e=[],t=null;do{let n=await Zg(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>a_(e))),t=n.nextCursor}while(t);return e}function i_(e){let t=Cg(Sg(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:s_(e.source),gitInfo:e.gitInfo?Sg(bg(e.gitInfo)):null,turns:e.turns.map(e=>o_(e))}}function a_(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 o_(e){return{id:e.id,status:e.status,error:e.error?Sg(bg(e.error)):null,items:e.items.map(e=>vg(e))}}function s_(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`}var c_=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;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.interruptRequested=!1,this.activeTurnStarted=!1,this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=kg(this.activeSessionConfig,t?.sessionConfig);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=p_(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:Ag(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=y_(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:b_(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)=>u_(e,t)?this.requestUserInput(e,t,n):l_(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${Om(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=d_(t),i=`req_${Om(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=y_(e),n=b_(t.session_id)??b_(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_${Om(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=w_(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=b_(e.tool_id)??b_(e.tool_use_id)??S_(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=b_(e.uuid);if(n)return this.activeToolItemId=n,n;let r=T_(b_(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=y_(e),n=b_(t.type);if(n===`user`){let e=h_(y_(t.message));return e?[{type:`item.completed`,item:{id:b_(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:e,turn_id:this.activeTurnId,source_event_type:b_(t.source_event_type)??`user`}}]:[]}if(n===`assistant`){let e=this.activeAssistantItemId,n=this.ensureAssistantItemId(t);e&&e!==n&&(this.assistantStarted=!1,this.assistantCompleted=!1);let r=m_(t),i=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(i.push({type:`item.started`,item:{id:n,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),i.push({type:`item.completed`,item:{id:n,type:`agent_message`,text:r,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,i}if(n===`stream_event`){let e=y_(t.event);if(b_(e.type)===`message_start`){let t=w_(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=g_(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||b_(t.subtype)?.startsWith(`error_`)===!0){let n=__(t);return[...e,{type:`turn.failed`,error:{message:n},usage:v_(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:v_(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=b_(t.summary)??`tool summary`,i=b_(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=b_(t.tool_name)??`tool`,i=b_(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=b_(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(b_(t.session_id)??b_(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:b_(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=b_(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}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 l_(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 u_(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function d_(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,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=f_(n.options);return{id:r,header:i,question:a,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function f_(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;return n?{label:n,description:r}:null}).filter(e=>e!==null);return t.length>0?t:null}function p_(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function m_(e){return h_(y_(e.message))||(x_(e.result)??``)}function h_(e){let t=x_(e.content);if(t)return t;let n=x_(e.text)??x_(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=y_(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
|
|
476
|
+
`)}function g_(e){let t=y_(y_(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text;if(typeof t.partial_json==`string`&&t.partial_json.length>0)return t.partial_json}function __(e){let t=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return t.length>0?t.join(`; `):b_(e.subtype)||`Claude turn failed`}function v_(e){let t=y_(e);return{input_tokens:C_(t.input_tokens)??C_(t.inputTokens)??0,cached_input_tokens:C_(t.cached_input_tokens)??C_(t.cache_read_input_tokens)??C_(t.cacheReadInputTokens)??0,output_tokens:C_(t.output_tokens)??C_(t.outputTokens)??0}}function y_(e){return typeof e==`object`&&e?e:{}}function b_(e){if(typeof e==`string`&&e.trim())return e}function x_(e){if(typeof e==`string`&&e.length>0)return e}function S_(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function C_(e){if(typeof e==`number`&&Number.isFinite(e))return e}function w_(e){let t=b_(y_(e.message).id);if(t)return t;let n=b_(y_(y_(e.event).message).id);if(n)return n}function T_(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var E_=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=D_(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 D_(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var O_=`@anthropic-ai/claude-agent-sdk`,k_=`claude-sonnet-4-6`,A_=1e4,j_=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(O_),!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(O_),n=await M_(N_(t,e),A_,`Claude native query session creation timed out`);if(n)return n;let r=await M_(P_(t,e),A_,`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 M_(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 N_(e,t){let n=F_(e);if(!n)return null;let r=t.model??k_;return new c_(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=I_(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 P_(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 E_(`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 E_(`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 E_(`claude`,t.sessionId,t.model,n)}return null}function F_(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function I_(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 L_(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new qg(n,r):new j_(n,r)}const R_=p.default.join(`.claude`,`projects`);async function z_(e){return(await(0,C.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>K_(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function B_(e,t){let n=W_(e,t?.homeDir),r;try{r=await d.default.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let i=[];for(let e of r){if(!e.isFile()||!e.name.endsWith(`.jsonl`))continue;let t=p.default.join(n,e.name),r=e.name.slice(0,-6),a=await $_(t);if(!X_(a))continue;let o=await d.default.stat(t),s=Y_(a,{createdAtFallbackMs:o.birthtimeMs,updatedAtFallbackMs:o.mtimeMs});i.push({nativeSessionId:r,model:s.model,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt})}return i.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function V_(e){let t=await ev(e.nativeSessionId,e.projectPath),n=await tv(e.projectPath,e.nativeSessionId,e.homeDir);return q_({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}async function H_(e){let t=await ev(e.nativeSessionId,e.projectPath),n=await tv(e.projectPath,e.nativeSessionId,e.homeDir);return J_({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs})}function U_(e,t,n){return p.default.join(W_(e,n),`${t}.jsonl`)}function W_(e,t){let n=t??f.default.homedir();return p.default.join(n,R_,G_(e))}function G_(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function K_(e){let t=Z_(e.customTitle)??Z_(e.summary)??Z_(e.firstPrompt),n=Q_(e.lastModified);return{nativeSessionId:e.sessionId,cwd:Z_(e.cwd),title:t,createdAt:n,updatedAt:n}}function q_(e){let t=[],n=Y_(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=0,s,c=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()},l=(n,r,a)=>{i+=1,t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`,ts:c(a),type:n,payload:{raw:r}})},u=(e,t)=>s||(o+=1,s={id:`claude_hist_turn_${o}`,terminal:!1,failed:!1},l(`turn.started`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s),d=(e,t)=>{if(!s||s.terminal){s=void 0;return}s.terminal=!0,l(`turn.completed`,{turn_id:s.id,source_event_type:`claude.history`,source_line:t},e),s=void 0},f=(e,t,n)=>{let r=u(t,n);r.terminal||(r.terminal=!0,r.failed=!0,l(`turn.failed`,{turn_id:r.id,source_event_type:`claude.history`,source_line:n,error:{message:e}},t),s=void 0)};l(`thread.started`,{thread_id:e.nativeSessionId,source:`claude.history.getSessionMessages`},n.createdAt),n.title&&l(`thread.title.updated`,{title:n.title,source:`claude.history.first_user_message`,thread_id:e.nativeSessionId},n.createdAt);for(let t of e.rows){let e=t.type;if(!e||e===`queue-operation`)continue;if(e===`user`){let e=cv(t.raw.message),n=av(e),r=iv(e);if(n){d(t.timestamp,t.line);let e=u(t.timestamp,t.line);l(`item.completed`,{item:{id:lv(t.raw.uuid)??`claude_user_${t.line}`,type:`user_message`,text:n,turn_id:e.id,source_event_type:`claude.user`},source_line:t.line},t.timestamp)}for(let e=0;e<r.length;e+=1){let n=r[e],i=u(t.timestamp,t.line);l(`item.completed`,{item:{id:n.toolUseId??`claude_tool_result_${t.line}_${e+1}`,type:`tool_status`,status:n.isError?`failed`:`completed`,tool_name:n.toolName??`tool`,text:n.text,turn_id:i.id,source_event_type:`claude.tool_result`},source_line:t.line},t.timestamp)}continue}if(e!==`assistant`)continue;let n=cv(t.raw.message),r=u(t.timestamp,t.line),i=rv(n);for(let e=0;e<i.length;e+=1){let n=i[e];l(`item.started`,{item:{id:n.id??`claude_tool_use_${t.line}_${e+1}`,type:`tool_status`,status:`running`,tool_name:n.name,text:n.summary,command:n.command,turn_id:r.id,source_event_type:`claude.tool_use`},source_line:t.line},t.timestamp)}let a=av(n);a&&l(`item.completed`,{item:{id:lv(n.id)??lv(t.raw.uuid)??`claude_assistant_${t.line}`,type:`agent_message`,text:a,turn_id:r.id,source_event_type:`claude.assistant`},source_line:t.line},t.timestamp);let o=lv(t.raw.error);o&&f(o,t.timestamp,t.line)}return d(n.updatedAt),t}function J_(e){let t=[],n=Y_(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 Y_(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=sv(av(cv(t.raw.message)))),!n&&t.type===`assistant`&&(n=lv(cv(t.raw.message).model));let o=i??dv(t.createdAtFallbackMs)??0,s=a??dv(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function X_(e){for(let t of e){if(t.type===`user`){let e=cv(t.raw.message);if(av(e)||iv(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=cv(t.raw.message);if(av(e)||rv(e).length>0||lv(t.raw.error))return!0}return!1}function Z_(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Q_(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function $_(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
|
477
|
+
`),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=cv(i),o=lv(a.timestamp),s=o?uv(o):void 0;n.push({line:e+1,raw:a,type:lv(a.type),timestamp:o,timestampMs:s})}return n}async function ev(e,t){let n=await(0,C.getSessionMessages)(e,{dir:t});if(n.length===0)throw Error(`Claude session ${e} returned no messages from getSessionMessages`);return n.map((e,t)=>nv(e,t+1))}async function tv(e,t,n){let r=U_(e,t,n);try{return await d.default.stat(r)}catch{let e=Date.now();return{birthtimeMs:e,mtimeMs:e}}}function nv(e,t){let n=cv(e),r=cv(n.message),i=lv(n.timestamp)??lv(r.timestamp)??lv(r.created_at)??lv(r.createdAt);return{line:t,raw:{...n,message:r},type:lv(n.type),timestamp:i,timestampMs:i?uv(i):void 0}}function rv(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=cv(e);if(lv(t.type)!==`tool_use`)continue;let r=cv(t.input),i=lv(r.command),a=lv(t.name)??`tool`,o=lv(r.description);n.push({id:lv(t.id),name:a,command:i,summary:o??i??`${a} started`})}return n}function iv(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=cv(e);if(lv(t.type)!==`tool_result`)continue;let r=lv(t.content)??lv(cv(t.toolUseResult).stdout)??lv(cv(t.tool_use_result).stdout)??lv(t.text);n.push({toolUseId:lv(t.tool_use_id)??lv(t.toolUseId),toolName:lv(t.tool_name)??lv(t.toolName),text:r,isError:t.is_error===!0})}return n}function av(e){let t=lv(e.content);if(t)return t;let n=lv(e.text)??lv(e.prompt);if(n)return 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=cv(e),n=lv(t.type);if(n&&n!==`text`)continue;let r=lv(t.text)??lv(t.content)??ov(t);r&&i.push(r)}if(i.length!==0)return i.join(`
|
|
478
|
+
`)}function ov(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=cv(e),r=lv(t.text)??lv(t.value);r&&n.push(r)}return n.length>0?n.join(``):void 0}function sv(e,t=60){if(!e)return;let n=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 cv(e){return typeof e==`object`&&e?e:{}}function lv(e){return typeof e==`string`&&e.trim()||void 0}function uv(e){let t=Date.parse(e);if(Number.isFinite(t))return t}function dv(e){if(!(!Number.isFinite(e)||e<=0))return Math.round(e)}var fv=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}=mv(r,[t,n]);if(hv(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=_v(await this.refreshProjects()),r=!0);let i=await gv(n.projects,t);if(!i)throw Error(`Discovered project not found: ${t}`);let a=await this.options.store.getProject(i.key);if(!a&&!r){if(n=_v(await this.refreshProjects()),i=await gv(n.projects,t),!i)throw Error(`Discovered project not found: ${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 t_({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 pv({sessions:[...n.values()],canonicalPathCache:e,getRawPath:e=>bv(e.cwd),mapSession:e=>{let t=xv(e.createdAt),n=xv(e.updatedAt,t);return{provider:`codex`,nativeSessionId:e.id,title:bv(e.name)??bv(e.preview),model:bv(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 pv({sessions:await z_(),canonicalPathCache:e,getRawPath:e=>bv(e.cwd),mapSession:e=>({provider:`claude`,nativeSessionId:e.nativeSessionId,title:bv(e.title),model:bv(e.model),createdAt:bv(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 pv(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 vv(i,e.canonicalPathCache);t.push({canonicalProjectPath:n,session:e.mapSession(r)})}catch{n+=1}}return{records:t,skippedCount:n}}function mv(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:yv(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=Sv(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(wv)})).sort((e,t)=>Cv(e.project,t.project));return{projects:r.map(e=>e.project),projectSessions:r}}function hv(e){return Object.values(e).some(e=>e?.status===`failed`)}async function gv(e,t){let n=e.find(e=>e.path===t);if(n)return n;let r=await pg(t);return e.find(e=>e.path===r)}function _v(e){return{v:1,generatedAt:e.generatedAt,providers:e.providers,projects:e.projects}}async function vv(e,t){let n=t.get(e);return n||(n=pg(e),t.set(e,n)),n}function yv(e){return(0,l.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}function bv(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function xv(e,t){return!Number.isFinite(e)||e<=0?t??new Date(0).toISOString():new Date(e*1e3).toISOString()}function Sv(e,t){return e&&e.updatedAt>=t.updatedAt?e:t}function Cv(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 wv(e,t){return e.updatedAt===t.updatedAt?`${e.provider}:${e.nativeSessionId}`.localeCompare(`${t.provider}:${t.nativeSessionId}`):t.updatedAt.localeCompare(e.updatedAt)}var Tv=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 Ev(this.getProjectPath(e),kv);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 Dv(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 Dv(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 Ev(this.indexPath,Ov)}getProjectPath(e){return p.default.join(this.projectsDir,`${e}.json`)}enqueueWrite(e){return this.writeQueue=this.writeQueue.then(e,e),this.writeQueue}};async function Ev(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 Dv(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 Ov(e){return!Av(e)||e.v!==1||typeof e.generatedAt!=`string`||!ba.safeParse(e.providers).success||!Array.isArray(e.projects)?!1:e.projects.every(e=>xa.safeParse(e).success)}function kv(e){return!Av(e)||e.v!==1||typeof e.projectKey!=`string`||e.projectKey.length===0||typeof e.canonicalProjectPath!=`string`||e.canonicalProjectPath.length===0||!xa.safeParse(e.project).success||!ba.safeParse(e.providers).success||!Array.isArray(e.sessions)?!1:e.sessions.every(e=>Sa.safeParse(e).success)}function Av(e){return typeof e==`object`&&!!e}const jv=Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]);function Mv(e){let t=Ja.parse(e.clientHello),n=(0,l.randomBytes)(32).toString(`base64`),{privateKey:r,publicKey:i}=(0,l.generateKeyPairSync)(`x25519`),a=Eo(ko(Iv(i.export({format:`jwk`})))),o=xo({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:Ya.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 Nv(e){let t=Ja.parse(e.clientHello),n=Ya.parse(e.gatewayHello),r=Xa.parse(e.clientAuth);if(t.version!==n.version||r.version!==t.version||!za.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([jv,Do(t.deviceIdentity.publicKey)])});if(!(0,l.verify)(null,Buffer.from(So({gatewayId:e.gatewayId,clientHello:t,gatewayHello:{gatewayNonce:n.gatewayNonce,gatewayPublicKeyFingerprint:n.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:n.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:r.clientEphemeralPublicKey}}),`utf8`),i,Do(r.signature)))throw Error(`transcript_invalid`)}function Pv(e){let t=Ya.parse(e.gatewayHello),n=Xa.parse(e.clientAuth),r=(0,l.createPublicKey)({key:{crv:`X25519`,kty:`OKP`,x:Oo(Do(n.clientEphemeralPublicKey))},format:`jwk`}),i=(0,l.diffieHellman)({privateKey:e.gatewayEphemeralPrivateKey,publicKey:r});return To({role:`gateway`,keySchedule:wo({gatewayId:e.gatewayId,clientHello:Ja.parse(e.clientHello),gatewayHello:{gatewayNonce:t.gatewayNonce,gatewayPublicKeyFingerprint:t.gatewayPublicKeyFingerprint,gatewayEphemeralPublicKey:t.gatewayEphemeralPublicKey},clientAuth:{clientEphemeralPublicKey:n.clientEphemeralPublicKey},sharedSecret:new Uint8Array(i),keyEpoch:1})})}function Fv(e){return eo.parse({version:1,gatewayId:e.gatewayId,deviceId:e.deviceId,code:e.code,message:e.message,retryable:e.retryable})}function Iv(e){if(typeof e.x!=`string`||e.x.length===0)throw Error(`x25519 public key export missing x`);return e.x}var Lv=class{OPEN=1;readyState=1;constructor(e){this.onPayload=e}send(e){let t=JSON.parse(e);this.onPayload(t)}close(){this.readyState=3}},Rv=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.mobileId,e.payload);return;case`rpc.request`:await this.handleRpcRequest(e.mobileId,e.requestId,e.payload);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(vo.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,t){if(!e){this.sendRelayError({code:`BAD_REQUEST`,status:400,message:`from_mobile 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`||!n.clientId){this.sendSecureError(e,n.deviceId,`transcript_invalid`,`secure handshake not ready`);return}await this.dependencies.dispatchCommand(t,n.deviceId,n.clientId)}async handlePairingClaim(e,t){try{let n=await this.dependencies.handlePairingClaim(t);this.dependencies.sendFrame(vo.parse({type:`pairing.claim.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Bv(t,`pairing.claim`)})}}async handleRefresh(e,t){try{let n=await this.dependencies.handleRefresh(t);this.dependencies.sendFrame(vo.parse({type:`auth.refresh.result`,gatewayId:this.dependencies.gatewayId,requestId:e,messageType:`system`,payload:n}))}catch(t){this.sendRelayError({requestId:e,...Bv(t,`auth.refresh`)})}}async handleRpcRequest(e,t,n){let r=this.mobileConnections.get(e);if(!r){this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,requestId:t,messageType:`rpc`,payload:{...zv(`BAD_REQUEST`,400,`Unknown mobile ${e}`),method:n.method}});return}if(r.handshake.status!==`ready`){this.sendSecureError(e,r.deviceId,`transcript_invalid`,`secure handshake not ready`);return}try{let i=await this.dependencies.handleRpcRequest(n,{mobileId:e,deviceId:r.deviceId});this.dependencies.sendFrame(vo.parse({type:`rpc.response`,gatewayId:this.dependencies.gatewayId,mobileId:e,requestId:t,messageType:`rpc`,payload:i}))}catch(r){let i=io.safeParse(r);this.dependencies.sendFrame({type:`rpc.error`,gatewayId:this.dependencies.gatewayId,mobileId:e,requestId:t,messageType:`rpc`,payload:{...i.success?i.data:zv(`INTERNAL`,500,String(r)),method:n.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=Mv({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(vo.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{Nv({gatewayId:this.dependencies.gatewayId,clientHello:n.handshake.clientHello,gatewayHello:n.handshake.gatewayHello,clientAuth:t})}catch(t){this.sendSecureError(e,n.deviceId,Vv(t),String(t));return}try{let r=await this.dependencies.verifyDeviceIdentityBinding(n.deviceId,n.handshake.clientHello.deviceIdentity),i=Pv({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(vo.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,Hv(t),String(t))}}ensureReadyMobileClient(e){if(e.clientId&&e.socket)return;let t=new Lv(t=>{let n=vo.parse({type:`to_mobile`,gatewayId:this.dependencies.gatewayId,mobileId:e.mobileId,messageType:`event`,payload:t});this.dependencies.sendFrame(n)}),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:Fv({gatewayId:this.dependencies.gatewayId,deviceId:t,code:n,message:r,retryable:n===`transcript_invalid`||n===`unsupported_version`})})}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:zv(e.code,e.status,e.message)})}};function zv(e,t,n){return io.parse({code:e,status:t,message:n})}function Bv(e,t){let n=String(e);return t===`pairing.claim`&&(n.includes(`Invalid pairing code`)||n.includes(`Pairing code expired`))?{code:`BAD_REQUEST`,status:400,message:n}:t===`auth.refresh`&&(n.includes(`Refresh token revoked`)||n.includes(`Device revoked`)||n.includes(`Refresh token device mismatch`)||n.includes(`TokenExpiredError:`)||n.includes(`JsonWebTokenError:`)||n.includes(`NotBeforeError:`))?{code:`UNAUTHORIZED`,status:401,message:n}:{code:`INTERNAL`,status:500,message:n}}function Vv(e){let t=String(e);return t.includes(`identity_mismatch`)?`identity_mismatch`:t.includes(`counter_replay`)?`counter_replay`:t.includes(`unsupported_version`)?`unsupported_version`:`transcript_invalid`}function Hv(e){let t=String(e);return t.includes(`revoked`)?`device_revoked`:t.includes(`mismatch`)||t.includes(`not registered`)?`identity_mismatch`:`transcript_invalid`}var Uv=class{logger;reconnectBaseDelayMs;reconnectMaxDelayMs;webSocketFactory;socket;reconnectTimer;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.webSocketFactory=e.webSocketFactory??Kv}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;this.socket=void 0,e?.close(1e3,`Gateway shutting down`)}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=vo.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=Wv(this.options.relayUrl,t);this.state=`connecting`;let r=this.webSocketFactory(n);this.socket=r,r.addEventListener(`open`,()=>{this.socket!==r||this.stopped||(this.reconnectAttempt=0,this.state=`connected`,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.addEventListener(`message`,e=>{if(this.socket===r)try{let t=vo.parse(JSON.parse(Gv(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.addEventListener(`error`,e=>{this.socket===r&&this.logger.warn?.({event:e},`relay websocket emitted error`)}),r.addEventListener(`close`,e=>{if(this.socket===r){if(this.socket=void 0,this.stopped){this.state=`stopped`;return}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)}};function Wv(e,t){let n=new URL(e);return n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`),n.pathname=`/ws/gateway`,n.searchParams.set(`gatewayAccessToken`,t),n.toString()}function Gv(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`data`in e){let t=e.data;return typeof t==`string`?t:t instanceof ArrayBuffer?Buffer.from(t).toString(`utf8`):ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString(`utf8`):String(t)}return String(e)}function Kv(e){let t=globalThis.WebSocket;if(!t)throw Error(`Global WebSocket is not available in this runtime`);return new t(e)}function qv(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 Jv(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(Yv(e.relayUrl),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(qv({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 uo.parse(JSON.parse(r)).token}function Yv(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()}const Xv=[{id:`gpt-5.3-codex`,label:`GPT-5.3 Codex`,isDefault:!0,supportedReasoningEfforts:[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]}],Zv=[{id:`default`,label:`Default`,isDefault:!0,supportedReasoningEfforts:[`low`,`medium`,`high`,`max`]}],Qv=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],$v=yi.options,ey=[`read-only`,`workspace-write`,`danger-full-access`],ty=[`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`],ny={codex:[{version:`codex-mobile-v1`,defaults:{model:`gpt-5.3-codex`,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}},{version:`codex-mobile-v2`,defaults:{model:`gpt-5.3-codex`,reasoningEffort:`low`,approvalPolicy:`on-request`,sandboxMode:`read-only`}}],claude:[{version:`claude-mobile-v1`,defaults:{model:`default`}}]},ry={idleTtlMs:900*1e3,sweepIntervalMs:60*1e3,maxSessions:24,maxCodexSessions:8,maxClaudeSessions:16};function iy(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function ay(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function oy(e,t){let n=t?.trim().toLowerCase();return n?(ny[e]??[]).find(e=>n===e.version.toLowerCase())??null:null}function sy(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:Qv}:{}},...e.map(e=>({...e,isDefault:!1}))]}function cy(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function ly(e){let t=new Set;for(let n of e){let e=cy(n);e&&t.add(e)}return[...t]}function uy(e){return e?.trim()||void 0}function dy(e){let t=uy(e.runtimeModel);if(t)return t;let n=uy(e.discoveredModel);if(n)return n;let r=uy(e.existingModel),i=uy(e.modelProvider)?.toLowerCase();if(r&&(!i||r.toLowerCase()!==i))return r}function fy(e){let t=e.filter(e=>!!e.id).map(e=>({id:e.id,label:e.displayName||e.model||e.id,isDefault:e.isDefault,supportedReasoningEfforts:ly(e.supportedReasoningEfforts)}));return t.length===0?Xv:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}async function py(){try{return fy(await r_())}catch{return null}}async function my(){try{let e=await import(`@anthropic-ai/claude-agent-sdk`),t=e.query??e.default?.query;if(typeof t!=`function`)return null;let n=t({prompt:`Model capability probe`,options:{permissionMode:`plan`,maxTurns:1,includePartialMessages:!1}});try{let e=await n.supportedModels(),t=[];for(let n of e){let e=typeof n.value==`string`?n.value:``;if(!e)continue;let r=n.supportsEffort?ly(n.supportedEffortLevels??[]):void 0;t.push({id:e,label:n.displayName||e,isDefault:e===`default`,supportedReasoningEfforts:r})}return t.length===0?null:(t.some(e=>e.isDefault)||(t[0]={...t[0],isDefault:!0}),t)}finally{n.close()}}catch{return null}}function hy(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]}var gy=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:iy(e.runtimeLifecycle?.idleTtlMs,ry.idleTtlMs),sweepIntervalMs:ay(e.runtimeLifecycle?.sweepIntervalMs,ry.sweepIntervalMs),maxSessions:iy(e.runtimeLifecycle?.maxSessions,ry.maxSessions),maxCodexSessions:iy(e.runtimeLifecycle?.maxCodexSessions,ry.maxCodexSessions),maxClaudeSessions:iy(e.runtimeLifecycle?.maxClaudeSessions,ry.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`))),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 Error(`Cannot delete project ${e} while sessions are running`);return this.options.projectStore.remove(e)}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 resolveProviderCapabilities(e,t,n){if(t&&!await this.options.projectStore.getById(t))throw Error(`Project not found: ${t}`);let r=oy(e,n),i=r?.version??`default`,a=`${e}::${i}`,o=Date.now(),s=this.providerCapabilitiesCache.get(a);if(s){if(s.expiresAt>o)return s.value;this.providerCapabilitiesCache.delete(a)}let c=this.providerCapabilitiesInFlight.get(a);if(c)return c;let l=(async()=>{let t=L_(e,{preferNative:this.options.preferNativeProviders,requireNative:!1}),n=this.options.preferNativeProviders?await t.isNativeAvailable().catch(()=>!1):!1,a=n?`native`:`fallback`,o=e===`codex`&&n?await py()??Xv:Xv,s=e===`claude`&&n?await my()??Zv:Zv,c=ly(s.flatMap(e=>e.supportedReasoningEfforts??[])),l=e===`codex`?{provider:e,source:a,models:o,support:{reasoningEffort:!0,approvalPolicy:!0,sandboxMode:!0,permissionMode:!1},options:{reasoningEfforts:Qv,approvalPolicies:$v,sandboxModes:ey,permissionModes:[]},defaults:{model:o.find(e=>e.isDefault)?.id??o[0]?.id,reasoningEffort:`medium`,approvalPolicy:`on-request`,sandboxMode:`workspace-write`}}:{provider:e,source:a,models:s,support:{reasoningEffort:c.length>0,approvalPolicy:!1,sandboxMode:!1,permissionMode:!0},options:{reasoningEfforts:c,approvalPolicies:[],sandboxModes:[],permissionModes:ty},defaults:{model:s.find(e=>e.isDefault)?.id??s[0]?.id,reasoningEffort:hy(s),permissionMode:`default`}};if(!r)return{capabilities:l,resolvedAgentVersion:i};let u={...l.defaults,...r.defaults},d=u.model?.trim(),f=d?sy(l.models,d,e):l.models;return{capabilities:{...l,models:f,defaults:u},resolvedAgentVersion:r.version}})();this.providerCapabilitiesInFlight.set(a,l);try{let e=await l;return this.providerCapabilitiesCache.set(a,{value:e,expiresAt:Date.now()+864e5}),e}finally{this.providerCapabilitiesInFlight.delete(a)}}async listProjectSessions(e,t=`all`,n){let r=await this.options.projectStore.getById(e);if(!r)throw Error(`Project not found: ${e}`);return n?.syncExternal&&(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r)),this.listProjectSessionsWithRuntime(e,t)}async getProjectSessionSummary(e,t){return this.getRuntimeSessionSummary(e,t)||this.options.historyStore.getProjectSession(e,t)}async getProjectSessionEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Error(`Project not found: ${e}`);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Error(`Session ${t} not found in project ${e}`);let s=await this.options.historyStore.getSessionEvents(t,Math.max(n,300));if(o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0)return s.slice(-Math.max(1,n));if(o.provider===`claude`){let t=ky(o);if(!t)return s.slice(-Math.max(1,n));try{let r=await V_({projectPath:o.projectPath,nativeSessionId:t,provider:o.provider,sessionId:o.id,projectId:e});return o.source===`native_discovered`?yy(r,s.filter(e=>!vy.has(e.type)),n):xy(s,r,vy,n)}catch{return s.slice(-Math.max(1,n))}}if(o.provider!==`codex`)return s.slice(-Math.max(1,n));let c=Dy([o.nativeSessionId,o.id]);for(let t of c)try{return xy(s,Ay({thread:await n_(t,!0),provider:o.provider,sessionId:o.id,projectId:e}),_y,n)}catch{}return s.slice(-Math.max(1,n))}async getProjectSessionRawEvents(e,t,n=300,r){let i=await this.options.projectStore.getById(e);if(!i)throw Error(`Project not found: ${e}`);let a=r?.syncExternal===!0,o=this.options.historyStore.getProjectSession(e,t);if(!o&&this.getRuntimeSessionSummary(e,t))return[];if(!o&&a&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(i),await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)):o?.provider===`codex`&&a?(await this.syncCodexSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o):o?.provider===`claude`&&a&&(await this.syncClaudeSessionsForProject(i),o=this.options.historyStore.getProjectSession(e,t)??o),!o)throw Error(`Session ${t} not found in project ${e}`);let s=await this.options.historyStore.getSessionRawEvents(o.id,Math.max(n,300));return o.source===`native_discovered`&&!a||o.source!==`native_discovered`&&!a&&s.length>0?s.slice(-Math.max(1,n)):(a?await this.syncExternalRawHistory(o,e,s):s).slice(-Math.max(1,n))}async getProjectSessionRawEventsCompacted(e,t,n=300,r){let i=await this.resolveProjectSessionForRawRead(e,t,r);return this.options.historyStore.getSessionRawEventsCompacted(i.id,n)}async getProjectSessionRawEventsSinceSeq(e,t,n,r=2e3,i){let a=await this.resolveProjectSessionForRawRead(e,t,i);return this.options.historyStore.getSessionRawEventsSinceSeq(a.id,n,r)}async getProjectSessionRawSeqRange(e,t,n){let r=await this.resolveProjectSessionForRawRead(e,t,n);return this.options.historyStore.getSessionRawSeqRange(r.id)}async resolveProjectSessionForRawRead(e,t,n){let r=await this.options.projectStore.getById(e);if(!r)throw Error(`Project not found: ${e}`);let i=n?.syncExternal===!0,a=this.options.historyStore.getProjectSession(e,t);if(!a&&i&&this.options.preferNativeProviders?(await this.syncCodexSessionsForProject(r),await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)):a?.provider===`codex`&&i?(await this.syncCodexSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a):a?.provider===`claude`&&i&&(await this.syncClaudeSessionsForProject(r),a=this.options.historyStore.getProjectSession(e,t)??a),!a)throw Error(`Session ${t} not found in project ${e}`);return a}async startSession(e){let t=await this.resolveProjectForSessionStart(e.projectId,e.cwd),n=`sess_${Om(10)}`,r=e.provider===`codex`&&this.options.requireNativeCodex,i=await L_(e.provider,{preferNative:this.options.preferNativeProviders,requireNative:r}).createSession({sessionId:n,model:e.model,cwd:t.path,sessionConfig:e.sessionConfig,metadata:e.metadata,logger:this.options.logger});if(r&&i.providerMode!==`native`)throw await i.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let a=this.resolveCanonicalSessionId(e.provider,i,n),o=this.resolveNativeSessionId(e.provider,i,a),s=new Date().toISOString(),c=await this.attachRuntimeSession({id:a,nativeSessionId:o,source:`gateway`,projectId:t.id,projectPath:t.path,provider:e.provider,providerMode:i.providerMode,model:e.model,title:void 0,createdAt:s,updatedAt:s,status:`idle`,providerSession:i,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!1,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return this.markSessionStreamReady(c),await this.options.auditLogger.record({ts:new Date().toISOString(),action:`session.start`,deviceId:e.deviceId,sessionId:c.id,detail:{provider:e.provider,model:e.model,sessionConfig:e.sessionConfig,projectId:t.id,projectPath:t.path}}),{sessionId:c.id,projectId:t.id}}async sendInput(e,t,n,r){let i=this.sessions.get(e)??await this.resumeSessionFromHistory(e);if(!i)throw Error(`Session not found: ${e}`);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:r?.model,sessionConfig:r?.sessionConfig}}),this.options.historyStore.getSession(i.id)||await this.persistSessionSnapshot(i),await i.providerSession.sendInput(t,{model:r?.model,sessionConfig:r?.sessionConfig}),!i.title){let e=Ny(t);e&&this.setSessionTitle(i,e)}if(typeof r?.model==`string`&&r.model.trim()){let e=r.model.trim();i.model!==e&&(i.model=e,i.updatedAt=new Date().toISOString(),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:Fy(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 Error(`Session not found: ${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_${Om(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=L_(t.provider,{preferNative:this.options.preferNativeProviders,requireNative:n}),i=t.provider===`claude`&&t.source===`native_discovered`?t.id:t.nativeSessionId??t.id,a=await r.createSession({sessionId:t.id,model:t.model,cwd:t.projectPath,resumeSessionId:i,metadata:{resumeFromHistory:!0},logger:this.options.logger});if(n&&a.providerMode!==`native`)throw await a.close(),Error(`Native Codex provider is required, but adapter fell back to mock. Check ENABLE_NATIVE_PROVIDERS and Codex app-server availability.`);let o=this.resolveCanonicalSessionId(t.provider,a,t.id),s=this.resolveNativeSessionId(t.provider,a,t.nativeSessionId),c=await this.attachRuntimeSession({id:o,nativeSessionId:s,source:t.source??`gateway`,projectId:t.projectId,projectPath:t.projectPath,provider:t.provider,providerMode:a.providerMode,model:t.model,title:t.title,createdAt:t.createdAt,updatedAt:t.updatedAt||new Date().toISOString(),status:`idle`,providerSession:a,pendingToolApprovals:new Set,pendingUserInputs:new Set,streamReady:!0,bufferedProviderEvents:[],lastActiveAtMs:Date.now(),dispatchInFlight:!1,closing:!1});return await this.persistSessionSnapshot(c),c}async syncCodexSessionsForProject(e){if(!this.options.preferNativeProviders)return;let t;try{t=await e_(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=Iy(n.createdAt),s=Iy(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:dy({runtimeModel:a?.model,discoveredModel:n.model,existingModel:t?.model,modelProvider:n.modelProvider}),title:a?.title??Ny(n.preview)??t?.title,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 B_(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??t?.title??n.title,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 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 Error(`Project not found: ${e}`);if((await this.options.projectStore.upsertByPath(t)).id!==n.id)throw Error(`projectId (${e}) does not match cwd (${t})`);return await Ly(n.path),n}if(e){let t=await this.options.projectStore.getById(e);if(!t)throw Error(`Project not found: ${e}`);return await Ly(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=Py(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===`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_${Om(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}: ${String(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)},`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_${Om(8)}`}:e}async maybePersistSyncedExternalRawEvents(e,t,n){if(!n||e.source!==`native_discovered`)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=ky(e);if(!r)return n;try{let i=await H_({projectPath:e.projectPath,nativeSessionId:r,provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,i)}catch(t){return e.source===`native_discovered`&&Oy(t)&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),n}}if(e.provider!==`codex`)return n;let r=Dy([e.nativeSessionId,e.id]);for(let i of r)try{let r=jy({thread:await n_(i,!0),provider:e.provider,sessionId:e.id,projectId:t});return this.finalizeExternalRawHistorySync(e,n,r)}catch{}return n}async finalizeExternalRawHistorySync(e,t,n){let r=by(t,n),i=await this.maybePersistSyncedExternalRawEvents(e,r,!0);return e.source===`native_discovered`&&await this.markExternalHistoryHydrated(e.id,e.updatedAt),i}async markExternalHistoryHydrated(e,t){await this.options.historyStore.patchSession(e,{lastHydratedExternalUpdatedAt:t})}mustGetSession(e){let t=this.sessions.get(e);if(!t)throw Error(`Session not found: ${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.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){let n=this.sessions.get(t);if(!(!n||n.projectId!==e))return this.toSessionSummary(n)}toSessionSummary(e){return{id:e.id,nativeSessionId:e.nativeSessionId,source:e.source,projectId:e.projectId,projectPath:e.projectPath,provider:e.provider,providerMode:e.providerMode,model:e.model,title:e.title,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=My(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 _y=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]),vy=new Set([`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`]);function yy(e,t,n){let r=new Map;for(let t of e)r.set(t.eventId,t);for(let e of t)r.set(e.eventId,e);return[...r.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,n))}function by(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[...n.values()].sort((e,t)=>e.ts.localeCompare(t.ts))}function xy(e,t,n,r){let i=new Map,a=new Map;for(let t of e)if(i.set(t.eventId,t),n.has(t.type)){let e=Sy(t);a.set(e,(a.get(e)??0)+1)}for(let e of t){if(!n.has(e.type))continue;let t=Sy(e),r=a.get(t)??0;if(r>0){r===1?a.delete(t):a.set(t,r-1);continue}i.set(e.eventId,e)}return[...i.values()].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-Math.max(1,r))}function Sy(e){let t=Cy(e.payload.raw),n=Cy(t.item),r=Cy(t.turn),i=wy(t.turn_id)??wy(t.turnId)??wy(r.id)??``,a=wy(r.status)??wy(t.status)??``,o=wy(t.thread_id)??wy(t.threadId)??``,s=wy(n.type)??``,c=wy(n.phase)??``,l=wy(n.status)??``,u=wy(n.command)??``,d=Ey(n),f=Ty(t.message)??``,p=Ty(t.title)??``;return e.type.startsWith(`item.`)?[e.type,s,c,l,u,d||f].join(`|`):e.type.startsWith(`turn.`)?[e.type,i,a].join(`|`):e.type===`thread.title.updated`?[e.type,p].join(`|`):[e.type,o,i,s,p||f].join(`|`)}function Cy(e){return typeof e==`object`&&e?e:{}}function wy(e){return typeof e==`string`&&e.trim()||void 0}function Ty(e){if(typeof e==`string`)return e.length>0?e:void 0}function Ey(e){let t=Ty(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=Ty(Cy(t).text);n&&e.push(n)}if(e.length>0)return e.join(`
|
|
479
|
+
`)}let r=Array.isArray(e.summary)?e.summary:[];if(r.length>0){let e=r.map(e=>Ty(e)).filter(e=>!!e);if(e.length>0)return e.join(`
|
|
480
|
+
`)}return``}function Dy(e){let t=new Set;for(let n of e)n&&t.add(n);return[...t]}function Oy(e){return String(e).includes(`returned no messages from getSessionMessages`)}function ky(e){return e.source===`native_discovered`?e.id:e.nativeSessionId}function Ay(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,new Date(n+r).toISOString()),a=(n,a)=>{let o=`hist_${e.sessionId}_${r.toString().padStart(6,`0`)}_${n.replace(/\./g,`_`)}`;t.push({v:`1.0`,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:o,ts:i(),type:n,payload:{raw:a}})};a(`thread.started`,{thread_id:e.thread.id,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,turns:[]}});let o=Ny(e.thread.preview);o&&a(`thread.title.updated`,{title:o,source:`codex.thread_read_preview`,thread_id:e.thread.id});for(let t of e.thread.turns){let e={id:t.id,status:t.status,items:[],error:t.error};a(`turn.started`,{turn:e});for(let e of t.items)a(`item.completed`,{turn_id:t.id,item:e});if(t.status===`failed`||t.status===`interrupted`){a(`turn.failed`,{status:t.status,turn:e,error:t.error??{message:t.status===`interrupted`?`Turn interrupted`:`Turn failed`}});continue}t.status===`completed`&&a(`turn.completed`,{status:t.status,turn:e})}return t}function jy(e){let t=[],n=e.thread.createdAt>0?e.thread.createdAt*1e3:Date.now(),r=0,i=()=>(r+=1,new Date(n+r).toISOString()),a=n=>{let a=t.length+1,o=`raw_hist_codex_${e.sessionId}_${r.toString().padStart(6,`0`)}`;t.push({v:`1.0`,kind:`provider.raw`,rawSeq:a,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:o,ts:i(),type:`native.raw`,payload:{raw:{source:`codex.history.thread_read`,native_type:`thread.read.snapshot`,message:n,historyReplay:!0,replaySynthetic:!0}}})};a({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}});for(let t of e.thread.turns){a({scope:`turn`,thread_id:e.thread.id,turn:{id:t.id,status:t.status,error:t.error}});for(let n of t.items)a({scope:`item`,thread_id:e.thread.id,turn_id:t.id,item:n})}return t}function My(e){let t=e.replace(/\s+/g,` `).trim();if(t)return t}function Ny(e,t=60){let n=My(e);if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function Py(e){if(typeof e!=`string`)return;let t=My(e);if(t)return t}function Fy(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}function Iy(e){return!Number.isFinite(e)||e<=0?new Date().toISOString():new Date(e*1e3).toISOString()}async function Ly(e){if(!(await d.default.stat(e)).isDirectory())throw Error(`Project path is not a directory: ${e}`)}var Ry=class{indexPath;eventsDir;sessions=new Map;rawEventsCacheBySession=new Map;compactedRawEventsCacheBySession=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 appendEvent(e){if(await this.ready,!this.sessions.has(e.sessionId))return;let t=p.default.join(this.eventsDir,`${e.sessionId}.jsonl`),n=`${JSON.stringify(e)}\n`;await this.enqueueWrite(async()=>{await d.default.appendFile(t,n,`utf8`)})}async appendRawEvent(e){await this.ready,this.sessions.has(e.sessionId)&&await this.enqueueWrite(async()=>{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.enqueueWrite(async()=>{r=Hy(await this.readSessionRawEventsLocked(e),n);let t=p.default.join(this.eventsDir,`${e}.raw.jsonl`),i=r.map(e=>Vy(e)).join(`
|
|
481
481
|
`);await d.default.writeFile(t,i?`${i}\n`:``,`utf8`),this.rawEventsCacheBySession.set(e,r),this.compactedRawEventsCacheBySession.delete(e)}),r}async getSessionRawEvents(e,t=300){return this.getSessionRawEventsCompacted(e,t)}async getSessionRawEventsCompacted(e,t=300){await this.ready;let n=Math.max(1,t),r=[];return await this.enqueueWrite(async()=>{r=(await this.readSessionRawEventsCompactedLocked(e)).slice(-n)}),r}async getSessionRawEventsSinceSeq(e,t,n=2e3){await this.ready;let r=Math.max(1,n),i=[];return await this.enqueueWrite(async()=>{i=(await this.readSessionRawEventsLocked(e)).filter(e=>e.rawSeq>t).slice(0,r)}),i}async getSessionRawSeqRange(e){await this.ready;let t=null;return await this.enqueueWrite(async()=>{let n=await this.readSessionRawEventsLocked(e);if(n.length===0){t=null;return}let r=n[0],i=n[n.length-1];if(!r||!i){t=null;return}t={min:r.rawSeq,max:i.rawSeq}}),t}async getSessionEvents(e,t=300){await this.ready;let n=p.default.join(this.eventsDir,`${e}.jsonl`);try{return(await d.default.readFile(n,`utf8`)).split(`
|
|
482
|
-
`).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>e!==null).slice(-Math.max(1,t))}catch(e){if(e.code===`ENOENT`)return[];throw e}}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 appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${
|
|
483
|
-
`).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!
|
|
484
|
-
`),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}};function Iy(e){return typeof e==`object`&&!!e}function Ly(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Ry(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 zy(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[...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 By=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${Tm(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))for(let n of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(n,e.sessionId));if(t?.paused){t.queued.push(e);continue}let r=this.clients.get(n);!r||r.socket.readyState!==r.socket.OPEN||r.socket.send(JSON.stringify(e))}}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)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 Vy(e,t={}){await pc(e.gatewayLogPath);let n=Uy(e,t),r=Hy(e,n.instance);await r.register(bm.default,{origin:!0}),await r.register(ym.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new rh(e);await s.init();let c=new lh(e.auditLogPath),l=new By,u=new Jh,d=new cg(e.projectStoreDir),f=new Fy(e.sessionHistoryDir);await f.init();let m=new Sv(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new lv({store:m});await h.init();let g,_=null,v=await rg(e.authStoreDir),y=new py({preferNativeProviders:e.enableNativeProviders,requireNativeCodex:e.requireNativeCodex,auditLogger:c,projectStore:d,historyStore:f,runtimeLifecycle:{idleTtlMs:e.runtimeIdleTtlMs,sweepIntervalMs:e.runtimeSweepIntervalMs,maxSessions:e.runtimeMaxSessions,maxCodexSessions:e.runtimeMaxCodexSessions,maxClaudeSessions:e.runtimeMaxClaudeSessions},onEnvelope:e=>{l.routeProviderRaw(e)}}),b=new Is({packageName:N.packageName,currentVersion:N.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()=>{_?.close(),x.close(),await b.shutdown(),await y.shutdown(),await f.shutdown(),n.close()}),i&&r.addHook(`onSend`,async(e,t,n)=>(r.log.info({method:e.method,url:e.url,statusCode:t.statusCode,responseBody:te(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:ys(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>hs({gatewayId:e.gatewayId,machineName:ys(),relayBaseUrl:e.relayEnabled?Ds({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:Ts({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=Yi.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=de(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}}),Jy(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=Qi.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await s.refreshAccessToken(n.data.refreshToken)}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(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(!L(e,t))return;let n=e.body,r=ia.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return la.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.get(`/api/discovery/projects`,async(e,t)=>{if(L(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(L(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(!L(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 n.includes(`Discovered project not found`)?t.code(404).send({error:n}):Qy(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(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(!L(e,t))return;let n=R(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return String(e).includes(`Project not found`)?t.code(404).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return String(e).includes(`Project not found`)?t.code(404).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(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(!L(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(!L(e,t))return;let n=e.params,r=e.query,i=ie(r.status,t);if(!i)return;let a=ae(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return t.code(404).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(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/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(!L(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})(),a=ae(r.syncExternal);try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i,{syncExternal:a})}}catch(e){return t.code(404).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(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=oe(t.headers.authorization)??se(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(Li(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 Fv({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=de(e.deviceName);return Jy(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await s.refreshAccessToken(t.refreshToken);return Gy(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>Ky(e,{authService:s,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});return;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 Error(`session ${t} not found in project ${n}`);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_${Tm(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_${Tm(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,te=e=>{if(e==null)return e;if(typeof e==`string`){let t=P(e);return t===void 0?F(e,a):I(ne(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=P(t);return n===void 0?F(t,a):I(ne(n))}return typeof e==`object`?I(ne(e)):String(e)},P=e=>{try{return JSON.parse(e)}catch{return}},F=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,ne=e=>{if(Array.isArray(e))return e.map(e=>ne(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]=ne(r)}return n}return e},I=e=>{let t=re(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:F(t,a)}},re=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=oe(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}},ie=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ae=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},R=(e,t)=>{let n=e.params,r=e.query,i=_i.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)},oe=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},se=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},ce=e.httpsEnabled?e.httpsPort:e.port,le=e.httpsEnabled?`https`:`http`,ue=ys(),de=e=>e?.trim()||ue||`Gateway`;await r.listen({host:e.host,port:ce});let z=r.server.address(),fe=typeof z==`object`&&z?z.port:ce;if(r.log.info({host:e.host,port:fe,protocol:le,machineName:ue},Wy(le,e.host,fe)),e.relayEnabled&&(_=new Bv({gatewayId:e.gatewayId,machineName:ue,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>Gv({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:Ts({protocol:le,host:e.host,port:fe}),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:le,listenPort:fe,machineName:ue,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),startupPairingCode:g}}function Hy(e,t){let n=t;if(!e.httpsEnabled)return(0,xm.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,xm.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 Uy(e,t){let n=process.env.NODE_ENV!==`production`,r=th.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?th.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,th.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function Wy(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function Gy(e,t){if(e&&e!==t)throw Error(`Refresh token device mismatch`)}async function Ky(e,t){try{let n=to.parse(e);switch(n.method){case`auth.refresh`:{let e=await t.authService.refreshAccessToken(n.params.refreshToken);return Gy(n.params.deviceId??t.relayDeviceId,e.deviceId),no.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return no.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return no.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return no.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return no.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return no.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return no.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw Xy(n.method,`NOT_FOUND`,404,`Project not found`);return no.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 no.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 no.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return no.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw Xy(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return no.parse({method:n.method,result:{session:e}})}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,{syncExternal:n.params.syncExternal});return no.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0);return no.parse({method:n.method,result:{capabilities:e}})}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 no.parse({method:n.method,result:e})}case`devices.list`:return no.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw Xy(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return no.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw Xy(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw qy(e)}}function qy(e){let t=io.safeParse(e);if(t.success)return t.data;let n=ro.safeParse(e);if(n.success)return Xy(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 Xy(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?Xy(`BAD_REQUEST`,400,r):Zy(r)?Xy(`UNAUTHORIZED`,401,r):r.includes(`Project not found`)||r.includes(`Discovered project not found`)||r.includes(`Session `)&&r.includes(` not found `)?Xy(`NOT_FOUND`,404,r):Qy(r)?Xy(`BAD_REQUEST`,400,r):r.includes(`Cannot delete project`)?Xy(`BAD_REQUEST`,409,r):Xy(`INTERNAL`,500,r)}function Jy(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:Yy(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:og(e.identity,e.privateKeyPem,i)}}function Yy(e){return e.replace(/\s+/gu,``).toUpperCase()}function Xy(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 io.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function Zy(e){return e.includes(`Refresh token revoked`)||e.includes(`Device revoked`)||e.includes(`Refresh token device mismatch`)||e.includes(`TokenExpiredError:`)||e.includes(`JsonWebTokenError:`)||e.includes(`NotBeforeError:`)}function Qy(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:`)}async function $y(e){let t=await yt({configPath:e.configPath,ensureConfigFile:!0});Ct(t.config);let n=await Vy(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{tb({type:`worker.update.prepared`,payload:e})}});tb({type:`worker.ready`,payload:eb(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=nb(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: ${String(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${String(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);tb({type:`worker.response`,id:e.id,ok:!0,result:t});return}}}catch(t){tb({type:`worker.response`,id:e.id,ok:!1,error:String(t)})}}await new Promise(()=>{})}function eb(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function tb(e){process.send&&process.send(e)}function nb(e){if(!rb(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.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:`gateway.update.apply`,requestedBy:e.requestedBy};default:return null}}function rb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}ib(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function ib(e){let t=te(e);switch(t.command){case`help`:lb();return;case`version`:console.log(N.version);return;case`init`:await ob(t);return;case`doctor`:await sb(t);return;case`start`:await ab(t);return;case`__worker`:await cb(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function ab(e){let t=await yt({configPath:e.configPath,ensureConfigFile:!0});Ct(t.config);let n=await Vt({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await cc({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(mc(e,t.config))}Ht(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function ob(e){let t=await vt({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 yt({configPath:t.configPath,ensureConfigFile:!1}),r=await Vt({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Ut(r))}async function sb(e){let t=await yt({configPath:_t(e.configPath),ensureConfigFile:!1}),n=await Vt({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Ut(n)),Ht(n)&&(process.exitCode=1)}async function cb(e){try{await $y(e)}catch(t){let n=await yt({configPath:e.configPath,ensureConfigFile:!0});throw Error(mc(t,n.config))}}function lb(){console.log(`${N.cliName} ${N.version}`),console.log(``),console.log(`Usage:`),console.log(` ${N.cliName} [start] [--config <path>] [--log]`),console.log(` ${N.cliName} init [--config <path>] [--force]`),console.log(` ${N.cliName} doctor [--config <path>]`),console.log(` ${N.cliName} --version`)}exports.runCli=ib;
|
|
482
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>e!==null).slice(-Math.max(1,t))}catch(e){if(e.code===`ENOENT`)return[];throw e}}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 appendRawEventLine(e){let t=p.default.join(this.eventsDir,`${e.sessionId}.raw.jsonl`),n=`${Vy(e)}\n`;await d.default.appendFile(t,n,`utf8`)}appendRawEventToCache(e){let t=this.rawEventsCacheBySession.get(e.sessionId);t&&t.push(e),this.compactedRawEventsCacheBySession.delete(e.sessionId)}async readSessionRawEventsCompactedLocked(e){let t=this.compactedRawEventsCacheBySession.get(e);if(t)return t;let n=Wo(await this.readSessionRawEventsLocked(e));return this.compactedRawEventsCacheBySession.set(e,n),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(`
|
|
483
|
+
`).map(e=>e.trim()).filter(Boolean),a=[];for(let e of i)try{let t=JSON.parse(e);if(!zy(t)||t.kind!==`provider.raw`)continue;let n=By(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=Bi.safeParse(e);t.success&&c.push(t.data)}if(o){let e=c.map(e=>Vy(e)).join(`
|
|
484
|
+
`),t=e?`${e}\n`:``;await d.default.writeFile(n,t,`utf8`)}return this.rawEventsCacheBySession.set(e,c),c}};function zy(e){return typeof e==`object`&&!!e}function By(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Vy(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 Hy(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[...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 Uy=class{clients=new Map;clientIdsBySessionId=new Map;deliveryStateByClientSession=new Map;addClient(e,t){let n=`ws_${Om(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))for(let n of t){let t=this.deliveryStateByClientSession.get(this.clientSessionKey(n,e.sessionId));if(t?.paused){t.queued.push(e);continue}let r=this.clients.get(n);!r||r.socket.readyState!==r.socket.OPEN||r.socket.send(JSON.stringify(e))}}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)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 Wy(e,t={}){await gc(e.gatewayLogPath);let n=Ky(e,t),r=Gy(e,n.instance);await r.register(Cm.default,{origin:!0}),await r.register(Sm.default);let i=process.env.NODE_ENV!==`production`,a=4e3,o=`[unserializable payload]`,s=new oh(e);await s.init();let c=new fh(e.auditLogPath),l=new Uy,u=new Zh,d=new dg(e.projectStoreDir),f=new Ry(e.sessionHistoryDir);await f.init();let m=new Tv(p.default.join(e.sessionHistoryDir,`discovery-v1`));await m.init();let h=new fv({store:m});await h.init();let g,_=null,v=await og(e.authStoreDir),y=new gy({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)}}),b=new Is({packageName:N.packageName,currentVersion:N.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:te(n)},`gateway response (dev)`),n)),r.get(`/health`,async()=>({ok:!0,service:`desktop-gateway`,now:new Date().toISOString(),wsClients:l.count(),machineName:ys(),gatewayIdentity:v.identity})),r.get(`/api/pairing/descriptor`,async()=>hs({gatewayId:e.gatewayId,machineName:ys(),relayBaseUrl:e.relayEnabled?Ds({relayUrl:e.relayUrl,gatewayHost:e.host}):``,directBaseUrls:Ts({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=Yi.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{let e=de(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}}),Zy(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=Qi.safeParse(e.body);if(!n.success)return t.code(400).send({error:`Invalid request`,detail:n.error.flatten()});try{return await s.refreshAccessToken(n.data.refreshToken)}catch(e){return t.code(401).send({error:String(e)})}}),r.get(`/api/projects`,async(e,t)=>{if(L(e,t))return{projects:await y.listProjects()}}),r.get(`/api/gateway/update`,async(e,t)=>{if(L(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(!L(e,t))return;let n=e.body,r=ia.safeParse(n?.requestedBy);try{let e=await b.applyUpdate(r.success?r.data:`mobile`);return la.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.get(`/api/discovery/projects`,async(e,t)=>{if(L(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(L(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(!L(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 n.includes(`Discovered project not found`)?t.code(404).send({error:n}):tb(n)?t.code(400).send({error:n}):t.code(500).send({error:n})}}),r.get(`/api/workspace/directories`,async(e,t)=>{if(!L(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(!L(e,t))return;let n=R(e,t);if(n)try{return{capabilities:await y.getProviderCapabilities(n.provider,n.projectId,n.agentVersion)}}catch(e){return String(e).includes(`Project not found`)?t.code(404).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.get(`/api/agents/:provider/config`,async(e,t)=>{if(!L(e,t))return;let n=R(e,t);if(n)try{return await y.getAgentConfig(n.provider,{projectId:n.projectId,agentVersion:n.agentVersion})}catch(e){return String(e).includes(`Project not found`)?t.code(404).send({error:String(e)}):t.code(400).send({error:String(e)})}}),r.post(`/api/projects`,async(e,t)=>{if(!L(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(!L(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(!L(e,t))return;let n=e.params,r=e.query,i=ie(r.status,t);if(!i)return;let a=ae(r.syncExternal);try{return{sessions:await y.listProjectSessions(n.projectId,i,{syncExternal:a})}}catch(e){return t.code(404).send({error:String(e)})}}),r.get(`/api/projects/:projectId/sessions/:sessionId`,async(e,t)=>{if(!L(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/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(!L(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})(),a=ae(r.syncExternal);try{return{events:await y.getProjectSessionRawEvents(n.projectId,n.sessionId,i,{syncExternal:a})}}catch(e){return t.code(404).send({error:String(e)})}}),r.get(`/api/projects/:projectId/fs/tree`,async(e,t)=>{if(!L(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=oe(t.headers.authorization)??se(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(Li(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 Rv({gatewayId:e.gatewayId,relayTransportSecurityLevel:e.relayEnabled?`e2ee-relay`:`plaintext-relay`,gatewayIdentity:v.identity,gatewayIdentityPrivateKeyPem:v.privateKeyPem,sessionHub:l,handlePairingClaim:async e=>{let t=de(e.deviceName);return Zy(v,await s.claimPairingCode(e.code,t,e.deviceIdentity),e.code,e.deviceIdentity)},handleRefresh:async t=>{let n=await s.refreshAccessToken(t.refreshToken);return Jy(t.deviceId,n.deviceId),{gatewayId:e.gatewayId,...n}},verifyDeviceIdentityBinding:async(e,t)=>s.verifyDeviceIdentityBinding(e,t),handleRpcRequest:async(e,t)=>Yy(e,{authService:s,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});return;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 Error(`session ${t} not found in project ${n}`);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_${Om(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_${Om(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,te=e=>{if(e==null)return e;if(typeof e==`string`){let t=P(e);return t===void 0?F(e,a):I(ne(t))}if(Buffer.isBuffer(e)){let t=e.toString(`utf8`),n=P(t);return n===void 0?F(t,a):I(ne(n))}return typeof e==`object`?I(ne(e)):String(e)},P=e=>{try{return JSON.parse(e)}catch{return}},F=(e,t)=>e.length<=t?e:`${e.slice(0,t)}...<truncated>`,ne=e=>{if(Array.isArray(e))return e.map(e=>ne(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]=ne(r)}return n}return e},I=e=>{let t=re(e);return t===o?t:t.length<=a?e:{truncated:!0,preview:F(t,a)}},re=e=>{try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}catch{return o}},L=(e,t)=>{let n=oe(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}},ie=(e,t)=>{let n=e??`all`;return[`running`,`idle`,`all`].includes(n)?n:(t.code(400).send({error:`Invalid status filter`}),null)},ae=e=>{let t=e?.trim().toLowerCase();return t===`true`||t===`1`},R=(e,t)=>{let n=e.params,r=e.query,i=_i.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)},oe=e=>{if(!e)return null;let[t,n]=e.split(` `);return t?.toLowerCase()!==`bearer`||!n?null:n},se=e=>{try{return new URL(e,`http://localhost`).searchParams.get(`token`)}catch{return null}},ce=e.httpsEnabled?e.httpsPort:e.port,le=e.httpsEnabled?`https`:`http`,ue=ys(),de=e=>e?.trim()||ue||`Gateway`;await r.listen({host:e.host,port:ce});let z=r.server.address(),fe=typeof z==`object`&&z?z.port:ce;if(r.log.info({host:e.host,port:fe,protocol:le,machineName:ue},qy(le,e.host,fe)),e.relayEnabled&&(_=new Uv({gatewayId:e.gatewayId,machineName:ue,relayUrl:e.relayUrl,relayGatewayAccessToken:e.relayGatewayAccessToken,resolveRelayGatewayAccessToken:e.relayGatewayAccessToken.trim()?void 0:()=>Jv({gatewayId:e.gatewayId,relayUrl:e.relayUrl,gatewayIdentity:v.identity,privateKeyPem:v.privateKeyPem}),gatewayIdentity:v.identity,directBaseUrls:Ts({protocol:le,host:e.host,port:fe}),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:le,listenPort:fe,machineName:ue,gatewayIdentity:v.identity,close:()=>r.close(),getGatewayUpdateInfo:()=>b.getInfo(),requestGatewayUpdate:(e=`console`)=>b.applyUpdate(e),startupPairingCode:g}}function Gy(e,t){let n=t;if(!e.httpsEnabled)return(0,wm.default)({disableRequestLogging:!0,loggerInstance:n});if(!e.tlsKeyPath||!e.tlsCertPath)throw Error(`TLS key/cert path is required when HTTPS is enabled.`);return(0,wm.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 Ky(e,t){let n=process.env.NODE_ENV!==`production`,r=ih.default.destination({dest:e.gatewayLogPath,mkdir:!0,sync:!1}),i=t.logToConsole?ih.default.multistream([{stream:r},{stream:process.stdout}]):r;return{instance:(0,ih.default)({level:n?`debug`:`info`},i),close:()=>{try{r.flushSync()}catch{}r.end()}}}function qy(e,t,n){return`desktop-gateway listening on ${e}://${t}:${n}`}function Jy(e,t){if(e&&e!==t)throw Error(`Refresh token device mismatch`)}async function Yy(e,t){try{let n=to.parse(e);switch(n.method){case`auth.refresh`:{let e=await t.authService.refreshAccessToken(n.params.refreshToken);return Jy(n.params.deviceId??t.relayDeviceId,e.deviceId),no.parse({method:n.method,result:e})}case`projects.list`:{let e=await t.sessionManager.listProjects();return no.parse({method:n.method,result:{projects:e}})}case`gateway.update.get`:{let e=await t.updateService.getOrCheckInfo(`mobile`);return no.parse({method:n.method,result:e})}case`gateway.update.apply`:{let e=await t.updateService.applyUpdate(n.params.requestedBy??`mobile`);return no.parse({method:n.method,result:e})}case`projects.discovery.get`:{let e=await t.projectDiscoveryService.getProjects();return no.parse({method:n.method,result:e})}case`projects.discovery.refresh`:{let e=await t.projectDiscoveryService.refreshProjects();return no.parse({method:n.method,result:e})}case`projects.create`:{let e=await t.sessionManager.createProject({path:n.params.path,title:n.params.title});return no.parse({method:n.method,result:{project:e}})}case`projects.delete`:if(!await t.sessionManager.deleteProject(n.params.projectId))throw $y(n.method,`NOT_FOUND`,404,`Project not found`);return no.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 no.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 no.parse({method:n.method,result:{sessions:e}})}case`sessions.discovery.list`:{let e=await t.projectDiscoveryService.listProjectSessions(n.params.projectPath);return no.parse({method:n.method,result:e})}case`sessions.get`:{let e=await t.sessionManager.getProjectSessionSummary(n.params.projectId,n.params.sessionId);if(!e)throw $y(n.method,`NOT_FOUND`,404,`Session ${n.params.sessionId} not found in project ${n.params.projectId}`);return no.parse({method:n.method,result:{session:e}})}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,{syncExternal:n.params.syncExternal});return no.parse({method:n.method,result:{events:e}})}case`providers.capabilities.get`:{let e=await t.sessionManager.getProviderCapabilities(n.params.provider,n.params.projectId??void 0,n.params.agentVersion??void 0);return no.parse({method:n.method,result:{capabilities:e}})}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 no.parse({method:n.method,result:e})}case`devices.list`:return no.parse({method:n.method,result:{devices:t.authService.listDevices()}});case`devices.revoke`:if(!await t.authService.revokeDevice(n.params.deviceId))throw $y(n.method,`NOT_FOUND`,404,`Device ${n.params.deviceId} not found`);return no.parse({method:n.method,result:{revoked:!0}});default:{let e=n;throw $y(void 0,`INTERNAL`,500,`Unhandled relay RPC method: ${JSON.stringify(e)}`)}}}catch(e){throw Xy(e)}}function Xy(e){let t=io.safeParse(e);if(t.success)return t.data;let n=ro.safeParse(e);if(n.success)return $y(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 $y(t.code,t.status,t.message,t.details)}let r=String(e);return e instanceof Error&&e.name===`ZodError`?$y(`BAD_REQUEST`,400,r):eb(r)?$y(`UNAUTHORIZED`,401,r):r.includes(`Project not found`)||r.includes(`Discovered project not found`)||r.includes(`Session `)&&r.includes(` not found `)?$y(`NOT_FOUND`,404,r):tb(r)?$y(`BAD_REQUEST`,400,r):r.includes(`Cannot delete project`)?$y(`BAD_REQUEST`,409,r):$y(`INTERNAL`,500,r)}function Zy(e,t,n,r){if(!r)return t;let i={gatewayId:t.gatewayId,deviceId:t.deviceId,mobilePublicKey:r.publicKey,pairingContext:{pairingCode:Qy(n),signedAt:new Date().toISOString()}};return{...t,gatewayIdentity:e.identity,pairingConfirmation:lg(e.identity,e.privateKeyPem,i)}}function Qy(e){return e.replace(/\s+/gu,``).toUpperCase()}function $y(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 io.parse({...o?{method:o}:{},code:s,status:c,message:l,...u===void 0?{}:{details:u}})}function eb(e){return e.includes(`Refresh token revoked`)||e.includes(`Device revoked`)||e.includes(`Refresh token device mismatch`)||e.includes(`TokenExpiredError:`)||e.includes(`JsonWebTokenError:`)||e.includes(`NotBeforeError:`)}function tb(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:`)}async function nb(e){let t=await yt({configPath:e.configPath,ensureConfigFile:!0});Ct(t.config);let n=await Wy(t.config,{logToConsole:e.logToConsole,onUpdatePrepared:async e=>{ib({type:`worker.update.prepared`,payload:e})}});ib({type:`worker.ready`,payload:rb(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=ab(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: ${String(e)}`),i(1)}),process.on(`unhandledRejection`,e=>{console.error(`[gateway] worker unhandled rejection: ${String(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);ib({type:`worker.response`,id:e.id,ok:!0,result:t});return}}}catch(t){ib({type:`worker.response`,id:e.id,ok:!1,error:String(t)})}}await new Promise(()=>{})}function rb(e){return{protocol:e.protocol,listenPort:e.listenPort,machineName:e.machineName,gatewayIdentity:e.gatewayIdentity,startupPairingCode:e.startupPairingCode}}function ib(e){process.send&&process.send(e)}function ab(e){if(!ob(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.requestedBy!==`console`&&e.requestedBy!==`mobile`&&e.requestedBy!==`system`?null:{type:`supervisor.request`,id:e.id,method:`gateway.update.apply`,requestedBy:e.requestedBy};default:return null}}function ob(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}sb(process.argv.slice(2)).catch(e=>{console.error(String(e)),process.exit(1)});async function sb(e){let t=te(e);switch(t.command){case`help`:fb();return;case`version`:console.log(N.version);return;case`init`:await lb(t);return;case`doctor`:await ub(t);return;case`start`:await cb(t);return;case`__worker`:await db(t);return;default:{let e=t.command;throw Error(`Unsupported command: ${e}`)}}}async function cb(e){let t=await yt({configPath:e.configPath,ensureConfigFile:!0});Ct(t.config);let n=await Vt({configPath:t.configPath,configExists:t.configExists,config:t.config});try{await cc({args:e,loaded:t,doctorReport:n})}catch(e){throw Error(_c(e,t.config))}Ht(n)&&console.warn(`[doctor] startup continued despite bundled runtime check failures.`)}async function lb(e){let t=await vt({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 yt({configPath:t.configPath,ensureConfigFile:!1}),r=await Vt({configPath:n.configPath,configExists:n.configExists,config:n.config});console.log(Ut(r))}async function ub(e){let t=await yt({configPath:_t(e.configPath),ensureConfigFile:!1}),n=await Vt({configPath:t.configPath,configExists:t.configExists,config:t.configExists?t.config:void 0});console.log(Ut(n)),Ht(n)&&(process.exitCode=1)}async function db(e){try{await nb(e)}catch(t){let n=await yt({configPath:e.configPath,ensureConfigFile:!0});throw Error(_c(t,n.config))}}function fb(){console.log(`${N.cliName} ${N.version}`),console.log(``),console.log(`Usage:`),console.log(` ${N.cliName} [start] [--config <path>] [--log]`),console.log(` ${N.cliName} init [--config <path>] [--force]`),console.log(` ${N.cliName} doctor [--config <path>]`),console.log(` ${N.cliName} --version`)}exports.runCli=sb;
|