@adhd/apigen-cli 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +890 -73
- package/README.md +371 -83
- package/index.js +96 -31
- package/index.mjs +12140 -4448
- package/lib/commands/generate-registry.d.ts +1 -1
- package/lib/commands/generate.d.ts +42 -1
- package/lib/commands/list-types.d.ts +11 -0
- package/lib/commands/run-registry.d.ts +1 -1
- package/lib/commands/run.d.ts +46 -1
- package/lib/commands/serve.d.ts +158 -0
- package/lib/import-source.d.ts +15 -4
- package/lib/logging.d.ts +1 -1
- package/lib/orchestrator.d.ts +76 -11
- package/lib/plugin-registry.d.ts +33 -0
- package/package.json +23 -9
- package/default-tsconfig.json +0 -10
- package/lib/pipeline.d.ts +0 -22
package/index.js
CHANGED
|
@@ -1,20 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Xs=Object.create;var dr=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var no=Object.getPrototypeOf,ro=Object.prototype.hasOwnProperty;var so=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of to(t))!ro.call(e,s)&&s!==n&&dr(e,s,{get:()=>t[s],enumerable:!(r=eo(t,s))||r.enumerable});return e};var oo=(e,t,n)=>(n=e!=null?Xs(no(e)):{},so(t||!e||!e.__esModule?dr(n,"default",{value:e,enumerable:!0}):n,e));const ao=require("commander"),io=require("node:fs"),Yr=require("node:path"),Nt=require("ts-morph"),co=require("ts-json-schema-generator"),uo=require("node:os"),yt=require("pino"),lo=require("node:url"),fr=require("node:http"),fo=require("@modelcontextprotocol/sdk/server/index.js"),po=require("@modelcontextprotocol/sdk/server/stdio.js"),ho=require("@modelcontextprotocol/sdk/server/sse.js"),mo=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),pr=require("@modelcontextprotocol/sdk/types.js"),go=require("fastify"),Qt=require("express"),yo=require("pino-http");function gn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const V=gn(io),A=gn(Yr),$o=gn(uo);function vo(e){const t=[];for(const n of e.getFunctions())n.isExported()&&t.push({name:n.getName()??"",params:n.getParameters().map(r=>({name:r.getName(),type:r.getType().getText(),optional:r.isOptional()||r.hasInitializer()})),returnType:n.getReturnType().getText()});for(const n of e.getVariableDeclarations()){const r=n.getVariableStatement();if(!(r!=null&&r.isExported()))continue;const s=n.getInitializer();if(!s)continue;const o=s.getKindName();if(!["ArrowFunction","FunctionExpression"].includes(o))continue;const a=n.getType().getCallSignatures();if(a.length===0)continue;const c=a[0];t.push({name:n.getName(),params:c.getParameters().map(u=>{var g;const l=u.getDeclarations(),f=l.length>0&&l[0].getKindName()==="Parameter"?l[0]:null,h=u.isOptional()||((f==null?void 0:f.hasInitializer())??!1)||(((g=f==null?void 0:f.hasQuestionToken)==null?void 0:g.call(f))??!1);return{name:u.getName(),type:u.getTypeAtLocation(n).getText(),optional:h}}),returnType:c.getReturnType().getText()})}return t}function _o(e){const t=[],n=e.getDefaultExportSymbol();if(!n||n.getDeclarations().length===0)return t;const s=e.getExportAssignment(i=>!i.isExportEquals());if(!s)return t;const o=s.getExpression().getType();for(const i of o.getProperties()){const c=i.getTypeAtLocation(s).getCallSignatures();if(c.length===0)continue;const u=c[0];t.push({name:i.getName(),params:u.getParameters().map(l=>{var m;const f=l.getDeclarations(),h=f.length>0&&f[0].getKindName()==="Parameter"?f[0]:null,g=l.isOptional()||((h==null?void 0:h.hasInitializer())??!1)||(((m=h==null?void 0:h.hasQuestionToken)==null?void 0:m.call(h))??!1);return{name:l.getName(),type:l.getTypeAtLocation(s).getText(),optional:g}}),returnType:u.getReturnType().getText()})}return t}function wo(e,t){const n=[],r=e.getVariableDeclarations().find(o=>o.getName()===t);if(!r)return console.error(`[apigen-core] No variable "${t}" in source`),n;const s=r.getType();for(const o of s.getProperties()){const a=o.getTypeAtLocation(r).getCallSignatures();if(a.length===0)continue;const c=a[0];n.push({name:o.getName(),params:c.getParameters().map(u=>{var g;const l=u.getDeclarations(),f=l.length>0&&l[0].getKindName()==="Parameter"?l[0]:null,h=u.isOptional()||((f==null?void 0:f.hasInitializer())??!1)||(((g=f==null?void 0:f.hasQuestionToken)==null?void 0:g.call(f))??!1);return{name:u.getName(),type:u.getTypeAtLocation(r).getText(),optional:h}}),returnType:c.getReturnType().getText()})}return n}function Pt(e,t){if(t>6)return{};const n=e.trim();if(n==="string")return{type:"string"};if(n==="number")return{type:"number"};if(n==="boolean")return{type:"boolean"};if(n==="null")return{type:"null"};if(n==="undefined")return{type:"null"};if(n.endsWith("[]"))return{type:"array",items:Pt(n.slice(0,-2),t+1)};if(n.includes("|")){const r=n.split("|").map(s=>s.trim());return r.every(s=>s.startsWith("'"))?{type:"string",enum:r.map(s=>s.replace(/'/g,""))}:{anyOf:r.map(s=>Pt(s,t+1))}}if(n.startsWith("{")&&n.endsWith("}")){const r=n.slice(1,-1).trim(),s={};for(const o of r.split(";").filter(Boolean)){const[i,a]=o.split(":").map(c=>c.trim());i&&a&&(s[i.replace("?","")]=Pt(a,t+1))}return{type:"object",properties:s}}return{}}async function lt(e,t,n,r){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};try{const s={path:t.getFilePath(),type:n,skipTypeCheck:!0,tsconfig:r};return co.createGenerator(s).createSchema(n)}catch{return Pt(n,0)}}async function Zr(e){const{sourceFile:t,exportMode:n={type:"named"},namespace:r="",phase:s="",tsconfig:o}=e,i=o?new Nt.Project({tsConfigFilePath:o,skipAddingFilesFromTsConfig:!0}):new Nt.Project({skipAddingFilesFromTsConfig:!0}),a=i.addSourceFileAtPath(t);let c;n.type==="named"?c=vo(a):n.type==="default"?c=_o(a):c=wo(a,n.name);const u={};for(const l of c){const f=l.params.length>0&&l.params[0].name==="ctx",h=l.params.filter(_=>_.name!=="ctx"),g=h.filter(_=>!_.optional).map(_=>_.name),m={};for(const _ of h)m[_.name]=await lt(i,a,_.type,o);const y=l.returnType.replace(/^Promise<(.+)>$/,"$1").trim(),p=await lt(i,a,y,o);u[l.name]={input:{type:"object",properties:m,required:g},output:p,...f?{hasCtx:!0}:{}}}return{metadata:{namespace:r,phase:s},schemas:u}}function Xr(e,t,n){const r={};for(const[s,o]of Object.entries(e.schemas)){const i=(n==null?void 0:n[s])??{},a=o.input.properties??{},c=o.input.required??[],u={},l=[];for(const h of t)if(h.envelope&&i[h.id]!==!1)for(const[g,m]of Object.entries(h.envelope))u[g]=m,l.includes(g)||l.push(g);const f={type:"object",properties:a,...c.length>0?{required:c}:{}};r[s]={input:{type:"object",properties:{...u,data:f},required:[...l,"data"]},output:o.output,...o.hasCtx?{hasCtx:!0}:{}}}return r}async function bo(e){var m;const{sourceFile:t,namespace:n="",tsconfig:r}=e,s=r?new Nt.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new Nt.Project({skipAddingFilesFromTsConfig:!0}),o=s.addSourceFileAtPath(t),i=Yr.basename(t),a=Se(Yt(i)),c=Se(n),u=[],l=new Set(o.getExportedDeclarations().keys());for(const v of o.getFunctions()){if(!v.isExported()||v.isDefaultExport())continue;const y=v.getName()??"";if(!y||Fe(y)||!l.has(y))continue;const p=v.getSignature(),_=Zt(p),E=p.getReturnType().getText();u.push(await et(s,o,c,a,y,_,E,v.isAsync(),r))}for(const v of o.getVariableDeclarations()){const y=v.getVariableStatement();if(!(y!=null&&y.isExported()))continue;const p=v.getName();if(Fe(p)||!l.has(p))continue;const _=v.getInitializer();if(!_)continue;const E=_.getKindName();if(["ArrowFunction","FunctionExpression"].includes(E)){const N=v.getType().getCallSignatures();if(N.length===0)continue;const q=N[0],F=Xt(q,v),W=q.getReturnType().getText(),B=(_.getKindName()==="ArrowFunction",_.isAsync());u.push(await et(s,o,c,a,p,F,W,B,r))}else if(["ObjectLiteralExpression"].includes(E)){const j=v.getType();for(const N of j.getProperties()){const q=N.getName();if(Fe(q))continue;const W=N.getTypeAtLocation(v).getCallSignatures();if(W.length===0)continue;const B=W[0],ee=Xt(B,v),ie=B.getReturnType().getText(),ne=[a,Se(p),Se(q)];u.push(await rt(s,o,c,ne,q,ee,ie,!1,r))}}else{const N=v.getType().getText();if(ko(N)){const q=await lt(s,o,N,r);u.push(So(c,a,p,q))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${p}`)}}const f=o.getDefaultExportSymbol();if(f){const v=o.getExportAssignment(y=>!y.isExportEquals());if(v){const y=v.getExpression(),p=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes(p)){const _=Yt(i).replace(/-/g,"_")+"_default",j=y.getType().getCallSignatures();if(j.length>0){const N=j[0],q=en(N),F=N.getReturnType().getText(),W=y.isAsync(),B={raw:_,words:ts(_)};u.push(await rt(s,o,c,[B],_,q,F,W,r))}}else{const _=y.getType();for(const E of _.getProperties()){const j=E.getName();if(Fe(j))continue;const q=E.getTypeAtLocation(v).getCallSignatures();if(q.length===0)continue;const F=q[0],W=en(F),B=F.getReturnType().getText(),ee=[a,Se("default"),Se(j)];u.push(await rt(s,o,c,ee,j,W,B,!1,r))}}}else{const y=f.getDeclarations();for(const p of y){if(p.getKindName()!=="FunctionDeclaration")continue;const _=p,E=_.getName(),j=E&&E.length>0?E:Yt(i).replace(/-/g,"_")+"_default",N=_.getSignature(),q=Zt(N),F=N.getReturnType().getText();u.push(await et(s,o,c,a,j,q,F,_.isAsync(),r))}}}const h=new Set(u.map(v=>v.path[v.path.length-1].raw));for(const v of o.getExportDeclarations())if(!v.getModuleSpecifier())for(const y of v.getNamedExports()){const p=y.getAliasNode();if(!p)continue;const _=p.getText();if(Fe(_)||h.has(_))continue;const E=((m=y.getSymbol())==null?void 0:m.getAliasedSymbol())??y.getSymbol(),j=(E==null?void 0:E.getDeclarations())??[];for(const N of j){const q=N.getKindName();if(q==="FunctionDeclaration"){const F=N,W=F.getSignature(),B=Zt(W),ee=W.getReturnType().getText();u.push(await et(s,o,c,a,_,B,ee,F.isAsync(),r)),h.add(_);break}if(q==="VariableDeclaration"){const F=N,B=F.getType().getCallSignatures();if(B.length===0)break;const ee=B[0],ie=Xt(ee,F),ne=ee.getReturnType().getText(),J=F.getInitializer(),Z=(J==null?void 0:J.getKindName())==="ArrowFunction"||(J==null?void 0:J.getKindName())==="FunctionExpression"?J.isAsync():!1;u.push(await et(s,o,c,a,_,ie,ne,Z,r)),h.add(_);break}}}const g=Po(o);if(g.length>0)for(const{name:v,sig:y}of g){if(Fe(v))continue;const p=en(y),_=y.getReturnType().getText(),E=[a,Se(v)];u.push(await rt(s,o,c,E,v,p,_,!1,r))}return u}async function et(e,t,n,r,s,o,i,a,c){const u=Se(s);return rt(e,t,n,[r,u],s,o,i,a,c)}async function rt(e,t,n,r,s,o,i,a,c){const u=o.filter(y=>y.name!=="ctx"),l=u.filter(y=>!y.optional).map(y=>y.name),f={};for(const y of u)f[y.name]=await lt(e,t,y.type,c);const h=i.replace(/^Promise<(.+)>$/,"$1").trim(),g=await lt(e,t,h,c),m={type:"object",properties:f,required:l};return{id:es(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:m,output:g,envelope:{},typeText:{lang:"ts",input:Eo(o),output:h}}}function So(e,t,n,r){const s=Se(n),o=[t,s];return{id:es(e,o),host:"ts",namespace:e,path:o,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function es(e,t){return(e.raw?[e,...t]:t).map(r=>r.words.join("-")).join("/")}function ts(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function Se(e){return{raw:e,words:ts(e)}}function Yt(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Po(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const s=r;if(s.getLeft().getText().trim()!=="module.exports"||s.getOperatorToken().getKindName()!=="EqualsToken")continue;const i=s.getRight(),a=i.getType();for(const c of a.getProperties()){const l=c.getTypeAtLocation(i).getCallSignatures();l.length!==0&&t.push({name:c.getName(),sig:l[0]})}}return t}function Zt(e){return e.getParameters().map(t=>{var o;const n=t.getDeclarations(),r=n.length>0&&n[0].getKindName()==="Parameter"?n[0]:null,s=t.isOptional()||((r==null?void 0:r.hasInitializer())??!1)||(((o=r==null?void 0:r.hasQuestionToken)==null?void 0:o.call(r))??!1);return{name:t.getName(),type:t.getTypeAtLocation(e.getDeclaration()).getText(),optional:s}})}function Xt(e,t){return e.getParameters().map(n=>{var i;const r=n.getDeclarations(),s=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,o=n.isOptional()||((s==null?void 0:s.hasInitializer())??!1)||(((i=s==null?void 0:s.hasQuestionToken)==null?void 0:i.call(s))??!1);return{name:n.getName(),type:n.getTypeAtLocation(t).getText(),optional:o}})}function en(e){return e.getParameters().map(t=>{var o,i,a;const n=t.getDeclarations(),r=n.length>0&&n[0].getKindName()==="Parameter"?n[0]:null,s=t.isOptional()||((r==null?void 0:r.hasInitializer())??!1)||(((o=r==null?void 0:r.hasQuestionToken)==null?void 0:o.call(r))??!1);return{name:t.getName(),type:r?r.getType().getText():((a=(i=t.getValueDeclaration())==null?void 0:i.getType())==null?void 0:a.getText())??"unknown",optional:s}})}function Eo(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Fe(e){return!!(e==="__samples__"||e.startsWith("__"))}function ko(e){const t=e.trim();return t.includes("=>")||t.startsWith("typeof ")||t.toLowerCase().includes("function")?!1:!!(["string","number","boolean","null","undefined"].includes(t)||t.startsWith("'")||t.startsWith('"')||/^\d/.test(t)||t.startsWith("{")||t.startsWith("[")||t.endsWith("[]"))}const jo={compilerOptions:{target:"ES2020",module:"esnext",moduleResolution:"bundler",esModuleInterop:!0,strict:!0,skipLibCheck:!0}};function To(){const e=typeof __dirname<"u"?__dirname:"";if(e){const n=[A.join(e,"default-tsconfig.json"),A.join(e,"lib","default-tsconfig.json"),A.join(e,"..","default-tsconfig.json")];for(const r of n)if(V.existsSync(r))return r}const t=A.join(V.mkdtempSync(A.join($o.tmpdir(),"apigen-tsconfig-")),"tsconfig.json");return V.writeFileSync(t,JSON.stringify(jo,null,2)),t}function ns(e){let t=e;for(;;){const n=A.join(t,"tsconfig.json");if(V.existsSync(n))return n;const r=A.dirname(t);if(r===t)return;t=r}}function He(e,t){if(t)return A.resolve(t);const n=ns(A.dirname(A.resolve(e)));return n||To()}function Mt(e,t={}){if(t.namespace)return t.namespace;const n=A.resolve(e);if(t.tsconfig)return A.basename(A.dirname(A.resolve(t.tsconfig)));const r=ns(A.dirname(n));return r?A.basename(A.dirname(r)):A.basename(A.dirname(n))}async function xt(e){var i,a,c;const t={sourceFile:e.sourceFile,exportMode:e.exportMode??{type:"named"},namespace:e.namespace,tsconfig:He(e.sourceFile,e.tsconfig)};(i=e.logger)==null||i.info(`compiling ${e.sourceFile}`);const n=await Zr(t),r=Object.keys(n.schemas);return(a=e.logger)==null||a.info(`extracted ${r.length} functions`),(c=e.logger)==null||c.debug({functions:r},"extracted functions"),{schemas:Xr(n,e.middlewares??[],e.overrides??{}),createClient:async u=>u}}function rs(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function ss(e){var n,r;const t=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data;return Object.keys((t==null?void 0:t.properties)??{})}async function dt(e,t,n,r,s,o){const a=ss(n).map(c=>o[c]);if(rs(n,"session")&&t){const c=await t({session:s.session});return e[r](c,...a)}if(n.hasCtx){const c=t?await t(s):void 0;return e[r](c,...a)}return e[r](...a)}function qt(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,s=e.format??(r?"pretty":"json"),o={level:t};if(s==="pretty")return o.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},yt(o);const i=n?yt.destination({dest:e.destination,mkdir:!0,sync:!0}):yt.destination(2);return yt(o,i)}function os(e){return e?e.type==="array"?`${os(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function yn(e){var a;const n=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,r=(n==null?void 0:n.properties)??{},s=new Set((n==null?void 0:n.required)??[]),o=Object.entries(r).map(([c,u])=>({name:c,type:os(u),required:s.has(c)})),i=o.map(c=>`${c.name}${c.required?"":"?"}: ${c.type}`).join(", ");return{params:o,text:i}}const hr=new Set(["default","module.exports","__esModule"]);function on(e){const t={},n=(r,s)=>{for(const[o,i]of Object.entries(r))if(typeof i=="function"){!hr.has(o)&&!(o in t)&&(t[o]=i);const a=i.name;a&&!(a in t)&&(t[a]=i)}else i&&typeof i=="object"&&s<2&&hr.has(o)&&n(i,s+1)};return n(e,0),t}function Oo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var an={exports:{}},as={},_e={},Oe={},pt={},K={},ft={};(function(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;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((E,j)=>`${E}${j}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((E,j)=>(j instanceof n&&(E[j.str]=(E[j.str]||0)+1),E),{})}}e._Code=r,e.nil=new r("");function s(p,..._){const E=[p[0]];let j=0;for(;j<_.length;)a(E,_[j]),E.push(p[++j]);return new r(E)}e._=s;const o=new r("+");function i(p,..._){const E=[g(p[0])];let j=0;for(;j<_.length;)E.push(o),a(E,_[j]),E.push(o,g(p[++j]));return c(E),new r(E)}e.str=i;function a(p,_){_ instanceof r?p.push(..._._items):_ instanceof n?p.push(_):p.push(f(_))}e.addCodeArg=a;function c(p){let _=1;for(;_<p.length-1;){if(p[_]===o){const E=u(p[_-1],p[_+1]);if(E!==void 0){p.splice(_-1,3,E);continue}p[_++]="+"}_++}}function u(p,_){if(_==='""')return p;if(p==='""')return _;if(typeof p=="string")return _ instanceof n||p[p.length-1]!=='"'?void 0:typeof _!="string"?`${p.slice(0,-1)}${_}"`:_[0]==='"'?p.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(p instanceof n))return`"${p}${_.slice(1)}`}function l(p,_){return _.emptyStr()?p:p.emptyStr()?_:i`${p}${_}`}e.strConcat=l;function f(p){return typeof p=="number"||typeof p=="boolean"||p===null?p:g(Array.isArray(p)?p.join(","):p)}function h(p){return new r(g(p))}e.stringify=h;function g(p){return JSON.stringify(p).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=g;function m(p){return typeof p=="string"&&e.IDENTIFIER.test(p)?new r(`.${p}`):s`[${p}]`}e.getProperty=m;function v(p){if(typeof p=="string"&&e.IDENTIFIER.test(p))return new r(`${p}`);throw new Error(`CodeGen: invalid export name: ${p}, use explicit $id name mapping`)}e.getEsmExportName=v;function y(p){return new r(p.toString())}e.regexpCode=y})(ft);var cn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ft;class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var r;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class s{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,f;if(!((f=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||f===void 0)&&f.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=s;class o extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:f}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${f}]`}}e.ValueScopeName=o;const i=(0,t._)`\n`;class a extends s{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:t.nil}}get(){return this._scope}name(u){return new o(u,this._newName(u))}value(u,l){var f;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const h=this.toName(u),{prefix:g}=h,m=(f=l.key)!==null&&f!==void 0?f:l.ref;let v=this._values[g];if(v){const _=v.get(m);if(_)return _}else v=this._values[g]=new Map;v.set(m,h);const y=this._scope[g]||(this._scope[g]=[]),p=y.length;return y[p]=l.ref,h.setValue(l,{property:g,itemIndex:p}),h}getValue(u,l){const f=this._values[u];if(f)return f.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${u}${f.scopePath}`})}scopeCode(u=this._values,l,f){return this._reduceValues(u,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},l,f)}_reduceValues(u,l,f={},h){let g=t.nil;for(const m in u){const v=u[m];if(!v)continue;const y=f[m]=f[m]||new Map;v.forEach(p=>{if(y.has(p))return;y.set(p,r.Started);let _=l(p);if(_){const E=this.opts.es5?e.varKinds.var:e.varKinds.const;g=(0,t._)`${g}${E} ${p} = ${_};${this.opts._n}`}else if(_=h==null?void 0:h(p))g=(0,t._)`${g}${_}${this.opts._n}`;else throw new n(p);y.set(p,r.Completed)})}return g}}e.ValueScope=a})(cn);(function(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;const t=ft,n=cn;var r=ft;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 s=cn;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return s.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("+")};class o{optimizeNodes(){return this}optimizeNames(d,$){return this}}class i extends o{constructor(d,$,k){super(),this.varKind=d,this.name=$,this.rhs=k}render({es5:d,_n:$}){const k=d?n.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${k} ${this.name}${M};`+$}optimizeNames(d,$){if(d[this.name.str])return this.rhs&&(this.rhs=Z(this.rhs,d,$)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends o{constructor(d,$,k){super(),this.lhs=d,this.rhs=$,this.sideEffects=k}render({_n:d}){return`${this.lhs} = ${this.rhs};`+d}optimizeNames(d,$){if(!(this.lhs instanceof t.Name&&!d[this.lhs.str]&&!this.sideEffects))return this.rhs=Z(this.rhs,d,$),this}get names(){const d=this.lhs instanceof t.Name?{}:{...this.lhs.names};return J(d,this.rhs)}}class c extends a{constructor(d,$,k,M){super(d,k,M),this.op=$}render({_n:d}){return`${this.lhs} ${this.op}= ${this.rhs};`+d}}class u extends o{constructor(d){super(),this.label=d,this.names={}}render({_n:d}){return`${this.label}:`+d}}class l extends o{constructor(d){super(),this.label=d,this.names={}}render({_n:d}){return`break${this.label?` ${this.label}`:""};`+d}}class f extends o{constructor(d){super(),this.error=d}render({_n:d}){return`throw ${this.error};`+d}get names(){return this.error.names}}class h extends o{constructor(d){super(),this.code=d}render({_n:d}){return`${this.code};`+d}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(d,$){return this.code=Z(this.code,d,$),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class g extends o{constructor(d=[]){super(),this.nodes=d}render(d){return this.nodes.reduce(($,k)=>$+k.render(d),"")}optimizeNodes(){const{nodes:d}=this;let $=d.length;for(;$--;){const k=d[$].optimizeNodes();Array.isArray(k)?d.splice($,1,...k):k?d[$]=k:d.splice($,1)}return d.length>0?this:void 0}optimizeNames(d,$){const{nodes:k}=this;let M=k.length;for(;M--;){const D=k[M];D.optimizeNames(d,$)||(ve(d,D.names),k.splice(M,1))}return k.length>0?this:void 0}get names(){return this.nodes.reduce((d,$)=>ne(d,$.names),{})}}class m extends g{render(d){return"{"+d._n+super.render(d)+"}"+d._n}}class v extends g{}class y extends m{}y.kind="else";class p extends m{constructor(d,$){super($),this.condition=d}render(d){let $=`if(${this.condition})`+super.render(d);return this.else&&($+="else "+this.else.render(d)),$}optimizeNodes(){super.optimizeNodes();const d=this.condition;if(d===!0)return this.nodes;let $=this.else;if($){const k=$.optimizeNodes();$=this.else=Array.isArray(k)?new y(k):k}if($)return d===!1?$ instanceof p?$:$.nodes:this.nodes.length?this:new p(Te(d),$ instanceof p?[$]:$.nodes);if(!(d===!1||!this.nodes.length))return this}optimizeNames(d,$){var k;if(this.else=(k=this.else)===null||k===void 0?void 0:k.optimizeNames(d,$),!!(super.optimizeNames(d,$)||this.else))return this.condition=Z(this.condition,d,$),this}get names(){const d=super.names;return J(d,this.condition),this.else&&ne(d,this.else.names),d}}p.kind="if";class _ extends m{}_.kind="for";class E extends _{constructor(d){super(),this.iteration=d}render(d){return`for(${this.iteration})`+super.render(d)}optimizeNames(d,$){if(super.optimizeNames(d,$))return this.iteration=Z(this.iteration,d,$),this}get names(){return ne(super.names,this.iteration.names)}}class j extends _{constructor(d,$,k,M){super(),this.varKind=d,this.name=$,this.from=k,this.to=M}render(d){const $=d.es5?n.varKinds.var:this.varKind,{name:k,from:M,to:D}=this;return`for(${$} ${k}=${M}; ${k}<${D}; ${k}++)`+super.render(d)}get names(){const d=J(super.names,this.from);return J(d,this.to)}}class N extends _{constructor(d,$,k,M){super(),this.loop=d,this.varKind=$,this.name=k,this.iterable=M}render(d){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(d)}optimizeNames(d,$){if(super.optimizeNames(d,$))return this.iterable=Z(this.iterable,d,$),this}get names(){return ne(super.names,this.iterable.names)}}class q extends m{constructor(d,$,k){super(),this.name=d,this.args=$,this.async=k}render(d){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(d)}}q.kind="func";class F extends g{render(d){return"return "+super.render(d)}}F.kind="return";class W extends m{render(d){let $="try"+super.render(d);return this.catch&&($+=this.catch.render(d)),this.finally&&($+=this.finally.render(d)),$}optimizeNodes(){var d,$;return super.optimizeNodes(),(d=this.catch)===null||d===void 0||d.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(d,$){var k,M;return super.optimizeNames(d,$),(k=this.catch)===null||k===void 0||k.optimizeNames(d,$),(M=this.finally)===null||M===void 0||M.optimizeNames(d,$),this}get names(){const d=super.names;return this.catch&&ne(d,this.catch.names),this.finally&&ne(d,this.finally.names),d}}class B extends m{constructor(d){super(),this.error=d}render(d){return`catch(${this.error})`+super.render(d)}}B.kind="catch";class ee extends m{render(d){return"finally"+super.render(d)}}ee.kind="finally";class ie{constructor(d,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
3
|
-
`:""},this._extScope=d,this._scope=new n.Scope({parent:d}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(d){return this._scope.name(d)}scopeName(d){return this._extScope.name(d)}scopeValue(d,$){const k=this._extScope.value(d,$);return(this._values[k.prefix]||(this._values[k.prefix]=new Set)).add(k),k}getScopeValue(d,$){return this._extScope.getValue(d,$)}scopeRefs(d){return this._extScope.scopeRefs(d,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(d,$,k,M){const D=this._scope.toName($);return k!==void 0&&M&&(this._constants[D.str]=k),this._leafNode(new i(d,D,k)),D}const(d,$,k){return this._def(n.varKinds.const,d,$,k)}let(d,$,k){return this._def(n.varKinds.let,d,$,k)}var(d,$,k){return this._def(n.varKinds.var,d,$,k)}assign(d,$,k){return this._leafNode(new a(d,$,k))}add(d,$){return this._leafNode(new c(d,e.operators.ADD,$))}code(d){return typeof d=="function"?d():d!==t.nil&&this._leafNode(new h(d)),this}object(...d){const $=["{"];for(const[k,M]of d)$.length>1&&$.push(","),$.push(k),(k!==M||this.opts.es5)&&($.push(":"),(0,t.addCodeArg)($,M));return $.push("}"),new t._Code($)}if(d,$,k){if(this._blockNode(new p(d)),$&&k)this.code($).else().code(k).endIf();else if($)this.code($).endIf();else if(k)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(d){return this._elseNode(new p(d))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(p,y)}_for(d,$){return this._blockNode(d),$&&this.code($).endFor(),this}for(d,$){return this._for(new E(d),$)}forRange(d,$,k,M,D=this.opts.es5?n.varKinds.var:n.varKinds.let){const G=this._scope.toName(d);return this._for(new j(D,G,$,k),()=>M(G))}forOf(d,$,k,M=n.varKinds.const){const D=this._scope.toName(d);if(this.opts.es5){const G=$ instanceof t.Name?$:this.var("_arr",$);return this.forRange("_i",0,(0,t._)`${G}.length`,H=>{this.var(D,(0,t._)`${G}[${H}]`),k(D)})}return this._for(new N("of",M,D,$),()=>k(D))}forIn(d,$,k,M=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(d,(0,t._)`Object.keys(${$})`,k);const D=this._scope.toName(d);return this._for(new N("in",M,D,$),()=>k(D))}endFor(){return this._endBlockNode(_)}label(d){return this._leafNode(new u(d))}break(d){return this._leafNode(new l(d))}return(d){const $=new F;if(this._blockNode($),this.code(d),$.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(F)}try(d,$,k){if(!$&&!k)throw new Error('CodeGen: "try" without "catch" and "finally"');const M=new W;if(this._blockNode(M),this.code(d),$){const D=this.name("e");this._currNode=M.catch=new B(D),$(D)}return k&&(this._currNode=M.finally=new ee,this.code(k)),this._endBlockNode(B,ee)}throw(d){return this._leafNode(new f(d))}block(d,$){return this._blockStarts.push(this._nodes.length),d&&this.code(d).endBlock($),this}endBlock(d){const $=this._blockStarts.pop();if($===void 0)throw new Error("CodeGen: not in self-balancing block");const k=this._nodes.length-$;if(k<0||d!==void 0&&k!==d)throw new Error(`CodeGen: wrong number of nodes: ${k} vs ${d} expected`);return this._nodes.length=$,this}func(d,$=t.nil,k,M){return this._blockNode(new q(d,$,k)),M&&this.code(M).endFunc(),this}endFunc(){return this._endBlockNode(q)}optimize(d=1){for(;d-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(d){return this._currNode.nodes.push(d),this}_blockNode(d){this._currNode.nodes.push(d),this._nodes.push(d)}_endBlockNode(d,$){const k=this._currNode;if(k instanceof d||$&&k instanceof $)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${$?`${d.kind}/${$.kind}`:d.kind}"`)}_elseNode(d){const $=this._currNode;if(!($ instanceof p))throw new Error('CodeGen: "else" without "if"');return this._currNode=$.else=d,this}get _root(){return this._nodes[0]}get _currNode(){const d=this._nodes;return d[d.length-1]}set _currNode(d){const $=this._nodes;$[$.length-1]=d}}e.CodeGen=ie;function ne(P,d){for(const $ in d)P[$]=(P[$]||0)+(d[$]||0);return P}function J(P,d){return d instanceof t._CodeOrName?ne(P,d.names):P}function Z(P,d,$){if(P instanceof t.Name)return k(P);if(!M(P))return P;return new t._Code(P._items.reduce((D,G)=>(G instanceof t.Name&&(G=k(G)),G instanceof t._Code?D.push(...G._items):D.push(G),D),[]));function k(D){const G=$[D.str];return G===void 0||d[D.str]!==1?D:(delete d[D.str],G)}function M(D){return D instanceof t._Code&&D._items.some(G=>G instanceof t.Name&&d[G.str]===1&&$[G.str]!==void 0)}}function ve(P,d){for(const $ in d)P[$]=(P[$]||0)-(d[$]||0)}function Te(P){return typeof P=="boolean"||typeof P=="number"||P===null?!P:(0,t._)`!${O(P)}`}e.not=Te;const xe=b(e.operators.AND);function Ze(...P){return P.reduce(xe)}e.and=Ze;const qe=b(e.operators.OR);function I(...P){return P.reduce(qe)}e.or=I;function b(P){return(d,$)=>d===t.nil?$:$===t.nil?d:(0,t._)`${O(d)} ${P} ${O($)}`}function O(P){return P instanceof t.Name?P:(0,t._)`(${P})`}})(K);var C={};Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;const Q=K,No=ft;function Ro(e){const t={};for(const n of e)t[n]=!0;return t}C.toHash=Ro;function Io(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(is(e,t),!cs(t,e.self.RULES.all))}C.alwaysValidSchema=Io;function is(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const s=r.RULES.keywords;for(const o in t)s[o]||ds(e,`unknown keyword: "${o}"`)}C.checkUnknownRules=is;function cs(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}C.schemaHasRules=cs;function Co(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}C.schemaHasRulesButRef=Co;function Ao({topSchemaRef:e,schemaPath:t},n,r,s){if(!s){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Q._)`${n}`}return(0,Q._)`${e}${t}${(0,Q.getProperty)(r)}`}C.schemaRefOrVal=Ao;function Mo(e){return us(decodeURIComponent(e))}C.unescapeFragment=Mo;function xo(e){return encodeURIComponent($n(e))}C.escapeFragment=xo;function $n(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=$n;function us(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=us;function qo(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}C.eachItem=qo;function mr({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(s,o,i,a)=>{const c=i===void 0?o:i instanceof Q.Name?(o instanceof Q.Name?e(s,o,i):t(s,o,i),i):o instanceof Q.Name?(t(s,i,o),o):n(o,i);return a===Q.Name&&!(c instanceof Q.Name)?r(s,c):c}}C.mergeEvaluated={props:mr({mergeNames:(e,t,n)=>e.if((0,Q._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,Q._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,Q._)`${n} || {}`).code((0,Q._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,Q._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,Q._)`${n} || {}`),vn(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:ls}),items:mr({mergeNames:(e,t,n)=>e.if((0,Q._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,Q._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,Q._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,Q._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function ls(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,Q._)`{}`);return t!==void 0&&vn(e,n,t),n}C.evaluatedPropsToName=ls;function vn(e,t,n){Object.keys(n).forEach(r=>e.assign((0,Q._)`${t}${(0,Q.getProperty)(r)}`,!0))}C.setEvaluated=vn;const gr={};function Do(e,t){return e.scopeValue("func",{ref:t,code:gr[t.code]||(gr[t.code]=new No._Code(t.code))})}C.useFunc=Do;var un;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(un||(C.Type=un={}));function Fo(e,t,n){if(e instanceof Q.Name){const r=t===un.Num;return n?r?(0,Q._)`"[" + ${e} + "]"`:(0,Q._)`"['" + ${e} + "']"`:r?(0,Q._)`"/" + ${e}`:(0,Q._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Q.getProperty)(e).toString():"/"+$n(e)}C.getErrorPath=Fo;function ds(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}C.checkStrictMode=ds;var $t={},yr;function je(){if(yr)return $t;yr=1,Object.defineProperty($t,"__esModule",{value:!0});const e=K,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return $t.default=t,$t}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=K,n=C,r=je();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:p})=>p?(0,t.str)`"${y}" keyword must be ${p} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function s(y,p=e.keywordError,_,E){const{it:j}=y,{gen:N,compositeRule:q,allErrors:F}=j,W=f(y,p,_);E??(q||F)?c(N,W):u(j,(0,t._)`[${W}]`)}e.reportError=s;function o(y,p=e.keywordError,_){const{it:E}=y,{gen:j,compositeRule:N,allErrors:q}=E,F=f(y,p,_);c(j,F),N||q||u(E,r.default.vErrors)}e.reportExtraError=o;function i(y,p){y.assign(r.default.errors,p),y.if((0,t._)`${r.default.vErrors} !== null`,()=>y.if(p,()=>y.assign((0,t._)`${r.default.vErrors}.length`,p),()=>y.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:y,keyword:p,schemaValue:_,data:E,errsCount:j,it:N}){if(j===void 0)throw new Error("ajv implementation error");const q=y.name("err");y.forRange("i",j,r.default.errors,F=>{y.const(q,(0,t._)`${r.default.vErrors}[${F}]`),y.if((0,t._)`${q}.instancePath === undefined`,()=>y.assign((0,t._)`${q}.instancePath`,(0,t.strConcat)(r.default.instancePath,N.errorPath))),y.assign((0,t._)`${q}.schemaPath`,(0,t.str)`${N.errSchemaPath}/${p}`),N.opts.verbose&&(y.assign((0,t._)`${q}.schema`,_),y.assign((0,t._)`${q}.data`,E))})}e.extendErrors=a;function c(y,p){const _=y.const("err",p);y.if((0,t._)`${r.default.vErrors} === null`,()=>y.assign(r.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${r.default.vErrors}.push(${_})`),y.code((0,t._)`${r.default.errors}++`)}function u(y,p){const{gen:_,validateName:E,schemaEnv:j}=y;j.$async?_.throw((0,t._)`new ${y.ValidationError}(${p})`):(_.assign((0,t._)`${E}.errors`,p),_.return(!1))}const l={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 f(y,p,_){const{createErrors:E}=y.it;return E===!1?(0,t._)`{}`:h(y,p,_)}function h(y,p,_={}){const{gen:E,it:j}=y,N=[g(j,_),m(y,_)];return v(y,p,N),E.object(...N)}function g({errorPath:y},{instancePath:p}){const _=p?(0,t.str)`${y}${(0,n.getErrorPath)(p,n.Type.Str)}`:y;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,_)]}function m({keyword:y,it:{errSchemaPath:p}},{schemaPath:_,parentSchema:E}){let j=E?p:(0,t.str)`${p}/${y}`;return _&&(j=(0,t.str)`${j}${(0,n.getErrorPath)(_,n.Type.Str)}`),[l.schemaPath,j]}function v(y,{params:p,message:_},E){const{keyword:j,data:N,schemaValue:q,it:F}=y,{opts:W,propertyName:B,topSchemaRef:ee,schemaPath:ie}=F;E.push([l.keyword,j],[l.params,typeof p=="function"?p(y):p||(0,t._)`{}`]),W.messages&&E.push([l.message,typeof _=="function"?_(y):_]),W.verbose&&E.push([l.schema,q],[l.parentSchema,(0,t._)`${ee}${ie}`],[r.default.data,N]),B&&E.push([l.propertyName,B])}})(pt);var $r;function Vo(){if($r)return Oe;$r=1,Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.boolOrEmptySchema=Oe.topBoolOrEmptySchema=void 0;const e=pt,t=K,n=je(),r={message:"boolean schema is false"};function s(a){const{gen:c,schema:u,validateName:l}=a;u===!1?i(a,!1):typeof u=="object"&&u.$async===!0?c.return(n.default.data):(c.assign((0,t._)`${l}.errors`,null),c.return(!0))}Oe.topBoolOrEmptySchema=s;function o(a,c){const{gen:u,schema:l}=a;l===!1?(u.var(c,!1),i(a)):u.var(c,!0)}Oe.boolOrEmptySchema=o;function i(a,c){const{gen:u,data:l}=a,f={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(f,r,void 0,c)}return Oe}var te={},Ce={};Object.defineProperty(Ce,"__esModule",{value:!0});Ce.getRules=Ce.isJSONType=void 0;const zo=["string","number","integer","boolean","null","object","array"],Lo=new Set(zo);function Uo(e){return typeof e=="string"&&Lo.has(e)}Ce.isJSONType=Uo;function Ko(){const 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:{}}}Ce.getRules=Ko;var we={},vr;function fs(){if(vr)return we;vr=1,Object.defineProperty(we,"__esModule",{value:!0}),we.shouldUseRule=we.shouldUseGroup=we.schemaHasRulesForType=void 0;function e({schema:r,self:s},o){const i=s.RULES.types[o];return i&&i!==!0&&t(r,i)}we.schemaHasRulesForType=e;function t(r,s){return s.rules.some(o=>n(r,o))}we.shouldUseGroup=t;function n(r,s){var o;return r[s.keyword]!==void 0||((o=s.definition.implements)===null||o===void 0?void 0:o.some(i=>r[i]!==void 0))}return we.shouldUseRule=n,we}Object.defineProperty(te,"__esModule",{value:!0});te.reportTypeError=te.checkDataTypes=te.checkDataType=te.coerceAndCheckDataType=te.getJSONTypes=te.getSchemaTypes=te.DataType=void 0;const Ho=Ce,Go=fs(),Jo=pt,z=K,ps=C;var Ue;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Ue||(te.DataType=Ue={}));function Wo(e){const t=hs(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}te.getSchemaTypes=Wo;function hs(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Ho.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}te.getJSONTypes=hs;function Bo(e,t){const{gen:n,data:r,opts:s}=e,o=Qo(t,s.coerceTypes),i=t.length>0&&!(o.length===0&&t.length===1&&(0,Go.schemaHasRulesForType)(e,t[0]));if(i){const a=_n(t,r,s.strictNumbers,Ue.Wrong);n.if(a,()=>{o.length?Yo(e,t,o):wn(e)})}return i}te.coerceAndCheckDataType=Bo;const ms=new Set(["string","number","integer","boolean","null"]);function Qo(e,t){return t?e.filter(n=>ms.has(n)||t==="array"&&n==="array"):[]}function Yo(e,t,n){const{gen:r,data:s,opts:o}=e,i=r.let("dataType",(0,z._)`typeof ${s}`),a=r.let("coerced",(0,z._)`undefined`);o.coerceTypes==="array"&&r.if((0,z._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,z._)`${s}[0]`).assign(i,(0,z._)`typeof ${s}`).if(_n(t,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,z._)`${a} !== undefined`);for(const u of n)(ms.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);r.else(),wn(e),r.endIf(),r.if((0,z._)`${a} !== undefined`,()=>{r.assign(s,a),Zo(e,a)});function c(u){switch(u){case"string":r.elseIf((0,z._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,z._)`"" + ${s}`).elseIf((0,z._)`${s} === null`).assign(a,(0,z._)`""`);return;case"number":r.elseIf((0,z._)`${i} == "boolean" || ${s} === null
|
|
4
|
-
|| (${i} == "string" && ${
|
|
5
|
-
|| (${i} === "string" && ${
|
|
6
|
-
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,z._)`[${s}]`)}}}function Zo({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,z._)`${t} !== undefined`,()=>e.assign((0,z._)`${t}[${n}]`,r))}function ln(e,t,n,r=Ue.Correct){const s=r===Ue.Correct?z.operators.EQ:z.operators.NEQ;let o;switch(e){case"null":return(0,z._)`${t} ${s} null`;case"array":o=(0,z._)`Array.isArray(${t})`;break;case"object":o=(0,z._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=i((0,z._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=i();break;default:return(0,z._)`typeof ${t} ${s} ${e}`}return r===Ue.Correct?o:(0,z.not)(o);function i(a=z.nil){return(0,z.and)((0,z._)`typeof ${t} == "number"`,a,n?(0,z._)`isFinite(${t})`:z.nil)}}te.checkDataType=ln;function _n(e,t,n,r){if(e.length===1)return ln(e[0],t,n,r);let s;const o=(0,ps.toHash)(e);if(o.array&&o.object){const i=(0,z._)`typeof ${t} != "object"`;s=o.null?i:(0,z._)`!${t} || ${i}`,delete o.null,delete o.array,delete o.object}else s=z.nil;o.number&&delete o.integer;for(const i in o)s=(0,z.and)(s,ln(i,t,n,r));return s}te.checkDataTypes=_n;const Xo={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,z._)`{type: ${e}}`:(0,z._)`{type: ${t}}`};function wn(e){const t=ea(e);(0,Jo.reportError)(t,Xo)}te.reportTypeError=wn;function ea(e){const{gen:t,data:n,schema:r}=e,s=(0,ps.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:e}}var tt={},_r;function ta(){if(_r)return tt;_r=1,Object.defineProperty(tt,"__esModule",{value:!0}),tt.assignDefaults=void 0;const e=K,t=C;function n(s,o){const{properties:i,items:a}=s.schema;if(o==="object"&&i)for(const c in i)r(s,c,i[c].default);else o==="array"&&Array.isArray(a)&&a.forEach((c,u)=>r(s,u,c.default))}tt.assignDefaults=n;function r(s,o,i){const{gen:a,compositeRule:c,data:u,opts:l}=s;if(i===void 0)return;const f=(0,e._)`${u}${(0,e.getProperty)(o)}`;if(c){(0,t.checkStrictMode)(s,`default is ignored for: ${f}`);return}let h=(0,e._)`${f} === undefined`;l.useDefaults==="empty"&&(h=(0,e._)`${h} || ${f} === null || ${f} === ""`),a.if(h,(0,e._)`${f} = ${(0,e.stringify)(i)}`)}return tt}var me={},U={};Object.defineProperty(U,"__esModule",{value:!0});U.validateUnion=U.validateArray=U.usePattern=U.callValidateCode=U.schemaProperties=U.allSchemaProperties=U.noPropertyInData=U.propertyInData=U.isOwnProperty=U.hasPropFunc=U.reportMissingProp=U.checkMissingProp=U.checkReportMissingProp=void 0;const Y=K,bn=C,Pe=je(),na=C;function ra(e,t){const{gen:n,data:r,it:s}=e;n.if(Pn(n,r,t,s.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Y._)`${t}`},!0),e.error()})}U.checkReportMissingProp=ra;function sa({gen:e,data:t,it:{opts:n}},r,s){return(0,Y.or)(...r.map(o=>(0,Y.and)(Pn(e,t,o,n.ownProperties),(0,Y._)`${s} = ${o}`)))}U.checkMissingProp=sa;function oa(e,t){e.setParams({missingProperty:t},!0),e.error()}U.reportMissingProp=oa;function gs(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Y._)`Object.prototype.hasOwnProperty`})}U.hasPropFunc=gs;function Sn(e,t,n){return(0,Y._)`${gs(e)}.call(${t}, ${n})`}U.isOwnProperty=Sn;function aa(e,t,n,r){const s=(0,Y._)`${t}${(0,Y.getProperty)(n)} !== undefined`;return r?(0,Y._)`${s} && ${Sn(e,t,n)}`:s}U.propertyInData=aa;function Pn(e,t,n,r){const s=(0,Y._)`${t}${(0,Y.getProperty)(n)} === undefined`;return r?(0,Y.or)(s,(0,Y.not)(Sn(e,t,n))):s}U.noPropertyInData=Pn;function ys(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}U.allSchemaProperties=ys;function ia(e,t){return ys(t).filter(n=>!(0,bn.alwaysValidSchema)(e,t[n]))}U.schemaProperties=ia;function ca({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,c,u){const l=u?(0,Y._)`${e}, ${t}, ${r}${s}`:t,f=[[Pe.default.instancePath,(0,Y.strConcat)(Pe.default.instancePath,o)],[Pe.default.parentData,i.parentData],[Pe.default.parentDataProperty,i.parentDataProperty],[Pe.default.rootData,Pe.default.rootData]];i.opts.dynamicRef&&f.push([Pe.default.dynamicAnchors,Pe.default.dynamicAnchors]);const h=(0,Y._)`${l}, ${n.object(...f)}`;return c!==Y.nil?(0,Y._)`${a}.call(${c}, ${h})`:(0,Y._)`${a}(${h})`}U.callValidateCode=ca;const ua=(0,Y._)`new RegExp`;function la({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:s}=t.code,o=s(n,r);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Y._)`${s.code==="new RegExp"?ua:(0,na.useFunc)(e,s)}(${n}, ${r})`})}U.usePattern=la;function da(e){const{gen:t,data:n,keyword:r,it:s}=e,o=t.name("valid");if(s.allErrors){const a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(o,!0),i(()=>t.break()),o;function i(a){const c=t.const("len",(0,Y._)`${n}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:r,dataProp:u,dataPropType:bn.Type.Num},o),t.if((0,Y.not)(o),a)})}}U.validateArray=da;function fa(e){const{gen:t,schema:n,keyword:r,it:s}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,bn.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;const i=t.let("valid",!1),a=t.name("_valid");t.block(()=>n.forEach((c,u)=>{const l=e.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,Y._)`${i} || ${a}`),e.mergeValidEvaluated(l,a)||t.if((0,Y.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}U.validateUnion=fa;var wr;function pa(){if(wr)return me;wr=1,Object.defineProperty(me,"__esModule",{value:!0}),me.validateKeywordUsage=me.validSchemaType=me.funcKeywordCode=me.macroKeywordCode=void 0;const e=K,t=je(),n=U,r=pt;function s(h,g){const{gen:m,keyword:v,schema:y,parentSchema:p,it:_}=h,E=g.macro.call(_.self,y,p,_),j=u(m,v,E);_.opts.validateSchema!==!1&&_.self.validateSchema(E,!0);const N=m.name("valid");h.subschema({schema:E,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${v}`,topSchemaRef:j,compositeRule:!0},N),h.pass(N,()=>h.error(!0))}me.macroKeywordCode=s;function o(h,g){var m;const{gen:v,keyword:y,schema:p,parentSchema:_,$data:E,it:j}=h;c(j,g);const N=!E&&g.compile?g.compile.call(j.self,p,_,j):g.validate,q=u(v,y,N),F=v.let("valid");h.block$data(F,W),h.ok((m=g.valid)!==null&&m!==void 0?m:F);function W(){if(g.errors===!1)ie(),g.modifying&&i(h),ne(()=>h.error());else{const J=g.async?B():ee();g.modifying&&i(h),ne(()=>a(h,J))}}function B(){const J=v.let("ruleErrs",null);return v.try(()=>ie((0,e._)`await `),Z=>v.assign(F,!1).if((0,e._)`${Z} instanceof ${j.ValidationError}`,()=>v.assign(J,(0,e._)`${Z}.errors`),()=>v.throw(Z))),J}function ee(){const J=(0,e._)`${q}.errors`;return v.assign(J,null),ie(e.nil),J}function ie(J=g.async?(0,e._)`await `:e.nil){const Z=j.opts.passContext?t.default.this:t.default.self,ve=!("compile"in g&&!E||g.schema===!1);v.assign(F,(0,e._)`${J}${(0,n.callValidateCode)(h,q,Z,ve)}`,g.modifying)}function ne(J){var Z;v.if((0,e.not)((Z=g.valid)!==null&&Z!==void 0?Z:F),J)}}me.funcKeywordCode=o;function i(h){const{gen:g,data:m,it:v}=h;g.if(v.parentData,()=>g.assign(m,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function a(h,g){const{gen:m}=h;m.if((0,e._)`Array.isArray(${g})`,()=>{m.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${g} : ${t.default.vErrors}.concat(${g})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,r.extendErrors)(h)},()=>h.error())}function c({schemaEnv:h},g){if(g.async&&!h.$async)throw new Error("async keyword in sync schema")}function u(h,g,m){if(m===void 0)throw new Error(`keyword "${g}" failed to compile`);return h.scopeValue("keyword",typeof m=="function"?{ref:m}:{ref:m,code:(0,e.stringify)(m)})}function l(h,g,m=!1){return!g.length||g.some(v=>v==="array"?Array.isArray(h):v==="object"?h&&typeof h=="object"&&!Array.isArray(h):typeof h==v||m&&typeof h>"u")}me.validSchemaType=l;function f({schema:h,opts:g,self:m,errSchemaPath:v},y,p){if(Array.isArray(y.keyword)?!y.keyword.includes(p):y.keyword!==p)throw new Error("ajv implementation error");const _=y.dependencies;if(_!=null&&_.some(E=>!Object.prototype.hasOwnProperty.call(h,E)))throw new Error(`parent schema must have dependencies of ${p}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(h[p])){const j=`keyword "${p}" value is invalid at path "${v}": `+m.errorsText(y.validateSchema.errors);if(g.validateSchema==="log")m.logger.error(j);else throw new Error(j)}}return me.validateKeywordUsage=f,me}var be={},br;function ha(){if(br)return be;br=1,Object.defineProperty(be,"__esModule",{value:!0}),be.extendSubschemaMode=be.extendSubschemaData=be.getSubschema=void 0;const e=K,t=C;function n(o,{keyword:i,schemaProp:a,schema:c,schemaPath:u,errSchemaPath:l,topSchemaRef:f}){if(i!==void 0&&c!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const h=o.schema[i];return a===void 0?{schema:h,schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${o.errSchemaPath}/${i}`}:{schema:h[a],schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(a)}`,errSchemaPath:`${o.errSchemaPath}/${i}/${(0,t.escapeFragment)(a)}`}}if(c!==void 0){if(u===void 0||l===void 0||f===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:u,topSchemaRef:f,errSchemaPath:l}}throw new Error('either "keyword" or "schema" must be passed')}be.getSubschema=n;function r(o,i,{dataProp:a,dataPropType:c,data:u,dataTypes:l,propertyName:f}){if(u!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=i;if(a!==void 0){const{errorPath:m,dataPathArr:v,opts:y}=i,p=h.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);g(p),o.errorPath=(0,e.str)`${m}${(0,t.getErrorPath)(a,c,y.jsPropertySyntax)}`,o.parentDataProperty=(0,e._)`${a}`,o.dataPathArr=[...v,o.parentDataProperty]}if(u!==void 0){const m=u instanceof e.Name?u:h.let("data",u,!0);g(m),f!==void 0&&(o.propertyName=f)}l&&(o.dataTypes=l);function g(m){o.data=m,o.dataLevel=i.dataLevel+1,o.dataTypes=[],i.definedProperties=new Set,o.parentData=i.data,o.dataNames=[...i.dataNames,m]}}be.extendSubschemaData=r;function s(o,{jtdDiscriminator:i,jtdMetadata:a,compositeRule:c,createErrors:u,allErrors:l}){c!==void 0&&(o.compositeRule=c),u!==void 0&&(o.createErrors=u),l!==void 0&&(o.allErrors=l),o.jtdDiscriminator=i,o.jtdMetadata=a}return be.extendSubschemaMode=s,be}var ae={},$s=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,s,o;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!e(t[s],n[s]))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(o=Object.keys(t),r=o.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;s--!==0;){var i=o[s];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n},vs={exports:{}},ke=vs.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},s=n.post||function(){};Et(t,r,s,e,"",e)};ke.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ke.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ke.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ke.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 Et(e,t,n,r,s,o,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,s,o,i,a,c,u);for(var l in r){var f=r[l];if(Array.isArray(f)){if(l in ke.arrayKeywords)for(var h=0;h<f.length;h++)Et(e,t,n,f[h],s+"/"+l+"/"+h,o,s,l,r,h)}else if(l in ke.propsKeywords){if(f&&typeof f=="object")for(var g in f)Et(e,t,n,f[g],s+"/"+l+"/"+ma(g),o,s,l,r,g)}else(l in ke.keywords||e.allKeys&&!(l in ke.skipKeywords))&&Et(e,t,n,f,s+"/"+l,o,s,l,r)}n(r,s,o,i,a,c,u)}}function ma(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var ga=vs.exports;Object.defineProperty(ae,"__esModule",{value:!0});ae.getSchemaRefs=ae.resolveUrl=ae.normalizeId=ae._getFullPath=ae.getFullPath=ae.inlineRef=void 0;const ya=C,$a=$s,va=ga,_a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wa(e,t=!0){return typeof e=="boolean"?!0:t===!0?!dn(e):t?_s(e)<=t:!1}ae.inlineRef=wa;const ba=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function dn(e){for(const t in e){if(ba.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(dn)||typeof n=="object"&&dn(n))return!0}return!1}function _s(e){let t=0;for(const n in e){if(n==="$ref")return 1/0;if(t++,!_a.has(n)&&(typeof e[n]=="object"&&(0,ya.eachItem)(e[n],r=>t+=_s(r)),t===1/0))return 1/0}return t}function ws(e,t="",n){n!==!1&&(t=Ke(t));const r=e.parse(t);return bs(e,r)}ae.getFullPath=ws;function bs(e,t){return e.serialize(t).split("#")[0]+"#"}ae._getFullPath=bs;const Sa=/#\/?$/;function Ke(e){return e?e.replace(Sa,""):""}ae.normalizeId=Ke;function Pa(e,t,n){return n=Ke(n),e.resolve(t,n)}ae.resolveUrl=Pa;const Ea=/^[a-z_][-a-z0-9._]*$/i;function ka(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,s=Ke(e[n]||t),o={"":s},i=ws(r,s,!1),a={},c=new Set;return va(e,{allKeys:!0},(f,h,g,m)=>{if(m===void 0)return;const v=i+h;let y=o[m];typeof f[n]=="string"&&(y=p.call(this,f[n])),_.call(this,f.$anchor),_.call(this,f.$dynamicAnchor),o[h]=y;function p(E){const j=this.opts.uriResolver.resolve;if(E=Ke(y?j(y,E):E),c.has(E))throw l(E);c.add(E);let N=this.refs[E];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(f,N.schema,E):E!==Ke(v)&&(E[0]==="#"?(u(f,a[E],E),a[E]=f):this.refs[E]=v),E}function _(E){if(typeof E=="string"){if(!Ea.test(E))throw new Error(`invalid anchor "${E}"`);p.call(this,`#${E}`)}}}),a;function u(f,h,g){if(h!==void 0&&!$a(f,h))throw l(g)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ae.getSchemaRefs=ka;var Sr;function Dt(){if(Sr)return _e;Sr=1,Object.defineProperty(_e,"__esModule",{value:!0}),_e.getData=_e.KeywordCxt=_e.validateFunctionCode=void 0;const e=Vo(),t=te,n=fs(),r=te,s=ta(),o=pa(),i=ha(),a=K,c=je(),u=ae,l=C,f=pt;function h(w){if(N(w)&&(F(w),j(w))){y(w);return}g(w,()=>(0,e.topBoolOrEmptySchema)(w))}_e.validateFunctionCode=h;function g({gen:w,validateName:S,schema:T,schemaEnv:R,opts:x},L){x.code.es5?w.func(S,(0,a._)`${c.default.data}, ${c.default.valCxt}`,R.$async,()=>{w.code((0,a._)`"use strict"; ${_(T,x)}`),v(w,x),w.code(L)}):w.func(S,(0,a._)`${c.default.data}, ${m(x)}`,R.$async,()=>w.code(_(T,x)).code(L))}function m(w){return(0,a._)`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${w.dynamicRef?(0,a._)`, ${c.default.dynamicAnchors}={}`:a.nil}}={}`}function v(w,S){w.if(c.default.valCxt,()=>{w.var(c.default.instancePath,(0,a._)`${c.default.valCxt}.${c.default.instancePath}`),w.var(c.default.parentData,(0,a._)`${c.default.valCxt}.${c.default.parentData}`),w.var(c.default.parentDataProperty,(0,a._)`${c.default.valCxt}.${c.default.parentDataProperty}`),w.var(c.default.rootData,(0,a._)`${c.default.valCxt}.${c.default.rootData}`),S.dynamicRef&&w.var(c.default.dynamicAnchors,(0,a._)`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{w.var(c.default.instancePath,(0,a._)`""`),w.var(c.default.parentData,(0,a._)`undefined`),w.var(c.default.parentDataProperty,(0,a._)`undefined`),w.var(c.default.rootData,c.default.data),S.dynamicRef&&w.var(c.default.dynamicAnchors,(0,a._)`{}`)})}function y(w){const{schema:S,opts:T,gen:R}=w;g(w,()=>{T.$comment&&S.$comment&&J(w),ee(w),R.let(c.default.vErrors,null),R.let(c.default.errors,0),T.unevaluated&&p(w),W(w),Z(w)})}function p(w){const{gen:S,validateName:T}=w;w.evaluated=S.const("evaluated",(0,a._)`${T}.evaluated`),S.if((0,a._)`${w.evaluated}.dynamicProps`,()=>S.assign((0,a._)`${w.evaluated}.props`,(0,a._)`undefined`)),S.if((0,a._)`${w.evaluated}.dynamicItems`,()=>S.assign((0,a._)`${w.evaluated}.items`,(0,a._)`undefined`))}function _(w,S){const T=typeof w=="object"&&w[S.schemaId];return T&&(S.code.source||S.code.process)?(0,a._)`/*# sourceURL=${T} */`:a.nil}function E(w,S){if(N(w)&&(F(w),j(w))){q(w,S);return}(0,e.boolOrEmptySchema)(w,S)}function j({schema:w,self:S}){if(typeof w=="boolean")return!w;for(const T in w)if(S.RULES.all[T])return!0;return!1}function N(w){return typeof w.schema!="boolean"}function q(w,S){const{schema:T,gen:R,opts:x}=w;x.$comment&&T.$comment&&J(w),ie(w),ne(w);const L=R.const("_errs",c.default.errors);W(w,L),R.var(S,(0,a._)`${L} === ${c.default.errors}`)}function F(w){(0,l.checkUnknownRules)(w),B(w)}function W(w,S){if(w.opts.jtd)return Te(w,[],!1,S);const T=(0,t.getSchemaTypes)(w.schema),R=(0,t.coerceAndCheckDataType)(w,T);Te(w,T,!R,S)}function B(w){const{schema:S,errSchemaPath:T,opts:R,self:x}=w;S.$ref&&R.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(S,x.RULES)&&x.logger.warn(`$ref: keywords ignored in schema at path "${T}"`)}function ee(w){const{schema:S,opts:T}=w;S.default!==void 0&&T.useDefaults&&T.strictSchema&&(0,l.checkStrictMode)(w,"default is ignored in the schema root")}function ie(w){const S=w.schema[w.opts.schemaId];S&&(w.baseId=(0,u.resolveUrl)(w.opts.uriResolver,w.baseId,S))}function ne(w){if(w.schema.$async&&!w.schemaEnv.$async)throw new Error("async schema in sync schema")}function J({gen:w,schemaEnv:S,schema:T,errSchemaPath:R,opts:x}){const L=T.$comment;if(x.$comment===!0)w.code((0,a._)`${c.default.self}.logger.log(${L})`);else if(typeof x.$comment=="function"){const re=(0,a.str)`${R}/$comment`,he=w.scopeValue("root",{ref:S.root});w.code((0,a._)`${c.default.self}.opts.$comment(${L}, ${re}, ${he}.schema)`)}}function Z(w){const{gen:S,schemaEnv:T,validateName:R,ValidationError:x,opts:L}=w;T.$async?S.if((0,a._)`${c.default.errors} === 0`,()=>S.return(c.default.data),()=>S.throw((0,a._)`new ${x}(${c.default.vErrors})`)):(S.assign((0,a._)`${R}.errors`,c.default.vErrors),L.unevaluated&&ve(w),S.return((0,a._)`${c.default.errors} === 0`))}function ve({gen:w,evaluated:S,props:T,items:R}){T instanceof a.Name&&w.assign((0,a._)`${S}.props`,T),R instanceof a.Name&&w.assign((0,a._)`${S}.items`,R)}function Te(w,S,T,R){const{gen:x,schema:L,data:re,allErrors:he,opts:ce,self:ue}=w,{RULES:se}=ue;if(L.$ref&&(ce.ignoreKeywordsWithRef||!(0,l.schemaHasRulesButRef)(L,se))){x.block(()=>M(w,"$ref",se.all.$ref.definition));return}ce.jtd||Ze(w,S),x.block(()=>{for(const fe of se.rules)De(fe);De(se.post)});function De(fe){(0,n.shouldUseGroup)(L,fe)&&(fe.type?(x.if((0,r.checkDataType)(fe.type,re,ce.strictNumbers)),xe(w,fe),S.length===1&&S[0]===fe.type&&T&&(x.else(),(0,r.reportTypeError)(w)),x.endIf()):xe(w,fe),he||x.if((0,a._)`${c.default.errors} === ${R||0}`))}}function xe(w,S){const{gen:T,schema:R,opts:{useDefaults:x}}=w;x&&(0,s.assignDefaults)(w,S.type),T.block(()=>{for(const L of S.rules)(0,n.shouldUseRule)(R,L)&&M(w,L.keyword,L.definition,S.type)})}function Ze(w,S){w.schemaEnv.meta||!w.opts.strictTypes||(qe(w,S),w.opts.allowUnionTypes||I(w,S),b(w,w.dataTypes))}function qe(w,S){if(S.length){if(!w.dataTypes.length){w.dataTypes=S;return}S.forEach(T=>{P(w.dataTypes,T)||$(w,`type "${T}" not allowed by context "${w.dataTypes.join(",")}"`)}),d(w,S)}}function I(w,S){S.length>1&&!(S.length===2&&S.includes("null"))&&$(w,"use allowUnionTypes to allow union type keyword")}function b(w,S){const T=w.self.RULES.all;for(const R in T){const x=T[R];if(typeof x=="object"&&(0,n.shouldUseRule)(w.schema,x)){const{type:L}=x.definition;L.length&&!L.some(re=>O(S,re))&&$(w,`missing type "${L.join(",")}" for keyword "${R}"`)}}}function O(w,S){return w.includes(S)||S==="number"&&w.includes("integer")}function P(w,S){return w.includes(S)||S==="integer"&&w.includes("number")}function d(w,S){const T=[];for(const R of w.dataTypes)P(S,R)?T.push(R):S.includes("integer")&&R==="number"&&T.push("integer");w.dataTypes=T}function $(w,S){const T=w.schemaEnv.baseId+w.errSchemaPath;S+=` at "${T}" (strictTypes)`,(0,l.checkStrictMode)(w,S,w.opts.strictTypes)}class k{constructor(S,T,R){if((0,o.validateKeywordUsage)(S,T,R),this.gen=S.gen,this.allErrors=S.allErrors,this.keyword=R,this.data=S.data,this.schema=S.schema[R],this.$data=T.$data&&S.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(S,this.schema,R,this.$data),this.schemaType=T.schemaType,this.parentSchema=S.schema,this.params={},this.it=S,this.def=T,this.$data)this.schemaCode=S.gen.const("vSchema",H(this.$data,S));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,T.schemaType,T.allowUndefined))throw new Error(`${R} value must be ${JSON.stringify(T.schemaType)}`);("code"in T?T.trackErrors:T.errors!==!1)&&(this.errsCount=S.gen.const("_errs",c.default.errors))}result(S,T,R){this.failResult((0,a.not)(S),T,R)}failResult(S,T,R){this.gen.if(S),R?R():this.error(),T?(this.gen.else(),T(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(S,T){this.failResult((0,a.not)(S),void 0,T)}fail(S){if(S===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(S),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(S){if(!this.$data)return this.fail(S);const{schemaCode:T}=this;this.fail((0,a._)`${T} !== undefined && (${(0,a.or)(this.invalid$data(),S)})`)}error(S,T,R){if(T){this.setParams(T),this._error(S,R),this.setParams({});return}this._error(S,R)}_error(S,T){(S?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 new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(S){this.allErrors||this.gen.if(S)}setParams(S,T){T?Object.assign(this.params,S):this.params=S}block$data(S,T,R=a.nil){this.gen.block(()=>{this.check$data(S,R),T()})}check$data(S=a.nil,T=a.nil){if(!this.$data)return;const{gen:R,schemaCode:x,schemaType:L,def:re}=this;R.if((0,a.or)((0,a._)`${x} === undefined`,T)),S!==a.nil&&R.assign(S,!0),(L.length||re.validateSchema)&&(R.elseIf(this.invalid$data()),this.$dataError(),S!==a.nil&&R.assign(S,!1)),R.else()}invalid$data(){const{gen:S,schemaCode:T,schemaType:R,def:x,it:L}=this;return(0,a.or)(re(),he());function re(){if(R.length){if(!(T instanceof a.Name))throw new Error("ajv implementation error");const ce=Array.isArray(R)?R:[R];return(0,a._)`${(0,r.checkDataTypes)(ce,T,L.opts.strictNumbers,r.DataType.Wrong)}`}return a.nil}function he(){if(x.validateSchema){const ce=S.scopeValue("validate$data",{ref:x.validateSchema});return(0,a._)`!${ce}(${T})`}return a.nil}}subschema(S,T){const R=(0,i.getSubschema)(this.it,S);(0,i.extendSubschemaData)(R,this.it,S),(0,i.extendSubschemaMode)(R,S);const x={...this.it,...R,items:void 0,props:void 0};return E(x,T),x}mergeEvaluated(S,T){const{it:R,gen:x}=this;R.opts.unevaluated&&(R.props!==!0&&S.props!==void 0&&(R.props=l.mergeEvaluated.props(x,S.props,R.props,T)),R.items!==!0&&S.items!==void 0&&(R.items=l.mergeEvaluated.items(x,S.items,R.items,T)))}mergeValidEvaluated(S,T){const{it:R,gen:x}=this;if(R.opts.unevaluated&&(R.props!==!0||R.items!==!0))return x.if(T,()=>this.mergeEvaluated(S,a.Name)),!0}}_e.KeywordCxt=k;function M(w,S,T,R){const x=new k(w,T,S);"code"in T?T.code(x,R):x.$data&&T.validate?(0,o.funcKeywordCode)(x,T):"macro"in T?(0,o.macroKeywordCode)(x,T):(T.compile||T.validate)&&(0,o.funcKeywordCode)(x,T)}const D=/^\/(?:[^~]|~0|~1)*$/,G=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function H(w,{dataLevel:S,dataNames:T,dataPathArr:R}){let x,L;if(w==="")return c.default.rootData;if(w[0]==="/"){if(!D.test(w))throw new Error(`Invalid JSON-pointer: ${w}`);x=w,L=c.default.rootData}else{const ue=G.exec(w);if(!ue)throw new Error(`Invalid JSON-pointer: ${w}`);const se=+ue[1];if(x=ue[2],x==="#"){if(se>=S)throw new Error(ce("property/index",se));return R[S-se]}if(se>S)throw new Error(ce("data",se));if(L=T[S-se],!x)return L}let re=L;const he=x.split("/");for(const ue of he)ue&&(L=(0,a._)`${L}${(0,a.getProperty)((0,l.unescapeJsonPointer)(ue))}`,re=(0,a._)`${re} && ${L}`);return re;function ce(ue,se){return`Cannot access ${ue} ${se} levels up, current level is ${S}`}}return _e.getData=H,_e}var ht={};Object.defineProperty(ht,"__esModule",{value:!0});class ja extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}}ht.default=ja;var We={};Object.defineProperty(We,"__esModule",{value:!0});const tn=ae;class Ta extends Error{constructor(t,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,tn.resolveUrl)(t,n,r),this.missingSchema=(0,tn.normalizeId)((0,tn.getFullPath)(t,this.missingRef))}}We.default=Ta;var de={};Object.defineProperty(de,"__esModule",{value:!0});de.resolveSchema=de.getCompilingSchema=de.resolveRef=de.compileSchema=de.SchemaEnv=void 0;const ge=K,Oa=ht,Ne=je(),$e=ae,Pr=C,Na=Dt();class Ft{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,$e.normalizeId)(r==null?void 0:r[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}de.SchemaEnv=Ft;function En(e){const t=Ss.call(this,e);if(t)return t;const n=(0,$e.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ge.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o});let a;e.$async&&(a=i.scopeValue("Error",{ref:Oa.default,code:(0,ge._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:Ne.default.data,parentData:Ne.default.parentData,parentDataProperty:Ne.default.parentDataProperty,dataNames:[Ne.default.data],dataPathArr:[ge.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,ge.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:ge.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ge._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Na.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(Ne.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const g=new Function(`${Ne.default.self}`,`${Ne.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:g}),g.errors=null,g.schema=e.schema,g.schemaEnv=e,e.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:c,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){const{props:m,items:v}=u;g.evaluated={props:m instanceof ge.Name?void 0:m,items:v instanceof ge.Name?void 0:v,dynamicProps:m instanceof ge.Name,dynamicItems:v instanceof ge.Name},g.source&&(g.source.evaluated=(0,ge.stringify)(g.evaluated))}return e.validate=g,e}catch(f){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),f}finally{this._compilations.delete(e)}}de.compileSchema=En;function Ra(e,t,n){var r;n=(0,$e.resolveUrl)(this.opts.uriResolver,t,n);const s=e.refs[n];if(s)return s;let o=Aa.call(this,e,n);if(o===void 0){const i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(o=new Ft({schema:i,schemaId:a,root:e,baseId:t}))}if(o!==void 0)return e.refs[n]=Ia.call(this,o)}de.resolveRef=Ra;function Ia(e){return(0,$e.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:En.call(this,e)}function Ss(e){for(const t of this._compilations)if(Ca(t,e))return t}de.getCompilingSchema=Ss;function Ca(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Aa(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Vt.call(this,e,t)}function Vt(e,t){const n=this.opts.uriResolver.parse(t),r=(0,$e._getFullPath)(this.opts.uriResolver,n);let s=(0,$e.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===s)return nn.call(this,n,e);const o=(0,$e.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){const a=Vt.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:nn.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||En.call(this,i),o===(0,$e.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,$e.resolveUrl)(this.opts.uriResolver,s,u)),new Ft({schema:a,schemaId:c,root:e,baseId:s})}return nn.call(this,n,i)}}de.resolveSchema=Vt;const Ma=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function nn(e,{baseId:t,schema:n,root:r}){var s;if(((s=e.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(const a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,Pr.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!Ma.has(a)&&u&&(t=(0,$e.resolveUrl)(this.opts.uriResolver,t,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,Pr.schemaHasRulesButRef)(n,this.RULES)){const a=(0,$e.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=Vt.call(this,r,a)}const{schemaId:i}=this.opts;if(o=o||new Ft({schema:n,schemaId:i,root:r,baseId:t}),o.schema!==o.root.schema)return o}const xa="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",qa="Meta-schema for $data reference (JSON AnySchema extension proposal)",Da="object",Fa=["$data"],Va={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},za=!1,La={$id:xa,description:qa,type:Da,required:Fa,properties:Va,additionalProperties:za};var kn={},zt={exports:{}};const Ua=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ps=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),jn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Es=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Ka=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Tn(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}const Ha=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Er(e){return e.length=0,!0}function Ga(e,t,n){if(e.length){const r=Tn(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function Ja(e){let t=0;const n={error:!1,address:"",zone:""},r=[],s=[];let o=!1,i=!1,a=Ga;for(let c=0;c<e.length;c++){const u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,r,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(o=!0),r.push(":");continue}else if(u==="%"){if(!a(s,r,n))break;a=Er}else{s.push(u);continue}}return s.length&&(a===Er?n.zone=s.join(""):i?r.push(s.join("")):r.push(Tn(s))),n.address=r.join(""),n}function ks(e){if(Wa(e,":")<2)return{host:e,isIPV6:!1};const t=Ja(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Wa(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function Ba(e){let t=e;const n=[];let r=-1,s=0;for(;s=t.length;){if(s===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(s===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(s===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("")}const Qa={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Ya=/[@/?#:]/g,Za=/[@/?#]/g;function js(e,t){const n=t?Za:Ya;return n.lastIndex=0,e.replace(n,r=>Qa[r])}function Xa(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){const s=e.slice(r+1,r+3);if(jn(s)){const o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));t&&Es(i)?n+=i:n+="%"+o,r+=2;continue}}n+=e[r]}return n}function ei(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(jn(r)){const s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Es(o)?t+=o:t+="%"+s,n+=2;continue}}Ka(e[n])?t+=e[n]:t+=escape(e[n])}return t}function ti(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(jn(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ni(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!Ps(n)){const r=ks(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=js(n,!1)}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}var Ts={nonSimpleDomain:Ha,recomposeAuthority:ni,reescapeHostDelimiters:js,normalizePercentEncoding:Xa,normalizePathEncoding:ei,escapePreservingEscapes:ti,removeDotSegments:Ba,isIPv4:Ps,isUUID:Ua,normalizeIPv6:ks,stringArrayToHexStripped:Tn};const{isUUID:ri}=Ts,si=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,oi=["http","https","ws","wss","urn","urn:uuid"];function ai(e){return oi.indexOf(e)!==-1}function On(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 Os(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Ns(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function ii(e){return e.secure=On(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function ci(e){if((e.port===(On(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){const[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 ui(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(si);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const s=`${r}:${t.nid||e.nid}`,o=Nn(s);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function li(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),s=`${n}:${t.nid||r}`,o=Nn(s);o&&(e=o.serialize(e,t));const i=e,a=e.nss;return i.path=`${r||t.nid}:${a}`,t.skipEscape=!0,i}function di(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!ri(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function fi(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Rs={scheme:"http",domainHost:!0,parse:Os,serialize:Ns},pi={scheme:"https",domainHost:Rs.domainHost,parse:Os,serialize:Ns},kt={scheme:"ws",domainHost:!0,parse:ii,serialize:ci},hi={scheme:"wss",domainHost:kt.domainHost,parse:kt.parse,serialize:kt.serialize},mi={scheme:"urn",parse:ui,serialize:li,skipNormalize:!0},gi={scheme:"urn:uuid",parse:di,serialize:fi,skipNormalize:!0},Rt={http:Rs,https:pi,ws:kt,wss:hi,urn:mi,"urn:uuid":gi};Object.setPrototypeOf(Rt,null);function Nn(e){return e&&(Rt[e]||Rt[e.toLowerCase()])||void 0}var yi={wsIsSecure:On,SCHEMES:Rt,isValidSchemeName:ai,getSchemeHandler:Nn};const{normalizeIPv6:$i,removeDotSegments:st,recomposeAuthority:vi,normalizePercentEncoding:_i,normalizePathEncoding:wi,escapePreservingEscapes:bi,reescapeHostDelimiters:Si,isIPv4:Pi,nonSimpleDomain:Ei}=Ts,{SCHEMES:ki,getSchemeHandler:Is}=yi;function ji(e,t){return typeof e=="string"?e=Ii(e,t):typeof e=="object"&&(e=Ge(Ae(e,t),t)),e}function Ti(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},s=Cs(Ge(e,r),Ge(t,r),r,!0);return r.skipEscape=!0,Ae(s,r)}function Cs(e,t,n,r){const s={};return r||(e=Ge(Ae(e,n),n),t=Ge(Ae(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(s.scheme=t.scheme,s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=st(t.path||""),s.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=st(t.path||""),s.query=t.query):(t.path?(t.path[0]==="/"?s.path=st(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?s.path="/"+t.path:e.path?s.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:s.path=t.path,s.path=st(s.path)),s.query=t.query):(s.path=e.path,t.query!==void 0?s.query=t.query:s.query=e.query),s.userinfo=e.userinfo,s.host=e.host,s.port=e.port),s.scheme=e.scheme),s.fragment=t.fragment,s}function Oi(e,t,n){const r=kr(e,n),s=kr(t,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function Ae(e,t){const 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:""},r=Object.assign({},t),s=[],o=Is(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=_i(n.path):(n.path=bi(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");const i=vi(n);if(i!==void 0&&(r.reference!=="suffix"&&s.push("//"),s.push(i),n.path&&n.path[0]!=="/"&&s.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!o||!o.absolutePath)&&(a=st(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return n.query!==void 0&&s.push("?",n.query),n.fragment!==void 0&&s.push("#",n.fragment),s.join("")}const Ni=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ri(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function As(e,t){const n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let s=!1,o=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);const i=e.match(Ni);if(i){r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]);const a=Ri(r,i);if(a!==void 0&&(r.error=r.error||a,s=!0),r.host)if(Pi(r.host)===!1){const l=$i(r.host);r.host=l.host.toLowerCase(),o=l.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const c=Is(n.scheme||r.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&r.host&&(n.domainHost||c&&c.domainHost)&&o===!1&&Ei(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(u){r.error=r.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Si(unescape(r.host),o))),r.path&&(r.path=wi(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}c&&c.parse&&c.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:s}}function Ge(e,t){return As(e,t).parsed}function Ii(e,t){return Ms(e,t).normalized}function Ms(e,t){const{parsed:n,malformedAuthorityOrPort:r}=As(e,t);return{normalized:r?e:Ae(n,t),malformedAuthorityOrPort:r}}function kr(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=Ms(e,t);return r?void 0:n}if(typeof e=="object")return Ae(e,t)}const Rn={SCHEMES:ki,normalize:ji,resolve:Ti,resolveComponent:Cs,equal:Oi,serialize:Ae,parse:Ge};zt.exports=Rn;zt.exports.default=Rn;zt.exports.fastUri=Rn;var Ci=zt.exports;Object.defineProperty(kn,"__esModule",{value:!0});const xs=Ci;xs.code='require("ajv/dist/runtime/uri").default';kn.default=xs;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Dt();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=K;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}});const r=ht,s=We,o=Ce,i=de,a=K,c=ae,u=te,l=C,f=La,h=kn,g=(I,b)=>new RegExp(I,b);g.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={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."},p={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function E(I){var b,O,P,d,$,k,M,D,G,H,w,S,T,R,x,L,re,he,ce,ue,se,De,fe,Jt,Wt;const Xe=I.strict,Bt=(b=I.code)===null||b===void 0?void 0:b.optimize,ur=Bt===!0||Bt===void 0?1:Bt||0,lr=(P=(O=I.code)===null||O===void 0?void 0:O.regExp)!==null&&P!==void 0?P:g,Zs=(d=I.uriResolver)!==null&&d!==void 0?d:h.default;return{strictSchema:(k=($=I.strictSchema)!==null&&$!==void 0?$:Xe)!==null&&k!==void 0?k:!0,strictNumbers:(D=(M=I.strictNumbers)!==null&&M!==void 0?M:Xe)!==null&&D!==void 0?D:!0,strictTypes:(H=(G=I.strictTypes)!==null&&G!==void 0?G:Xe)!==null&&H!==void 0?H:"log",strictTuples:(S=(w=I.strictTuples)!==null&&w!==void 0?w:Xe)!==null&&S!==void 0?S:"log",strictRequired:(R=(T=I.strictRequired)!==null&&T!==void 0?T:Xe)!==null&&R!==void 0?R:!1,code:I.code?{...I.code,optimize:ur,regExp:lr}:{optimize:ur,regExp:lr},loopRequired:(x=I.loopRequired)!==null&&x!==void 0?x:_,loopEnum:(L=I.loopEnum)!==null&&L!==void 0?L:_,meta:(re=I.meta)!==null&&re!==void 0?re:!0,messages:(he=I.messages)!==null&&he!==void 0?he:!0,inlineRefs:(ce=I.inlineRefs)!==null&&ce!==void 0?ce:!0,schemaId:(ue=I.schemaId)!==null&&ue!==void 0?ue:"$id",addUsedSchema:(se=I.addUsedSchema)!==null&&se!==void 0?se:!0,validateSchema:(De=I.validateSchema)!==null&&De!==void 0?De:!0,validateFormats:(fe=I.validateFormats)!==null&&fe!==void 0?fe:!0,unicodeRegExp:(Jt=I.unicodeRegExp)!==null&&Jt!==void 0?Jt:!0,int32range:(Wt=I.int32range)!==null&&Wt!==void 0?Wt:!0,uriResolver:Zs}}class j{constructor(b={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,...E(b)};const{es5:O,lines:P}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:O,lines:P}),this.logger=ne(b.logger);const d=b.validateFormats;b.validateFormats=!1,this.RULES=(0,o.getRules)(),N.call(this,y,b,"NOT SUPPORTED"),N.call(this,p,b,"DEPRECATED","warn"),this._metaOpts=ee.call(this),b.formats&&W.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords&&B.call(this,b.keywords),typeof b.meta=="object"&&this.addMetaSchema(b.meta),F.call(this),b.validateFormats=d}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:b,meta:O,schemaId:P}=this.opts;let d=f;P==="id"&&(d={...f},d.id=d.$id,delete d.$id),O&&b&&this.addMetaSchema(d,d[P],!1)}defaultMeta(){const{meta:b,schemaId:O}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[O]||b:void 0}validate(b,O){let P;if(typeof b=="string"){if(P=this.getSchema(b),!P)throw new Error(`no schema with key or ref "${b}"`)}else P=this.compile(b);const d=P(O);return"$async"in P||(this.errors=P.errors),d}compile(b,O){const P=this._addSchema(b,O);return P.validate||this._compileSchemaEnv(P)}compileAsync(b,O){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:P}=this.opts;return d.call(this,b,O);async function d(H,w){await $.call(this,H.$schema);const S=this._addSchema(H,w);return S.validate||k.call(this,S)}async function $(H){H&&!this.getSchema(H)&&await d.call(this,{$ref:H},!0)}async function k(H){try{return this._compileSchemaEnv(H)}catch(w){if(!(w instanceof s.default))throw w;return M.call(this,w),await D.call(this,w.missingSchema),k.call(this,H)}}function M({missingSchema:H,missingRef:w}){if(this.refs[H])throw new Error(`AnySchema ${H} is loaded but ${w} cannot be resolved`)}async function D(H){const w=await G.call(this,H);this.refs[H]||await $.call(this,w.$schema),this.refs[H]||this.addSchema(w,H,O)}async function G(H){const w=this._loading[H];if(w)return w;try{return await(this._loading[H]=P(H))}finally{delete this._loading[H]}}}addSchema(b,O,P,d=this.opts.validateSchema){if(Array.isArray(b)){for(const k of b)this.addSchema(k,void 0,P,d);return this}let $;if(typeof b=="object"){const{schemaId:k}=this.opts;if($=b[k],$!==void 0&&typeof $!="string")throw new Error(`schema ${k} must be string`)}return O=(0,c.normalizeId)(O||$),this._checkUnique(O),this.schemas[O]=this._addSchema(b,P,O,d,!0),this}addMetaSchema(b,O,P=this.opts.validateSchema){return this.addSchema(b,O,!0,P),this}validateSchema(b,O){if(typeof b=="boolean")return!0;let P;if(P=b.$schema,P!==void 0&&typeof P!="string")throw new Error("$schema must be a string");if(P=P||this.opts.defaultMeta||this.defaultMeta(),!P)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const d=this.validate(P,b);if(!d&&O){const $="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error($);else throw new Error($)}return d}getSchema(b){let O;for(;typeof(O=q.call(this,b))=="string";)b=O;if(O===void 0){const{schemaId:P}=this.opts,d=new i.SchemaEnv({schema:{},schemaId:P});if(O=i.resolveSchema.call(this,d,b),!O)return;this.refs[b]=O}return O.validate||this._compileSchemaEnv(O)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const O=q.call(this,b);return typeof O=="object"&&this._cache.delete(O.schema),delete this.schemas[b],delete this.refs[b],this}case"object":{const O=b;this._cache.delete(O);let P=b[this.opts.schemaId];return P&&(P=(0,c.normalizeId)(P),delete this.schemas[P],delete this.refs[P]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(const O of b)this.addKeyword(O);return this}addKeyword(b,O){let P;if(typeof b=="string")P=b,typeof O=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),O.keyword=P);else if(typeof b=="object"&&O===void 0){if(O=b,P=O.keyword,Array.isArray(P)&&!P.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Z.call(this,P,O),!O)return(0,l.eachItem)(P,$=>ve.call(this,$)),this;xe.call(this,O);const d={...O,type:(0,u.getJSONTypes)(O.type),schemaType:(0,u.getJSONTypes)(O.schemaType)};return(0,l.eachItem)(P,d.type.length===0?$=>ve.call(this,$,d):$=>d.type.forEach(k=>ve.call(this,$,d,k))),this}getKeyword(b){const O=this.RULES.all[b];return typeof O=="object"?O.definition:!!O}removeKeyword(b){const{RULES:O}=this;delete O.keywords[b],delete O.all[b];for(const P of O.rules){const d=P.rules.findIndex($=>$.keyword===b);d>=0&&P.rules.splice(d,1)}return this}addFormat(b,O){return typeof O=="string"&&(O=new RegExp(O)),this.formats[b]=O,this}errorsText(b=this.errors,{separator:O=", ",dataVar:P="data"}={}){return!b||b.length===0?"No errors":b.map(d=>`${P}${d.instancePath} ${d.message}`).reduce((d,$)=>d+O+$)}$dataMetaSchema(b,O){const P=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(const d of O){const $=d.split("/").slice(1);let k=b;for(const M of $)k=k[M];for(const M in P){const D=P[M];if(typeof D!="object")continue;const{$data:G}=D.definition,H=k[M];G&&H&&(k[M]=qe(H))}}return b}_removeAllSchemas(b,O){for(const P in b){const d=b[P];(!O||O.test(P))&&(typeof d=="string"?delete b[P]:d&&!d.meta&&(this._cache.delete(d.schema),delete b[P]))}}_addSchema(b,O,P,d=this.opts.validateSchema,$=this.opts.addUsedSchema){let k;const{schemaId:M}=this.opts;if(typeof b=="object")k=b[M];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof b!="boolean")throw new Error("schema must be object or boolean")}let D=this._cache.get(b);if(D!==void 0)return D;P=(0,c.normalizeId)(k||P);const G=c.getSchemaRefs.call(this,b,P);return D=new i.SchemaEnv({schema:b,schemaId:M,meta:O,baseId:P,localRefs:G}),this._cache.set(D.schema,D),$&&!P.startsWith("#")&&(P&&this._checkUnique(P),this.refs[P]=D),d&&this.validateSchema(b,!0),D}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw new Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta?this._compileMetaSchema(b):i.compileSchema.call(this,b),!b.validate)throw new Error("ajv implementation error");return b.validate}_compileMetaSchema(b){const O=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,b)}finally{this.opts=O}}}j.ValidationError=r.default,j.MissingRefError=s.default,e.default=j;function N(I,b,O,P="error"){for(const d in I){const $=d;$ in b&&this.logger[P](`${O}: option ${d}. ${I[$]}`)}}function q(I){return I=(0,c.normalizeId)(I),this.schemas[I]||this.refs[I]}function F(){const I=this.opts.schemas;if(I)if(Array.isArray(I))this.addSchema(I);else for(const b in I)this.addSchema(I[b],b)}function W(){for(const I in this.opts.formats){const b=this.opts.formats[I];b&&this.addFormat(I,b)}}function B(I){if(Array.isArray(I)){this.addVocabulary(I);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const b in I){const O=I[b];O.keyword||(O.keyword=b),this.addKeyword(O)}}function ee(){const I={...this.opts};for(const b of m)delete I[b];return I}const ie={log(){},warn(){},error(){}};function ne(I){if(I===!1)return ie;if(I===void 0)return console;if(I.log&&I.warn&&I.error)return I;throw new Error("logger must implement log, warn and error methods")}const J=/^[a-z_$][a-z0-9_$:-]*$/i;function Z(I,b){const{RULES:O}=this;if((0,l.eachItem)(I,P=>{if(O.keywords[P])throw new Error(`Keyword ${P} is already defined`);if(!J.test(P))throw new Error(`Keyword ${P} has invalid name`)}),!!b&&b.$data&&!("code"in b||"validate"in b))throw new Error('$data keyword must have "code" or "validate" function')}function ve(I,b,O){var P;const d=b==null?void 0:b.post;if(O&&d)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:$}=this;let k=d?$.post:$.rules.find(({type:D})=>D===O);if(k||(k={type:O,rules:[]},$.rules.push(k)),$.keywords[I]=!0,!b)return;const M={keyword:I,definition:{...b,type:(0,u.getJSONTypes)(b.type),schemaType:(0,u.getJSONTypes)(b.schemaType)}};b.before?Te.call(this,k,M,b.before):k.rules.push(M),$.all[I]=M,(P=b.implements)===null||P===void 0||P.forEach(D=>this.addKeyword(D))}function Te(I,b,O){const P=I.rules.findIndex(d=>d.keyword===O);P>=0?I.rules.splice(P,0,b):(I.rules.push(b),this.logger.warn(`rule ${O} is not defined`))}function xe(I){let{metaSchema:b}=I;b!==void 0&&(I.$data&&this.opts.$data&&(b=qe(b)),I.validateSchema=this.compile(b,!0))}const Ze={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qe(I){return{anyOf:[I,Ze]}}})(as);var In={},Cn={},An={};Object.defineProperty(An,"__esModule",{value:!0});const Ai={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};An.default=Ai;var Me={};Object.defineProperty(Me,"__esModule",{value:!0});Me.callRef=Me.getValidate=void 0;const Mi=We,jr=U,le=K,Ve=je(),Tr=de,vt=C,xi={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=r,{root:u}=o;if((n==="#"||n==="#/")&&s===u.baseId)return f();const l=Tr.resolveRef.call(c,u,s,n);if(l===void 0)throw new Mi.default(r.opts.uriResolver,s,n);if(l instanceof Tr.SchemaEnv)return h(l);return g(l);function f(){if(o===u)return jt(e,i,o,o.$async);const m=t.scopeValue("root",{ref:u});return jt(e,(0,le._)`${m}.validate`,u,u.$async)}function h(m){const v=qs(e,m);jt(e,v,m,m.$async)}function g(m){const v=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,le.stringify)(m)}:{ref:m}),y=t.name("valid"),p=e.subschema({schema:m,dataTypes:[],schemaPath:le.nil,topSchemaRef:v,errSchemaPath:n},y);e.mergeEvaluated(p),e.ok(y)}}};function qs(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,le._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Me.getValidate=qs;function jt(e,t,n,r){const{gen:s,it:o}=e,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?Ve.default.this:le.nil;r?l():f();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const m=s.let("valid");s.try(()=>{s.code((0,le._)`await ${(0,jr.callValidateCode)(e,t,u)}`),g(t),i||s.assign(m,!0)},v=>{s.if((0,le._)`!(${v} instanceof ${o.ValidationError})`,()=>s.throw(v)),h(v),i||s.assign(m,!1)}),e.ok(m)}function f(){e.result((0,jr.callValidateCode)(e,t,u),()=>g(t),()=>h(t))}function h(m){const v=(0,le._)`${m}.errors`;s.assign(Ve.default.vErrors,(0,le._)`${Ve.default.vErrors} === null ? ${v} : ${Ve.default.vErrors}.concat(${v})`),s.assign(Ve.default.errors,(0,le._)`${Ve.default.vErrors}.length`)}function g(m){var v;if(!o.opts.unevaluated)return;const y=(v=n==null?void 0:n.validate)===null||v===void 0?void 0:v.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=vt.mergeEvaluated.props(s,y.props,o.props));else{const p=s.var("props",(0,le._)`${m}.evaluated.props`);o.props=vt.mergeEvaluated.props(s,p,o.props,le.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=vt.mergeEvaluated.items(s,y.items,o.items));else{const p=s.var("items",(0,le._)`${m}.evaluated.items`);o.items=vt.mergeEvaluated.items(s,p,o.items,le.Name)}}}Me.callRef=jt;Me.default=xi;Object.defineProperty(Cn,"__esModule",{value:!0});const qi=An,Di=Me,Fi=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",qi.default,Di.default];Cn.default=Fi;var Mn={},xn={};Object.defineProperty(xn,"__esModule",{value:!0});const It=K,Ee=It.operators,Ct={maximum:{okStr:"<=",ok:Ee.LTE,fail:Ee.GT},minimum:{okStr:">=",ok:Ee.GTE,fail:Ee.LT},exclusiveMaximum:{okStr:"<",ok:Ee.LT,fail:Ee.GTE},exclusiveMinimum:{okStr:">",ok:Ee.GT,fail:Ee.LTE}},Vi={message:({keyword:e,schemaCode:t})=>(0,It.str)`must be ${Ct[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,It._)`{comparison: ${Ct[e].okStr}, limit: ${t}}`},zi={keyword:Object.keys(Ct),type:"number",schemaType:"number",$data:!0,error:Vi,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,It._)`${n} ${Ct[t].fail} ${r} || isNaN(${n})`)}};xn.default=zi;var qn={};Object.defineProperty(qn,"__esModule",{value:!0});const at=K,Li={message:({schemaCode:e})=>(0,at.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,at._)`{multipleOf: ${e}}`},Ui={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Li,code(e){const{gen:t,data:n,schemaCode:r,it:s}=e,o=s.opts.multipleOfPrecision,i=t.let("res"),a=o?(0,at._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,at._)`${i} !== parseInt(${i})`;e.fail$data((0,at._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};qn.default=Ui;var Dn={},Fn={};Object.defineProperty(Fn,"__esModule",{value:!0});function Ds(e){const t=e.length;let n=0,r=0,s;for(;r<t;)n++,s=e.charCodeAt(r++),s>=55296&&s<=56319&&r<t&&(s=e.charCodeAt(r),(s&64512)===56320&&r++);return n}Fn.default=Ds;Ds.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(Dn,"__esModule",{value:!0});const Re=K,Ki=C,Hi=Fn,Gi={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,Re.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,Re._)`{limit: ${e}}`},Ji={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Gi,code(e){const{keyword:t,data:n,schemaCode:r,it:s}=e,o=t==="maxLength"?Re.operators.GT:Re.operators.LT,i=s.opts.unicode===!1?(0,Re._)`${n}.length`:(0,Re._)`${(0,Ki.useFunc)(e.gen,Hi.default)}(${n})`;e.fail$data((0,Re._)`${i} ${o} ${r}`)}};Dn.default=Ji;var Vn={};Object.defineProperty(Vn,"__esModule",{value:!0});const Wi=U,Bi=C,Le=K,Qi={message:({schemaCode:e})=>(0,Le.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Le._)`{pattern: ${e}}`},Yi={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Qi,code(e){const{gen:t,data:n,$data:r,schema:s,schemaCode:o,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Le._)`new RegExp`:(0,Bi.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,Le._)`${u}(${o}, ${a}).test(${n})`),()=>t.assign(l,!1)),e.fail$data((0,Le._)`!${l}`)}else{const c=(0,Wi.usePattern)(e,s);e.fail$data((0,Le._)`!${c}.test(${n})`)}}};Vn.default=Yi;var zn={};Object.defineProperty(zn,"__esModule",{value:!0});const it=K,Zi={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,it.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,it._)`{limit: ${e}}`},Xi={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Zi,code(e){const{keyword:t,data:n,schemaCode:r}=e,s=t==="maxProperties"?it.operators.GT:it.operators.LT;e.fail$data((0,it._)`Object.keys(${n}).length ${s} ${r}`)}};zn.default=Xi;var Ln={};Object.defineProperty(Ln,"__esModule",{value:!0});const nt=U,ct=K,ec=C,tc={message:({params:{missingProperty:e}})=>(0,ct.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,ct._)`{missingProperty: ${e}}`},nc={keyword:"required",type:"object",schemaType:"array",$data:!0,error:tc,code(e){const{gen:t,schema:n,schemaCode:r,data:s,$data:o,it:i}=e,{opts:a}=i;if(!o&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const g=e.parentSchema.properties,{definedProperties:m}=e.it;for(const v of n)if((g==null?void 0:g[v])===void 0&&!m.has(v)){const y=i.schemaEnv.baseId+i.errSchemaPath,p=`required property "${v}" is not defined at "${y}" (strictRequired)`;(0,ec.checkStrictMode)(i,p,i.opts.strictRequired)}}function u(){if(c||o)e.block$data(ct.nil,f);else for(const g of n)(0,nt.checkReportMissingProp)(e,g)}function l(){const g=t.let("missing");if(c||o){const m=t.let("valid",!0);e.block$data(m,()=>h(g,m)),e.ok(m)}else t.if((0,nt.checkMissingProp)(e,n,g)),(0,nt.reportMissingProp)(e,g),t.else()}function f(){t.forOf("prop",r,g=>{e.setParams({missingProperty:g}),t.if((0,nt.noPropertyInData)(t,s,g,a.ownProperties),()=>e.error())})}function h(g,m){e.setParams({missingProperty:g}),t.forOf(g,r,()=>{t.assign(m,(0,nt.propertyInData)(t,s,g,a.ownProperties)),t.if((0,ct.not)(m),()=>{e.error(),t.break()})},ct.nil)}}};Ln.default=nc;var Un={};Object.defineProperty(Un,"__esModule",{value:!0});const ut=K,rc={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,ut.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,ut._)`{limit: ${e}}`},sc={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rc,code(e){const{keyword:t,data:n,schemaCode:r}=e,s=t==="maxItems"?ut.operators.GT:ut.operators.LT;e.fail$data((0,ut._)`${n}.length ${s} ${r}`)}};Un.default=sc;var Kn={},mt={};Object.defineProperty(mt,"__esModule",{value:!0});const Fs=$s;Fs.code='require("ajv/dist/runtime/equal").default';mt.default=Fs;Object.defineProperty(Kn,"__esModule",{value:!0});const rn=te,oe=K,oc=C,ac=mt,ic={message:({params:{i:e,j:t}})=>(0,oe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,oe._)`{i: ${e}, j: ${t}}`},cc={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ic,code(e){const{gen:t,data:n,$data:r,schema:s,parentSchema:o,schemaCode:i,it:a}=e;if(!r&&!s)return;const c=t.let("valid"),u=o.items?(0,rn.getSchemaTypes)(o.items):[];e.block$data(c,l,(0,oe._)`${i} === false`),e.ok(c);function l(){const m=t.let("i",(0,oe._)`${n}.length`),v=t.let("j");e.setParams({i:m,j:v}),t.assign(c,!0),t.if((0,oe._)`${m} > 1`,()=>(f()?h:g)(m,v))}function f(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function h(m,v){const y=t.name("item"),p=(0,rn.checkDataTypes)(u,y,a.opts.strictNumbers,rn.DataType.Wrong),_=t.const("indices",(0,oe._)`{}`);t.for((0,oe._)`;${m}--;`,()=>{t.let(y,(0,oe._)`${n}[${m}]`),t.if(p,(0,oe._)`continue`),u.length>1&&t.if((0,oe._)`typeof ${y} == "string"`,(0,oe._)`${y} += "_"`),t.if((0,oe._)`typeof ${_}[${y}] == "number"`,()=>{t.assign(v,(0,oe._)`${_}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,oe._)`${_}[${y}] = ${m}`)})}function g(m,v){const y=(0,oc.useFunc)(t,ac.default),p=t.name("outer");t.label(p).for((0,oe._)`;${m}--;`,()=>t.for((0,oe._)`${v} = ${m}; ${v}--;`,()=>t.if((0,oe._)`${y}(${n}[${m}], ${n}[${v}])`,()=>{e.error(),t.assign(c,!1).break(p)})))}}};Kn.default=cc;var Hn={};Object.defineProperty(Hn,"__esModule",{value:!0});const fn=K,uc=C,lc=mt,dc={message:"must be equal to constant",params:({schemaCode:e})=>(0,fn._)`{allowedValue: ${e}}`},fc={keyword:"const",$data:!0,error:dc,code(e){const{gen:t,data:n,$data:r,schemaCode:s,schema:o}=e;r||o&&typeof o=="object"?e.fail$data((0,fn._)`!${(0,uc.useFunc)(t,lc.default)}(${n}, ${s})`):e.fail((0,fn._)`${o} !== ${n}`)}};Hn.default=fc;var Gn={};Object.defineProperty(Gn,"__esModule",{value:!0});const ot=K,pc=C,hc=mt,mc={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,ot._)`{allowedValues: ${e}}`},gc={keyword:"enum",schemaType:"array",$data:!0,error:mc,code(e){const{gen:t,data:n,$data:r,schema:s,schemaCode:o,it:i}=e;if(!r&&s.length===0)throw new Error("enum must have non-empty array");const a=s.length>=i.opts.loopEnum;let c;const u=()=>c??(c=(0,pc.useFunc)(t,hc.default));let l;if(a||r)l=t.let("valid"),e.block$data(l,f);else{if(!Array.isArray(s))throw new Error("ajv implementation error");const g=t.const("vSchema",o);l=(0,ot.or)(...s.map((m,v)=>h(g,v)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",o,g=>t.if((0,ot._)`${u()}(${n}, ${g})`,()=>t.assign(l,!0).break()))}function h(g,m){const v=s[m];return typeof v=="object"&&v!==null?(0,ot._)`${u()}(${n}, ${g}[${m}])`:(0,ot._)`${n} === ${v}`}}};Gn.default=gc;Object.defineProperty(Mn,"__esModule",{value:!0});const yc=xn,$c=qn,vc=Dn,_c=Vn,wc=zn,bc=Ln,Sc=Un,Pc=Kn,Ec=Hn,kc=Gn,jc=[yc.default,$c.default,vc.default,_c.default,wc.default,bc.default,Sc.default,Pc.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ec.default,kc.default];Mn.default=jc;var Jn={},Be={};Object.defineProperty(Be,"__esModule",{value:!0});Be.validateAdditionalItems=void 0;const Ie=K,pn=C,Tc={message:({params:{len:e}})=>(0,Ie.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Ie._)`{limit: ${e}}`},Oc={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Tc,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,pn.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Vs(e,r)}};function Vs(e,t){const{gen:n,schema:r,data:s,keyword:o,it:i}=e;i.items=!0;const a=n.const("len",(0,Ie._)`${s}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,Ie._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,pn.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,Ie._)`${a} <= ${t.length}`);n.if((0,Ie.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:o,dataProp:l,dataPropType:pn.Type.Num},u),i.allErrors||n.if((0,Ie.not)(u),()=>n.break())})}}Be.validateAdditionalItems=Vs;Be.default=Oc;var Wn={},Qe={};Object.defineProperty(Qe,"__esModule",{value:!0});Qe.validateTuple=void 0;const Or=K,Tt=C,Nc=U,Rc={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return zs(e,"additionalItems",t);n.items=!0,!(0,Tt.alwaysValidSchema)(n,t)&&e.ok((0,Nc.validateArray)(e))}};function zs(e,t,n=e.schema){const{gen:r,parentSchema:s,data:o,keyword:i,it:a}=e;l(s),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Tt.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,Or._)`${o}.length`);n.forEach((f,h)=>{(0,Tt.alwaysValidSchema)(a,f)||(r.if((0,Or._)`${u} > ${h}`,()=>e.subschema({keyword:i,schemaProp:h,dataProp:h},c)),e.ok(c))});function l(f){const{opts:h,errSchemaPath:g}=a,m=n.length,v=m===f.minItems&&(m===f.maxItems||f[t]===!1);if(h.strictTuples&&!v){const y=`"${i}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${g}"`;(0,Tt.checkStrictMode)(a,y,h.strictTuples)}}}Qe.validateTuple=zs;Qe.default=Rc;Object.defineProperty(Wn,"__esModule",{value:!0});const Ic=Qe,Cc={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ic.validateTuple)(e,"items")};Wn.default=Cc;var Bn={};Object.defineProperty(Bn,"__esModule",{value:!0});const Nr=K,Ac=C,Mc=U,xc=Be,qc={message:({params:{len:e}})=>(0,Nr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Nr._)`{limit: ${e}}`},Dc={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qc,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:s}=n;r.items=!0,!(0,Ac.alwaysValidSchema)(r,t)&&(s?(0,xc.validateAdditionalItems)(e,s):e.ok((0,Mc.validateArray)(e)))}};Bn.default=Dc;var Qn={};Object.defineProperty(Qn,"__esModule",{value:!0});const pe=K,_t=C,Fc={message:({params:{min:e,max:t}})=>t===void 0?(0,pe.str)`must contain at least ${e} valid item(s)`:(0,pe.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,pe._)`{minContains: ${e}}`:(0,pe._)`{minContains: ${e}, maxContains: ${t}}`},Vc={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Fc,code(e){const{gen:t,schema:n,parentSchema:r,data:s,it:o}=e;let i,a;const{minContains:c,maxContains:u}=r;o.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=t.const("len",(0,pe._)`${s}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,_t.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,_t.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,_t.alwaysValidSchema)(o,n)){let v=(0,pe._)`${l} >= ${i}`;a!==void 0&&(v=(0,pe._)`${v} && ${l} <= ${a}`),e.pass(v);return}o.items=!0;const f=t.name("valid");a===void 0&&i===1?g(f,()=>t.if(f,()=>t.break())):i===0?(t.let(f,!0),a!==void 0&&t.if((0,pe._)`${s}.length > 0`,h)):(t.let(f,!1),h()),e.result(f,()=>e.reset());function h(){const v=t.name("_valid"),y=t.let("count",0);g(v,()=>t.if(v,()=>m(y)))}function g(v,y){t.forRange("i",0,l,p=>{e.subschema({keyword:"contains",dataProp:p,dataPropType:_t.Type.Num,compositeRule:!0},v),y()})}function m(v){t.code((0,pe._)`${v}++`),a===void 0?t.if((0,pe._)`${v} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,pe._)`${v} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,pe._)`${v} >= ${i}`,()=>t.assign(f,!0)))}}};Qn.default=Vc;var Ls={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=K,n=C,r=U;e.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const f=u===1?"property":"properties";return(0,t.str)`must have ${f} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:f}})=>(0,t._)`{property: ${c},
|
|
7
|
-
missingProperty: ${
|
|
2
|
+
"use strict";var ed=Object.create;var Zs=Object.defineProperty;var td=Object.getOwnPropertyDescriptor;var rd=Object.getOwnPropertyNames;var nd=Object.getPrototypeOf,od=Object.prototype.hasOwnProperty;var sd=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rd(t))!od.call(e,o)&&o!==r&&Zs(e,o,{get:()=>t[o],enumerable:!(n=td(t,o))||n.enumerable});return e};var Kr=(e,t,r)=>(r=e!=null?ed(nd(e)):{},sd(t||!e||!e.__esModule?Zs(r,"default",{value:e,enumerable:!0}):r,e));const id=require("commander"),qa=require("node:fs"),io=require("node:path"),Qs=require("ts-morph"),Me=require("ts-json-schema-generator"),te=require("pino"),ad=require("node:os"),Va=require("node:url"),gn=require("node:http"),cd=require("node:http2"),ud=require("node:net"),dd=require("node:readline"),Q=require("node:child_process"),ao=require("node:crypto"),ld=require("@modelcontextprotocol/sdk/server/index.js"),fd=require("@modelcontextprotocol/sdk/server/stdio.js"),pd=require("@modelcontextprotocol/sdk/server/sse.js"),md=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Xs=require("@modelcontextprotocol/sdk/types.js"),hd=require("fastify"),Br=require("express"),yd=require("pino-http");function Be(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const k=Be(qa),N=Be(io),Ge=Be(ad),fr=Be(gn),Ga=Be(cd),co=Be(ud),uo=Be(dd);function Ha(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $n={exports:{}},Ja={},pe={},pt={},Rt={},z={},Ct={};(function(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;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(w){if(super(),!e.IDENTIFIER.test(w))throw new Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(w){super(),this._items=typeof w=="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((_,E)=>`${_}${E}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((_,E)=>(E instanceof r&&(_[E.str]=(_[E.str]||0)+1),_),{})}}e._Code=n,e.nil=new n("");function o(g,...w){const _=[g[0]];let E=0;for(;E<w.length;)a(_,w[E]),_.push(g[++E]);return new n(_)}e._=o;const s=new n("+");function i(g,...w){const _=[h(g[0])];let E=0;for(;E<w.length;)_.push(s),a(_,w[E]),_.push(s,h(g[++E]));return c(_),new n(_)}e.str=i;function a(g,w){w instanceof n?g.push(...w._items):w instanceof r?g.push(w):g.push(l(w))}e.addCodeArg=a;function c(g){let w=1;for(;w<g.length-1;){if(g[w]===s){const _=u(g[w-1],g[w+1]);if(_!==void 0){g.splice(w-1,3,_);continue}g[w++]="+"}w++}}function u(g,w){if(w==='""')return g;if(g==='""')return w;if(typeof g=="string")return w instanceof r||g[g.length-1]!=='"'?void 0:typeof w!="string"?`${g.slice(0,-1)}${w}"`:w[0]==='"'?g.slice(0,-1)+w.slice(1):void 0;if(typeof w=="string"&&w[0]==='"'&&!(g instanceof r))return`"${g}${w.slice(1)}`}function d(g,w){return w.emptyStr()?g:g.emptyStr()?w:i`${g}${w}`}e.strConcat=d;function l(g){return typeof g=="number"||typeof g=="boolean"||g===null?g:h(Array.isArray(g)?g.join(","):g)}function p(g){return new n(h(g))}e.stringify=p;function h(g){return JSON.stringify(g).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function f(g){return typeof g=="string"&&e.IDENTIFIER.test(g)?new n(`.${g}`):o`[${g}]`}e.getProperty=f;function y(g){if(typeof g=="string"&&e.IDENTIFIER.test(g))return new n(`${g}`);throw new Error(`CodeGen: invalid export name: ${g}, use explicit $id name mapping`)}e.getEsmExportName=y;function $(g){return new n(g.toString())}e.regexpCode=$})(Ct);var vn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Ct;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:u,parent:d}={}){this._names={},this._prefixes=u,this._parent=d}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const d=this._names[u]||this._nameGroup(u);return`${u}${d.index++}`}_nameGroup(u){var d,l;if(!((l=(d=this._parent)===null||d===void 0?void 0:d._prefixes)===null||l===void 0)&&l.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=o;class s extends t.Name{constructor(u,d){super(d),this.prefix=u}setValue(u,{property:d,itemIndex:l}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(d)}[${l}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:t.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,d){var l;if(d.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:h}=p,f=(l=d.key)!==null&&l!==void 0?l:d.ref;let y=this._values[h];if(y){const w=y.get(f);if(w)return w}else y=this._values[h]=new Map;y.set(f,p);const $=this._scope[h]||(this._scope[h]=[]),g=$.length;return $[g]=d.ref,p.setValue(d,{property:h,itemIndex:g}),p}getValue(u,d){const l=this._values[u];if(l)return l.get(d)}scopeRefs(u,d=this._values){return this._reduceValues(d,l=>{if(l.scopePath===void 0)throw new Error(`CodeGen: name "${l}" has no value`);return(0,t._)`${u}${l.scopePath}`})}scopeCode(u=this._values,d,l){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},d,l)}_reduceValues(u,d,l={},p){let h=t.nil;for(const f in u){const y=u[f];if(!y)continue;const $=l[f]=l[f]||new Map;y.forEach(g=>{if($.has(g))return;$.set(g,n.Started);let w=d(g);if(w){const _=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${_} ${g} = ${w};${this.opts._n}`}else if(w=p==null?void 0:p(g))h=(0,t._)`${h}${w}${this.opts._n}`;else throw new r(g);$.set(g,n.Completed)})}return h}}e.ValueScope=a})(vn);(function(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;const t=Ct,r=vn;var n=Ct;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=vn;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.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("+")};class s{optimizeNodes(){return this}optimizeNames(m,v){return this}}class i extends s{constructor(m,v,O){super(),this.varKind=m,this.name=v,this.rhs=O}render({es5:m,_n:v}){const O=m?r.varKinds.var:this.varKind,R=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${R};`+v}optimizeNames(m,v){if(m[this.name.str])return this.rhs&&(this.rhs=se(this.rhs,m,v)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(m,v,O){super(),this.lhs=m,this.rhs=v,this.sideEffects=O}render({_n:m}){return`${this.lhs} = ${this.rhs};`+m}optimizeNames(m,v){if(!(this.lhs instanceof t.Name&&!m[this.lhs.str]&&!this.sideEffects))return this.rhs=se(this.rhs,m,v),this}get names(){const m=this.lhs instanceof t.Name?{}:{...this.lhs.names};return X(m,this.rhs)}}class c extends a{constructor(m,v,O,R){super(m,O,R),this.op=v}render({_n:m}){return`${this.lhs} ${this.op}= ${this.rhs};`+m}}class u extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`${this.label}:`+m}}class d extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`break${this.label?` ${this.label}`:""};`+m}}class l extends s{constructor(m){super(),this.error=m}render({_n:m}){return`throw ${this.error};`+m}get names(){return this.error.names}}class p extends s{constructor(m){super(),this.code=m}render({_n:m}){return`${this.code};`+m}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(m,v){return this.code=se(this.code,m,v),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(m=[]){super(),this.nodes=m}render(m){return this.nodes.reduce((v,O)=>v+O.render(m),"")}optimizeNodes(){const{nodes:m}=this;let v=m.length;for(;v--;){const O=m[v].optimizeNodes();Array.isArray(O)?m.splice(v,1,...O):O?m[v]=O:m.splice(v,1)}return m.length>0?this:void 0}optimizeNames(m,v){const{nodes:O}=this;let R=O.length;for(;R--;){const M=O[R];M.optimizeNames(m,v)||(me(m,M.names),O.splice(R,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((m,v)=>J(m,v.names),{})}}class f extends h{render(m){return"{"+m._n+super.render(m)+"}"+m._n}}class y extends h{}class $ extends f{}$.kind="else";class g extends f{constructor(m,v){super(v),this.condition=m}render(m){let v=`if(${this.condition})`+super.render(m);return this.else&&(v+="else "+this.else.render(m)),v}optimizeNodes(){super.optimizeNodes();const m=this.condition;if(m===!0)return this.nodes;let v=this.else;if(v){const O=v.optimizeNodes();v=this.else=Array.isArray(O)?new $(O):O}if(v)return m===!1?v instanceof g?v:v.nodes:this.nodes.length?this:new g(qt(m),v instanceof g?[v]:v.nodes);if(!(m===!1||!this.nodes.length))return this}optimizeNames(m,v){var O;if(this.else=(O=this.else)===null||O===void 0?void 0:O.optimizeNames(m,v),!!(super.optimizeNames(m,v)||this.else))return this.condition=se(this.condition,m,v),this}get names(){const m=super.names;return X(m,this.condition),this.else&&J(m,this.else.names),m}}g.kind="if";class w extends f{}w.kind="for";class _ extends w{constructor(m){super(),this.iteration=m}render(m){return`for(${this.iteration})`+super.render(m)}optimizeNames(m,v){if(super.optimizeNames(m,v))return this.iteration=se(this.iteration,m,v),this}get names(){return J(super.names,this.iteration.names)}}class E extends w{constructor(m,v,O,R){super(),this.varKind=m,this.name=v,this.from=O,this.to=R}render(m){const v=m.es5?r.varKinds.var:this.varKind,{name:O,from:R,to:M}=this;return`for(${v} ${O}=${R}; ${O}<${M}; ${O}++)`+super.render(m)}get names(){const m=X(super.names,this.from);return X(m,this.to)}}class j extends w{constructor(m,v,O,R){super(),this.loop=m,this.varKind=v,this.name=O,this.iterable=R}render(m){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(m)}optimizeNames(m,v){if(super.optimizeNames(m,v))return this.iterable=se(this.iterable,m,v),this}get names(){return J(super.names,this.iterable.names)}}class I extends f{constructor(m,v,O){super(),this.name=m,this.args=v,this.async=O}render(m){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(m)}}I.kind="func";class x extends h{render(m){return"return "+super.render(m)}}x.kind="return";class V extends f{render(m){let v="try"+super.render(m);return this.catch&&(v+=this.catch.render(m)),this.finally&&(v+=this.finally.render(m)),v}optimizeNodes(){var m,v;return super.optimizeNodes(),(m=this.catch)===null||m===void 0||m.optimizeNodes(),(v=this.finally)===null||v===void 0||v.optimizeNodes(),this}optimizeNames(m,v){var O,R;return super.optimizeNames(m,v),(O=this.catch)===null||O===void 0||O.optimizeNames(m,v),(R=this.finally)===null||R===void 0||R.optimizeNames(m,v),this}get names(){const m=super.names;return this.catch&&J(m,this.catch.names),this.finally&&J(m,this.finally.names),m}}class D extends f{constructor(m){super(),this.error=m}render(m){return`catch(${this.error})`+super.render(m)}}D.kind="catch";class U extends f{render(m){return"finally"+super.render(m)}}U.kind="finally";class H{constructor(m,v={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...v,_n:v.lines?`
|
|
3
|
+
`:""},this._extScope=m,this._scope=new r.Scope({parent:m}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(m){return this._scope.name(m)}scopeName(m){return this._extScope.name(m)}scopeValue(m,v){const O=this._extScope.value(m,v);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(m,v){return this._extScope.getValue(m,v)}scopeRefs(m){return this._extScope.scopeRefs(m,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(m,v,O,R){const M=this._scope.toName(v);return O!==void 0&&R&&(this._constants[M.str]=O),this._leafNode(new i(m,M,O)),M}const(m,v,O){return this._def(r.varKinds.const,m,v,O)}let(m,v,O){return this._def(r.varKinds.let,m,v,O)}var(m,v,O){return this._def(r.varKinds.var,m,v,O)}assign(m,v,O){return this._leafNode(new a(m,v,O))}add(m,v){return this._leafNode(new c(m,e.operators.ADD,v))}code(m){return typeof m=="function"?m():m!==t.nil&&this._leafNode(new p(m)),this}object(...m){const v=["{"];for(const[O,R]of m)v.length>1&&v.push(","),v.push(O),(O!==R||this.opts.es5)&&(v.push(":"),(0,t.addCodeArg)(v,R));return v.push("}"),new t._Code(v)}if(m,v,O){if(this._blockNode(new g(m)),v&&O)this.code(v).else().code(O).endIf();else if(v)this.code(v).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(m){return this._elseNode(new g(m))}else(){return this._elseNode(new $)}endIf(){return this._endBlockNode(g,$)}_for(m,v){return this._blockNode(m),v&&this.code(v).endFor(),this}for(m,v){return this._for(new _(m),v)}forRange(m,v,O,R,M=this.opts.es5?r.varKinds.var:r.varKinds.let){const K=this._scope.toName(m);return this._for(new E(M,K,v,O),()=>R(K))}forOf(m,v,O,R=r.varKinds.const){const M=this._scope.toName(m);if(this.opts.es5){const K=v instanceof t.Name?v:this.var("_arr",v);return this.forRange("_i",0,(0,t._)`${K}.length`,G=>{this.var(M,(0,t._)`${K}[${G}]`),O(M)})}return this._for(new j("of",R,M,v),()=>O(M))}forIn(m,v,O,R=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(m,(0,t._)`Object.keys(${v})`,O);const M=this._scope.toName(m);return this._for(new j("in",R,M,v),()=>O(M))}endFor(){return this._endBlockNode(w)}label(m){return this._leafNode(new u(m))}break(m){return this._leafNode(new d(m))}return(m){const v=new x;if(this._blockNode(v),this.code(m),v.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(x)}try(m,v,O){if(!v&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');const R=new V;if(this._blockNode(R),this.code(m),v){const M=this.name("e");this._currNode=R.catch=new D(M),v(M)}return O&&(this._currNode=R.finally=new U,this.code(O)),this._endBlockNode(D,U)}throw(m){return this._leafNode(new l(m))}block(m,v){return this._blockStarts.push(this._nodes.length),m&&this.code(m).endBlock(v),this}endBlock(m){const v=this._blockStarts.pop();if(v===void 0)throw new Error("CodeGen: not in self-balancing block");const O=this._nodes.length-v;if(O<0||m!==void 0&&O!==m)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${m} expected`);return this._nodes.length=v,this}func(m,v=t.nil,O,R){return this._blockNode(new I(m,v,O)),R&&this.code(R).endFunc(),this}endFunc(){return this._endBlockNode(I)}optimize(m=1){for(;m-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(m){return this._currNode.nodes.push(m),this}_blockNode(m){this._currNode.nodes.push(m),this._nodes.push(m)}_endBlockNode(m,v){const O=this._currNode;if(O instanceof m||v&&O instanceof v)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${v?`${m.kind}/${v.kind}`:m.kind}"`)}_elseNode(m){const v=this._currNode;if(!(v instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=v.else=m,this}get _root(){return this._nodes[0]}get _currNode(){const m=this._nodes;return m[m.length-1]}set _currNode(m){const v=this._nodes;v[v.length-1]=m}}e.CodeGen=H;function J(S,m){for(const v in m)S[v]=(S[v]||0)+(m[v]||0);return S}function X(S,m){return m instanceof t._CodeOrName?J(S,m.names):S}function se(S,m,v){if(S instanceof t.Name)return O(S);if(!R(S))return S;return new t._Code(S._items.reduce((M,K)=>(K instanceof t.Name&&(K=O(K)),K instanceof t._Code?M.push(...K._items):M.push(K),M),[]));function O(M){const K=v[M.str];return K===void 0||m[M.str]!==1?M:(delete m[M.str],K)}function R(M){return M instanceof t._Code&&M._items.some(K=>K instanceof t.Name&&m[K.str]===1&&v[K.str]!==void 0)}}function me(S,m){for(const v in m)S[v]=(S[v]||0)-(m[v]||0)}function qt(S){return typeof S=="boolean"||typeof S=="number"||S===null?!S:(0,t._)`!${P(S)}`}e.not=qt;const Tr=b(e.operators.AND);function Ir(...S){return S.reduce(Tr)}e.and=Ir;const Vt=b(e.operators.OR);function A(...S){return S.reduce(Vt)}e.or=A;function b(S){return(m,v)=>m===t.nil?v:v===t.nil?m:(0,t._)`${P(m)} ${S} ${P(v)}`}function P(S){return S instanceof t.Name?S:(0,t._)`(${S})`}})(z);var T={};Object.defineProperty(T,"__esModule",{value:!0});T.checkStrictMode=T.getErrorPath=T.Type=T.useFunc=T.setEvaluated=T.evaluatedPropsToName=T.mergeEvaluated=T.eachItem=T.unescapeJsonPointer=T.escapeJsonPointer=T.escapeFragment=T.unescapeFragment=T.schemaRefOrVal=T.schemaHasRulesButRef=T.schemaHasRules=T.checkUnknownRules=T.alwaysValidSchema=T.toHash=void 0;const B=z,gd=Ct;function $d(e){const t={};for(const r of e)t[r]=!0;return t}T.toHash=$d;function vd(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Ka(e,t),!Ba(t,e.self.RULES.all))}T.alwaysValidSchema=vd;function Ka(e,t=e.schema){const{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;const o=n.RULES.keywords;for(const s in t)o[s]||Za(e,`unknown keyword: "${s}"`)}T.checkUnknownRules=Ka;function Ba(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(t[r])return!0;return!1}T.schemaHasRules=Ba;function wd(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}T.schemaHasRulesButRef=wd;function _d({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,B._)`${r}`}return(0,B._)`${e}${t}${(0,B.getProperty)(n)}`}T.schemaRefOrVal=_d;function bd(e){return Wa(decodeURIComponent(e))}T.unescapeFragment=bd;function Sd(e){return encodeURIComponent(lo(e))}T.escapeFragment=Sd;function lo(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}T.escapeJsonPointer=lo;function Wa(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}T.unescapeJsonPointer=Wa;function Ed(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}T.eachItem=Ed;function ei({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof B.Name?(s instanceof B.Name?e(o,s,i):t(o,s,i),i):s instanceof B.Name?(t(o,i,s),s):r(s,i);return a===B.Name&&!(c instanceof B.Name)?n(o,c):c}}T.mergeEvaluated={props:ei({mergeNames:(e,t,r)=>e.if((0,B._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,B._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,B._)`${r} || {}`).code((0,B._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,B._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,B._)`${r} || {}`),fo(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Ya}),items:ei({mergeNames:(e,t,r)=>e.if((0,B._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,B._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,B._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,B._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Ya(e,t){if(t===!0)return e.var("props",!0);const r=e.var("props",(0,B._)`{}`);return t!==void 0&&fo(e,r,t),r}T.evaluatedPropsToName=Ya;function fo(e,t,r){Object.keys(r).forEach(n=>e.assign((0,B._)`${t}${(0,B.getProperty)(n)}`,!0))}T.setEvaluated=fo;const ti={};function Nd(e,t){return e.scopeValue("func",{ref:t,code:ti[t.code]||(ti[t.code]=new gd._Code(t.code))})}T.useFunc=Nd;var wn;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(wn||(T.Type=wn={}));function Od(e,t,r){if(e instanceof B.Name){const n=t===wn.Num;return r?n?(0,B._)`"[" + ${e} + "]"`:(0,B._)`"['" + ${e} + "']"`:n?(0,B._)`"/" + ${e}`:(0,B._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,B.getProperty)(e).toString():"/"+lo(e)}T.getErrorPath=Od;function Za(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}T.checkStrictMode=Za;var ge={};Object.defineProperty(ge,"__esModule",{value:!0});const oe=z,jd={data:new oe.Name("data"),valCxt:new oe.Name("valCxt"),instancePath:new oe.Name("instancePath"),parentData:new oe.Name("parentData"),parentDataProperty:new oe.Name("parentDataProperty"),rootData:new oe.Name("rootData"),dynamicAnchors:new oe.Name("dynamicAnchors"),vErrors:new oe.Name("vErrors"),errors:new oe.Name("errors"),this:new oe.Name("this"),self:new oe.Name("self"),scope:new oe.Name("scope"),json:new oe.Name("json"),jsonPos:new oe.Name("jsonPos"),jsonLen:new oe.Name("jsonLen"),jsonPart:new oe.Name("jsonPart")};ge.default=jd;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=z,r=T,n=ge;e.keywordError={message:({keyword:$})=>(0,t.str)`must pass "${$}" keyword validation`},e.keyword$DataError={message:({keyword:$,schemaType:g})=>g?(0,t.str)`"${$}" keyword must be ${g} ($data)`:(0,t.str)`"${$}" keyword is invalid ($data)`};function o($,g=e.keywordError,w,_){const{it:E}=$,{gen:j,compositeRule:I,allErrors:x}=E,V=l($,g,w);_??(I||x)?c(j,V):u(E,(0,t._)`[${V}]`)}e.reportError=o;function s($,g=e.keywordError,w){const{it:_}=$,{gen:E,compositeRule:j,allErrors:I}=_,x=l($,g,w);c(E,x),j||I||u(_,n.default.vErrors)}e.reportExtraError=s;function i($,g){$.assign(n.default.errors,g),$.if((0,t._)`${n.default.vErrors} !== null`,()=>$.if(g,()=>$.assign((0,t._)`${n.default.vErrors}.length`,g),()=>$.assign(n.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:$,keyword:g,schemaValue:w,data:_,errsCount:E,it:j}){if(E===void 0)throw new Error("ajv implementation error");const I=$.name("err");$.forRange("i",E,n.default.errors,x=>{$.const(I,(0,t._)`${n.default.vErrors}[${x}]`),$.if((0,t._)`${I}.instancePath === undefined`,()=>$.assign((0,t._)`${I}.instancePath`,(0,t.strConcat)(n.default.instancePath,j.errorPath))),$.assign((0,t._)`${I}.schemaPath`,(0,t.str)`${j.errSchemaPath}/${g}`),j.opts.verbose&&($.assign((0,t._)`${I}.schema`,w),$.assign((0,t._)`${I}.data`,_))})}e.extendErrors=a;function c($,g){const w=$.const("err",g);$.if((0,t._)`${n.default.vErrors} === null`,()=>$.assign(n.default.vErrors,(0,t._)`[${w}]`),(0,t._)`${n.default.vErrors}.push(${w})`),$.code((0,t._)`${n.default.errors}++`)}function u($,g){const{gen:w,validateName:_,schemaEnv:E}=$;E.$async?w.throw((0,t._)`new ${$.ValidationError}(${g})`):(w.assign((0,t._)`${_}.errors`,g),w.return(!1))}const d={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 l($,g,w){const{createErrors:_}=$.it;return _===!1?(0,t._)`{}`:p($,g,w)}function p($,g,w={}){const{gen:_,it:E}=$,j=[h(E,w),f($,w)];return y($,g,j),_.object(...j)}function h({errorPath:$},{instancePath:g}){const w=g?(0,t.str)`${$}${(0,r.getErrorPath)(g,r.Type.Str)}`:$;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,w)]}function f({keyword:$,it:{errSchemaPath:g}},{schemaPath:w,parentSchema:_}){let E=_?g:(0,t.str)`${g}/${$}`;return w&&(E=(0,t.str)`${E}${(0,r.getErrorPath)(w,r.Type.Str)}`),[d.schemaPath,E]}function y($,{params:g,message:w},_){const{keyword:E,data:j,schemaValue:I,it:x}=$,{opts:V,propertyName:D,topSchemaRef:U,schemaPath:H}=x;_.push([d.keyword,E],[d.params,typeof g=="function"?g($):g||(0,t._)`{}`]),V.messages&&_.push([d.message,typeof w=="function"?w($):w]),V.verbose&&_.push([d.schema,I],[d.parentSchema,(0,t._)`${U}${H}`],[n.default.data,j]),D&&_.push([d.propertyName,D])}})(Rt);Object.defineProperty(pt,"__esModule",{value:!0});pt.boolOrEmptySchema=pt.topBoolOrEmptySchema=void 0;const kd=Rt,Pd=z,Ad=ge,Td={message:"boolean schema is false"};function Id(e){const{gen:t,schema:r,validateName:n}=e;r===!1?Qa(e,!1):typeof r=="object"&&r.$async===!0?t.return(Ad.default.data):(t.assign((0,Pd._)`${n}.errors`,null),t.return(!0))}pt.topBoolOrEmptySchema=Id;function Cd(e,t){const{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Qa(e)):r.var(t,!0)}pt.boolOrEmptySchema=Cd;function Qa(e,t){const{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,kd.reportError)(o,Td,void 0,t)}var Z={},He={};Object.defineProperty(He,"__esModule",{value:!0});He.getRules=He.isJSONType=void 0;const Dd=["string","number","integer","boolean","null","object","array"],Rd=new Set(Dd);function xd(e){return typeof e=="string"&&Rd.has(e)}He.isJSONType=xd;function Md(){const 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:{}}}He.getRules=Md;var ve={};Object.defineProperty(ve,"__esModule",{value:!0});ve.shouldUseRule=ve.shouldUseGroup=ve.schemaHasRulesForType=void 0;function Fd({schema:e,self:t},r){const n=t.RULES.types[r];return n&&n!==!0&&Xa(e,n)}ve.schemaHasRulesForType=Fd;function Xa(e,t){return t.rules.some(r=>ec(e,r))}ve.shouldUseGroup=Xa;function ec(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}ve.shouldUseRule=ec;Object.defineProperty(Z,"__esModule",{value:!0});Z.reportTypeError=Z.checkDataTypes=Z.checkDataType=Z.coerceAndCheckDataType=Z.getJSONTypes=Z.getSchemaTypes=Z.DataType=void 0;const Ud=He,Ld=ve,zd=Rt,L=z,tc=T;var lt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(lt||(Z.DataType=lt={}));function qd(e){const t=rc(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Z.getSchemaTypes=qd;function rc(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Ud.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Z.getJSONTypes=rc;function Vd(e,t){const{gen:r,data:n,opts:o}=e,s=Gd(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Ld.schemaHasRulesForType)(e,t[0]));if(i){const a=po(t,n,o.strictNumbers,lt.Wrong);r.if(a,()=>{s.length?Hd(e,t,s):mo(e)})}return i}Z.coerceAndCheckDataType=Vd;const nc=new Set(["string","number","integer","boolean","null"]);function Gd(e,t){return t?e.filter(r=>nc.has(r)||t==="array"&&r==="array"):[]}function Hd(e,t,r){const{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,L._)`typeof ${o}`),a=n.let("coerced",(0,L._)`undefined`);s.coerceTypes==="array"&&n.if((0,L._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,L._)`${o}[0]`).assign(i,(0,L._)`typeof ${o}`).if(po(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,L._)`${a} !== undefined`);for(const u of r)(nc.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),mo(e),n.endIf(),n.if((0,L._)`${a} !== undefined`,()=>{n.assign(o,a),Jd(e,a)});function c(u){switch(u){case"string":n.elseIf((0,L._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,L._)`"" + ${o}`).elseIf((0,L._)`${o} === null`).assign(a,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${i} == "boolean" || ${o} === null
|
|
4
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,L._)`+${o}`);return;case"integer":n.elseIf((0,L._)`${i} === "boolean" || ${o} === null
|
|
5
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,L._)`+${o}`);return;case"boolean":n.elseIf((0,L._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,L._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,L._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,L._)`${i} === "string" || ${i} === "number"
|
|
6
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,L._)`[${o}]`)}}}function Jd({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${r}]`,n))}function _n(e,t,r,n=lt.Correct){const o=n===lt.Correct?L.operators.EQ:L.operators.NEQ;let s;switch(e){case"null":return(0,L._)`${t} ${o} null`;case"array":s=(0,L._)`Array.isArray(${t})`;break;case"object":s=(0,L._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,L._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,L._)`typeof ${t} ${o} ${e}`}return n===lt.Correct?s:(0,L.not)(s);function i(a=L.nil){return(0,L.and)((0,L._)`typeof ${t} == "number"`,a,r?(0,L._)`isFinite(${t})`:L.nil)}}Z.checkDataType=_n;function po(e,t,r,n){if(e.length===1)return _n(e[0],t,r,n);let o;const s=(0,tc.toHash)(e);if(s.array&&s.object){const i=(0,L._)`typeof ${t} != "object"`;o=s.null?i:(0,L._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=L.nil;s.number&&delete s.integer;for(const i in s)o=(0,L.and)(o,_n(i,t,r,n));return o}Z.checkDataTypes=po;const Kd={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function mo(e){const t=Bd(e);(0,zd.reportError)(t,Kd)}Z.reportTypeError=mo;function Bd(e){const{gen:t,data:r,schema:n}=e,o=(0,tc.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}var _r={};Object.defineProperty(_r,"__esModule",{value:!0});_r.assignDefaults=void 0;const Ye=z,Wd=T;function Yd(e,t){const{properties:r,items:n}=e.schema;if(t==="object"&&r)for(const o in r)ri(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>ri(e,s,o.default))}_r.assignDefaults=Yd;function ri(e,t,r){const{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;const a=(0,Ye._)`${s}${(0,Ye.getProperty)(t)}`;if(o){(0,Wd.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Ye._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ye._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Ye._)`${a} = ${(0,Ye.stringify)(r)}`)}var ye={},q={};Object.defineProperty(q,"__esModule",{value:!0});q.validateUnion=q.validateArray=q.usePattern=q.callValidateCode=q.schemaProperties=q.allSchemaProperties=q.noPropertyInData=q.propertyInData=q.isOwnProperty=q.hasPropFunc=q.reportMissingProp=q.checkMissingProp=q.checkReportMissingProp=void 0;const W=z,ho=T,_e=ge,Zd=T;function Qd(e,t){const{gen:r,data:n,it:o}=e;r.if(go(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,W._)`${t}`},!0),e.error()})}q.checkReportMissingProp=Qd;function Xd({gen:e,data:t,it:{opts:r}},n,o){return(0,W.or)(...n.map(s=>(0,W.and)(go(e,t,s,r.ownProperties),(0,W._)`${o} = ${s}`)))}q.checkMissingProp=Xd;function el(e,t){e.setParams({missingProperty:t},!0),e.error()}q.reportMissingProp=el;function oc(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,W._)`Object.prototype.hasOwnProperty`})}q.hasPropFunc=oc;function yo(e,t,r){return(0,W._)`${oc(e)}.call(${t}, ${r})`}q.isOwnProperty=yo;function tl(e,t,r,n){const o=(0,W._)`${t}${(0,W.getProperty)(r)} !== undefined`;return n?(0,W._)`${o} && ${yo(e,t,r)}`:o}q.propertyInData=tl;function go(e,t,r,n){const o=(0,W._)`${t}${(0,W.getProperty)(r)} === undefined`;return n?(0,W.or)(o,(0,W.not)(yo(e,t,r))):o}q.noPropertyInData=go;function sc(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}q.allSchemaProperties=sc;function rl(e,t){return sc(t).filter(r=>!(0,ho.alwaysValidSchema)(e,t[r]))}q.schemaProperties=rl;function nl({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){const d=u?(0,W._)`${e}, ${t}, ${n}${o}`:t,l=[[_e.default.instancePath,(0,W.strConcat)(_e.default.instancePath,s)],[_e.default.parentData,i.parentData],[_e.default.parentDataProperty,i.parentDataProperty],[_e.default.rootData,_e.default.rootData]];i.opts.dynamicRef&&l.push([_e.default.dynamicAnchors,_e.default.dynamicAnchors]);const p=(0,W._)`${d}, ${r.object(...l)}`;return c!==W.nil?(0,W._)`${a}.call(${c}, ${p})`:(0,W._)`${a}(${p})`}q.callValidateCode=nl;const ol=(0,W._)`new RegExp`;function sl({gen:e,it:{opts:t}},r){const n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,W._)`${o.code==="new RegExp"?ol:(0,Zd.useFunc)(e,o)}(${r}, ${n})`})}q.usePattern=sl;function il(e){const{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){const a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){const c=t.const("len",(0,W._)`${r}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:ho.Type.Num},s),t.if((0,W.not)(s),a)})}}q.validateArray=il;function al(e){const{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,ho.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;const i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{const d=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,W._)`${i} || ${a}`),e.mergeValidEvaluated(d,a)||t.if((0,W.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}q.validateUnion=al;Object.defineProperty(ye,"__esModule",{value:!0});ye.validateKeywordUsage=ye.validSchemaType=ye.funcKeywordCode=ye.macroKeywordCode=void 0;const ie=z,De=ge,cl=q,ul=Rt;function dl(e,t){const{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=ic(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=r.name("valid");e.subschema({schema:a,schemaPath:ie.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}ye.macroKeywordCode=dl;function ll(e,t){var r;const{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;pl(c,t);const u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,d=ic(n,o,u),l=n.let("valid");e.block$data(l,p),e.ok((r=t.valid)!==null&&r!==void 0?r:l);function p(){if(t.errors===!1)y(),t.modifying&&ni(e),$(()=>e.error());else{const g=t.async?h():f();t.modifying&&ni(e),$(()=>fl(e,g))}}function h(){const g=n.let("ruleErrs",null);return n.try(()=>y((0,ie._)`await `),w=>n.assign(l,!1).if((0,ie._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,ie._)`${w}.errors`),()=>n.throw(w))),g}function f(){const g=(0,ie._)`${d}.errors`;return n.assign(g,null),y(ie.nil),g}function y(g=t.async?(0,ie._)`await `:ie.nil){const w=c.opts.passContext?De.default.this:De.default.self,_=!("compile"in t&&!a||t.schema===!1);n.assign(l,(0,ie._)`${g}${(0,cl.callValidateCode)(e,d,w,_)}`,t.modifying)}function $(g){var w;n.if((0,ie.not)((w=t.valid)!==null&&w!==void 0?w:l),g)}}ye.funcKeywordCode=ll;function ni(e){const{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,ie._)`${n.parentData}[${n.parentDataProperty}]`))}function fl(e,t){const{gen:r}=e;r.if((0,ie._)`Array.isArray(${t})`,()=>{r.assign(De.default.vErrors,(0,ie._)`${De.default.vErrors} === null ? ${t} : ${De.default.vErrors}.concat(${t})`).assign(De.default.errors,(0,ie._)`${De.default.vErrors}.length`),(0,ul.extendErrors)(e)},()=>e.error())}function pl({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function ic(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ie.stringify)(r)})}function ml(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}ye.validSchemaType=ml;function hl({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const i=o.dependencies;if(i!=null&&i.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){const c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}ye.validateKeywordUsage=hl;var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.extendSubschemaMode=Ne.extendSubschemaData=Ne.getSubschema=void 0;const he=z,ac=T;function yl(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){const a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,he._)`${e.schemaPath}${(0,he.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,he._)`${e.schemaPath}${(0,he.getProperty)(t)}${(0,he.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ac.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Ne.getSubschema=yl;function gl(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=t;if(r!==void 0){const{errorPath:u,dataPathArr:d,opts:l}=t,p=a.let("data",(0,he._)`${t.data}${(0,he.getProperty)(r)}`,!0);c(p),e.errorPath=(0,he.str)`${u}${(0,ac.getErrorPath)(r,n,l.jsPropertySyntax)}`,e.parentDataProperty=(0,he._)`${r}`,e.dataPathArr=[...d,e.parentDataProperty]}if(o!==void 0){const u=o instanceof he.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}Ne.extendSubschemaData=gl;function $l(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}Ne.extendSubschemaMode=$l;var ne={},cc=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r},uc={exports:{}},Ee=uc.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};nr(t,n,o,e,"",e)};Ee.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ee.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ee.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ee.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 nr(e,t,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Ee.arrayKeywords)for(var p=0;p<l.length;p++)nr(e,t,r,l[p],o+"/"+d+"/"+p,s,o,d,n,p)}else if(d in Ee.propsKeywords){if(l&&typeof l=="object")for(var h in l)nr(e,t,r,l[h],o+"/"+d+"/"+vl(h),s,o,d,n,h)}else(d in Ee.keywords||e.allKeys&&!(d in Ee.skipKeywords))&&nr(e,t,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function vl(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var wl=uc.exports;Object.defineProperty(ne,"__esModule",{value:!0});ne.getSchemaRefs=ne.resolveUrl=ne.normalizeId=ne._getFullPath=ne.getFullPath=ne.inlineRef=void 0;const _l=T,bl=cc,Sl=wl,El=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Nl(e,t=!0){return typeof e=="boolean"?!0:t===!0?!bn(e):t?dc(e)<=t:!1}ne.inlineRef=Nl;const Ol=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bn(e){for(const t in e){if(Ol.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(bn)||typeof r=="object"&&bn(r))return!0}return!1}function dc(e){let t=0;for(const r in e){if(r==="$ref")return 1/0;if(t++,!El.has(r)&&(typeof e[r]=="object"&&(0,_l.eachItem)(e[r],n=>t+=dc(n)),t===1/0))return 1/0}return t}function lc(e,t="",r){r!==!1&&(t=ft(t));const n=e.parse(t);return fc(e,n)}ne.getFullPath=lc;function fc(e,t){return e.serialize(t).split("#")[0]+"#"}ne._getFullPath=fc;const jl=/#\/?$/;function ft(e){return e?e.replace(jl,""):""}ne.normalizeId=ft;function kl(e,t,r){return r=ft(r),e.resolve(t,r)}ne.resolveUrl=kl;const Pl=/^[a-z_][-a-z0-9._]*$/i;function Al(e,t){if(typeof e=="boolean")return{};const{schemaId:r,uriResolver:n}=this.opts,o=ft(e[r]||t),s={"":o},i=lc(n,o,!1),a={},c=new Set;return Sl(e,{allKeys:!0},(l,p,h,f)=>{if(f===void 0)return;const y=i+p;let $=s[f];typeof l[r]=="string"&&($=g.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),s[p]=$;function g(_){const E=this.opts.uriResolver.resolve;if(_=ft($?E($,_):_),c.has(_))throw d(_);c.add(_);let j=this.refs[_];return typeof j=="string"&&(j=this.refs[j]),typeof j=="object"?u(l,j.schema,_):_!==ft(y)&&(_[0]==="#"?(u(l,a[_],_),a[_]=l):this.refs[_]=y),_}function w(_){if(typeof _=="string"){if(!Pl.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function u(l,p,h){if(p!==void 0&&!bl(l,p))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}ne.getSchemaRefs=Al;Object.defineProperty(pe,"__esModule",{value:!0});pe.getData=pe.KeywordCxt=pe.validateFunctionCode=void 0;const pc=pt,oi=Z,$o=ve,pr=Z,Tl=_r,kt=ye,Wr=Ne,C=z,F=ge,Il=ne,we=T,wt=Rt;function Cl(e){if(yc(e)&&(gc(e),hc(e))){xl(e);return}mc(e,()=>(0,pc.topBoolOrEmptySchema)(e))}pe.validateFunctionCode=Cl;function mc({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,C._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{e.code((0,C._)`"use strict"; ${si(r,o)}`),Rl(e,o),e.code(s)}):e.func(t,(0,C._)`${F.default.data}, ${Dl(o)}`,n.$async,()=>e.code(si(r,o)).code(s))}function Dl(e){return(0,C._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${e.dynamicRef?(0,C._)`, ${F.default.dynamicAnchors}={}`:C.nil}}={}`}function Rl(e,t){e.if(F.default.valCxt,()=>{e.var(F.default.instancePath,(0,C._)`${F.default.valCxt}.${F.default.instancePath}`),e.var(F.default.parentData,(0,C._)`${F.default.valCxt}.${F.default.parentData}`),e.var(F.default.parentDataProperty,(0,C._)`${F.default.valCxt}.${F.default.parentDataProperty}`),e.var(F.default.rootData,(0,C._)`${F.default.valCxt}.${F.default.rootData}`),t.dynamicRef&&e.var(F.default.dynamicAnchors,(0,C._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{e.var(F.default.instancePath,(0,C._)`""`),e.var(F.default.parentData,(0,C._)`undefined`),e.var(F.default.parentDataProperty,(0,C._)`undefined`),e.var(F.default.rootData,F.default.data),t.dynamicRef&&e.var(F.default.dynamicAnchors,(0,C._)`{}`)})}function xl(e){const{schema:t,opts:r,gen:n}=e;mc(e,()=>{r.$comment&&t.$comment&&vc(e),zl(e),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&Ml(e),$c(e),Gl(e)})}function Ml(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,C._)`${r}.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 si(e,t){const r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,C._)`/*# sourceURL=${r} */`:C.nil}function Fl(e,t){if(yc(e)&&(gc(e),hc(e))){Ul(e,t);return}(0,pc.boolOrEmptySchema)(e,t)}function hc({schema:e,self:t}){if(typeof e=="boolean")return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function yc(e){return typeof e.schema!="boolean"}function Ul(e,t){const{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&vc(e),ql(e),Vl(e);const s=n.const("_errs",F.default.errors);$c(e,s),n.var(t,(0,C._)`${s} === ${F.default.errors}`)}function gc(e){(0,we.checkUnknownRules)(e),Ll(e)}function $c(e,t){if(e.opts.jtd)return ii(e,[],!1,t);const r=(0,oi.getSchemaTypes)(e.schema),n=(0,oi.coerceAndCheckDataType)(e,r);ii(e,r,!n,t)}function Ll(e){const{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,we.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function zl(e){const{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,we.checkStrictMode)(e,"default is ignored in the schema root")}function ql(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Il.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Vl(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function vc({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){const s=r.$comment;if(o.$comment===!0)e.code((0,C._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,C.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,C._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Gl(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,C._)`${F.default.errors} === 0`,()=>t.return(F.default.data),()=>t.throw((0,C._)`new ${o}(${F.default.vErrors})`)):(t.assign((0,C._)`${n}.errors`,F.default.vErrors),s.unevaluated&&Hl(e),t.return((0,C._)`${F.default.errors} === 0`))}function Hl({gen:e,evaluated:t,props:r,items:n}){r instanceof C.Name&&e.assign((0,C._)`${t}.props`,r),n instanceof C.Name&&e.assign((0,C._)`${t}.items`,n)}function ii(e,t,r,n){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,we.schemaHasRulesButRef)(s,d))){o.block(()=>bc(e,"$ref",d.all.$ref.definition));return}c.jtd||Jl(e,t),o.block(()=>{for(const p of d.rules)l(p);l(d.post)});function l(p){(0,$o.shouldUseGroup)(s,p)&&(p.type?(o.if((0,pr.checkDataType)(p.type,i,c.strictNumbers)),ai(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,pr.reportTypeError)(e)),o.endIf()):ai(e,p),a||o.if((0,C._)`${F.default.errors} === ${n||0}`))}}function ai(e,t){const{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,Tl.assignDefaults)(e,t.type),r.block(()=>{for(const s of t.rules)(0,$o.shouldUseRule)(n,s)&&bc(e,s.keyword,s.definition,t.type)})}function Jl(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Kl(e,t),e.opts.allowUnionTypes||Bl(e,t),Wl(e,e.dataTypes))}function Kl(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{wc(e.dataTypes,r)||vo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),Zl(e,t)}}function Bl(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&vo(e,"use allowUnionTypes to allow union type keyword")}function Wl(e,t){const r=e.self.RULES.all;for(const n in r){const o=r[n];if(typeof o=="object"&&(0,$o.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>Yl(t,i))&&vo(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Yl(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function wc(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Zl(e,t){const r=[];for(const n of e.dataTypes)wc(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function vo(e,t){const r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,we.checkStrictMode)(e,t,e.opts.strictTypes)}class _c{constructor(t,r,n){if((0,kt.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,we.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Sc(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,kt.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",F.default.errors))}result(t,r,n){this.failResult((0,C.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,C.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);const{schemaCode:r}=this;this.fail((0,C._)`${r} !== undefined && (${(0,C.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?wt.reportExtraError:wt.reportError)(this,this.def.error,r)}$dataError(){(0,wt.reportError)(this,this.def.$dataError||wt.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,wt.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=C.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=C.nil,r=C.nil){if(!this.$data)return;const{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,C.or)((0,C._)`${o} === undefined`,r)),t!==C.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==C.nil&&n.assign(t,!1)),n.else()}invalid$data(){const{gen:t,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,C.or)(i(),a());function i(){if(n.length){if(!(r instanceof C.Name))throw new Error("ajv implementation error");const c=Array.isArray(n)?n:[n];return(0,C._)`${(0,pr.checkDataTypes)(c,r,s.opts.strictNumbers,pr.DataType.Wrong)}`}return C.nil}function a(){if(o.validateSchema){const c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,C._)`!${c}(${r})`}return C.nil}}subschema(t,r){const n=(0,Wr.getSubschema)(this.it,t);(0,Wr.extendSubschemaData)(n,this.it,t),(0,Wr.extendSubschemaMode)(n,t);const o={...this.it,...n,items:void 0,props:void 0};return Fl(o,r),o}mergeEvaluated(t,r){const{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=we.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=we.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){const{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,C.Name)),!0}}pe.KeywordCxt=_c;function bc(e,t,r,n){const o=new _c(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,kt.funcKeywordCode)(o,r):"macro"in r?(0,kt.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,kt.funcKeywordCode)(o,r)}const Ql=/^\/(?:[^~]|~0|~1)*$/,Xl=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Sc(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return F.default.rootData;if(e[0]==="/"){if(!Ql.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=F.default.rootData}else{const u=Xl.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);const d=+u[1];if(o=u[2],o==="#"){if(d>=t)throw new Error(c("property/index",d));return n[t-d]}if(d>t)throw new Error(c("data",d));if(s=r[t-d],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,C._)`${s}${(0,C.getProperty)((0,we.unescapeJsonPointer)(u))}`,i=(0,C._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${t}`}}pe.getData=Sc;var xt={};Object.defineProperty(xt,"__esModule",{value:!0});class ef extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}}xt.default=ef;var yt={};Object.defineProperty(yt,"__esModule",{value:!0});const Yr=ne;class tf extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Yr.resolveUrl)(t,r,n),this.missingSchema=(0,Yr.normalizeId)((0,Yr.getFullPath)(t,this.missingRef))}}yt.default=tf;var ce={};Object.defineProperty(ce,"__esModule",{value:!0});ce.resolveSchema=ce.getCompilingSchema=ce.resolveRef=ce.compileSchema=ce.SchemaEnv=void 0;const de=z,rf=xt,je=ge,fe=ne,ci=T,nf=pe;class br{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,fe.normalizeId)(n==null?void 0:n[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n==null?void 0:n.$async,this.refs={}}}ce.SchemaEnv=br;function wo(e){const t=Ec.call(this,e);if(t)return t;const r=(0,fe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new de.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:rf.default,code:(0,de._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:je.default.data,parentData:je.default.parentData,parentDataProperty:je.default.parentDataProperty,dataNames:[je.default.data],dataPathArr:[de.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,de.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:de.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,de._)`""`,opts:this.opts,self:this};let d;try{this._compilations.add(e),(0,nf.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const l=i.toString();d=`${i.scopeRefs(je.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,e));const h=new Function(`${je.default.self}`,`${je.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=e.schema,h.schemaEnv=e,e.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){const{props:f,items:y}=u;h.evaluated={props:f instanceof de.Name?void 0:f,items:y instanceof de.Name?void 0:y,dynamicProps:f instanceof de.Name,dynamicItems:y instanceof de.Name},h.source&&(h.source.evaluated=(0,de.stringify)(h.evaluated))}return e.validate=h,e}catch(l){throw delete e.validate,delete e.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(e)}}ce.compileSchema=wo;function of(e,t,r){var n;r=(0,fe.resolveUrl)(this.opts.uriResolver,t,r);const o=e.refs[r];if(o)return o;let s=cf.call(this,e,r);if(s===void 0){const i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new br({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=sf.call(this,s)}ce.resolveRef=of;function sf(e){return(0,fe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:wo.call(this,e)}function Ec(e){for(const t of this._compilations)if(af(t,e))return t}ce.getCompilingSchema=Ec;function af(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function cf(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Sr.call(this,e,t)}function Sr(e,t){const r=this.opts.uriResolver.parse(t),n=(0,fe._getFullPath)(this.opts.uriResolver,r);let o=(0,fe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Zr.call(this,r,e);const s=(0,fe.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Sr.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:Zr.call(this,r,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||wo.call(this,i),s===(0,fe.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,fe.resolveUrl)(this.opts.uriResolver,o,u)),new br({schema:a,schemaId:c,root:e,baseId:o})}return Zr.call(this,r,i)}}ce.resolveSchema=Sr;const uf=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Zr(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;const c=r[(0,ci.unescapeFragment)(a)];if(c===void 0)return;r=c;const u=typeof r=="object"&&r[this.opts.schemaId];!uf.has(a)&&u&&(t=(0,fe.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,ci.schemaHasRulesButRef)(r,this.RULES)){const a=(0,fe.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Sr.call(this,n,a)}const{schemaId:i}=this.opts;if(s=s||new br({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}const df="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",lf="Meta-schema for $data reference (JSON AnySchema extension proposal)",ff="object",pf=["$data"],mf={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},hf=!1,yf={$id:df,description:lf,type:ff,required:pf,properties:mf,additionalProperties:hf};var _o={},Er={exports:{}};const gf=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Nc=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),bo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Oc=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),$f=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function jc(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}const vf=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ui(e){return e.length=0,!0}function wf(e,t,r){if(e.length){const n=jc(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function _f(e){let t=0;const r={error:!1,address:"",zone:""},n=[],o=[];let s=!1,i=!1,a=wf;for(let c=0;c<e.length;c++){const u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=ui}else{o.push(u);continue}}return o.length&&(a===ui?r.zone=o.join(""):i?n.push(o.join("")):n.push(jc(o))),r.address=n.join(""),r}function kc(e){if(bf(e,":")<2)return{host:e,isIPV6:!1};const t=_f(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function bf(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Sf(e){let t=e;const r=[];let n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.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),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}const Ef={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Nf=/[@/?#:]/g,Of=/[@/?#]/g;function Pc(e,t){const r=t?Of:Nf;return r.lastIndex=0,e.replace(r,n=>Ef[n])}function jf(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const o=e.slice(n+1,n+3);if(bo(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Oc(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function kf(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){const n=e.slice(r+1,r+3);if(bo(n)){const o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Oc(s)?t+=s:t+="%"+o,r+=2;continue}}$f(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Pf(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){const n=e.slice(r+1,r+3);if(bo(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Af(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Nc(r)){const n=kc(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Pc(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}var Ac={nonSimpleDomain:vf,recomposeAuthority:Af,reescapeHostDelimiters:Pc,normalizePercentEncoding:jf,normalizePathEncoding:kf,escapePreservingEscapes:Pf,removeDotSegments:Sf,isIPv4:Nc,isUUID:gf,normalizeIPv6:kc};const{isUUID:Tf}=Ac,If=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function Tc(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 Ic(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Cc(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function Cf(e){return e.secure=Tc(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Df(e){if((e.port===(Tc(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){const[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Rf(e,t){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(If);if(r){const n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const o=`${n}:${t.nid||e.nid}`,s=So(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function xf(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,s=So(o);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function Mf(e,t){const r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Tf(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Ff(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Dc={scheme:"http",domainHost:!0,parse:Ic,serialize:Cc},Uf={scheme:"https",domainHost:Dc.domainHost,parse:Ic,serialize:Cc},or={scheme:"ws",domainHost:!0,parse:Cf,serialize:Df},Lf={scheme:"wss",domainHost:or.domainHost,parse:or.parse,serialize:or.serialize},zf={scheme:"urn",parse:Rf,serialize:xf,skipNormalize:!0},qf={scheme:"urn:uuid",parse:Mf,serialize:Ff,skipNormalize:!0},mr={http:Dc,https:Uf,ws:or,wss:Lf,urn:zf,"urn:uuid":qf};Object.setPrototypeOf(mr,null);function So(e){return e&&(mr[e]||mr[e.toLowerCase()])||void 0}var Vf={SCHEMES:mr,getSchemeHandler:So};const{normalizeIPv6:Gf,removeDotSegments:Ot,recomposeAuthority:Hf,normalizePercentEncoding:Jf,normalizePathEncoding:Kf,escapePreservingEscapes:Bf,reescapeHostDelimiters:Wf,isIPv4:Yf,nonSimpleDomain:Zf}=Ac,{SCHEMES:Qf,getSchemeHandler:Rc}=Vf;function Xf(e,t){return typeof e=="string"?e=op(e,t):typeof e=="object"&&(e=mt(Je(e,t),t)),e}function ep(e,t,r){const n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=xc(mt(e,n),mt(t,n),n,!0);return n.skipEscape=!0,Je(o,n)}function xc(e,t,r,n){const o={};return n||(e=mt(Je(e,r),r),t=mt(Je(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Ot(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=Ot(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=Ot(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=Ot(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function tp(e,t,r){const n=di(e,r),o=di(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Je(e,t){const r={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:""},n=Object.assign({},t),o=[],s=Rc(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Jf(r.path):(r.path=Bf(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");const i=Hf(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Ot(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}const rp=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function np(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Mc(e,t){const r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1,s=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);const i=e.match(rp);if(i){n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]);const a=np(n,i);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(Yf(n.host)===!1){const d=Gf(n.host);n.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");const c=Rc(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&s===!1&&Zf(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Wf(unescape(n.host),s))),n.path&&(n.path=Kf(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function mt(e,t){return Mc(e,t).parsed}function op(e,t){return Fc(e,t).normalized}function Fc(e,t){const{parsed:r,malformedAuthorityOrPort:n}=Mc(e,t);return{normalized:n?e:Je(r,t),malformedAuthorityOrPort:n}}function di(e,t){if(typeof e=="string"){const{normalized:r,malformedAuthorityOrPort:n}=Fc(e,t);return n?void 0:r}if(typeof e=="object")return Je(e,t)}const Eo={SCHEMES:Qf,normalize:Xf,resolve:ep,resolveComponent:xc,equal:tp,serialize:Je,parse:mt};Er.exports=Eo;Er.exports.default=Eo;Er.exports.fastUri=Eo;var sp=Er.exports;Object.defineProperty(_o,"__esModule",{value:!0});const Uc=sp;Uc.code='require("ajv/dist/runtime/uri").default';_o.default=Uc;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=pe;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=z;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=xt,o=yt,s=He,i=ce,a=z,c=ne,u=Z,d=T,l=yf,p=_o,h=(A,b)=>new RegExp(A,b);h.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),$={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."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},w=200;function _(A){var b,P,S,m,v,O,R,M,K,G,ee,We,Cr,Dr,Rr,xr,Mr,Fr,Ur,Lr,zr,qr,Vr,Gr,Hr;const vt=A.strict,Jr=(b=A.code)===null||b===void 0?void 0:b.optimize,Ws=Jr===!0||Jr===void 0?1:Jr||0,Ys=(S=(P=A.code)===null||P===void 0?void 0:P.regExp)!==null&&S!==void 0?S:h,Xu=(m=A.uriResolver)!==null&&m!==void 0?m:p.default;return{strictSchema:(O=(v=A.strictSchema)!==null&&v!==void 0?v:vt)!==null&&O!==void 0?O:!0,strictNumbers:(M=(R=A.strictNumbers)!==null&&R!==void 0?R:vt)!==null&&M!==void 0?M:!0,strictTypes:(G=(K=A.strictTypes)!==null&&K!==void 0?K:vt)!==null&&G!==void 0?G:"log",strictTuples:(We=(ee=A.strictTuples)!==null&&ee!==void 0?ee:vt)!==null&&We!==void 0?We:"log",strictRequired:(Dr=(Cr=A.strictRequired)!==null&&Cr!==void 0?Cr:vt)!==null&&Dr!==void 0?Dr:!1,code:A.code?{...A.code,optimize:Ws,regExp:Ys}:{optimize:Ws,regExp:Ys},loopRequired:(Rr=A.loopRequired)!==null&&Rr!==void 0?Rr:w,loopEnum:(xr=A.loopEnum)!==null&&xr!==void 0?xr:w,meta:(Mr=A.meta)!==null&&Mr!==void 0?Mr:!0,messages:(Fr=A.messages)!==null&&Fr!==void 0?Fr:!0,inlineRefs:(Ur=A.inlineRefs)!==null&&Ur!==void 0?Ur:!0,schemaId:(Lr=A.schemaId)!==null&&Lr!==void 0?Lr:"$id",addUsedSchema:(zr=A.addUsedSchema)!==null&&zr!==void 0?zr:!0,validateSchema:(qr=A.validateSchema)!==null&&qr!==void 0?qr:!0,validateFormats:(Vr=A.validateFormats)!==null&&Vr!==void 0?Vr:!0,unicodeRegExp:(Gr=A.unicodeRegExp)!==null&&Gr!==void 0?Gr:!0,int32range:(Hr=A.int32range)!==null&&Hr!==void 0?Hr:!0,uriResolver:Xu}}class E{constructor(b={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,b=this.opts={...b,..._(b)};const{es5:P,lines:S}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:P,lines:S}),this.logger=J(b.logger);const m=b.validateFormats;b.validateFormats=!1,this.RULES=(0,s.getRules)(),j.call(this,$,b,"NOT SUPPORTED"),j.call(this,g,b,"DEPRECATED","warn"),this._metaOpts=U.call(this),b.formats&&V.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),b.keywords&&D.call(this,b.keywords),typeof b.meta=="object"&&this.addMetaSchema(b.meta),x.call(this),b.validateFormats=m}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:b,meta:P,schemaId:S}=this.opts;let m=l;S==="id"&&(m={...l},m.id=m.$id,delete m.$id),P&&b&&this.addMetaSchema(m,m[S],!1)}defaultMeta(){const{meta:b,schemaId:P}=this.opts;return this.opts.defaultMeta=typeof b=="object"?b[P]||b:void 0}validate(b,P){let S;if(typeof b=="string"){if(S=this.getSchema(b),!S)throw new Error(`no schema with key or ref "${b}"`)}else S=this.compile(b);const m=S(P);return"$async"in S||(this.errors=S.errors),m}compile(b,P){const S=this._addSchema(b,P);return S.validate||this._compileSchemaEnv(S)}compileAsync(b,P){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:S}=this.opts;return m.call(this,b,P);async function m(G,ee){await v.call(this,G.$schema);const We=this._addSchema(G,ee);return We.validate||O.call(this,We)}async function v(G){G&&!this.getSchema(G)&&await m.call(this,{$ref:G},!0)}async function O(G){try{return this._compileSchemaEnv(G)}catch(ee){if(!(ee instanceof o.default))throw ee;return R.call(this,ee),await M.call(this,ee.missingSchema),O.call(this,G)}}function R({missingSchema:G,missingRef:ee}){if(this.refs[G])throw new Error(`AnySchema ${G} is loaded but ${ee} cannot be resolved`)}async function M(G){const ee=await K.call(this,G);this.refs[G]||await v.call(this,ee.$schema),this.refs[G]||this.addSchema(ee,G,P)}async function K(G){const ee=this._loading[G];if(ee)return ee;try{return await(this._loading[G]=S(G))}finally{delete this._loading[G]}}}addSchema(b,P,S,m=this.opts.validateSchema){if(Array.isArray(b)){for(const O of b)this.addSchema(O,void 0,S,m);return this}let v;if(typeof b=="object"){const{schemaId:O}=this.opts;if(v=b[O],v!==void 0&&typeof v!="string")throw new Error(`schema ${O} must be string`)}return P=(0,c.normalizeId)(P||v),this._checkUnique(P),this.schemas[P]=this._addSchema(b,S,P,m,!0),this}addMetaSchema(b,P,S=this.opts.validateSchema){return this.addSchema(b,P,!0,S),this}validateSchema(b,P){if(typeof b=="boolean")return!0;let S;if(S=b.$schema,S!==void 0&&typeof S!="string")throw new Error("$schema must be a string");if(S=S||this.opts.defaultMeta||this.defaultMeta(),!S)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const m=this.validate(S,b);if(!m&&P){const v="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(v);else throw new Error(v)}return m}getSchema(b){let P;for(;typeof(P=I.call(this,b))=="string";)b=P;if(P===void 0){const{schemaId:S}=this.opts,m=new i.SchemaEnv({schema:{},schemaId:S});if(P=i.resolveSchema.call(this,m,b),!P)return;this.refs[b]=P}return P.validate||this._compileSchemaEnv(P)}removeSchema(b){if(b instanceof RegExp)return this._removeAllSchemas(this.schemas,b),this._removeAllSchemas(this.refs,b),this;switch(typeof b){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const P=I.call(this,b);return typeof P=="object"&&this._cache.delete(P.schema),delete this.schemas[b],delete this.refs[b],this}case"object":{const P=b;this._cache.delete(P);let S=b[this.opts.schemaId];return S&&(S=(0,c.normalizeId)(S),delete this.schemas[S],delete this.refs[S]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(b){for(const P of b)this.addKeyword(P);return this}addKeyword(b,P){let S;if(typeof b=="string")S=b,typeof P=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),P.keyword=S);else if(typeof b=="object"&&P===void 0){if(P=b,S=P.keyword,Array.isArray(S)&&!S.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(se.call(this,S,P),!P)return(0,d.eachItem)(S,v=>me.call(this,v)),this;Tr.call(this,P);const m={...P,type:(0,u.getJSONTypes)(P.type),schemaType:(0,u.getJSONTypes)(P.schemaType)};return(0,d.eachItem)(S,m.type.length===0?v=>me.call(this,v,m):v=>m.type.forEach(O=>me.call(this,v,m,O))),this}getKeyword(b){const P=this.RULES.all[b];return typeof P=="object"?P.definition:!!P}removeKeyword(b){const{RULES:P}=this;delete P.keywords[b],delete P.all[b];for(const S of P.rules){const m=S.rules.findIndex(v=>v.keyword===b);m>=0&&S.rules.splice(m,1)}return this}addFormat(b,P){return typeof P=="string"&&(P=new RegExp(P)),this.formats[b]=P,this}errorsText(b=this.errors,{separator:P=", ",dataVar:S="data"}={}){return!b||b.length===0?"No errors":b.map(m=>`${S}${m.instancePath} ${m.message}`).reduce((m,v)=>m+P+v)}$dataMetaSchema(b,P){const S=this.RULES.all;b=JSON.parse(JSON.stringify(b));for(const m of P){const v=m.split("/").slice(1);let O=b;for(const R of v)O=O[R];for(const R in S){const M=S[R];if(typeof M!="object")continue;const{$data:K}=M.definition,G=O[R];K&&G&&(O[R]=Vt(G))}}return b}_removeAllSchemas(b,P){for(const S in b){const m=b[S];(!P||P.test(S))&&(typeof m=="string"?delete b[S]:m&&!m.meta&&(this._cache.delete(m.schema),delete b[S]))}}_addSchema(b,P,S,m=this.opts.validateSchema,v=this.opts.addUsedSchema){let O;const{schemaId:R}=this.opts;if(typeof b=="object")O=b[R];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof b!="boolean")throw new Error("schema must be object or boolean")}let M=this._cache.get(b);if(M!==void 0)return M;S=(0,c.normalizeId)(O||S);const K=c.getSchemaRefs.call(this,b,S);return M=new i.SchemaEnv({schema:b,schemaId:R,meta:P,baseId:S,localRefs:K}),this._cache.set(M.schema,M),v&&!S.startsWith("#")&&(S&&this._checkUnique(S),this.refs[S]=M),m&&this.validateSchema(b,!0),M}_checkUnique(b){if(this.schemas[b]||this.refs[b])throw new Error(`schema with key or id "${b}" already exists`)}_compileSchemaEnv(b){if(b.meta?this._compileMetaSchema(b):i.compileSchema.call(this,b),!b.validate)throw new Error("ajv implementation error");return b.validate}_compileMetaSchema(b){const P=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,b)}finally{this.opts=P}}}E.ValidationError=n.default,E.MissingRefError=o.default,e.default=E;function j(A,b,P,S="error"){for(const m in A){const v=m;v in b&&this.logger[S](`${P}: option ${m}. ${A[v]}`)}}function I(A){return A=(0,c.normalizeId)(A),this.schemas[A]||this.refs[A]}function x(){const A=this.opts.schemas;if(A)if(Array.isArray(A))this.addSchema(A);else for(const b in A)this.addSchema(A[b],b)}function V(){for(const A in this.opts.formats){const b=this.opts.formats[A];b&&this.addFormat(A,b)}}function D(A){if(Array.isArray(A)){this.addVocabulary(A);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const b in A){const P=A[b];P.keyword||(P.keyword=b),this.addKeyword(P)}}function U(){const A={...this.opts};for(const b of f)delete A[b];return A}const H={log(){},warn(){},error(){}};function J(A){if(A===!1)return H;if(A===void 0)return console;if(A.log&&A.warn&&A.error)return A;throw new Error("logger must implement log, warn and error methods")}const X=/^[a-z_$][a-z0-9_$:-]*$/i;function se(A,b){const{RULES:P}=this;if((0,d.eachItem)(A,S=>{if(P.keywords[S])throw new Error(`Keyword ${S} is already defined`);if(!X.test(S))throw new Error(`Keyword ${S} has invalid name`)}),!!b&&b.$data&&!("code"in b||"validate"in b))throw new Error('$data keyword must have "code" or "validate" function')}function me(A,b,P){var S;const m=b==null?void 0:b.post;if(P&&m)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:v}=this;let O=m?v.post:v.rules.find(({type:M})=>M===P);if(O||(O={type:P,rules:[]},v.rules.push(O)),v.keywords[A]=!0,!b)return;const R={keyword:A,definition:{...b,type:(0,u.getJSONTypes)(b.type),schemaType:(0,u.getJSONTypes)(b.schemaType)}};b.before?qt.call(this,O,R,b.before):O.rules.push(R),v.all[A]=R,(S=b.implements)===null||S===void 0||S.forEach(M=>this.addKeyword(M))}function qt(A,b,P){const S=A.rules.findIndex(m=>m.keyword===P);S>=0?A.rules.splice(S,0,b):(A.rules.push(b),this.logger.warn(`rule ${P} is not defined`))}function Tr(A){let{metaSchema:b}=A;b!==void 0&&(A.$data&&this.opts.$data&&(b=Vt(b)),A.validateSchema=this.compile(b,!0))}const Ir={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Vt(A){return{anyOf:[A,Ir]}}})(Ja);var No={},Oo={},jo={};Object.defineProperty(jo,"__esModule",{value:!0});const ip={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jo.default=ip;var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.callRef=Ke.getValidate=void 0;const ap=yt,li=q,ae=z,Ze=ge,fi=ce,Gt=T,cp={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();const d=fi.resolveRef.call(c,u,o,r);if(d===void 0)throw new ap.default(n.opts.uriResolver,o,r);if(d instanceof fi.SchemaEnv)return p(d);return h(d);function l(){if(s===u)return sr(e,i,s,s.$async);const f=t.scopeValue("root",{ref:u});return sr(e,(0,ae._)`${f}.validate`,u,u.$async)}function p(f){const y=Lc(e,f);sr(e,y,f,f.$async)}function h(f){const y=t.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,ae.stringify)(f)}:{ref:f}),$=t.name("valid"),g=e.subschema({schema:f,dataTypes:[],schemaPath:ae.nil,topSchemaRef:y,errSchemaPath:r},$);e.mergeEvaluated(g),e.ok($)}}};function Lc(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,ae._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Ke.getValidate=Lc;function sr(e,t,r,n){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Ze.default.this:ae.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");const f=o.let("valid");o.try(()=>{o.code((0,ae._)`await ${(0,li.callValidateCode)(e,t,u)}`),h(t),i||o.assign(f,!0)},y=>{o.if((0,ae._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),p(y),i||o.assign(f,!1)}),e.ok(f)}function l(){e.result((0,li.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(f){const y=(0,ae._)`${f}.errors`;o.assign(Ze.default.vErrors,(0,ae._)`${Ze.default.vErrors} === null ? ${y} : ${Ze.default.vErrors}.concat(${y})`),o.assign(Ze.default.errors,(0,ae._)`${Ze.default.vErrors}.length`)}function h(f){var y;if(!s.opts.unevaluated)return;const $=(y=r==null?void 0:r.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=Gt.mergeEvaluated.props(o,$.props,s.props));else{const g=o.var("props",(0,ae._)`${f}.evaluated.props`);s.props=Gt.mergeEvaluated.props(o,g,s.props,ae.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=Gt.mergeEvaluated.items(o,$.items,s.items));else{const g=o.var("items",(0,ae._)`${f}.evaluated.items`);s.items=Gt.mergeEvaluated.items(o,g,s.items,ae.Name)}}}Ke.callRef=sr;Ke.default=cp;Object.defineProperty(Oo,"__esModule",{value:!0});const up=jo,dp=Ke,lp=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",up.default,dp.default];Oo.default=lp;var ko={},Po={};Object.defineProperty(Po,"__esModule",{value:!0});const hr=z,be=hr.operators,yr={maximum:{okStr:"<=",ok:be.LTE,fail:be.GT},minimum:{okStr:">=",ok:be.GTE,fail:be.LT},exclusiveMaximum:{okStr:"<",ok:be.LT,fail:be.GTE},exclusiveMinimum:{okStr:">",ok:be.GT,fail:be.LTE}},fp={message:({keyword:e,schemaCode:t})=>(0,hr.str)`must be ${yr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,hr._)`{comparison: ${yr[e].okStr}, limit: ${t}}`},pp={keyword:Object.keys(yr),type:"number",schemaType:"number",$data:!0,error:fp,code(e){const{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,hr._)`${r} ${yr[t].fail} ${n} || isNaN(${r})`)}};Po.default=pp;var Ao={};Object.defineProperty(Ao,"__esModule",{value:!0});const Pt=z,mp={message:({schemaCode:e})=>(0,Pt.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Pt._)`{multipleOf: ${e}}`},hp={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:mp,code(e){const{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,Pt._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Pt._)`${i} !== parseInt(${i})`;e.fail$data((0,Pt._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Ao.default=hp;var To={},Io={};Object.defineProperty(Io,"__esModule",{value:!0});function zc(e){const t=e.length;let r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}Io.default=zc;zc.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(To,"__esModule",{value:!0});const Re=z,yp=T,gp=Io,$p={message({keyword:e,schemaCode:t}){const r=e==="maxLength"?"more":"fewer";return(0,Re.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Re._)`{limit: ${e}}`},vp={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:$p,code(e){const{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?Re.operators.GT:Re.operators.LT,i=o.opts.unicode===!1?(0,Re._)`${r}.length`:(0,Re._)`${(0,yp.useFunc)(e.gen,gp.default)}(${r})`;e.fail$data((0,Re._)`${i} ${s} ${n}`)}};To.default=vp;var Co={};Object.defineProperty(Co,"__esModule",{value:!0});const wp=q,_p=T,ut=z,bp={message:({schemaCode:e})=>(0,ut.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,ut._)`{pattern: ${e}}`},Sp={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:bp,code(e){const{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ut._)`new RegExp`:(0,_p.useFunc)(t,c),d=t.let("valid");t.try(()=>t.assign(d,(0,ut._)`${u}(${s}, ${a}).test(${r})`),()=>t.assign(d,!1)),e.fail$data((0,ut._)`!${d}`)}else{const c=(0,wp.usePattern)(e,o);e.fail$data((0,ut._)`!${c}.test(${r})`)}}};Co.default=Sp;var Do={};Object.defineProperty(Do,"__esModule",{value:!0});const At=z,Ep={message({keyword:e,schemaCode:t}){const r=e==="maxProperties"?"more":"fewer";return(0,At.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,At._)`{limit: ${e}}`},Np={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Ep,code(e){const{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?At.operators.GT:At.operators.LT;e.fail$data((0,At._)`Object.keys(${r}).length ${o} ${n}`)}};Do.default=Np;var Ro={};Object.defineProperty(Ro,"__esModule",{value:!0});const _t=q,Tt=z,Op=T,jp={message:({params:{missingProperty:e}})=>(0,Tt.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Tt._)`{missingProperty: ${e}}`},kp={keyword:"required",type:"object",schemaType:"array",$data:!0,error:jp,code(e){const{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;const c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){const h=e.parentSchema.properties,{definedProperties:f}=e.it;for(const y of r)if((h==null?void 0:h[y])===void 0&&!f.has(y)){const $=i.schemaEnv.baseId+i.errSchemaPath,g=`required property "${y}" is not defined at "${$}" (strictRequired)`;(0,Op.checkStrictMode)(i,g,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(Tt.nil,l);else for(const h of r)(0,_t.checkReportMissingProp)(e,h)}function d(){const h=t.let("missing");if(c||s){const f=t.let("valid",!0);e.block$data(f,()=>p(h,f)),e.ok(f)}else t.if((0,_t.checkMissingProp)(e,r,h)),(0,_t.reportMissingProp)(e,h),t.else()}function l(){t.forOf("prop",n,h=>{e.setParams({missingProperty:h}),t.if((0,_t.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,f){e.setParams({missingProperty:h}),t.forOf(h,n,()=>{t.assign(f,(0,_t.propertyInData)(t,o,h,a.ownProperties)),t.if((0,Tt.not)(f),()=>{e.error(),t.break()})},Tt.nil)}}};Ro.default=kp;var xo={};Object.defineProperty(xo,"__esModule",{value:!0});const It=z,Pp={message({keyword:e,schemaCode:t}){const r=e==="maxItems"?"more":"fewer";return(0,It.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,It._)`{limit: ${e}}`},Ap={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Pp,code(e){const{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?It.operators.GT:It.operators.LT;e.fail$data((0,It._)`${r}.length ${o} ${n}`)}};xo.default=Ap;var Mo={},Mt={};Object.defineProperty(Mt,"__esModule",{value:!0});const qc=cc;qc.code='require("ajv/dist/runtime/equal").default';Mt.default=qc;Object.defineProperty(Mo,"__esModule",{value:!0});const Qr=Z,re=z,Tp=T,Ip=Mt,Cp={message:({params:{i:e,j:t}})=>(0,re.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,re._)`{i: ${e}, j: ${t}}`},Dp={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Cp,code(e){const{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;const c=t.let("valid"),u=s.items?(0,Qr.getSchemaTypes)(s.items):[];e.block$data(c,d,(0,re._)`${i} === false`),e.ok(c);function d(){const f=t.let("i",(0,re._)`${r}.length`),y=t.let("j");e.setParams({i:f,j:y}),t.assign(c,!0),t.if((0,re._)`${f} > 1`,()=>(l()?p:h)(f,y))}function l(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,y){const $=t.name("item"),g=(0,Qr.checkDataTypes)(u,$,a.opts.strictNumbers,Qr.DataType.Wrong),w=t.const("indices",(0,re._)`{}`);t.for((0,re._)`;${f}--;`,()=>{t.let($,(0,re._)`${r}[${f}]`),t.if(g,(0,re._)`continue`),u.length>1&&t.if((0,re._)`typeof ${$} == "string"`,(0,re._)`${$} += "_"`),t.if((0,re._)`typeof ${w}[${$}] == "number"`,()=>{t.assign(y,(0,re._)`${w}[${$}]`),e.error(),t.assign(c,!1).break()}).code((0,re._)`${w}[${$}] = ${f}`)})}function h(f,y){const $=(0,Tp.useFunc)(t,Ip.default),g=t.name("outer");t.label(g).for((0,re._)`;${f}--;`,()=>t.for((0,re._)`${y} = ${f}; ${y}--;`,()=>t.if((0,re._)`${$}(${r}[${f}], ${r}[${y}])`,()=>{e.error(),t.assign(c,!1).break(g)})))}}};Mo.default=Dp;var Fo={};Object.defineProperty(Fo,"__esModule",{value:!0});const Sn=z,Rp=T,xp=Mt,Mp={message:"must be equal to constant",params:({schemaCode:e})=>(0,Sn._)`{allowedValue: ${e}}`},Fp={keyword:"const",$data:!0,error:Mp,code(e){const{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,Sn._)`!${(0,Rp.useFunc)(t,xp.default)}(${r}, ${o})`):e.fail((0,Sn._)`${s} !== ${r}`)}};Fo.default=Fp;var Uo={};Object.defineProperty(Uo,"__esModule",{value:!0});const jt=z,Up=T,Lp=Mt,zp={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,jt._)`{allowedValues: ${e}}`},qp={keyword:"enum",schemaType:"array",$data:!0,error:zp,code(e){const{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");const a=o.length>=i.opts.loopEnum;let c;const u=()=>c??(c=(0,Up.useFunc)(t,Lp.default));let d;if(a||n)d=t.let("valid"),e.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const h=t.const("vSchema",s);d=(0,jt.or)(...o.map((f,y)=>p(h,y)))}e.pass(d);function l(){t.assign(d,!1),t.forOf("v",s,h=>t.if((0,jt._)`${u()}(${r}, ${h})`,()=>t.assign(d,!0).break()))}function p(h,f){const y=o[f];return typeof y=="object"&&y!==null?(0,jt._)`${u()}(${r}, ${h}[${f}])`:(0,jt._)`${r} === ${y}`}}};Uo.default=qp;Object.defineProperty(ko,"__esModule",{value:!0});const Vp=Po,Gp=Ao,Hp=To,Jp=Co,Kp=Do,Bp=Ro,Wp=xo,Yp=Mo,Zp=Fo,Qp=Uo,Xp=[Vp.default,Gp.default,Hp.default,Jp.default,Kp.default,Bp.default,Wp.default,Yp.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Zp.default,Qp.default];ko.default=Xp;var Lo={},gt={};Object.defineProperty(gt,"__esModule",{value:!0});gt.validateAdditionalItems=void 0;const xe=z,En=T,em={message:({params:{len:e}})=>(0,xe.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,xe._)`{limit: ${e}}`},tm={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:em,code(e){const{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,En.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Vc(e,n)}};function Vc(e,t){const{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;const a=r.const("len",(0,xe._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,xe._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,En.alwaysValidSchema)(i,n)){const u=r.var("valid",(0,xe._)`${a} <= ${t.length}`);r.if((0,xe.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,d=>{e.subschema({keyword:s,dataProp:d,dataPropType:En.Type.Num},u),i.allErrors||r.if((0,xe.not)(u),()=>r.break())})}}gt.validateAdditionalItems=Vc;gt.default=tm;var zo={},$t={};Object.defineProperty($t,"__esModule",{value:!0});$t.validateTuple=void 0;const pi=z,ir=T,rm=q,nm={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return Gc(e,"additionalItems",t);r.items=!0,!(0,ir.alwaysValidSchema)(r,t)&&e.ok((0,rm.validateArray)(e))}};function Gc(e,t,r=e.schema){const{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ir.mergeEvaluated.items(n,r.length,a.items));const c=n.name("valid"),u=n.const("len",(0,pi._)`${s}.length`);r.forEach((l,p)=>{(0,ir.alwaysValidSchema)(a,l)||(n.if((0,pi._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function d(l){const{opts:p,errSchemaPath:h}=a,f=r.length,y=f===l.minItems&&(f===l.maxItems||l[t]===!1);if(p.strictTuples&&!y){const $=`"${i}" is ${f}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,ir.checkStrictMode)(a,$,p.strictTuples)}}}$t.validateTuple=Gc;$t.default=nm;Object.defineProperty(zo,"__esModule",{value:!0});const om=$t,sm={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,om.validateTuple)(e,"items")};zo.default=sm;var qo={};Object.defineProperty(qo,"__esModule",{value:!0});const mi=z,im=T,am=q,cm=gt,um={message:({params:{len:e}})=>(0,mi.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,mi._)`{limit: ${e}}`},dm={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:um,code(e){const{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,im.alwaysValidSchema)(n,t)&&(o?(0,cm.validateAdditionalItems)(e,o):e.ok((0,am.validateArray)(e)))}};qo.default=dm;var Vo={};Object.defineProperty(Vo,"__esModule",{value:!0});const ue=z,Ht=T,lm={message:({params:{min:e,max:t}})=>t===void 0?(0,ue.str)`must contain at least ${e} valid item(s)`:(0,ue.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,ue._)`{minContains: ${e}}`:(0,ue._)`{minContains: ${e}, maxContains: ${t}}`},fm={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lm,code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;let i,a;const{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const d=t.const("len",(0,ue._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ht.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ht.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ht.alwaysValidSchema)(s,r)){let y=(0,ue._)`${d} >= ${i}`;a!==void 0&&(y=(0,ue._)`${y} && ${d} <= ${a}`),e.pass(y);return}s.items=!0;const l=t.name("valid");a===void 0&&i===1?h(l,()=>t.if(l,()=>t.break())):i===0?(t.let(l,!0),a!==void 0&&t.if((0,ue._)`${o}.length > 0`,p)):(t.let(l,!1),p()),e.result(l,()=>e.reset());function p(){const y=t.name("_valid"),$=t.let("count",0);h(y,()=>t.if(y,()=>f($)))}function h(y,$){t.forRange("i",0,d,g=>{e.subschema({keyword:"contains",dataProp:g,dataPropType:Ht.Type.Num,compositeRule:!0},y),$()})}function f(y){t.code((0,ue._)`${y}++`),a===void 0?t.if((0,ue._)`${y} >= ${i}`,()=>t.assign(l,!0).break()):(t.if((0,ue._)`${y} > ${a}`,()=>t.assign(l,!1).break()),i===1?t.assign(l,!0):t.if((0,ue._)`${y} >= ${i}`,()=>t.assign(l,!0)))}}};Vo.default=fm;var Hc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=z,r=T,n=q;e.error={message:({params:{property:c,depsCount:u,deps:d}})=>{const l=u===1?"property":"properties";return(0,t.str)`must have ${l} ${d} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:d,missingProperty:l}})=>(0,t._)`{property: ${c},
|
|
7
|
+
missingProperty: ${l},
|
|
8
8
|
depsCount: ${u},
|
|
9
|
-
deps: ${l}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){const[u,l]=o(c);i(c,u),a(c,l)}};function o({schema:c}){const u={},l={};for(const f in c){if(f==="__proto__")continue;const h=Array.isArray(c[f])?u:l;h[f]=c[f]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:f,it:h}=c;if(Object.keys(u).length===0)return;const g=l.let("missing");for(const m in u){const v=u[m];if(v.length===0)continue;const y=(0,r.propertyInData)(l,f,m,h.opts.ownProperties);c.setParams({property:m,depsCount:v.length,deps:v.join(", ")}),h.allErrors?l.if(y,()=>{for(const p of v)(0,r.checkReportMissingProp)(c,p)}):(l.if((0,t._)`${y} && (${(0,r.checkMissingProp)(c,v,g)})`),(0,r.reportMissingProp)(c,g),l.else())}}e.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:f,keyword:h,it:g}=c,m=l.name("valid");for(const v in u)(0,n.alwaysValidSchema)(g,u[v])||(l.if((0,r.propertyInData)(l,f,v,g.opts.ownProperties),()=>{const y=c.subschema({keyword:h,schemaProp:v},m);c.mergeValidEvaluated(y,m)},()=>l.var(m,!0)),c.ok(m))}e.validateSchemaDeps=a,e.default=s})(Ls);var Yn={};Object.defineProperty(Yn,"__esModule",{value:!0});const Us=K,zc=C,Lc={message:"property name must be valid",params:({params:e})=>(0,Us._)`{propertyName: ${e.propertyName}}`},Uc={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Lc,code(e){const{gen:t,schema:n,data:r,it:s}=e;if((0,zc.alwaysValidSchema)(s,n))return;const o=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),t.if((0,Us.not)(o),()=>{e.error(!0),s.allErrors||t.break()})}),e.ok(o)}};Yn.default=Uc;var Lt={};Object.defineProperty(Lt,"__esModule",{value:!0});const wt=U,ye=K,Kc=je(),bt=C,Hc={message:"must NOT have additional properties",params:({params:e})=>(0,ye._)`{additionalProperty: ${e.additionalProperty}}`},Gc={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Hc,code(e){const{gen:t,schema:n,parentSchema:r,data:s,errsCount:o,it:i}=e;if(!o)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,bt.alwaysValidSchema)(i,n))return;const u=(0,wt.allSchemaProperties)(r.properties),l=(0,wt.allSchemaProperties)(r.patternProperties);f(),e.ok((0,ye._)`${o} === ${Kc.default.errors}`);function f(){t.forIn("key",s,y=>{!u.length&&!l.length?m(y):t.if(h(y),()=>m(y))})}function h(y){let p;if(u.length>8){const _=(0,bt.schemaRefOrVal)(i,r.properties,"properties");p=(0,wt.isOwnProperty)(t,_,y)}else u.length?p=(0,ye.or)(...u.map(_=>(0,ye._)`${y} === ${_}`)):p=ye.nil;return l.length&&(p=(0,ye.or)(p,...l.map(_=>(0,ye._)`${(0,wt.usePattern)(e,_)}.test(${y})`))),(0,ye.not)(p)}function g(y){t.code((0,ye._)`delete ${s}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){g(y);return}if(n===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,bt.alwaysValidSchema)(i,n)){const p=t.name("valid");c.removeAdditional==="failing"?(v(y,p,!1),t.if((0,ye.not)(p),()=>{e.reset(),g(y)})):(v(y,p),a||t.if((0,ye.not)(p),()=>t.break()))}}function v(y,p,_){const E={keyword:"additionalProperties",dataProp:y,dataPropType:bt.Type.Str};_===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(E,p)}}};Lt.default=Gc;var Zn={};Object.defineProperty(Zn,"__esModule",{value:!0});const Jc=Dt(),Rr=U,sn=C,Ir=Lt,Wc={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:s,it:o}=e;o.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Ir.default.code(new Jc.KeywordCxt(o,Ir.default,"additionalProperties"));const i=(0,Rr.allSchemaProperties)(n);for(const f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=sn.mergeEvaluated.props(t,(0,sn.toHash)(i),o.props));const a=i.filter(f=>!(0,sn.alwaysValidSchema)(o,n[f]));if(a.length===0)return;const c=t.name("valid");for(const f of a)u(f)?l(f):(t.if((0,Rr.propertyInData)(t,s,f,o.opts.ownProperties)),l(f),o.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function u(f){return o.opts.useDefaults&&!o.compositeRule&&n[f].default!==void 0}function l(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};Zn.default=Wc;var Xn={};Object.defineProperty(Xn,"__esModule",{value:!0});const Cr=U,St=K,Ar=C,Mr=C,Bc={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:s,it:o}=e,{opts:i}=o,a=(0,Cr.allSchemaProperties)(n),c=a.filter(v=>(0,Ar.alwaysValidSchema)(o,n[v]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,l=t.name("valid");o.props!==!0&&!(o.props instanceof St.Name)&&(o.props=(0,Mr.evaluatedPropsToName)(t,o.props));const{props:f}=o;h();function h(){for(const v of a)u&&g(v),o.allErrors?m(v):(t.var(l,!0),m(v),t.if(l))}function g(v){for(const y in u)new RegExp(v).test(y)&&(0,Ar.checkStrictMode)(o,`property ${y} matches pattern ${v} (use allowMatchingProperties)`)}function m(v){t.forIn("key",r,y=>{t.if((0,St._)`${(0,Cr.usePattern)(e,v)}.test(${y})`,()=>{const p=c.includes(v);p||e.subschema({keyword:"patternProperties",schemaProp:v,dataProp:y,dataPropType:Mr.Type.Str},l),o.opts.unevaluated&&f!==!0?t.assign((0,St._)`${f}[${y}]`,!0):!p&&!o.allErrors&&t.if((0,St.not)(l),()=>t.break())})})}}};Xn.default=Bc;var er={};Object.defineProperty(er,"__esModule",{value:!0});const Qc=C,Yc={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,Qc.alwaysValidSchema)(r,n)){e.fail();return}const s=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),e.failResult(s,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};er.default=Yc;var tr={};Object.defineProperty(tr,"__esModule",{value:!0});const Zc=U,Xc={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Zc.validateUnion,error:{message:"must match a schema in anyOf"}};tr.default=Xc;var nr={};Object.defineProperty(nr,"__esModule",{value:!0});const Ot=K,eu=C,tu={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Ot._)`{passingSchemas: ${e.passing}}`},nu={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:tu,code(e){const{gen:t,schema:n,parentSchema:r,it:s}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(s.opts.discriminator&&r.discriminator)return;const o=n,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){o.forEach((l,f)=>{let h;(0,eu.alwaysValidSchema)(s,l)?t.var(c,!0):h=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,Ot._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ot._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),h&&e.mergeEvaluated(h,Ot.Name)})})}}};nr.default=nu;var rr={};Object.defineProperty(rr,"__esModule",{value:!0});const ru=C,su={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const s=t.name("valid");n.forEach((o,i)=>{if((0,ru.alwaysValidSchema)(r,o))return;const a=e.subschema({keyword:"allOf",schemaProp:i},s);e.ok(s),e.mergeEvaluated(a)})}};rr.default=su;var sr={};Object.defineProperty(sr,"__esModule",{value:!0});const At=K,Ks=C,ou={message:({params:e})=>(0,At.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,At._)`{failingKeyword: ${e.ifClause}}`},au={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ou,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,Ks.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const s=xr(r,"then"),o=xr(r,"else");if(!s&&!o)return;const i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),s&&o){const l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else s?t.if(a,u("then")):t.if((0,At.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){const l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,f){return()=>{const h=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(h,i),f?t.assign(f,(0,At._)`${l}`):e.setParams({ifClause:l})}}}};function xr(e,t){const n=e.schema[t];return n!==void 0&&!(0,Ks.alwaysValidSchema)(e,n)}sr.default=au;var or={};Object.defineProperty(or,"__esModule",{value:!0});const iu=C,cu={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,iu.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};or.default=cu;Object.defineProperty(Jn,"__esModule",{value:!0});const uu=Be,lu=Wn,du=Qe,fu=Bn,pu=Qn,hu=Ls,mu=Yn,gu=Lt,yu=Zn,$u=Xn,vu=er,_u=tr,wu=nr,bu=rr,Su=sr,Pu=or;function Eu(e=!1){const t=[vu.default,_u.default,wu.default,bu.default,Su.default,Pu.default,mu.default,gu.default,hu.default,yu.default,$u.default];return e?t.push(lu.default,fu.default):t.push(uu.default,du.default),t.push(pu.default),t}Jn.default=Eu;var ar={},ir={};Object.defineProperty(ir,"__esModule",{value:!0});const X=K,ku={message:({schemaCode:e})=>(0,X.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,X._)`{format: ${e}}`},ju={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ku,code(e,t){const{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:f}=a;if(!c.validateFormats)return;s?h():g();function h(){const m=n.scopeValue("formats",{ref:f.formats,code:c.code.formats}),v=n.const("fDef",(0,X._)`${m}[${i}]`),y=n.let("fType"),p=n.let("format");n.if((0,X._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>n.assign(y,(0,X._)`${v}.type || "string"`).assign(p,(0,X._)`${v}.validate`),()=>n.assign(y,(0,X._)`"string"`).assign(p,v)),e.fail$data((0,X.or)(_(),E()));function _(){return c.strictSchema===!1?X.nil:(0,X._)`${i} && !${p}`}function E(){const j=l.$async?(0,X._)`(${v}.async ? await ${p}(${r}) : ${p}(${r}))`:(0,X._)`${p}(${r})`,N=(0,X._)`(typeof ${p} == "function" ? ${j} : ${p}.test(${r}))`;return(0,X._)`${p} && ${p} !== true && ${y} === ${t} && !${N}`}}function g(){const m=f.formats[o];if(!m){_();return}if(m===!0)return;const[v,y,p]=E(m);v===t&&e.pass(j());function _(){if(c.strictSchema===!1){f.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function E(N){const q=N instanceof RegExp?(0,X.regexpCode)(N):c.code.formats?(0,X._)`${c.code.formats}${(0,X.getProperty)(o)}`:void 0,F=n.scopeValue("formats",{key:o,ref:N,code:q});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,X._)`${F}.validate`]:["string",N,F]}function j(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,X._)`await ${p}(${r})`}return typeof y=="function"?(0,X._)`${p}(${r})`:(0,X._)`${p}.test(${r})`}}}};ir.default=ju;Object.defineProperty(ar,"__esModule",{value:!0});const Tu=ir,Ou=[Tu.default];ar.default=Ou;var Je={};Object.defineProperty(Je,"__esModule",{value:!0});Je.contentVocabulary=Je.metadataVocabulary=void 0;Je.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Je.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(In,"__esModule",{value:!0});const Nu=Cn,Ru=Mn,Iu=Jn,Cu=ar,qr=Je,Au=[Nu.default,Ru.default,(0,Iu.default)(),Cu.default,qr.metadataVocabulary,qr.contentVocabulary];In.default=Au;var cr={},Ut={};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.DiscrError=void 0;var Dr;(function(e){e.Tag="tag",e.Mapping="mapping"})(Dr||(Ut.DiscrError=Dr={}));Object.defineProperty(cr,"__esModule",{value:!0});const ze=K,hn=Ut,Fr=de,Mu=We,xu=C,qu={message:({params:{discrError:e,tagName:t}})=>e===hn.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,ze._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},Du={keyword:"discriminator",type:"object",schemaType:"object",error:qu,code(e){const{gen:t,data:n,schema:r,parentSchema:s,it:o}=e,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",(0,ze._)`${n}${(0,ze.getProperty)(a)}`);t.if((0,ze._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:hn.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){const g=h();t.if(!1);for(const m in g)t.elseIf((0,ze._)`${u} === ${m}`),t.assign(c,f(g[m]));t.else(),e.error(!1,{discrError:hn.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(g){const m=t.name("valid"),v=e.subschema({keyword:"oneOf",schemaProp:g},m);return e.mergeEvaluated(v,ze.Name),m}function h(){var g;const m={},v=p(s);let y=!0;for(let j=0;j<i.length;j++){let N=i[j];if(N!=null&&N.$ref&&!(0,xu.schemaHasRulesButRef)(N,o.self.RULES)){const F=N.$ref;if(N=Fr.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,F),N instanceof Fr.SchemaEnv&&(N=N.schema),N===void 0)throw new Mu.default(o.opts.uriResolver,o.baseId,F)}const q=(g=N==null?void 0:N.properties)===null||g===void 0?void 0:g[a];if(typeof q!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(v||p(N)),_(q,j)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function p({required:j}){return Array.isArray(j)&&j.includes(a)}function _(j,N){if(j.const)E(j.const,N);else if(j.enum)for(const q of j.enum)E(q,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(j,N){if(typeof j!="string"||j in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[j]=N}}}};cr.default=Du;const Fu="http://json-schema.org/draft-07/schema#",Vu="http://json-schema.org/draft-07/schema#",zu="Core schema meta-schema",Lu={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:[]}},Uu=["object","boolean"],Ku={$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:"#"}},Hu={$schema:Fu,$id:Vu,title:zu,definitions:Lu,type:Uu,properties:Ku,default:!0};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=as,r=In,s=cr,o=Hu,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(o,i):o;this.addMetaSchema(m,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Dt();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=K;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var f=ht;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var h=We;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})(an,an.exports);var Gu=an.exports;const Ju=Oo(Gu),Hs={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};class Kt extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}new Ju({allErrors:!0});function Wu(e){return e.option("--log-level <level>","Log level: trace|debug|info|warn|error|fatal|silent (env APIGEN_LOG_LEVEL)").option("--log-format <format>","Log format: json|pretty (env APIGEN_LOG_FORMAT)").option("--log-file <path>","Write logs to a file instead of stderr (env APIGEN_LOG_FILE)")}function Ht(e){const t=e.opts(),n=t.logLevel??process.env.APIGEN_LOG_LEVEL??"info",r=t.logFormat??process.env.APIGEN_LOG_FORMAT,s=r==="json"||r==="pretty"?r:void 0,o=t.logFile??process.env.APIGEN_LOG_FILE;return qt({level:n,format:s,destination:o})}function Vr(e){return e.words.join("-")}function zr(e){return e.words.map(el).join("")}function Lr(e){return e.words.join("_")}function Bu(e,t={}){var h,g;const n=[e.namespace,...e.path],r=e.safe?"GET":"POST",s=((g=(h=t.http)==null?void 0:h.verb)==null?void 0:g[e.id])??r,o="/"+n.map(m=>Vr(m)).join("/"),i=n.map(m=>Lr(m)).join("_"),c=n.map(m=>Lr(m)).slice(0,-1).join("."),u=zr(n[n.length-2]??n[0]),l=zr(n[n.length-1]),f=n.map(m=>Vr(m));return{http:{verb:s,route:o},mcp:{name:i},grpc:{package:c,service:u,method:l},cli:{path:f}}}class Gs extends Error{constructor(t){const n=t.map(r=>` [${r.transport}] "${r.target}" ← ${r.ids[0]} vs ${r.ids[1]}`);super(`apigen-naming: ${t.length} projection collision(s) detected:
|
|
10
|
-
${
|
|
11
|
-
`)}`),this.name="CollisionDetectedError",this.collisions=t}}function
|
|
12
|
-
`)&&
|
|
13
|
-
`)&&
|
|
9
|
+
deps: ${d}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){const[u,d]=s(c);i(c,u),a(c,d)}};function s({schema:c}){const u={},d={};for(const l in c){if(l==="__proto__")continue;const p=Array.isArray(c[l])?u:d;p[l]=c[l]}return[u,d]}function i(c,u=c.schema){const{gen:d,data:l,it:p}=c;if(Object.keys(u).length===0)return;const h=d.let("missing");for(const f in u){const y=u[f];if(y.length===0)continue;const $=(0,n.propertyInData)(d,l,f,p.opts.ownProperties);c.setParams({property:f,depsCount:y.length,deps:y.join(", ")}),p.allErrors?d.if($,()=>{for(const g of y)(0,n.checkReportMissingProp)(c,g)}):(d.if((0,t._)`${$} && (${(0,n.checkMissingProp)(c,y,h)})`),(0,n.reportMissingProp)(c,h),d.else())}}e.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:d,data:l,keyword:p,it:h}=c,f=d.name("valid");for(const y in u)(0,r.alwaysValidSchema)(h,u[y])||(d.if((0,n.propertyInData)(d,l,y,h.opts.ownProperties),()=>{const $=c.subschema({keyword:p,schemaProp:y},f);c.mergeValidEvaluated($,f)},()=>d.var(f,!0)),c.ok(f))}e.validateSchemaDeps=a,e.default=o})(Hc);var Go={};Object.defineProperty(Go,"__esModule",{value:!0});const Jc=z,pm=T,mm={message:"property name must be valid",params:({params:e})=>(0,Jc._)`{propertyName: ${e.propertyName}}`},hm={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:mm,code(e){const{gen:t,schema:r,data:n,it:o}=e;if((0,pm.alwaysValidSchema)(o,r))return;const s=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,Jc.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Go.default=hm;var Nr={};Object.defineProperty(Nr,"__esModule",{value:!0});const Jt=q,le=z,ym=ge,Kt=T,gm={message:"must NOT have additional properties",params:({params:e})=>(0,le._)`{additionalProperty: ${e.additionalProperty}}`},$m={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gm,code(e){const{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Kt.alwaysValidSchema)(i,r))return;const u=(0,Jt.allSchemaProperties)(n.properties),d=(0,Jt.allSchemaProperties)(n.patternProperties);l(),e.ok((0,le._)`${s} === ${ym.default.errors}`);function l(){t.forIn("key",o,$=>{!u.length&&!d.length?f($):t.if(p($),()=>f($))})}function p($){let g;if(u.length>8){const w=(0,Kt.schemaRefOrVal)(i,n.properties,"properties");g=(0,Jt.isOwnProperty)(t,w,$)}else u.length?g=(0,le.or)(...u.map(w=>(0,le._)`${$} === ${w}`)):g=le.nil;return d.length&&(g=(0,le.or)(g,...d.map(w=>(0,le._)`${(0,Jt.usePattern)(e,w)}.test(${$})`))),(0,le.not)(g)}function h($){t.code((0,le._)`delete ${o}[${$}]`)}function f($){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h($);return}if(r===!1){e.setParams({additionalProperty:$}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Kt.alwaysValidSchema)(i,r)){const g=t.name("valid");c.removeAdditional==="failing"?(y($,g,!1),t.if((0,le.not)(g),()=>{e.reset(),h($)})):(y($,g),a||t.if((0,le.not)(g),()=>t.break()))}}function y($,g,w){const _={keyword:"additionalProperties",dataProp:$,dataPropType:Kt.Type.Str};w===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(_,g)}}};Nr.default=$m;var Ho={};Object.defineProperty(Ho,"__esModule",{value:!0});const vm=pe,hi=q,Xr=T,yi=Nr,wm={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&yi.default.code(new vm.KeywordCxt(s,yi.default,"additionalProperties"));const i=(0,hi.allSchemaProperties)(r);for(const l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Xr.mergeEvaluated.props(t,(0,Xr.toHash)(i),s.props));const a=i.filter(l=>!(0,Xr.alwaysValidSchema)(s,r[l]));if(a.length===0)return;const c=t.name("valid");for(const l of a)u(l)?d(l):(t.if((0,hi.propertyInData)(t,o,l,s.opts.ownProperties)),d(l),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(l),e.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){e.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};Ho.default=wm;var Jo={};Object.defineProperty(Jo,"__esModule",{value:!0});const gi=q,Bt=z,$i=T,vi=T,_m={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,gi.allSchemaProperties)(r),c=a.filter(y=>(0,$i.alwaysValidSchema)(s,r[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=t.name("valid");s.props!==!0&&!(s.props instanceof Bt.Name)&&(s.props=(0,vi.evaluatedPropsToName)(t,s.props));const{props:l}=s;p();function p(){for(const y of a)u&&h(y),s.allErrors?f(y):(t.var(d,!0),f(y),t.if(d))}function h(y){for(const $ in u)new RegExp(y).test($)&&(0,$i.checkStrictMode)(s,`property ${$} matches pattern ${y} (use allowMatchingProperties)`)}function f(y){t.forIn("key",n,$=>{t.if((0,Bt._)`${(0,gi.usePattern)(e,y)}.test(${$})`,()=>{const g=c.includes(y);g||e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:$,dataPropType:vi.Type.Str},d),s.opts.unevaluated&&l!==!0?t.assign((0,Bt._)`${l}[${$}]`,!0):!g&&!s.allErrors&&t.if((0,Bt.not)(d),()=>t.break())})})}}};Jo.default=_m;var Ko={};Object.defineProperty(Ko,"__esModule",{value:!0});const bm=T,Sm={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:n}=e;if((0,bm.alwaysValidSchema)(n,r)){e.fail();return}const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ko.default=Sm;var Bo={};Object.defineProperty(Bo,"__esModule",{value:!0});const Em=q,Nm={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Em.validateUnion,error:{message:"must match a schema in anyOf"}};Bo.default=Nm;var Wo={};Object.defineProperty(Wo,"__esModule",{value:!0});const ar=z,Om=T,jm={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ar._)`{passingSchemas: ${e.passing}}`},km={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:jm,code(e){const{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;const s=r,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((d,l)=>{let p;(0,Om.alwaysValidSchema)(o,d)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&t.if((0,ar._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ar._)`[${a}, ${l}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,l),p&&e.mergeEvaluated(p,ar.Name)})})}}};Wo.default=km;var Yo={};Object.defineProperty(Yo,"__esModule",{value:!0});const Pm=T,Am={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const o=t.name("valid");r.forEach((s,i)=>{if((0,Pm.alwaysValidSchema)(n,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Yo.default=Am;var Zo={};Object.defineProperty(Zo,"__esModule",{value:!0});const gr=z,Kc=T,Tm={message:({params:e})=>(0,gr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,gr._)`{failingKeyword: ${e.ifClause}}`},Im={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Tm,code(e){const{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Kc.checkStrictMode)(n,'"if" without "then" and "else" is ignored');const o=wi(n,"then"),s=wi(n,"else");if(!o&&!s)return;const i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){const d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,u("then",d),u("else",d))}else o?t.if(a,u("then")):t.if((0,gr.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){const d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function u(d,l){return()=>{const p=e.subschema({keyword:d},a);t.assign(i,a),e.mergeValidEvaluated(p,i),l?t.assign(l,(0,gr._)`${d}`):e.setParams({ifClause:d})}}}};function wi(e,t){const r=e.schema[t];return r!==void 0&&!(0,Kc.alwaysValidSchema)(e,r)}Zo.default=Im;var Qo={};Object.defineProperty(Qo,"__esModule",{value:!0});const Cm=T,Dm={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,Cm.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Qo.default=Dm;Object.defineProperty(Lo,"__esModule",{value:!0});const Rm=gt,xm=zo,Mm=$t,Fm=qo,Um=Vo,Lm=Hc,zm=Go,qm=Nr,Vm=Ho,Gm=Jo,Hm=Ko,Jm=Bo,Km=Wo,Bm=Yo,Wm=Zo,Ym=Qo;function Zm(e=!1){const t=[Hm.default,Jm.default,Km.default,Bm.default,Wm.default,Ym.default,zm.default,qm.default,Lm.default,Vm.default,Gm.default];return e?t.push(xm.default,Fm.default):t.push(Rm.default,Mm.default),t.push(Um.default),t}Lo.default=Zm;var Xo={},es={};Object.defineProperty(es,"__esModule",{value:!0});const Y=z,Qm={message:({schemaCode:e})=>(0,Y.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Y._)`{format: ${e}}`},Xm={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Qm,code(e,t){const{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?p():h();function p(){const f=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),y=r.const("fDef",(0,Y._)`${f}[${i}]`),$=r.let("fType"),g=r.let("format");r.if((0,Y._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign($,(0,Y._)`${y}.type || "string"`).assign(g,(0,Y._)`${y}.validate`),()=>r.assign($,(0,Y._)`"string"`).assign(g,y)),e.fail$data((0,Y.or)(w(),_()));function w(){return c.strictSchema===!1?Y.nil:(0,Y._)`${i} && !${g}`}function _(){const E=d.$async?(0,Y._)`(${y}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Y._)`${g}(${n})`,j=(0,Y._)`(typeof ${g} == "function" ? ${E} : ${g}.test(${n}))`;return(0,Y._)`${g} && ${g} !== true && ${$} === ${t} && !${j}`}}function h(){const f=l.formats[s];if(!f){w();return}if(f===!0)return;const[y,$,g]=_(f);y===t&&e.pass(E());function w(){if(c.strictSchema===!1){l.logger.warn(j());return}throw new Error(j());function j(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(j){const I=j instanceof RegExp?(0,Y.regexpCode)(j):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:j,code:I});return typeof j=="object"&&!(j instanceof RegExp)?[j.type||"string",j.validate,(0,Y._)`${x}.validate`]:["string",j,x]}function E(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Y._)`await ${g}(${n})`}return typeof $=="function"?(0,Y._)`${g}(${n})`:(0,Y._)`${g}.test(${n})`}}}};es.default=Xm;Object.defineProperty(Xo,"__esModule",{value:!0});const eh=es,th=[eh.default];Xo.default=th;var ht={};Object.defineProperty(ht,"__esModule",{value:!0});ht.contentVocabulary=ht.metadataVocabulary=void 0;ht.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ht.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(No,"__esModule",{value:!0});const rh=Oo,nh=ko,oh=Lo,sh=Xo,_i=ht,ih=[rh.default,nh.default,(0,oh.default)(),sh.default,_i.metadataVocabulary,_i.contentVocabulary];No.default=ih;var ts={},Or={};Object.defineProperty(Or,"__esModule",{value:!0});Or.DiscrError=void 0;var bi;(function(e){e.Tag="tag",e.Mapping="mapping"})(bi||(Or.DiscrError=bi={}));Object.defineProperty(ts,"__esModule",{value:!0});const Qe=z,Nn=Or,Si=ce,ah=yt,ch=T,uh={message:({params:{discrError:e,tagName:t}})=>e===Nn.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Qe._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},dh={keyword:"discriminator",type:"object",schemaType:"object",error:uh,code(e){const{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",(0,Qe._)`${r}${(0,Qe.getProperty)(a)}`);t.if((0,Qe._)`typeof ${u} == "string"`,()=>d(),()=>e.error(!1,{discrError:Nn.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function d(){const h=p();t.if(!1);for(const f in h)t.elseIf((0,Qe._)`${u} === ${f}`),t.assign(c,l(h[f]));t.else(),e.error(!1,{discrError:Nn.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function l(h){const f=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:h},f);return e.mergeEvaluated(y,Qe.Name),f}function p(){var h;const f={},y=g(o);let $=!0;for(let E=0;E<i.length;E++){let j=i[E];if(j!=null&&j.$ref&&!(0,ch.schemaHasRulesButRef)(j,s.self.RULES)){const x=j.$ref;if(j=Si.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),j instanceof Si.SchemaEnv&&(j=j.schema),j===void 0)throw new ah.default(s.opts.uriResolver,s.baseId,x)}const I=(h=j==null?void 0:j.properties)===null||h===void 0?void 0:h[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(y||g(j)),w(I,E)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return f;function g({required:E}){return Array.isArray(E)&&E.includes(a)}function w(E,j){if(E.const)_(E.const,j);else if(E.enum)for(const I of E.enum)_(I,j);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(E,j){if(typeof E!="string"||E in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[E]=j}}}};ts.default=dh;const lh="http://json-schema.org/draft-07/schema#",fh="http://json-schema.org/draft-07/schema#",ph="Core schema meta-schema",mh={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:[]}},hh=["object","boolean"],yh={$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:"#"}},gh={$schema:lh,$id:fh,title:ph,definitions:mh,type:hh,properties:yh,default:!0};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=Ja,n=No,o=ts,s=gh,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(f,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=pe;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var d=z;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return d._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return d.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return d.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return d.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return d.CodeGen}});var l=xt;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return l.default}});var p=yt;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})($n,$n.exports);var Bc=$n.exports;const Ft=Ha(Bc);var On={exports:{}},Wc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(D,U){return{validate:D,compare:U}}e.fullFormats={date:t(s,i),time:t(c,u),"date-time":t(l,p),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"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|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\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:V,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:g,int32:{type:"number",validate:E},int64:{type:"number",validate:j},float:{type:"number",validate:I},double:{type:"number",validate:I},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,i),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"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,p),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 r(D){return D%4===0&&(D%100!==0||D%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(D){const U=n.exec(D);if(!U)return!1;const H=+U[1],J=+U[2],X=+U[3];return J>=1&&J<=12&&X>=1&&X<=(J===2&&r(H)?29:o[J])}function i(D,U){if(D&&U)return D>U?1:D<U?-1:0}const a=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function c(D,U){const H=a.exec(D);if(!H)return!1;const J=+H[1],X=+H[2],se=+H[3],me=H[5];return(J<=23&&X<=59&&se<=59||J===23&&X===59&&se===60)&&(!U||me!=="")}function u(D,U){if(!(D&&U))return;const H=a.exec(D),J=a.exec(U);if(H&&J)return D=H[1]+H[2]+H[3]+(H[4]||""),U=J[1]+J[2]+J[3]+(J[4]||""),D>U?1:D<U?-1:0}const d=/t|\s/i;function l(D){const U=D.split(d);return U.length===2&&s(U[0])&&c(U[1],!0)}function p(D,U){if(!(D&&U))return;const[H,J]=D.split(d),[X,se]=U.split(d),me=i(H,X);if(me!==void 0)return me||u(J,se)}const h=/\/|:/,f=/^(?:[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 y(D){return h.test(D)&&f.test(D)}const $=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(D){return $.lastIndex=0,$.test(D)}const w=-2147483648,_=2**31-1;function E(D){return Number.isInteger(D)&&D<=_&&D>=w}function j(D){return Number.isInteger(D)}function I(){return!0}const x=/[^\\]\\Z/;function V(D){if(x.test(D))return!1;try{return new RegExp(D),!0}catch{return!1}}})(Wc);var Yc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Bc,r=z,n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:a,schemaCode:c})=>r.str`should be ${o[a].okStr} ${c}`,params:({keyword:a,schemaCode:c})=>r._`{comparison: ${o[a].okStr}, limit: ${c}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(a){const{gen:c,data:u,schemaCode:d,keyword:l,it:p}=a,{opts:h,self:f}=p;if(!h.validateFormats)return;const y=new t.KeywordCxt(p,f.RULES.all.format.definition,"format");y.$data?$():g();function $(){const _=c.scopeValue("formats",{ref:f.formats,code:h.code.formats}),E=c.const("fmt",r._`${_}[${y.schemaCode}]`);a.fail$data(r.or(r._`typeof ${E} != "object"`,r._`${E} instanceof RegExp`,r._`typeof ${E}.compare != "function"`,w(E)))}function g(){const _=y.schema,E=f.formats[_];if(!E||E===!0)return;if(typeof E!="object"||E instanceof RegExp||typeof E.compare!="function")throw new Error(`"${l}": format "${_}" does not define "compare" function`);const j=c.scopeValue("formats",{key:_,ref:E,code:h.code.formats?r._`${h.code.formats}${r.getProperty(_)}`:void 0});a.fail$data(w(j))}function w(_){return r._`${_}.compare(${u}, ${d}) ${o[l].fail} 0`}},dependencies:["format"]};const i=a=>(a.addKeyword(e.formatLimitDefinition),a);e.default=i})(Yc);(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Wc,n=Yc,o=z,s=new o.Name("fullFormats"),i=new o.Name("fastFormats"),a=(u,d={keywords:!0})=>{if(Array.isArray(d))return c(u,d,r.fullFormats,s),u;const[l,p]=d.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,s],h=d.formats||r.formatNames;return c(u,h,l,p),d.keywords&&n.default(u),u};a.get=(u,d="full")=>{const p=(d==="fast"?r.fastFormats:r.fullFormats)[u];if(!p)throw new Error(`Unknown format "${u}"`);return p};function c(u,d,l,p){var h,f;(h=(f=u.opts.code).formats)!==null&&h!==void 0||(f.formats=o._`require("ajv-formats/dist/formats").${p}`);for(const y of d)u.addFormat(y,l[y])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a})(On,On.exports);var $h=On.exports;const Ut=Ha($h),jn="$apigen";let Ei=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function vh(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new Ei(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const n of t.values())if(n.matches(r))return n},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),n={register(){throw new Ei("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of r.values())if(s.matches(o))return s},get(o){return r.get(o)},ids(){return[...r.keys()]},freeze(){return n}};return n}}}const rs="x-apigen-logical",ns="x-apigen-codec",kn="x-apigen-ctor",Pn="x-apigen-tojson",wh="0.1.0";function Ni(e,t){return{registry:e,resolve:r=>{throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Xe(e,t,r){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return Xe(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Zc(e,s,t);return Xe(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return en(e,t,r);const a=t.items;if(!a)return e.map(u=>Fe(u));const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?Fe(u):Xe(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>Xe(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return en(e,t,r);const a=t.properties;if(!a)return Fe(e);const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=Xe(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?en(e,t,r):Fe(e)}function et(e,t,r){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return et(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Zc(e,s,t);return et(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?u:et(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>et(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=et(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?_h(e,r):e}function Zc(e,t,r,n){const o=r.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function en(e,t,r){for(const n of r.registry.ids()){const o=r.registry.get(n);if(o)try{const s=o.encode(e,o.schema,r);return{[jn]:n,v:s}}catch{}}return Fe(e)}function _h(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&jn in e){const r=e,n=r[jn],o=t.registry.get(n);if(o)return o.decode(r.v,o.schema,t)}return e}function Fe(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Fe);if(typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))n!==void 0&&(t[r]=Fe(n));return t}return null}function bh(e){return{encode(t,r,n){const o=Ni(e,n);return Xe(t,r,o)},decode(t,r,n){const o=Ni(e,n);return et(t,r,o)}}}const os={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,r){return e.toISOString()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${r.path}", got ${typeof e}`);return new Date(String(e))}if(r.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${r.path}": ${JSON.stringify(e)}`);return new Date(e)}},ss={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,r){return String(e)},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${r.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(r.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},is={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,r){return e},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e)}if(r.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${r.path}" is not a valid decimal string`);return e}},as={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,r){return Buffer.from(e).toString("base64")},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${r.path}", got ${typeof e}`);return new Uint8Array(0)}if(r.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${r.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},Sh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,cs={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,r){return e.toLowerCase()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e).toLowerCase()}if(r.mode==="strict"&&!Sh.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},An="NaN",Tn="Infinity",In="-Infinity",Eh=new Set([An,Tn,In]),us={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,r){return Number.isNaN(e)?An:e===1/0?Tn:e===-1/0?In:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===An)return NaN;if(e===Tn)return 1/0;if(e===In)return-1/0;const n=Number(e);if(!Number.isNaN(n))return n}if(r.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${r.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Eh].join(", ")}.`);return NaN}},Nh=[os,ss,is,as,cs,us];function Oh(e,t={}){for(const r of Nh)e.register(r,{override:t.override??!1})}os.id,ss.id,is.id,as.id,cs.id,us.id;const Qc=vh();Oh(Qc);bh(Qc.freeze());const jh={"decimal.js":"Decimal"};function kh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(jh).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${kh(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ph(e={}){const t=e.level??"info",r=typeof e.destination=="string"&&e.destination.length>0,n=!r&&!!process.stderr.isTTY,o=e.format??(n?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!r,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...r?{destination:e.destination,mkdir:!0}:{destination:2}}},te(s);const i=r?te.destination({dest:e.destination,mkdir:!0,sync:!0}):te.destination(2);return te(s,i)}const Oi=new Set(["default","module.exports","__esModule"]);function Xc(e){const t={},r=(n,o)=>{for(const[s,i]of Object.entries(n))if(typeof i=="function"){!Oi.has(s)&&!(s in t)&&(t[s]=i);const a=i.name;a&&!(a in t)&&(t[a]=i)}else i&&typeof i=="object"&&o<2&&Oi.has(s)&&r(i,o+1)};return r(e,0),t}const ds=new Ft({allErrors:!0});Ut(ds);for(const e of[rs,ns,kn,Pn,"discriminator"])ds.addKeyword({keyword:e,valid:!0});ds.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);let ke=class extends Error{constructor(t,r){super(r),this.name="UnionCodecError",this.code=t}};function tn(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t;if(typeof r.propertyName!="string")return;const n=r.mapping;if(!(n===null||typeof n!="object"||Array.isArray(n)))return{propertyName:r.propertyName,mapping:n}}function eu(e,t){const r=e[ns];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function Ah(e,t,r){const n=eu(t,r);return n?n.encode(e,t,r):e}function Th(e,t,r){const n=eu(t,r);return n?n.decode(e,t,r):e}function Ih(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[rs]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:tn(n)!==void 0},encode(n,o,s){const i=tn(o);if(!i)throw new ke("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=n[a];if(u==null)throw new ke("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const d=String(u),l=c[d];if(!l)throw new ke("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${d}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(l);return Ah(n,p,{...s,path:`${s.path}[${d}]`})},decode(n,o,s){if(n===null||typeof n!="object"||Array.isArray(n)){let f;throw n===null?f="null":Array.isArray(n)?f="array":f=typeof n,new ke("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${f}.`)}const i=n,a=tn(o);if(!a)throw new ke("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,d=i[c];if(d==null)throw new ke("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const l=String(d),p=u[l];if(!p)throw new ke("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Th(n,h,{...s,path:`${s.path}[${l}]`})}}}const Ch="x-apigen-instances";let Wt=class extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}};function ji(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Dh(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function ki(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function Rh(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function xh(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[rs]==="nominal"?!0:o[ns]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Wt("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=ji(s),c=typeof s[Pn]=="string"?s[Pn]:"toJSON",u=o[c];if(typeof u=="function"){const f=u.call(o);if(f!==null&&typeof f=="object"&&!Array.isArray(f)){const y={};for(const[$,g]of Object.entries(f))y[$]=ki(g,a[$],{...i,path:`${i.path}/${$}`});return y}return f}const d={},l=Object.keys(a),p=o,h=l.length>0?l:Object.keys(p);for(const f of h){const y=p[f];y!==void 0&&(d[f]=ki(y,a[f],{...i,path:`${i.path}/${f}`}))}return d}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let d;throw o===null?d="null":Array.isArray(o)?d="array":d=typeof o,new Wt("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${d}.`)}const a=o;for(const d of Dh(s))if(!(d in a))throw new Wt("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${d}" missing on the wire at "${i.path}".`);if(s[Ch]===!1)throw new Wt("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=ji(s),u={};for(const[d,l]of Object.entries(a))u[d]=Rh(l,c[d],{...i,path:`${i.path}/${d}`});if(n){const d=typeof s[kn]=="string"?s[kn]:"fromJSON",l=n[d];if(typeof l=="function")return l.call(n,u);const p=n;return new p(u)}return u}}}const Mh=[os,ss,is,as,cs,us],Fh={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Pi=xh({id:"ts.NominalSentinel",schema:Fh}),Uh={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Ai=Ih({id:"ts.UnionSentinel",schema:Uh});function Lh(){const e=[...Mh.map(t=>[t.id,t]),[Pi.id,Pi],[Ai.id,Ai]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:wh,codecs:Lh()});function zh(e){return e.option("--log-level <level>","Log level: trace|debug|info|warn|error|fatal|silent (env APIGEN_LOG_LEVEL)").option("--log-format <format>","Log format: json|pretty (env APIGEN_LOG_FORMAT)").option("--log-file <path>","Write logs to a file instead of stderr (env APIGEN_LOG_FILE)")}function jr(e){const t=e.opts(),r=t.logLevel??process.env.APIGEN_LOG_LEVEL??"info",n=t.logFormat??process.env.APIGEN_LOG_FORMAT,o=n==="json"||n==="pretty"?n:void 0,s=t.logFile??process.env.APIGEN_LOG_FILE;return Ph({level:r,format:o,destination:s})}const tu=Symbol.for("adhd.apigen.extraction-session");function ru(e,t){const r=[...e.getImportDeclarations().map(n=>n.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(n=>n.getModuleSpecifierSourceFile())];for(const n of r){if(!n)continue;const o=n.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{n.refreshFromFileSystemSync()}catch{}ru(n,t)}}}function nu(e){try{const t=qa.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const cr=new Map,Ti=new Map;function qh(e,t,r){const n=t??"",o=cr.get(n);let s=r;if(o&&o.fileVersions.size>0){const c=[r],u=[...o.fileVersions.entries()].sort(([d],[l])=>d.localeCompare(l));for(const[d,l]of u)d!==e&&c.push(`${d}:${l}`);s=c.join("|")}const i=`${e}\0${t??""}`;let a=Ti.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},Ti.set(i,a)),a.schemas}function ou(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let r=!1;return{[tu]:!0,stats:e,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(n){if(r)throw new Error("apigen-core: ExtractionSession used after dispose()");const o=n??"",s=n?this.statVersion(n):"";let i=cr.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:n?new Qs.Project({tsConfigFilePath:n,skipAddingFilesFromTsConfig:!0}):new Qs.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},cr.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(n,o){const s=this.projectFor(o),i=cr.get(o??""),a=this.statVersion(n);let c=s.getSourceFile(n);if(c===void 0?c=s.addSourceFileAtPath(n):i&&i.fileVersions.get(n)!==a&&c.refreshFromFileSystemSync(),i==null||i.fileVersions.set(n,a),i){const u=new Set([n]);ru(c,u);for(const d of u)d!==n&&i.fileVersions.set(d,this.statVersion(d))}return c},statVersion(n){let o=t.get(n);return o===void 0&&(o=nu(n),t.set(n,o)),o},dispose(){r=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function Vh(e){const t=e;if(t[tu]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const $r="x-apigen-logical";function Ii(e,t){const r=new Set,n=[e];for(;n.length>0;){const o=n.pop();if(!o||r.has(o))continue;r.add(o);const s=o.$ref;if(typeof s=="string"){if(t){const l=t[s];if(!l){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${p}`)}n.push(l)}continue}const i=o.oneOf;if(Array.isArray(i))for(const l of i)typeof l=="object"&&l!==null&&n.push(l);const a=o.properties;if(a)for(const l of Object.values(a))n.push(l);const c=o.items;if(Array.isArray(c))for(const l of c)typeof l=="object"&&l!==null&&n.push(l);else typeof c=="object"&&c!==null&&n.push(c);const u=o.additionalProperties;typeof u=="object"&&u!==null&&n.push(u);const d=o.propertyNames;typeof d=="object"&&d!==null&&n.push(d)}}const Ci=new Set(["string","number","boolean","integer"]);function Gh(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:r}=t;return typeof r=="string"?Ci.has(r):Array.isArray(r)?r.every(n=>Ci.has(n)||n==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(n=>["string","number","boolean"].includes(typeof n)):!1}function su(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Gh)}function Hh(e){const t={},r=n=>{for(const o of["definitions","$defs"]){const s=n[o];if(s)for(const[i,a]of Object.entries(s)){const c=i.startsWith("#/")?i:`#/${o}/${i}`;t[c]=a}}};for(const n of Object.values(e.schemas))r(n.input),r(n.output);if(Object.keys(t).length!==0)for(const[n,o]of Object.entries(e.schemas))try{Ii(o.input,t),Ii(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${n}": ${s.message}`)}}function Jh(e,t){const r=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&r.push(`Field(s) ${e.map(n=>`"${n}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),r.join(" ")}function Kh(e,t,r){Hh(e);const n={};for(const[o,s]of Object.entries(e.schemas)){const i=(r==null?void 0:r[o])??{},a=s.input.properties??{},c=s.input.required??[],u={},d=[];for(const y of t)if(y.envelope&&i[y.id]!==!1)for(const[$,g]of Object.entries(y.envelope))u[$]=g,d.includes($)||d.push($);const l={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},p=s.safe===!0||su(s.input),h=s.input.definitions,f=s.input.$defs;n[o]={input:{type:"object",properties:{...u,data:l},required:[...d,...c.length>0?["data"]:[]],additionalProperties:!1,description:Jh(Object.keys(u),Object.keys(a).length>0),...h?{definitions:h}:{},...f?{$defs:f}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":p}}return n}const Bh=8;function Wh(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let Yh=0;async function Zh(e,t,r,n){const o=`__ApigenProbe_${process.pid}_${Yh++}`;let s;try{s=t.addTypeAlias({name:o,type:r});const i=s.getType();return await n(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function iu(e,t,r){if(r>Bh)return{};if(e.isString()||e.isStringLiteral())return e.isStringLiteral()?{type:"string",enum:[e.getLiteralValue()]}:{type:"string"};if(e.isNumber()||e.isNumberLiteral())return e.isNumberLiteral()?{type:"number",enum:[e.getLiteralValue()]}:{type:"number"};if(e.isBoolean())return{type:"boolean"};if(e.isBooleanLiteral())return{type:"boolean"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const n=e.getUnionTypes();if(n.every(i=>i.isStringLiteral())&&n.length>0)return{type:"string",enum:n.map(i=>i.getLiteralValue())};if(n.every(i=>i.isNumberLiteral())&&n.length>0)return{type:"number",enum:n.map(i=>i.getLiteralValue())};const o=await Promise.all(n.map(i=>iu(i,t,r+1))),s=ls(o);return{oneOf:o,...s?{discriminator:s}:{},[$r]:"union"}}if(e.isArray()){const n=e.getArrayElementType();return{type:"array",items:n?await t(n.getText()):{}}}if(e.isTuple()){const n=e.getTupleElements(),o=await Promise.all(n.map(s=>t(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const n=e.getStringIndexType(),o=e.getNumberIndexType(),s=n??o,i=e.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await t(s.getText())};const a={};for(const c of i){const u=c.getName(),d=c.getDeclarations()[0];let l;if(d)try{l=c.getTypeAtLocation(d)}catch{l=void 0}if(l!==void 0&&l.getCallSignatures().length>0)continue;const p=l!==void 0?Wh(l,d):void 0;a[u]=p!==void 0?await t(p):{}}return Object.keys(a).length>0?{type:"object",properties:a}:{}}return{}}function ls(e){if(e.length<2)return;const t=[];for(const n of e){if(n.type!=="object")return;const o=n.properties;if(!o||typeof o!="object")return;t.push(o)}const r=Object.keys(t[0]).filter(n=>t.every(o=>Object.prototype.hasOwnProperty.call(o,n)));for(const n of r){const o=[];let s=!0;for(const a of t){const c=a[n],u=c&&(c.type==="string"||c.type==="number"),d=c==null?void 0:c.enum;if(!u||!Array.isArray(d)||d.length!==1){s=!1;break}o.push(String(d[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:n,mapping:i}}}function ur(e,t,r){if(t>6)return{};const n=e.trim();if(n==="string")return{type:"string"};if(n==="number")return{type:"number"};if(n==="boolean")return{type:"boolean"};if(n==="null")return{type:"null"};if(n==="undefined")return{type:"null"};const o=Cn[n];if(o!==void 0)return o;if(r!=null&&r.size){const s=r.get(n);if(s!==void 0){const i=Cn[s];if(i!==void 0)return i}}if(n.endsWith("[]"))return{type:"array",items:ur(n.slice(0,-2),t+1,r)};if(n.includes("|")){const s=n.split("|").map(c=>c.trim());if(s.every(c=>c.startsWith("'")))return{type:"string",enum:s.map(c=>c.replace(/'/g,""))};const i=s.map(c=>ur(c,t+1,r)),a=ls(i);return{oneOf:i,...a?{discriminator:a}:{},[$r]:"union"}}if(n.startsWith("{")&&n.endsWith("}")){const s=n.slice(1,-1).trim(),i={};for(const a of s.split(";").filter(Boolean)){const[c,u]=a.split(":").map(d=>d.trim());c&&u&&(i[c.replace("?","")]=ur(u,t+1,r))}return{type:"object",properties:i}}return{}}function au(e){const t=[];let r=0,n=0;for(let s=0;s<e.length;s++){const i=e[s];i==="<"||i==="["||i==="{"||i==="("?r++:i===">"||i==="]"||i==="}"||i===")"?r--:i===","&&r===0&&(t.push(e.slice(n,s).trim()),n=s+1)}const o=e.slice(n).trim();return o.length>0&&t.push(o),t}function Qh(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function Xh(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function ey(e){let t=e.trim();if(t.startsWith("readonly ")&&(t=t.slice(9).trim()),!t.startsWith("[")||!t.endsWith("]"))return;const r=t.slice(1,-1).trim();if(r.length!==0)return au(r)}async function ty(e,t){const r=e.trim(),n=Qh(r);if(n!==void 0){const i=au(n);if(i.length===2){const[a,c]=await Promise.all([t(i[0]),t(i[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=Xh(r);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=ey(r);if(s!==void 0){const i=await Promise.all(s.map(a=>t(a)));return{type:"array",items:i,minItems:i.length,maxItems:i.length}}}const cu={"decimal.js":"Decimal"},Cn={Date:{type:"string",format:"date-time"},bigint:{type:"string",format:"int64"},Uint8Array:{type:"string",format:"byte"},Buffer:{type:"string",format:"byte"},URL:{type:"string",format:"uri"},RegExp:{type:"string",format:"regex"},Decimal:{type:"string",format:"decimal"}},Di={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Ri(e){var t;const r=new Map;for(const n of e.getImportDeclarations()){const o=n.getModuleSpecifierValue(),s=cu[o];if(!s)continue;const i=n.getDefaultImport();if(i){const a=i.getText();a!==s&&r.set(a,s)}for(const a of n.getNamedImports()){const c=((t=a.getAliasNode())==null?void 0:t.getText())??a.getName();c!==s&&r.set(c,s)}}return r}function ry(e,t){return r=>{r.addNodeParser({supportsNode(n){var o,s,i;if(n.kind!==t)return!1;const a=((o=n.typeName)==null?void 0:o.escapedText)??((i=(s=n.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return a!==void 0&&Object.prototype.hasOwnProperty.call(Di,a)},createType(n){var o,s,i;const a=((o=n.typeName)==null?void 0:o.escapedText)??((i=(s=n.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return new Me.AnnotatedType(new Me.StringType,{format:Di[a]},!1)}}),r.addNodeParser({supportsNode(n){return n.kind===e},createType(){return new Me.AnnotatedType(new Me.StringType,{format:"int64"},!1)}})}}let bt;function ny(){if(bt)return bt;try{const e=io.dirname(require.resolve("ts-json-schema-generator/package.json"));bt=require(require.resolve("typescript",{paths:[e]}))}catch{bt=require("typescript")}return bt}const Se=new Map;function oy(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function sy(e){const t=Se.get(e);return t&&(Se.delete(e),Se.set(e,t)),t}function iy(e,t){const r=oy();if(r!==0)for(Se.delete(e),Se.set(e,t);Se.size>r;){const n=Se.keys().next().value;Se.delete(n)}}function ay(e,t){return`${e}\0${t??""}`}const cy=new Set(["zod",/^zod\/./]);function uy(e){for(const t of e.getImportDeclarations()){const r=t.getModuleSpecifierValue();for(const n of cy)if(typeof n=="string"){if(r===n)return!0}else if(n.test(r))return!0}return!1}function dy(e){for(const t of["$defs","definitions"]){const r=e[t];if(!r||typeof r!="object")continue;const n=Object.keys(r);if(n.length===0)continue;const o=new Set(n.filter(s=>/zod/i.test(s)));for(const[s,i]of Object.entries(r)){if(o.has(s)||typeof i!="object"||i===null)continue;const a=i,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const u of o)if(c.includes(u)){o.add(s);break}}}for(const s of o)delete r[s]}Dn(e)}function Dn(e,t){if(!e||typeof e!="object")return;const r=t??new WeakSet;if(!r.has(e)){r.add(e);for(const n of Object.keys(e))if(n==="$ref"&&typeof e[n]=="string"){const o=e[n];/zod/i.test(o)&&delete e[n]}for(const[,n]of Object.entries(e))if(typeof n=="object"&&n!==null)if(Array.isArray(n))for(const o of n)typeof o=="object"&&o!==null&&Dn(o,r);else Dn(n,r)}}function ly(e){const t=new Set;for(const n of["$defs","definitions"]){const o=e[n];if(o&&typeof o=="object")for(const s of Object.keys(o))t.add(s)}const r=Rn(e,t);if(r.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${r.length} unresolvable $ref(s): ${r.join(", ")}. This usually means zod-internal definitions were stripped but $ref references to them remain. Check the source file's imports or the ts-json-schema-generator output.`)}function Rn(e,t){if(!e||typeof e!="object")return[];const r=[];for(const[n,o]of Object.entries(e))if(n==="$ref"&&typeof o=="string"){const s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!t.has(s[1])&&r.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const s of o)typeof s=="object"&&s!==null&&r.push(...Rn(s,t));else r.push(...Rn(o,t));return r}function fy(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const r=t,n=ls(r),o={...e};return delete o.anyOf,{...o,oneOf:r,...n?{discriminator:n}:{},[$r]:o[$r]??"union"}}function py(e,t,r){const{DEFAULT_CONFIG:n}=require("ts-json-schema-generator/dist/src/Config.js"),o={...n,...e},s=o.path,i=ay(s,o.tsconfig);let a;a=r?r.statVersion(s):nu(s);let c;if(i!==void 0){const d=(r==null?void 0:r.generatorCache.get(i))??sy(i);d&&d.version===a&&(c=d.gen)}if(!c){const{createProgram:d}=require("ts-json-schema-generator/dist/factory/program.js"),l=ny(),p=ry(l.SyntaxKind.BigIntKeyword,l.SyntaxKind.TypeReference),h=d(o),f=Me.createParser(h,o,p),y=Me.createFormatter(o);if(c=new Me.SchemaGenerator(h,f,y,o),r&&r.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const $={version:a,gen:c};iy(i,$),r==null||r.generatorCache.set(i,$)}}const u=c.createSchema(o.type);return dy(u),ly(u),u}function my(e,t){let r=e.trim();if(r=du(r),t!=null&&t.size){const o=t.get(r);if(o!==void 0)return o}const n=r.match(/^ReadonlyArray<(.+)>$/);for(n&&(r=`${n[1].trim()}[]`);r.startsWith("readonly ");)r=r.slice(9).trim();return r}function uu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const hy=Object.entries(cu).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${uu(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function du(e){let t=e;for(const{pattern:r,key:n}of hy)t=t.replace(r,n);return t}function yy(e,t){let r=du(e);for(const[n,o]of t)r=r.replace(new RegExp(`\\b${uu(n)}\\b`,"g"),o);return r}async function Dt(e,t,r,n,o,s){const i=t.getFilePath(),a=`${i}\0${n??""}\0${r}`,c=s??new Set;if(c.has(a))return{};if(!o){const f=new Set(c);return f.add(a),xi(e,t,r,n,void 0,f)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const d=qh(i,n,o.statVersion(i)),l=d.get(r);if(l!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(l)),l;o.stats.schemaCacheMisses++;const p=new Set(c);p.add(a);const h=xi(e,t,r,n,o,p).then(f=>(d.set(r,f),f)).catch(f=>{throw o.schemaCache.delete(a),f});return o.schemaCache.set(a,h),h}async function xi(e,t,r,n,o,s){if(["void","undefined","null","Promise<void>"].includes(r))return{type:"null"};let i;if(o){const p=o.aliasCache.get(t);i=p??Ri(t),p||o.aliasCache.set(t,i)}else i=Ri(t);const a=my(r,i),c=Cn[a];if(c!==void 0)return c;const u=await ty(a,p=>Dt(e,t,p,n,o,s));if(u!==void 0)return u;const d=(o==null?void 0:o.zodImportCache.get(t))??uy(t);if(o&&o.zodImportCache.set(t,d),!d)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:n,topRef:!1},h=py(p,!0,o);return fy(h)}catch{}try{const p=await Zh(e,t,a,h=>iu(h,f=>Dt(e,t,f,n,o,s),0));if(p!==void 0)return p}catch{}const l=yy(a,i);return ur(l,0,i)}function fs(e,t,r){if(e!=null&&e.hasInitializer()){const n=e.getInitializer();if(n)return n.getText()}return gy(r,t)}function gy(e,t){var r;const n=e,o=((r=n==null?void 0:n.getJsDocs)==null?void 0:r.call(n))??[],s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${s}\\s*=\\s*([^\\]]+)\\]`);for(const a of o)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const u=c.getText().match(i);if(u)return u[1].trim()}}function $y(e){const t=e.trim(),r=t.match(/^(['"`])([\s\S]*)\1$/);if(r)return r[2];if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;if(t!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(t))return Number(t);try{return JSON.parse(t)}catch{return t}}}function vy(e,t){const r=$y(t);if(r===void 0)return;e.default=r;const n=typeof r=="string"?r:JSON.stringify(r),o=typeof e.description=="string"?e.description:void 0;e.description=o?`${o} (default: ${n})`:`(default: ${n})`}async function wy(e){const t=e.session===void 0,r=Vh(e.session??ou());try{return await _y(e,r)}finally{t&&r.dispose()}}async function _y(e,t){const{sourceFile:r,namespace:n="",tsconfig:o}=e,s=t.projectFor(o),i=t.sourceFileFor(r,o),a=io.basename(r),c=$e(Ny(a)),u=$e(n),d=[];for(const[h,f]of i.getExportedDeclarations()){if(h==="default"||Zt(h))continue;const y=jy(f);if(y){const _=y.getSignature(),E=Mi(_,y),j=_.getReturnType().getText();d.push(await Yt(s,i,u,c,h,E,j,y.isAsync(),o,t));continue}const $=f.find(_=>_.getKindName()==="VariableDeclaration");if(!$)continue;const g=$.getInitializer(),w=g==null?void 0:g.getKindName();if(g&&["ArrowFunction","FunctionExpression"].includes(w??"")){const _=$.getType().getCallSignatures();if(_.length===0)continue;const E=_[0],j=Fi(E,$,$.getVariableStatement()),I=E.getReturnType().getText(),x=g.isAsync();d.push(await Yt(s,i,u,c,h,j,I,x,o,t))}else if(w==="ObjectLiteralExpression"){const _=$.getType();for(const E of _.getProperties()){const j=E.getName();if(Zt(j))continue;const I=E.getTypeAtLocation($).getCallSignatures();if(I.length===0)continue;const x=I[0],V=Fi(x,$,$.getVariableStatement()),D=x.getReturnType().getText(),U=[c,$e(h),$e(j)];d.push(await dr(s,i,u,U,j,V,D,!1,o,t))}}else{const _=$.getType(),E=_.getText();if(Ce(_,$)){const j=await Dt(s,i,E,o,t);d.push(Sy(u,c,h,j))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${h}`)}}const l=i.getDefaultExportSymbol();if(l){const h=i.getExportAssignment(f=>!f.isExportEquals());if(h){const f=h.getExpression(),y=f.getKindName();if(["ArrowFunction","FunctionExpression"].includes(y)){const $=f.getType().getCallSignatures();if($.length>0){const g=$[0],w=rn(g,h),_=g.getReturnType().getText(),E=f.isAsync();d.push(await Yt(s,i,u,c,"default",w,_,E,o,t))}}else{const $=f.getType();for(const g of $.getProperties()){const w=g.getName();if(Zt(w))continue;const _=g.getTypeAtLocation(h).getCallSignatures();if(_.length===0)continue;const E=_[0],j=rn(E,h),I=E.getReturnType().getText(),x=[c,$e("default"),$e(w)];d.push(await dr(s,i,u,x,w,j,I,!1,o,t))}}}else{const f=l.getDeclarations();for(const y of f){if(y.getKindName()!=="FunctionDeclaration")continue;const $=y,g=$.getName(),w=g&&g.length>0?g:"default",_=$.getSignature(),E=Mi(_,$),j=_.getReturnType().getText();d.push(await Yt(s,i,u,c,w,E,j,$.isAsync(),o,t))}}}const p=Oy(i);if(p.length>0)for(const{name:h,sig:f}of p){if(Zt(h))continue;const y=rn(f),$=f.getReturnType().getText(),g=[c,$e(h)];d.push(await dr(s,i,u,g,h,y,$,!1,o,t))}return d}function by(e,t,r,n){const o=new Set,s=i=>{if(Array.isArray(i))return i.map(s);if(!i||typeof i!="object"||o.has(i))return i;o.add(i);try{const a=i,c={};for(const[u,d]of Object.entries(a)){if(u==="definitions"||u==="$defs"){const l=u,p=t[l];for(const[h,f]of Object.entries(d)){const y=s(f),$=p[h];if($!==void 0&&JSON.stringify($)!==JSON.stringify(y))throw new Error(`[apigen-core-client] Function "${r}": param "${n}" contributes a "${l}.${h}" definition that conflicts with an identically-named definition already hoisted from another param/output in the same function. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one function-level schema.`);p[h]=y}continue}c[u]=s(d)}return c}finally{o.delete(i)}};return s(e)}async function Yt(e,t,r,n,o,s,i,a,c,u){const d=$e(o);return dr(e,t,r,[n,d],o,s,i,a,c,u)}async function dr(e,t,r,n,o,s,i,a,c,u){const d=s.length>0&&s[0].name==="ctx",l=s.filter(w=>w.name!=="ctx"),p=l.filter(w=>!w.optional).map(w=>w.name),h={},f={definitions:{},$defs:{}};for(const w of l){const _=await Dt(e,t,w.type,c,u),E=by(_,f,o,w.name);w.defaultValue!==void 0&&vy(E,w.defaultValue),h[w.name]=E}const y=i.replace(/^Promise<(.+)>$/,"$1").trim(),$=await Dt(e,t,y,c,u),g={type:"object",properties:h,required:p,...Object.keys(f.definitions).length>0?{definitions:f.definitions}:{},...Object.keys(f.$defs).length>0?{$defs:f.$defs}:{}};return{id:lu(r,n),host:"ts",namespace:r,path:n,kind:"action",async:a,streaming:!1,safe:!1,input:g,output:$,envelope:{},typeText:{lang:"ts",input:ky(s),output:y},...d?{hasCtx:!0}:{}}}function Sy(e,t,r,n){const o=$e(r),s=[t,o];return{id:lu(e,s),host:"ts",namespace:e,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:n,envelope:{},typeText:null}}function lu(e,t){return(e.raw?[e,...t]:t).map(r=>r.words.join("-")).join("/")}function Ey(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function $e(e){return{raw:e,words:Ey(e)}}function Ny(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Oy(e){const t=[];for(const r of e.getStatements()){if(r.getKindName()!=="ExpressionStatement")continue;const n=r.getExpression();if(n.getKindName()!=="BinaryExpression")continue;const o=n;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),i=s.getType();for(const a of i.getProperties()){const c=a.getTypeAtLocation(s).getCallSignatures();c.length!==0&&t.push({name:a.getName(),sig:c[0]})}}return t}function jy(e){let t;for(const r of e){if(r.getKindName()!=="FunctionDeclaration")continue;const n=r;if(t||(t=n),n.getBody())return n}return t}function Mi(e,t){return e.getParameters().map(r=>{var n;const o=r.getDeclarations(),s=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=r.isOptional()||((s==null?void 0:s.hasInitializer())??!1)||(((n=s==null?void 0:s.hasQuestionToken)==null?void 0:n.call(s))??!1);return{name:r.getName(),type:r.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:fs(s,r.getName(),t)}})}function Fi(e,t,r){return e.getParameters().map(n=>{var o;const s=n.getDeclarations(),i=s.length>0&&s[0].getKindName()==="Parameter"?s[0]:null,a=n.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((o=i==null?void 0:i.hasQuestionToken)==null?void 0:o.call(i))??!1);return{name:n.getName(),type:n.getTypeAtLocation(t).getText(),optional:a,defaultValue:fs(i,n.getName(),r??t)}})}function rn(e,t){return e.getParameters().map(r=>{var n,o,s;const i=r.getDeclarations(),a=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,c=r.isOptional()||((a==null?void 0:a.hasInitializer())??!1)||(((n=a==null?void 0:a.hasQuestionToken)==null?void 0:n.call(a))??!1);return{name:r.getName(),type:a?a.getType().getText():((s=(o=r.getValueDeclaration())==null?void 0:o.getType())==null?void 0:s.getText())??"unknown",optional:c,defaultValue:fs(a,r.getName(),t)}})}function ky(e){const t=e.filter(r=>r.name!=="ctx");return t.length===0?"()":"("+t.map(r=>`${r.name}${r.optional?"?":""}: ${r.type}`).join(", ")+")"}function Zt(e){return!!(e==="__samples__"||e.startsWith("__"))}function Ce(e,t,r=new Set){if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0)return!1;if(e.isString()||e.isNumber()||e.isBoolean()||e.isNull()||e.isUndefined()||e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isEnumLiteral())return!0;if(e.isArray()||e.isReadonlyArray()){const n=e.getArrayElementType();return n?Ce(n,t,r):!1}if(e.isTuple())return e.getTupleElements().every(n=>Ce(n,t,r));if(e.isUnion())return e.getUnionTypes().every(n=>Ce(n,t,r));if(e.isIntersection())return e.getIntersectionTypes().every(n=>Ce(n,t,r));if(e.isObject()){const n=e.getText(t);if(r.has(n))return!0;r.add(n);const o=e.getStringIndexType(),s=e.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||Ce(a,t,r));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return Ce(c,t,r)})}return!1}const Py=new Map([[".ts","ts"],[".tsx","ts"],[".mts","ts"],[".cts","ts"],[".py","py"],[".rs","rust"],[".go","go"],[".java","java"]]);function Ay(e){const t=N.extname(e).toLowerCase();return Py.get(t)}function Ty(e){return e.language??"ts"}function Ui(e){return e.words.join("-")}function Li(e){return e.words.map(Dy).join("")}function zi(e){return e.words.join("_")}function Iy(e,t={}){var p,h;const r=[e.namespace,...e.path],n=e.safe||su(e.input)?"GET":"POST",o=((h=(p=t.http)==null?void 0:p.verb)==null?void 0:h[e.id])??n,s="/"+r.map(f=>Ui(f)).join("/"),i=r.map(f=>zi(f)).join("_"),c=r.map(f=>zi(f)).slice(0,-1).join("."),u=Li(r[r.length-2]??r[0]),d=Li(r[r.length-1]),l=r.map(f=>Ui(f));return{http:{verb:o,route:s},mcp:{name:i},grpc:{package:c,service:u,method:d},cli:{path:l}}}class fu extends Error{constructor(t){const r=t.map(n=>` [${n.transport}] "${n.target}" ← ${n.ids[0]} vs ${n.ids[1]}`);super(`apigen-naming: ${t.length} projection collision(s) detected:
|
|
10
|
+
${r.join(`
|
|
11
|
+
`)}`),this.name="CollisionDetectedError",this.collisions=t}}function Cy(e,t={}){const r=new Map,n=new Map,o=new Map,s=new Map,i=[];for(const a of e){const c=Iy(a,t),u=`${c.http.verb} ${c.http.route}`,d=r.get(u);d!==void 0&&d!==a.id?i.push({transport:"http",target:u,ids:[d,a.id]}):r.set(u,a.id);const l=n.get(c.mcp.name);l!==void 0&&l!==a.id?i.push({transport:"mcp",target:c.mcp.name,ids:[l,a.id]}):n.set(c.mcp.name,a.id);const p=`${c.grpc.package}.${c.grpc.service}/${c.grpc.method}`,h=o.get(p);h!==void 0&&h!==a.id?i.push({transport:"grpc",target:p,ids:[h,a.id]}):o.set(p,a.id);const f=c.cli.path.join(" "),y=s.get(f);y!==void 0&&y!==a.id?i.push({transport:"cli",target:f,ids:[y,a.id]}):s.set(f,a.id)}if(i.length>0)throw new fu(i)}function Dy(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}const Ry={compilerOptions:{target:"ES2020",module:"esnext",moduleResolution:"bundler",esModuleInterop:!0,strict:!0,skipLibCheck:!0}};let Qt;function xy(){if(Qt)return Qt;const e=typeof __dirname<"u"?__dirname:"";if(e){const r=[N.join(e,"default-tsconfig.json"),N.join(e,"lib","default-tsconfig.json"),N.join(e,"..","default-tsconfig.json")];for(const n of r)if(k.existsSync(n))return Qt=n,n}const t=N.join(k.mkdtempSync(N.join(Ge.tmpdir(),"apigen-tsconfig-")),"tsconfig.json");return k.writeFileSync(t,JSON.stringify(Ry,null,2)),Qt=t,t}function pu(e){let t=e;for(;;){const r=N.join(t,"tsconfig.json");if(k.existsSync(r))return r;const n=N.dirname(t);if(n===t)return;t=n}}function ps(e,t){if(t)return N.resolve(t);const r=pu(N.dirname(N.resolve(e)));return r||xy()}function mu(e,t={}){if(t.namespace)return t.namespace;const r=N.resolve(e);if(t.tsconfig)return N.basename(N.dirname(N.resolve(t.tsconfig)));const n=pu(N.dirname(r));return n?N.basename(N.dirname(n)):N.basename(N.dirname(r))}function My(e){const t=N.extname(e).toLowerCase();if(t===".ts"||t===".tsx"||t===".mts"||t===".cts")return"ts";throw new Error(`apigen-orchestrator: unsupported source extension "${t}" for file "${e}". Currently supported: .ts .tsx .mts .cts`)}function hu(e){var r;const t={};for(const n of e){const o=n.indexOf("=");if(o===-1)continue;const s=n.slice(0,o),i=n.slice(o+1),a=/^http\.verb\.(.+)$/.exec(s);if(a){const c=a[1];t.http??(t.http={}),(r=t.http).verb??(r.verb={}),t.http.verb[c]=i}}return t}function yu(e,t){var s,i;const r=e??N.join(process.cwd(),"apigen.config.json");let n={};if(k.existsSync(r))try{n=JSON.parse(k.readFileSync(r,"utf8"))}catch{}const o={...n};return(s=t.http)!=null&&s.verb&&(o.http={...o.http,verb:{...(i=o.http)==null?void 0:i.verb,...t.http.verb}}),o}async function Fy(e,t,r){const n=My(e.file);if(n==="ts"){const o=ps(e.file,e.tsconfig),s=e.namespace??mu(e.file,{tsconfig:e.tsconfig});t==null||t.info(`extracting ${e.file} (host: ts, ns: ${s})`);const i=await wy({sourceFile:e.file,namespace:s,tsconfig:o,session:r});return t==null||t.info(`extracted ${i.length} operations from ${N.basename(e.file)}`),t==null||t.debug({ops:i.map(a=>a.id)},"operation ids"),{namespace:s,ops:i}}throw new Error(`apigen-orchestrator: host "${n}" extractor not implemented`)}function Uy(e){return e.flat()}function Ly(e,t){var r,n;return t.type==="named"?e.path.length===2:t.type==="default"?e.path.length===3&&((r=e.path[1])==null?void 0:r.raw)==="default":e.path.length===3&&((n=e.path[1])==null?void 0:n.raw)===t.name}async function gu(e){const{sources:t,overrides:r={},logger:n}=e;if(t.length===0)throw new Error("apigen-orchestrator: at least one source must be provided");const o=ou();try{const s=await Promise.all(t.map(u=>Fy(u,n,o))),i=Uy(s.map(u=>u.ops));n==null||n.info(`merged ${i.length} total operations from ${t.length} source(s)`);try{Cy(i,r)}catch(u){throw u instanceof fu&&(n==null||n.error({collisions:u.collisions},u.message)),u}const a=new Map,c=new Map;for(let u=0;u<t.length;u++){const d=t[u],l=s[u].namespace;if(c.has(l))throw new Error(`apigen-orchestrator: duplicate namespace "${l}" — two sources resolve to the same namespace; the second source's operations would silently overwrite the first's in packageSchemas. Give one source an explicit, distinct \`namespace\` to disambiguate.`);c.set(l,{namespace:l,importPath:d.importPath??d.file,generated:{metadata:{namespace:l,phase:""},schemas:{}},exportMode:d.exportMode})}for(const u of i){if(u.kind!=="action")continue;const d=c.get(u.namespace.raw);if(!d||d.exportMode&&!Ly(u,d.exportMode))continue;const l=u.path[u.path.length-1].raw;d.generated.schemas[l]={input:u.input,output:u.output,...u.hasCtx?{hasCtx:!0}:{},safe:u.safe}}for(const u of c.values()){n==null||n.info(`composing schemas for namespace "${u.namespace}" (${Object.keys(u.generated.schemas).length} action(s))`);const d=Kh(u.generated,[],{});a.set(u.namespace,{id:u.namespace,schemas:d,importPath:u.importPath})}return{operations:i,packageSchemas:a}}finally{o.dispose()}}async function $u(e,t,r,n={}){const o=await gu(e),i={packages:Array.from(o.packageSchemas.values()).map(c=>({id:c.id,schemas:c.schemas,importPath:c.importPath})),outputDir:r,options:n,logger:e.logger},a=await t.generate(i);return{descriptor:o,pluginOutput:a}}async function vu(e,t,r,n,o={}){if(!t.run)throw new Error(`Plugin "${t.id}" does not support run mode`);const s=await gu(e),i=new Map;for(const u of e.sources){const d=u.namespace??mu(u.file,{tsconfig:u.tsconfig});i.set(d,u)}const c={packages:await Promise.all(Array.from(s.packageSchemas.values()).map(async u=>{const d=i.get(u.id);if(!d)throw new Error(`apigen-orchestrator: internal error — no source entry for namespace "${u.id}"`);const{fns:l,createClient:p}=await r(d,u.schemas);return{id:u.id,schemas:u.schemas,importPath:u.importPath,fns:l,createClient:p}})),outputDir:"",options:o,signal:n,logger:e.logger,operations:s.operations};await t.run(c)}const zy={mcp:["@modelcontextprotocol/sdk","@adhd/apigen-engine-runtime"],cli:["commander","@adhd/apigen-engine-runtime"]};function qy(e,t){const r={},n=e?wu(e):new Map;for(const o of t){let s="*";try{if(o.startsWith("@adhd/")){const i=n.get(o),a=i&&N.join(N.dirname(i),"package.json");a&&k.existsSync(a)&&(s=`^${JSON.parse(k.readFileSync(a,"utf8")).version}`)}else if(e){const i=N.join(e,"node_modules",...o.split("/"),"package.json");k.existsSync(i)&&(s=`^${JSON.parse(k.readFileSync(i,"utf8")).version}`)}}catch{s="*"}r[o]=s}return r}function qi(e){let t=e;for(;;){if(k.existsSync(N.join(t,"node_modules"))&&k.existsSync(N.join(t,"tsconfig.base.json")))return t;const r=N.dirname(t);if(r===t)return;t=r}}function Vy(e){var s;const t=N.join(e,"tsconfig.base.json");let r;try{r=JSON.parse(k.readFileSync(t,"utf8"))}catch{return{}}const n=((s=r.compilerOptions)==null?void 0:s.paths)??{},o={};for(const[i,a]of Object.entries(n))o[i]=a.map(c=>N.resolve(e,c));return o}function Vi(e,t){if(k.existsSync(t)||!k.existsSync(e))return!1;try{return k.symlinkSync(e,t,"dir"),!0}catch{return!1}}function wu(e){var o;const t=new Map,r=N.join(e,"tsconfig.base.json");let n;try{n=JSON.parse(k.readFileSync(r,"utf8"))}catch{return t}for(const[s,i]of Object.entries(((o=n.compilerOptions)==null?void 0:o.paths)??{})){if(!s.startsWith("@adhd/"))continue;const a=N.resolve(e,i[0]),c=N.dirname(a);k.existsSync(c)&&t.set(s,c)}return t}function Gy(e,t){const r=N.join(e,"node_modules");if(k.existsSync(r))return!1;const n=N.join(t,"node_modules");if(!k.existsSync(n))return!1;k.mkdirSync(r,{recursive:!0});for(const o of k.readdirSync(n,{withFileTypes:!0})){const s=o.name;if(!(s===".bin"||s===".cache"||s==="@adhd"))if(s.startsWith("@")){const i=N.join(n,s),a=N.join(r,s);k.mkdirSync(a,{recursive:!0});for(const c of k.readdirSync(i,{withFileTypes:!0}))Vi(N.join(i,c.name),N.join(a,c.name))}else Vi(N.join(n,s),N.join(r,s))}for(const[o,s]of wu(t)){const i=N.join(r,...o.split("/"));k.mkdirSync(i,{recursive:!0}),k.cpSync(s,N.join(i,"src"),{recursive:!0}),k.writeFileSync(N.join(i,"package.json"),JSON.stringify({name:o,version:"0.0.0",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"}},null,2))}return!0}function Gi(e,t){return k.existsSync(e)?!1:(k.writeFileSync(e,t),!0)}function Hy(e,t,r={}){const n=[],o=qi(e)??qi(__dirname),s=qy(o,zy[t]??[]),i=N.join(e,"package.json");Gi(i,JSON.stringify({name:"apigen-generated-output",version:"0.0.0",private:!0,type:"module",dependencies:s},null,2)+`
|
|
12
|
+
`)&&n.push("package.json");const a=N.join(e,"tsconfig.json"),c=r.linkWorkspace&&o?Vy(o):{};return Gi(a,JSON.stringify({compilerOptions:{target:"ES2020",module:"esnext",moduleResolution:"bundler",esModuleInterop:!0,strict:!0,skipLibCheck:!0,baseUrl:".",paths:c}},null,2)+`
|
|
13
|
+
`)&&n.push("tsconfig.json"),r.linkWorkspace&&o&&Gy(e,o)&&n.push("node_modules"),n}function Lt(e){return Object.keys(e)}function ms(e){return Lt(e).filter(t=>{var r;return typeof((r=e[t])==null?void 0:r.run)=="function"})}function Jy(e){return Lt(e).filter(t=>{var r;return typeof((r=e[t])==null?void 0:r.run)!="function"})}function _u(e){return`Output target — one of: ${Lt(e).sort().join(" | ")} (see \`apigen list-types\`)`}function bu(e){return`Output target — one of: ${ms(e).sort().join(" | ")} (see \`apigen list-types\`)`}function kr(e,t){return new Error(`Unknown --type: ${e}. Available: ${Lt(t).join(", ")}`)}function Su(e,t){const r=ms(t),n=Jy(t);return new Error(`Plugin ${e} does not support run mode. Generate-only plugins: ${n.join(", ")||"(none registered)"}. Run-capable plugins: ${r.join(", ")||"(none registered)"}.`)}function Ky(e){const t=Lt(e).slice().sort(),r=new Set(ms(e)),n=t.reduce((s,i)=>Math.max(s,i.length),0);return["Available --type plugins:","",...t.map(s=>{const i=e[s],a=r.has(s)?"generate, run":"generate";return` ${s.padEnd(n)} (${a}) ${i.description}`}),"","Use --type <id> with generate, generate-registry, run, or run-registry.","Plugins marked (generate) only do not support run / run-registry."].join(`
|
|
14
|
+
`)}const By={id:"date-time"},Wy={id:"int64"},Yy={id:"decimal"},Zy={id:"byte"},Qy={id:"uuid"},Xy={id:"number-special"},eg=[By.id,Wy.id,Yy.id,Zy.id,Qy.id,Xy.id],tg={"date-time":{encode:"$.toISOString()",decode:"new Date($)",mode:"native"},int64:{encode:"String($)",decode:"BigInt($)",mode:"native"},decimal:{encode:"$.toString()",decode:"new Decimal($)",imports:[],dep:{name:"decimal.js",version:"^10"},mode:"branded"},byte:{encode:"Buffer.from($).toString('base64')",decode:"new Uint8Array(Buffer.from($, 'base64'))",mode:"native"},uuid:{encode:"$.toLowerCase()",decode:"$",mode:"native"},"number-special":{encode:"numToWire($)",decode:"wireToNum($)",mode:"native"}},rg={"date-time":{encode:"$.isoformat()",decode:"datetime.fromisoformat($)",imports:["from datetime import datetime"],mode:"native"},int64:{encode:"str($)",decode:"int($)",mode:"native"},decimal:{encode:"str($)",decode:"Decimal($)",imports:["from decimal import Decimal"],mode:"native"},byte:{encode:"b64encode($).decode()",decode:"b64decode($)",imports:["from base64 import b64encode, b64decode"],mode:"native"},uuid:{encode:"str($)",decode:"UUID($)",imports:["from uuid import UUID"],mode:"native"},"number-special":{encode:"num_to_wire($)",decode:"wire_to_num($)",mode:"native"}},ng={"date-time":{encode:"__SCAFFOLD_RUST_DATETIME_ENCODE__",decode:"__SCAFFOLD_RUST_DATETIME_DECODE__",imports:["use chrono::{DateTime, Utc};"],dep:{name:"chrono",version:"^0.4"},mode:"lib"},int64:{encode:"__SCAFFOLD_RUST_INT64_ENCODE__",decode:"__SCAFFOLD_RUST_INT64_DECODE__",imports:["use serde_with::DisplayFromStr;"],dep:{name:"serde_with",version:"^3"},mode:"lib"},decimal:{encode:"__SCAFFOLD_RUST_DECIMAL_ENCODE__",decode:"__SCAFFOLD_RUST_DECIMAL_DECODE__",imports:["use rust_decimal::Decimal;"],dep:{name:"rust_decimal",version:"^1"},mode:"lib"},byte:{encode:"__SCAFFOLD_RUST_BYTE_ENCODE__",decode:"__SCAFFOLD_RUST_BYTE_DECODE__",imports:["use serde_with::base64::Base64;"],dep:{name:"serde_with",version:"^3"},mode:"lib"},uuid:{encode:"__SCAFFOLD_RUST_UUID_ENCODE__",decode:"__SCAFFOLD_RUST_UUID_DECODE__",imports:["use uuid::Uuid;"],dep:{name:"uuid",version:"^1"},mode:"lib"},"number-special":{encode:"__SCAFFOLD_RUST_NUMSPECIAL_ENCODE__",decode:"__SCAFFOLD_RUST_NUMSPECIAL_DECODE__",mode:"native"}},og={"date-time":{encode:"__SCAFFOLD_GO_DATETIME_ENCODE__",decode:"__SCAFFOLD_GO_DATETIME_DECODE__",imports:['"time"'],mode:"native"},int64:{encode:"__SCAFFOLD_GO_INT64_ENCODE__",decode:"__SCAFFOLD_GO_INT64_DECODE__",imports:['"strconv"'],mode:"native"},decimal:{encode:"__SCAFFOLD_GO_DECIMAL_ENCODE__",decode:"__SCAFFOLD_GO_DECIMAL_DECODE__",imports:['"github.com/shopspring/decimal"'],dep:{name:"github.com/shopspring/decimal",version:"v1"},mode:"lib"},byte:{encode:"__SCAFFOLD_GO_BYTE_ENCODE__",decode:"__SCAFFOLD_GO_BYTE_DECODE__",imports:['"encoding/base64"'],mode:"native"},uuid:{encode:"__SCAFFOLD_GO_UUID_ENCODE__",decode:"__SCAFFOLD_GO_UUID_DECODE__",imports:['"github.com/google/uuid"'],dep:{name:"github.com/google/uuid",version:"v1"},mode:"lib"},"number-special":{encode:"__SCAFFOLD_GO_NUMSPECIAL_ENCODE__",decode:"__SCAFFOLD_GO_NUMSPECIAL_DECODE__",mode:"native"}},sg={"date-time":{encode:"__SCAFFOLD_JAVA_DATETIME_ENCODE__",decode:"__SCAFFOLD_JAVA_DATETIME_DECODE__",imports:["import java.time.Instant;"],dep:{name:"jackson-datatype-jsr310",version:"2.x"},mode:"lib"},int64:{encode:"__SCAFFOLD_JAVA_INT64_ENCODE__",decode:"__SCAFFOLD_JAVA_INT64_DECODE__",imports:["import com.fasterxml.jackson.annotation.JsonFormat;"],mode:"native"},decimal:{encode:"__SCAFFOLD_JAVA_DECIMAL_ENCODE__",decode:"__SCAFFOLD_JAVA_DECIMAL_DECODE__",imports:["import java.math.BigDecimal;"],mode:"native"},byte:{encode:"__SCAFFOLD_JAVA_BYTE_ENCODE__",decode:"__SCAFFOLD_JAVA_BYTE_DECODE__",mode:"native"},uuid:{encode:"__SCAFFOLD_JAVA_UUID_ENCODE__",decode:"__SCAFFOLD_JAVA_UUID_DECODE__",imports:["import java.util.UUID;"],mode:"native"},"number-special":{encode:"__SCAFFOLD_JAVA_NUMSPECIAL_ENCODE__",decode:"__SCAFFOLD_JAVA_NUMSPECIAL_DECODE__",mode:"native"}},ig=Object.freeze({typescript:tg,python:rg,rust:ng,go:og,java:sg});function ag(){const e=ig.typescript,t={};for(const r of eg){const n=e[r].dep;n&&(t[r]=n)}return Object.freeze(t)}function vr(e,t=new WeakSet){const r=new Set;if(e===null||typeof e!="object"||t.has(e))return r;if(t.add(e),Array.isArray(e)){for(const o of e)for(const s of vr(o,t))r.add(s);return r}const n=e;typeof n.format=="string"&&r.add(n.format);for(const o of Object.values(n))for(const s of vr(o,t))r.add(s);return r}function cg(e){const t=new Set;for(const o of Object.values(e)){for(const s of vr(o.input))t.add(s);for(const s of vr(o.output))t.add(s)}const r=ag(),n={};for(const o of t){const s=r[o];s&&(n[s.name]=s.version)}return n}function ug(e){const t={};for(const{schemas:r}of e.values())Object.assign(t,cg(r));return t}function dg(e,t){if(Object.keys(t).length===0)return;const r=N.join(e,"package.json");if(!k.existsSync(r))return;let n;try{n=JSON.parse(k.readFileSync(r,"utf8"))}catch{return}const o=n.dependencies??{};n.dependencies={...o,...t},k.writeFileSync(r,JSON.stringify(n,null,2)+`
|
|
15
|
+
`)}function lg(e){return Object.fromEntries(e.map(t=>{const r=t.indexOf("=");return[t.slice(0,r),t.slice(r+1)]}))}function fg(e){return e==="default"?{type:"default"}:e?{type:"named-object",name:e}:{type:"named"}}function pg(e,t){e.command("generate").requiredOption("--source <path>","Path to TypeScript source file").requiredOption("--type <plugin-id>",_u(t)).requiredOption("--out-dir <path>","Output directory").option("--export <mode>",'Export mode: "default" | "<named-object-name>" | omit for named exports').option("--tsconfig <path>","Explicit tsconfig.json; default resolves the nearest config or a builtin one").option("--namespace <name>","Package namespace/id (default: tsconfig folder name, else source folder)").option("--opt <key=value>","Plugin option (repeatable). Projection overrides: http.verb.<id>=GET",(r,n)=>[...n,r],[]).option("--use <plugin>","Layer/mount/envelope plugin to activate (repeatable; accepts package specifier or local path)",(r,n)=>[...n,r],[]).option("--config <path>","Path to apigen.config.json projection-override file (Tenet 1)").option("--link-workspace","PRE-PUBLISH ONLY: also emit a workspace-linked node_modules + tsconfig paths so the output runs in place before @adhd/apigen-* are published (a published consumer runs `npm install` instead)").action(async r=>{const n=t[r.type];if(!n)throw kr(r.type,t);const o=jr(e),s=fg(r.export),i=N.resolve(r.source),a=N.resolve(r.outDir),c=r.opt,u=hu(c),d=yu(r.config,u),l=lg(c),{pluginOutput:p,descriptor:h}=await $u({sources:[{file:i,exportMode:s,namespace:r.namespace,tsconfig:r.tsconfig}],usePlugins:r.use,overrides:d,logger:o},n,a,l);k.mkdirSync(a,{recursive:!0});for(const y of p.files){const $=N.join(a,y.path);k.mkdirSync(N.dirname($),{recursive:!0}),k.writeFileSync($,y.content)}const f=Hy(a,n.id,{linkWorkspace:r.linkWorkspace});f.length>0&&o.info(`scaffolded ${f.join(", ")} in ${a}`),dg(a,ug(h.packageSchemas)),o.info(`wrote ${p.files.length} files to ${a}`)})}function Eu(e){const{packagesDir:t,includeTags:r=[],excludeTags:n=[]}=e,o=k.readdirSync(t,{withFileTypes:!0}).filter(i=>i.isDirectory()),s=[];for(const i of o){const a=N.join(t,i.name,"package.json");if(!k.existsSync(a))continue;const c=JSON.parse(k.readFileSync(a,"utf8")),u=c.tags??c.keywords??[];r.length&&!r.every(d=>u.includes(d))||n.some(d=>u.includes(d))||s.push({id:i.name,dir:N.join(t,i.name),importPath:c.name??i.name,tags:u})}return s.sort((i,a)=>i.id.localeCompare(a.id))}function mg(e){return Object.fromEntries(e.map(t=>{const r=t.indexOf("=");return[t.slice(0,r),t.slice(r+1)]}))}function hg(e,t){e.command("generate-registry").requiredOption("--packages-dir <path>","Directory containing package subdirectories").requiredOption("--type <plugin-id>",_u(t)).requiredOption("--out-dir <path>","Output directory").option("--tag <tag>","Include only packages with this tag (repeatable)",(r,n)=>[...n,r],[]).option("--exclude-tag <tag>","Exclude packages with this tag (repeatable)",(r,n)=>[...n,r],[]).option("--tsconfig <path>","Explicit tsconfig.json; default resolves the nearest config or a builtin one").option("--opt <key=value>","Plugin option (repeatable)",(r,n)=>[...n,r],[]).action(async r=>{const n=t[r.type];if(!n)throw kr(r.type,t);const o=jr(e),s=mg(r.opt),i=N.resolve(r.packagesDir),a=N.resolve(r.outDir),c=Eu({packagesDir:i,includeTags:r.tag,excludeTags:r.excludeTag}),u=[];for(const l of c){const p=yg(l.dir);p&&u.push({file:p,namespace:l.id,importPath:l.importPath,tsconfig:r.tsconfig})}if(u.length===0){o.info(`no packages with an entry file found under ${i} — nothing to generate`);return}const{pluginOutput:d}=await $u({sources:u,logger:o},n,a,s);k.mkdirSync(a,{recursive:!0});for(const l of d.files){const p=N.join(a,l.path);k.mkdirSync(N.dirname(p),{recursive:!0}),k.writeFileSync(p,l.content)}o.info(`wrote ${d.files.length} files to ${a}`)})}function yg(e){const t=["index.ts","src/index.ts","lib/index.ts"];for(const r of t){const n=N.join(e,r);if(k.existsSync(n))return n}}async function Nu(e,t){const r=Va.pathToFileURL(e).href;let n,o;try{const{register:s}=await import("tsx/esm/api");n=s(t?{tsconfig:t}:void 0)}catch{}try{const{register:s}=await import("tsx/cjs/api");o=s()}catch{}try{return await import(r)}finally{await(n==null?void 0:n()),o==null||o()}}function Hi(e){return{raw:e,words:[e]}}function gg(e,t={}){return[{id:"_meta/health",host:e.host,namespace:Hi("meta"),path:[Hi("health")],kind:"query",async:!1,streaming:!1,safe:!0,input:{},output:{type:"object",required:["status","host"],properties:{status:{const:"ok"},host:{type:"string"},meta:{type:"object"}}},envelope:{},typeText:null,transports:["http","grpc"],handler:r=>{const n={status:"ok",host:e.host};return t.meta!==void 0&&Object.keys(t.meta).length>0&&(n.meta=t.meta),n}}]}const $g={id:"health",description:"Mount plugin: exposes GET /meta/health for gateway readiness (SPEC §13.1)",language:"ts",optionsSchema:{type:"object",properties:{meta:{type:"object",description:"Extra metadata included in the health response"}},additionalProperties:!1},capabilities:{mount:{operations(e,t){return gg(e,t)}}}};let lr=class{constructor(t){this._inner=t}info(t,r){this._inner.info(t,r)}error(t,r){this._inner.error(t,r)}debug(t,r){this._inner.debug(t,r)}warn(t,r){this._inner.warn(t,r)}get pino(){return this._inner}};function vg(e,t){const r=e.ctx.get(lr);if(r!==void 0)return r;const n=new lr(t.pino.child({op:e.operation.id}));return e.ctx.set(lr,n),n}const wg=new lr(te({level:"info"},te.destination(2)));function _g(e){return function(t,r){const n=vg(t,e),o=t.operation.id,s=Date.now();n.info({op:o},`→ ${o}`);const i=r();function a(c){return c!==null&&typeof c=="object"&&Symbol.asyncIterator in c}return a(i)?async function*(){let c=0;try{for await(const u of i)c++,n.debug({op:o,chunk:c},`chunk ${c}`),yield u;n.info({op:o,ms:Date.now()-s,chunks:c},`← ${o} ok`)}catch(u){throw n.error({op:o,ms:Date.now()-s,err:u},`✗ ${o} stream error`),u}}():i.then(c=>(n.info({op:o,ms:Date.now()-s},`← ${o} ok`),c),c=>{throw n.error({op:o,ms:Date.now()-s,err:c},`✗ ${o} error`),c})}}const bg={id:"logger",description:"Layer plugin: wraps every operation with entry/exit/error logging (SPEC §7.2a / §8.1). Seeds Logger into call.ctx for downstream consumers.",language:"ts",optionsSchema:{type:"object",properties:{level:{type:"string",description:"pino log level (trace|debug|info|warn|error|fatal). Default: info.",default:"info"},format:{type:"string",enum:["json","pretty"],description:"Log output format. Default: pretty on a TTY stderr, json otherwise."},destination:{type:"string",description:"File path to write logs to. Default: stderr (fd 2). Never stdout."}}},capabilities:{target:{name:"logger",generate(e,t){return[]}},layer:{layer:_g(wg)}}},Ji=new Set(["string","number","boolean","integer"]);function Sg(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:r}=t;return typeof r=="string"?Ji.has(r):Array.isArray(r)?r.every(n=>Ji.has(n)||n==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(n=>["string","number","boolean"].includes(typeof n)):!1}function Eg(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Sg)}const Ng={"decimal.js":"Decimal"};function Og(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ng).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Og(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ki(e){return e.words.join("-")}function Bi(e){return e.words.map(kg).join("")}function Wi(e){return e.words.join("_")}function jg(e,t={}){var r,n;const o=[e.namespace,...e.path],s=e.safe||Eg(e.input)?"GET":"POST",i=((n=(r=t.http)==null?void 0:r.verb)==null?void 0:n[e.id])??s,a="/"+o.map(h=>Ki(h)).join("/"),c=o.map(h=>Wi(h)).join("_"),u=o.map(h=>Wi(h)).slice(0,-1).join("."),d=Bi(o[o.length-2]??o[0]),l=Bi(o[o.length-1]),p=o.map(h=>Ki(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:d,method:l},cli:{path:p}}}function kg(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Pg(e,t={}){const r=t.title??"API",n=t.version??"0.0.0",o={};for(const s of e){const i=jg(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),d={operationId:s.id,summary:s.id,responses:{200:Ag(s.output)}};if(a==="GET")d.parameters=Tg(s.input);else{const l=s.input;typeof l=="object"&&l!==null&&Object.keys(l).length>0&&(d.requestBody={required:!0,content:{"application/json":{schema:l}}})}o[c]===void 0&&(o[c]={}),o[c][u]=d}return{openapi:"3.1.0",info:{title:r,version:n},paths:o}}function Ag(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function Tg(e){if(typeof e!="object"||e===null||typeof e.properties!="object"||e.properties===null)return[];const t=Array.isArray(e.required)?e.required:[],r=e.properties;return Object.entries(r).map(([n,o])=>({name:n,in:"query",required:t.includes(n),schema:o}))}function Yi(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Ig(e,t={}){return[{id:"_meta/openapi",host:e.host,namespace:Yi("meta"),path:[Yi("openapi")],kind:"query",async:!1,streaming:!1,safe:!0,input:{},output:{type:"object"},envelope:{},typeText:null,transports:["http"],handler:r=>Pg(e.operations,{title:t.title,version:t.version})}]}const Cg={id:"openapi",description:"Mount plugin: serves the OpenAPI 3.1 doc at GET /meta/openapi",language:"ts",optionsSchema:{type:"object",properties:{title:{type:"string",description:"OpenAPI info.title"},version:{type:"string",description:"OpenAPI info.version"}},additionalProperties:!1},capabilities:{mount:{operations(e,t){return Ig(e,t)}}}};function Dg(e){return Object.fromEntries(e.map(t=>{const r=t.indexOf("=");return[t.slice(0,r),t.slice(r+1)]}))}function Rg(e,t){if(Object.keys(e).length===0)throw new Error(`0 functions found in --source ${t} — looks like generated output or the wrong source file. Point --source at the original TypeScript source that exports your API functions.`)}function wr(e,t=0){if(t>20||!e||typeof e!="object")return!1;const r=e;if(r.format==="decimal")return!0;for(const n of Object.values(r))if(Array.isArray(n)){for(const o of n)if(wr(o,t+1))return!0}else if(wr(n,t+1))return!0;return!1}function xg(e){const t=[];for(const[r,n]of Object.entries(e))(wr(n.input)||wr(n.output))&&t.push(r);return t}const Mg=e=>require.resolve(e);function Fg(e,t=Mg){const r=xg(e);if(r.length!==0)try{t("decimal.js")}catch{const n=r.join(", ");throw new Error(`function ${r[0]} takes a Decimal; install \`decimal.js\` (affected functions: ${n})`)}}const Ug={health:$g,logger:bg,openapi:Cg};async function Lg(e){const t=[];for(const r of e){const n=Ug[r];if(n){t.push(n);continue}const i=await import(r.startsWith(".")||N.isAbsolute(r)||!/^[a-zA-Z]+:\/\//.test(r)&&/\.(js|mjs|cjs|ts|json|txt)$/i.test(r)?Va.pathToFileURL(N.resolve(r)).href:r),a=i.default??i.plugin??Object.values(i).find(c=>!!c&&typeof c=="object"&&"capabilities"in c);if(!a)throw new Error(`--use ${r}: module exported no plugin (expected a default export, a \`plugin\` export, or an object with a \`capabilities\` field)`);t.push(a)}return t}function zg(e,t){e.command("run").requiredOption("--source <path>","Path to TypeScript source file").requiredOption("--type <plugin-id>",bu(t)).option("--export <mode>",'Export mode: "default" | "<named-object-name>" | omit for named exports').option("--tsconfig <path>","Explicit tsconfig.json; default resolves the nearest config or a builtin one").option("--namespace <name>","Package namespace/id (default: tsconfig folder name, else source folder)").option("--opt <key=value>","Plugin option (repeatable). Projection overrides: http.verb.<id>=GET",(r,n)=>[...n,r],[]).option("--use <plugin>","Layer/mount/envelope plugin to activate (repeatable; accepts package specifier or local path)",(r,n)=>[...n,r],[]).option("--config <path>","Path to apigen.config.json projection-override file (Tenet 1)").action(async r=>{const n=t[r.type];if(!n)throw kr(r.type,t);if(!n.run)throw Su(r.type,t);let o;r.export==="default"?o={type:"default"}:r.export?o={type:"named-object",name:r.export}:o={type:"named"};const s=jr(e),i=r.opt,a=Dg(i),c=await Lg(r.use);c.length>0&&(a.usePlugins=c);const u=N.resolve(r.source),d=new AbortController;if(process.on("SIGINT",()=>d.abort()),process.on("SIGTERM",()=>d.abort()),Ty(n)!=="ts"){const $={packages:[{id:r.namespace??N.basename(N.dirname(u)),schemas:{},importPath:u}],outputDir:"",options:a,signal:d.signal,logger:s};await n.run($);return}const p=hu(i),h=yu(r.config,p),f={file:u,exportMode:o,namespace:r.namespace,tsconfig:r.tsconfig};await vu({sources:[f],usePlugins:r.use,overrides:h,logger:s},n,async(y,$)=>{Fg($);const g=ps(y.file,y.tsconfig),w=await Nu(y.file,g),_=Xc(w);return Rg(_,y.file),{fns:_,createClient:async j=>j}},d.signal,a)})}function qg(e){return Object.fromEntries(e.map(t=>{const r=t.indexOf("=");return[t.slice(0,r),t.slice(r+1)]}))}function Vg(e){const t=["index.ts","src/index.ts","lib/index.ts"];for(const r of t){const n=N.join(e,r);if(k.existsSync(n))return n}}function Gg(e,t){e.command("run-registry").requiredOption("--packages-dir <path>","Directory containing package subdirectories").requiredOption("--type <plugin-id>",bu(t)).option("--tag <tag>","Include only packages with this tag (repeatable)",(r,n)=>[...n,r],[]).option("--exclude-tag <tag>","Exclude packages with this tag (repeatable)",(r,n)=>[...n,r],[]).option("--tsconfig <path>","Explicit tsconfig.json; default resolves the nearest config or a builtin one").option("--opt <key=value>","Plugin option (repeatable)",(r,n)=>[...n,r],[]).action(async r=>{const n=t[r.type];if(!n)throw kr(r.type,t);if(!n.run)throw Su(r.type,t);const o=jr(e),s=qg(r.opt),i=N.resolve(r.packagesDir),a=Eu({packagesDir:i,includeTags:r.tag,excludeTags:r.excludeTag}),c=[];for(const d of a){const l=Vg(d.dir);l&&c.push({file:l,namespace:d.id,importPath:d.importPath,tsconfig:r.tsconfig})}if(c.length===0){o.info(`no packages with an entry file found under ${i} — nothing to run`);return}const u=new AbortController;process.on("SIGINT",()=>u.abort()),process.on("SIGTERM",()=>u.abort()),await vu({sources:c,logger:o},n,async d=>{const l=ps(d.file,d.tsconfig),p=await Nu(d.file,l);return{fns:Xc(p),createClient:async y=>y}},u.signal,s)})}function Hg(e){const t=__dirname,r=N.resolve(t,"..","..","..","python");if(k.existsSync(N.join(r,"apigen_python")))return r;let n=t;for(let o=0;o<20;o++){const s=N.join(n,"packages","apigen","python");if(k.existsSync(N.join(s,"apigen_python")))return s;const i=N.dirname(n);if(i===n)break;n=i}return r}const Zi=["python3.13","python3.12","python3.11","python3"],St=[3,11];function Jg(e){const t=Q.spawnSync(e,["-c",'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")'],{encoding:"utf8",timeout:15e3});if(t.status!==0||!t.stdout)return;const[r,n]=t.stdout.trim().split(".").map(Number);if(!(!Number.isFinite(r)||!Number.isFinite(n)))return[r,n]}function Kg(){for(const e of Zi){const t=Jg(e);if(t&&(t[0]>St[0]||t[0]===St[0]&&t[1]>=St[1]))return e}throw new Error(`apigen-python-env: no Python >= ${St.join(".")} found on PATH (tried: ${Zi.join(", ")}). Install Python ${St.join(".")}+ or set APIGEN_PYTHON to a provisioned interpreter.`)}function Bg(e){return process.platform==="win32"?N.join(e,"Scripts","python.exe"):N.join(e,"bin","python3")}function Wg(e){const t=k.readFileSync(N.join(e,"pyproject.toml"));return ao.createHash("sha256").update(t).digest("hex")}function Qi(e){try{const t=JSON.parse(k.readFileSync(e,"utf8"));if(typeof t.pyprojectHash=="string"&&Array.isArray(t.extras))return t}catch{}}function Yg(e,t,r){const n=Date.now()+t;for(;;)try{k.mkdirSync(e,{recursive:!1});break}catch{if(Date.now()>n){try{k.rmdirSync(e)}catch{}continue}Q.spawnSync(process.execPath,["-e","setTimeout(()=>{}, 250)"],{timeout:5e3})}try{return r()}finally{try{k.rmdirSync(e)}catch{}}}function Zg(e={}){const t=Hg(),r=process.env.APIGEN_PYTHON;if(r){if(!k.existsSync(r))throw new Error(`apigen-python-env: APIGEN_PYTHON points to a missing file: ${r}`);return{python:r,venvDir:"",pythonPkgDir:t}}const n=[...new Set(e.extras??[])].sort(),o=e.envHome??process.env.APIGEN_PYENV_HOME??N.join(Ge.homedir(),".adhd","apigen"),s=N.join(o,"pyvenv"),i=N.join(s,".apigen-stamp"),a=Wg(t),c=Bg(s),u=()=>{if(!k.existsSync(c))return!1;const p=Qi(i);return!p||p.pyprojectHash!==a?!1:n.every(h=>p.extras.includes(h))};if(u())return{python:c,venvDir:s,pythonPkgDir:t};k.mkdirSync(o,{recursive:!0});const d=N.join(o,"pyvenv.lock"),l=e.lockTimeoutMs??3e5;return Yg(d,l,()=>{if(u())return{python:c,venvDir:s,pythonPkgDir:t};const p=Qi(i),h=[...new Set([...(p==null?void 0:p.extras)??[],...n])].sort();k.rmSync(s,{recursive:!0,force:!0});const f=Kg(),y=Q.spawnSync(f,["-m","venv",s],{encoding:"utf8",timeout:12e4});if(y.status!==0)throw new Error(`apigen-python-env: "${f} -m venv" failed (exit ${y.status}):
|
|
16
|
+
${y.stderr}`);const $=N.join(t,"build");k.existsSync($)&&k.rmSync($,{recursive:!0,force:!0});for(const _ of k.readdirSync(t))_.endsWith(".egg-info")&&k.rmSync(N.join(t,_),{recursive:!0,force:!0});const g=k.mkdtempSync(N.join(Ge.tmpdir(),"apigen-python-wheel-"));try{const _=Q.spawnSync(c,["-m","pip","wheel","--no-deps","--wheel-dir",g,t],{encoding:"utf8",timeout:6e5});if(_.status!==0)throw new Error(`apigen-python-env: pip wheel failed (exit ${_.status}):
|
|
17
|
+
${_.stderr}
|
|
18
|
+
stdout:
|
|
19
|
+
${_.stdout}`);const E=k.readdirSync(g).filter(V=>V.endsWith(".whl"));if(E.length===0)throw new Error("apigen-python-env: pip wheel produced no .whl file");const j=N.join(g,E[0]),I=h.length?`${j}[${h.join(",")}]`:j,x=Q.spawnSync(c,["-m","pip","install","--quiet","--disable-pip-version-check",I],{encoding:"utf8",timeout:6e5});if(x.status!==0)throw new Error(`apigen-python-env: pip install "${I}" failed (exit ${x.status}):
|
|
20
|
+
${x.stderr}
|
|
21
|
+
stdout:
|
|
22
|
+
${x.stdout}`)}finally{k.rmSync(g,{recursive:!0,force:!0})}const w={pyprojectHash:a,extras:h};return k.writeFileSync(i,JSON.stringify(w)),{python:c,venvDir:s,pythonPkgDir:t}})}let Xi;const Qg={ts:"api-fastify",py:"py-flask"},Xg=new Set(["py-grpc"]);function e$(e){const t={};for(const r of e){const n=r.indexOf("=");if(n<=0||n===r.length-1)throw new Error(`--mount expects <namespace>=<plugin> (got "${r}")`);t[r.slice(0,n)]=r.slice(n+1)}return t}function t$(e){return N.basename(e,N.extname(e))}function r$(e,t){const r=[],n=new Set;for(const o of e){const s=N.resolve(o),i=Ay(s);if(i===void 0)throw new Error(`--source ${o}: unrecognised extension; expected one of .ts/.tsx/.mts/.cts (TypeScript) or .py (Python)`);const a=t$(s);if(n.has(a))throw new Error(`duplicate namespace "${a}" — two sources resolve to the same /${a}/* prefix; rename one file or use --mount to disambiguate`);n.add(a);const c=t[a]??Qg[i];if(!c)throw new Error(`no default plugin for language "${i}" (source ${o}); pin one with --mount ${a}=<plugin>`);const u=Xg.has(c)?"grpc":"http";r.push({namespace:a,language:i,plugin:c,source:s,port:0,transport:u,alive:!1,ready:!1})}return r}function Ou(e){const t=e.split("?")[0]??"",r=t.startsWith("/")?t.slice(1):t,n=r.indexOf("/");return n===-1?r:r.slice(0,n)}function n$(){return new Promise((e,t)=>{const r=co.createServer();r.unref(),r.once("error",t),r.listen(0,"127.0.0.1",()=>{const n=r.address();if(n&&typeof n=="object"){const{port:o}=n;r.close(()=>e(o))}else r.close(()=>t(new Error("could not determine a free port")))})})}function o$(e){return new Promise(t=>{const r=fr.get({host:"127.0.0.1",port:e,path:"/_meta/health",timeout:1e3},n=>{const o=(n.statusCode??500)>=200&&(n.statusCode??500)<300;n.resume(),t(o)});r.on("error",()=>t(!1)),r.on("timeout",()=>{r.destroy(),t(!1)})})}function s$(e){return new Promise(t=>{const r=new co.Socket;r.setTimeout(1e3),r.once("connect",()=>{r.destroy(),t(!0)}),r.once("error",()=>t(!1)),r.once("timeout",()=>{r.destroy(),t(!1)}),r.connect(e,"127.0.0.1")})}async function i$(e,t=15e3,r=100){if(e.transport==="grpc")return a$(e,t,r);const n=Date.now()+t;for(;Date.now()<n;){if(!e.alive)throw new Error(`host "${e.namespace}" (${e.plugin}) exited before becoming ready`);if(await o$(e.port)){e.ready=!0;return}await new Promise(o=>setTimeout(o,r))}throw new Error(`host "${e.namespace}" (${e.plugin}) did not become ready within ${t}ms (port ${e.port})`)}async function a$(e,t=15e3,r=100){const n=Date.now()+t;for(;Date.now()<n;){if(!e.alive)throw new Error(`gRPC host "${e.namespace}" (${e.plugin}) exited before becoming ready`);if(await s$(e.port)){e.ready=!0;return}await new Promise(o=>setTimeout(o,r))}throw new Error(`gRPC host "${e.namespace}" (${e.plugin}) did not become ready within ${t}ms (port ${e.port})`)}function c$(){return process.argv[1]??""}function u$(e,t,r,n=[]){if(e.transport==="grpc")return d$(e,t,r,n);const o=[t,"run","--type",e.plugin,"--source",e.source,"--namespace",e.namespace,"--opt",`port=${e.port}`,"--opt","host=127.0.0.1"];e.language==="ts"&&o.push("--use","health"),o.push(...n);const s=Q.spawn(process.execPath,o,{stdio:["ignore","inherit","inherit"],env:process.env,detached:!1});return e.child=s,e.alive=!0,s.on("exit",(i,a)=>{e.alive=!1,e.ready=!1,r==null||r(e,i,a)}),s}function d$(e,t,r,n=[]){const o=[t,"run","--type",e.plugin,"--source",e.source,"--namespace",e.namespace,"--opt",`port=${e.port}`,"--opt","host=127.0.0.1",...n],s=Q.spawn(process.execPath,o,{stdio:["ignore","pipe","inherit"],env:process.env,detached:!1});e.child=s,e.alive=!0;const i=s.stdout;if(!i)throw new Error("child process stdout is null");const a=uo.createInterface({input:i});return a.on("line",c=>{try{JSON.parse(c.trim()).ready===!0&&!e.ready&&(e.ready=!0,a.close())}catch{}}),s.on("exit",(c,u)=>{e.alive=!1,e.ready=!1,a.close(),r==null||r(e,c,u)}),s}async function l$(e,t=3e3){var s,i;const r=e.filter(a=>a.child&&a.alive);if(r.length===0)return;const n=r.map(a=>new Promise(c=>{if(!a.child||a.child.exitCode!==null||!a.alive)return c();a.child.once("exit",()=>c())}));for(const a of r)(s=a.child)==null||s.kill("SIGTERM");const o=setTimeout(()=>{var a;for(const c of r)c.alive&&((a=c.child)==null||a.kill("SIGKILL"))},t);(i=o.unref)==null||i.call(o),await Promise.all(n),clearTimeout(o)}const dt=new Map;function f$(e){const t=`127.0.0.1:${e}`;let r=dt.get(t);return(!r||r.closed||r.destroyed)&&(r=Ga.connect(`http://127.0.0.1:${e}`),r.once("close",()=>dt.delete(t)),r.once("error",()=>{dt.delete(t),r==null||r.destroy()}),r.setTimeout(6e4,()=>r==null?void 0:r.close()),r.unref(),dt.set(t,r)),r}function p$(){for(const e of dt.values())try{e.destroy()}catch{}dt.clear()}const m$=Buffer.from(`PRI * HTTP/2.0\r
|
|
23
|
+
\r
|
|
24
|
+
SM\r
|
|
25
|
+
\r
|
|
26
|
+
`),ju=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","host"]);function ea(e,t){return JSON.stringify({code:"internal",message:`host '${e}' unavailable: ${t}`,details:{gatewayCode:"unavailable",host:e,httpStatus:503}})}function h$(e){const t={};let r=!0;for(const n of e){const o=n.alive&&n.ready?"ready":"down";t[n.namespace]=o,o!=="ready"&&(r=!1)}return{status:r?"ok":"degraded",hosts:t}}function Ue(e,t,r){if(!(e.destroyed||e.closed))try{e.respond({":status":200,"content-type":"application/grpc"},{waitForTrailers:!0}),e.once("wantTrailers",()=>{try{e.sendTrailers({"grpc-status":"14","grpc-message":`host '${t}' unavailable: ${r}`})}catch{}}),e.end()}catch{e.destroy()}}const y$=new Set(["grpc-status","grpc-message","grpc-encoding"]);function ta(e,t,r,n){let o;try{o=f$(r)}catch(d){Ue(e,n,`session error: ${d}`);return}const s={":method":t[":method"]??"POST"},i=t[":path"];i!==void 0&&(s[":path"]=i),s[":scheme"]="http";for(const[d,l]of Object.entries(t))d.startsWith(":")||ju.has(d.toLowerCase())||l!==void 0&&(s[d]=l);s.te="trailers";let a;try{a=o.request(s,{endStream:!1})}catch(d){Ue(e,n,`upstream request failed: ${d}`);return}e.on("data",d=>{a.destroyed||a.write(d)}),e.on("end",()=>{a.destroyed||a.end()});let c=null,u=!1;a.once("response",(d,l)=>{if(e.destroyed||e.closed)return;const p=(l&1)!==0,h={},f={};for(const[y,$]of Object.entries(d)){if(y===":status"){h[":status"]=$;continue}y.startsWith(":")||(p&&y$.has(y)?f[y]=$:h[y]=$)}if(h[":status"]===void 0&&(h[":status"]=200),p){u=!0,c=Object.keys(f).length>0?f:{"grpc-status":"0"};try{e.respond(h,{waitForTrailers:!0}),e.once("wantTrailers",()=>{try{e.sendTrailers(c??{})}catch{}}),e.end()}catch{e.destroy(),a.destroy()}return}try{e.respond(h,{waitForTrailers:!0})}catch{e.destroy(),a.destroy();return}a.on("data",y=>{e.destroyed||e.write(y)})}),a.once("trailers",d=>{const l={};for(const[p,h]of Object.entries(d))!p.startsWith(":")&&h!==void 0&&(l[p]=h);c=l}),a.once("end",()=>{if(!u&&!e.destroyed&&!e.closed){e.once("wantTrailers",()=>{try{e.sendTrailers(c??{})}catch{}});try{e.end()}catch{}}}),a.once("error",d=>{e.destroyed||Ue(e,n,`upstream error: ${d}`)}),e.once("error",()=>{a.destroyed||a.destroy()}),e.once("close",()=>{a.destroyed||a.destroy()})}function ra(e,t,r,n){const o=e.url??"/",s=Ou(o);if(s==="_meta"){const u=o.split("?")[0];if(u==="/_meta/health"){const d=JSON.stringify(h$(n));t.writeHead(200,{"content-type":"application/json"}),t.end(d);return}t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({code:"not_found",message:`unknown meta route ${u}`}));return}const i=r.get(s);if(!i){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({code:"not_found",message:`no host mounted at /${s}`}));return}if(i.transport==="grpc"){t.writeHead(426,{"content-type":"application/json",upgrade:"h2c"}),t.end(JSON.stringify({code:"invalid_argument",message:`host '${s}' is a gRPC endpoint; use gRPC/HTTP-2 (content-type: application/grpc)`}));return}if(!i.alive){t.writeHead(503,{"content-type":"application/json"}),t.end(ea(s,"child process is not running"));return}const a={};for(const[u,d]of Object.entries(e.headers))!ju.has(u.toLowerCase())&&d!==void 0&&(a[u]=d);const c=fr.request({host:"127.0.0.1",port:i.port,method:e.method,path:o,headers:a},u=>{t.writeHead(u.statusCode??502,u.headers),u.pipe(t)});c.on("error",()=>{if(t.headersSent){t.destroy();return}t.writeHead(503,{"content-type":"application/json"}),t.end(ea(s,"child connection failed"))}),e.pipe(c)}function g$(e,t,r,n){const o=t[":path"]??"",s=o.indexOf(".");let i="";if(s>1?i=o.slice(1,s):i=Ou(o),i==="grpc"){const c=n.find(u=>u.transport==="grpc"&&u.alive);if(!c){Ue(e,"grpc","no gRPC host available for reflection");return}ta(e,t,c.port,"grpc");return}const a=r.get(i);if(!a){Ue(e,i,`no host mounted at namespace "${i}"`);return}if(!a.alive){Ue(e,i,"child process is not running");return}if(a.transport!=="grpc"){Ue(e,i,`host '${i}' is not a gRPC host`);return}ta(e,t,a.port,i)}function $$(e){const t=new Map;for(const i of e)t.set(i.namespace,i);if(!e.some(i=>i.transport==="grpc"))return fr.createServer((i,a)=>{ra(i,a,t,e)});const n=fr.createServer((i,a)=>{ra(i,a,t,e)}),o=Ga.createServer();o.on("stream",(i,a)=>{g$(i,a,t,e)}),o.on("error",()=>{});const s=co.createServer();return s.on("connection",i=>{i.once("error",()=>i.destroy()),i.once("readable",()=>{const a=i.read(3);if(!a){i.destroy();return}const c=a.length>=3&&a.slice(0,3).equals(m$.slice(0,3));if(i.unshift(a),c){const u=i;u.alpnProtocol="h2",o.emit("connection",i)}else n.emit("connection",i)})}),s.on("error",i=>n.emit("error",i)),n.listen.bind(n),n.close.bind(n),n.address.bind(n),n._rawServer=s,n.listen=(...i)=>s.listen(...i),n.close=i=>(o.close(),s.close(i)),n.address=()=>s.address(),n}async function v$(e){const t=e.log??(d=>process.stderr.write(`${d}
|
|
27
|
+
`)),r=e.cliPath??c$(),n=r$(e.sources,e.mounts??{}),o=new Set(["py-flask","py-grpc"]),s=process.env.APIGEN_PYTHON,i=s!==void 0&&s!==Xi;if(n.some(d=>o.has(d.plugin))&&!i){const d=n.some(p=>p.plugin==="py-grpc");t(`[serve] provisioning python env${d?" (grpc)":""}…`),delete process.env.APIGEN_PYTHON;const l=Zg({extras:d?["grpc"]:[]});Xi=l.python,process.env.APIGEN_PYTHON=l.python,t(`[serve] python: ${l.python}`)}for(const d of n)d.port=await n$(),u$(d,r,(l,p,h)=>{t(`[serve] host "${l.namespace}" (${l.plugin}) exited code=${p} signal=${h} — /${l.namespace}/* now unavailable`)}),t(`[serve] spawned "${d.namespace}" (${d.plugin}/${d.transport}) → :${d.port} [${d.source}]`);await Promise.all(n.map(d=>i$(d).then(()=>t(`[serve] host "${d.namespace}" ready on :${d.port} (${d.transport})`))));const a=$$(n);await new Promise((d,l)=>{a.once("error",l),a.listen(e.port,"127.0.0.1",d)}),t(`[serve] front listening on :${e.port}`);for(const d of n)t(`[serve] /${d.namespace}/* → :${d.port} (${d.plugin}/${d.transport})`);let c=!1;return{hosts:n,front:a,shutdown:async()=>{c||(c=!0,t("[serve] shutting down — killing children…"),p$(),await new Promise(d=>a.close(()=>d())),await l$(n),t("[serve] all children terminated"))}}}function w$(e){e.command("serve").description("Mount many sources/languages behind one HTTP/gRPC front").requiredOption("--source <path>","Source file to mount (repeatable; .ts → api-fastify, .py → py-flask)",(t,r)=>[...r,t],[]).requiredOption("--port <port>","Front HTTP/gRPC port",t=>Number.parseInt(t,10)).option("--mount <ns=plugin>","Pin a namespace to an explicit plugin (repeatable; use py-grpc for gRPC)",(t,r)=>[...r,t],[]).action(async t=>{const r=e$(t.mount),{shutdown:n}=await v$({sources:t.source,port:t.port,mounts:r});let o=!1;const s=i=>{o||(o=!0,process.stderr.write(`
|
|
28
|
+
[serve] received ${i}
|
|
29
|
+
`),n().then(()=>process.exit(0)).catch(a=>{process.stderr.write(`[serve] shutdown error: ${a}
|
|
30
|
+
`),process.exit(1)}))};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM")),process.on("uncaughtException",i=>{s("SIGTERM"),setImmediate(()=>{throw i})}),process.on("unhandledRejection",i=>{s("SIGTERM"),setImmediate(()=>{throw i})})})}function _$(e,t,r=n=>{process.stdout.write(n)}){e.command("list-types").description("List every registered --type plugin id, its description, and generate/run capability").action(()=>{r(Ky(t)+`
|
|
31
|
+
`)})}const xn="$apigen";let na=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function b$(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new na(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const n of t.values())if(n.matches(r))return n},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),n={register(){throw new na("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of r.values())if(s.matches(o))return s},get(o){return r.get(o)},ids(){return[...r.keys()]},freeze(){return n}};return n}}}const hs="x-apigen-logical",ys="x-apigen-codec",Mn="x-apigen-ctor",Fn="x-apigen-tojson",S$="0.1.0";function oa(e,t){return{registry:e,resolve:r=>{throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function tt(e,t,r){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return tt(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=ku(e,s,t);return tt(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return nn(e,t,r);const a=t.items;if(!a)return e.map(u=>Le(u));const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?Le(u):tt(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>tt(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return nn(e,t,r);const a=t.properties;if(!a)return Le(e);const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=tt(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?nn(e,t,r):Le(e)}function rt(e,t,r){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return rt(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=ku(e,s,t);return rt(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?u:rt(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>rt(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=rt(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?E$(e,r):e}function ku(e,t,r,n){const o=r.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function nn(e,t,r){for(const n of r.registry.ids()){const o=r.registry.get(n);if(o)try{const s=o.encode(e,o.schema,r);return{[xn]:n,v:s}}catch{}}return Le(e)}function E$(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&xn in e){const r=e,n=r[xn],o=t.registry.get(n);if(o)return o.decode(r.v,o.schema,t)}return e}function Le(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Le);if(typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))n!==void 0&&(t[r]=Le(n));return t}return null}function N$(e){return{encode(t,r,n){const o=oa(e,n);return tt(t,r,o)},decode(t,r,n){const o=oa(e,n);return rt(t,r,o)}}}const gs={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,r){return e.toISOString()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${r.path}", got ${typeof e}`);return new Date(String(e))}if(r.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${r.path}": ${JSON.stringify(e)}`);return new Date(e)}},$s={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,r){return String(e)},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${r.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(r.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},vs={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,r){return e},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e)}if(r.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${r.path}" is not a valid decimal string`);return e}},ws={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,r){return Buffer.from(e).toString("base64")},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${r.path}", got ${typeof e}`);return new Uint8Array(0)}if(r.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${r.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},O$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,_s={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,r){return e.toLowerCase()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e).toLowerCase()}if(r.mode==="strict"&&!O$.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Un="NaN",Ln="Infinity",zn="-Infinity",j$=new Set([Un,Ln,zn]),bs={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,r){return Number.isNaN(e)?Un:e===1/0?Ln:e===-1/0?zn:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Un)return NaN;if(e===Ln)return 1/0;if(e===zn)return-1/0;const n=Number(e);if(!Number.isNaN(n))return n}if(r.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${r.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...j$].join(", ")}.`);return NaN}},k$=[gs,$s,vs,ws,_s,bs];function P$(e,t={}){for(const r of k$)e.register(r,{override:t.override??!1})}gs.id,$s.id,vs.id,ws.id,_s.id,bs.id;const Pu=b$();P$(Pu);const Au=N$(Pu.freeze());function A$(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function T$(e){var t,r;const n=(r=(t=e.input)==null?void 0:t.properties)==null?void 0:r.data;return Object.keys((n==null?void 0:n.properties)??{})}function I$(e,t){var r,n,o;const s=(o=(n=(r=e.input)==null?void 0:r.properties)==null?void 0:n.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function C$(e,t){return t===void 0||e===void 0?e:Au.decode(e,t)}function on(e,t){const r=t.output;return!r||Object.keys(r).length===0?e:Au.encode(e,r)}async function D$(e,t,r,n,o,s){const i=T$(r).map(c=>C$(s[c],I$(r,c)));if(A$(r,"session")&&t){const c=await t({session:o.session}),u=await e[n](c,...i);return on(u,r)}if(r.hasCtx){const c=t?await t(o):void 0,u=await e[n](c,...i);return on(u,r)}const a=await e[n](...i);return on(a,r)}const R$={"decimal.js":"Decimal"};function x$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(R$).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${x$(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function M$(e={}){const t=e.level??"info",r=typeof e.destination=="string"&&e.destination.length>0,n=!r&&!!process.stderr.isTTY,o=e.format??(n?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!r,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...r?{destination:e.destination,mkdir:!0}:{destination:2}}},te(s);const i=r?te.destination({dest:e.destination,mkdir:!0,sync:!0}):te.destination(2);return te(s,i)}function Tu(e){return e?e.type==="array"?`${Tu(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function F$(e){var t;const r=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,n=(r==null?void 0:r.properties)??{},o=new Set((r==null?void 0:r.required)??[]),s=Object.entries(n).map(([a,c])=>({name:a,type:Tu(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const Ss=new Ft({allErrors:!0});Ut(Ss);for(const e of[hs,ys,Mn,Fn,"discriminator"])Ss.addKeyword({keyword:e,valid:!0});Ss.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);class Pe extends Error{constructor(t,r){super(r),this.name="UnionCodecError",this.code=t}}function sn(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t;if(typeof r.propertyName!="string")return;const n=r.mapping;if(!(n===null||typeof n!="object"||Array.isArray(n)))return{propertyName:r.propertyName,mapping:n}}function Iu(e,t){const r=e[ys];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function U$(e,t,r){const n=Iu(t,r);return n?n.encode(e,t,r):e}function L$(e,t,r){const n=Iu(t,r);return n?n.decode(e,t,r):e}function z$(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[hs]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:sn(n)!==void 0},encode(n,o,s){const i=sn(o);if(!i)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=n[a];if(u==null)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const d=String(u),l=c[d];if(!l)throw new Pe("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${d}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(l);return U$(n,p,{...s,path:`${s.path}[${d}]`})},decode(n,o,s){if(n===null||typeof n!="object"||Array.isArray(n)){let f;throw n===null?f="null":Array.isArray(n)?f="array":f=typeof n,new Pe("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${f}.`)}const i=n,a=sn(o);if(!a)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,d=i[c];if(d==null)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const l=String(d),p=u[l];if(!p)throw new Pe("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return L$(n,h,{...s,path:`${s.path}[${l}]`})}}}const q$="x-apigen-instances";let Xt=class extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}};function sa(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function V$(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function ia(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function G$(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function H$(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[hs]==="nominal"?!0:o[ys]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Xt("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=sa(s),c=typeof s[Fn]=="string"?s[Fn]:"toJSON",u=o[c];if(typeof u=="function"){const f=u.call(o);if(f!==null&&typeof f=="object"&&!Array.isArray(f)){const y={};for(const[$,g]of Object.entries(f))y[$]=ia(g,a[$],{...i,path:`${i.path}/${$}`});return y}return f}const d={},l=Object.keys(a),p=o,h=l.length>0?l:Object.keys(p);for(const f of h){const y=p[f];y!==void 0&&(d[f]=ia(y,a[f],{...i,path:`${i.path}/${f}`}))}return d}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let d;throw o===null?d="null":Array.isArray(o)?d="array":d=typeof o,new Xt("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${d}.`)}const a=o;for(const d of V$(s))if(!(d in a))throw new Xt("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${d}" missing on the wire at "${i.path}".`);if(s[q$]===!1)throw new Xt("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=sa(s),u={};for(const[d,l]of Object.entries(a))u[d]=G$(l,c[d],{...i,path:`${i.path}/${d}`});if(n){const d=typeof s[Mn]=="string"?s[Mn]:"fromJSON",l=n[d];if(typeof l=="function")return l.call(n,u);const p=n;return new p(u)}return u}}}const J$=[gs,$s,vs,ws,_s,bs],K$={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},aa=H$({id:"ts.NominalSentinel",schema:K$}),B$={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ca=z$({id:"ts.UnionSentinel",schema:B$});function W$(){const e=[...J$.map(t=>[t.id,t]),[aa.id,aa],[ca.id,ca]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:S$,codecs:W$()});function Cu(e,t,r){var n;const o=typeof((n=t==null?void 0:t.input)==null?void 0:n.description)=="string"?t.input.description:void 0,s=[r,o].filter(i=>typeof i=="string"&&i.length>0);return s.length>0?s.join(" — "):e}function ua(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};const t=e;return t.type==="object"?{outputSchema:t,wrapped:!1}:{outputSchema:{type:"object",properties:{result:t},required:["result"]},wrapped:!0}}function Y$(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Z$(){return`// Auto-generated by @adhd/apigen-cli — do not edit
|
|
14
32
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
15
33
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
16
34
|
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
17
|
-
import { dispatch } from '@adhd/apigen-runtime'
|
|
35
|
+
import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
|
|
18
36
|
import { toolMetas, groupFns, groupCreateClient } from './index.js'
|
|
19
37
|
|
|
20
38
|
// §9.1 — extract envelope from MCP _meta["x-<pluginId>-<field>"].
|
|
@@ -35,11 +53,21 @@ function extractEnvelope(schema: Record<string, unknown>, meta: Record<string, u
|
|
|
35
53
|
const server = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabilities: { tools: {} } })
|
|
36
54
|
|
|
37
55
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
38
|
-
tools: Object.entries(toolMetas).map(([name, meta]) =>
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
56
|
+
tools: Object.entries(toolMetas).map(([name, meta]) => {
|
|
57
|
+
// BUG-APIGEN-019: publish the function's return-type schema (oneOf+discriminator
|
|
58
|
+
// for unions) as MCP's outputSchema — wrapped under \`result\` when it isn't
|
|
59
|
+
// top-level type:"object", since the MCP protocol requires that shape.
|
|
60
|
+
const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
|
|
61
|
+
return {
|
|
62
|
+
name,
|
|
63
|
+
// BUG-APIGEN-020: description baked at generate time by generate.ts —
|
|
64
|
+
// documents the "data" envelope calling convention (+ any envelope
|
|
65
|
+
// fields) so consumers don't have to discover it by trial and error.
|
|
66
|
+
description: (meta as any).description ?? name,
|
|
67
|
+
inputSchema: (meta.schema as any).input,
|
|
68
|
+
...(outputSchema ? { outputSchema } : {}),
|
|
69
|
+
}
|
|
70
|
+
}),
|
|
43
71
|
}))
|
|
44
72
|
|
|
45
73
|
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
@@ -57,17 +85,23 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
|
57
85
|
envelope,
|
|
58
86
|
((args as any)['data'] ?? {}) as Record<string, unknown>,
|
|
59
87
|
)
|
|
60
|
-
|
|
88
|
+
// BUG-APIGEN-019: pair outputSchema with a matching structuredContent value.
|
|
89
|
+
const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
|
|
90
|
+
const structuredContent = wrapMcpStructuredContent(wrapped, result)
|
|
91
|
+
return {
|
|
92
|
+
content: [{ type: 'text', text: JSON.stringify(result) }],
|
|
93
|
+
...(structuredContent ? { structuredContent } : {}),
|
|
94
|
+
}
|
|
61
95
|
})
|
|
62
96
|
|
|
63
97
|
const transport = new StdioServerTransport()
|
|
64
98
|
server.connect(transport)
|
|
65
|
-
`}function
|
|
99
|
+
`}function Q$(e,t){return`// Auto-generated by @adhd/apigen-cli — do not edit
|
|
66
100
|
import { createServer } from 'node:http'
|
|
67
101
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
68
102
|
${e==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
|
|
69
103
|
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
70
|
-
import { dispatch } from '@adhd/apigen-runtime'
|
|
104
|
+
import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
|
|
71
105
|
import { toolMetas, groupFns, groupCreateClient } from './index.js'
|
|
72
106
|
|
|
73
107
|
// §9.1 — extract envelope from MCP _meta["x-<pluginId>-<field>"].
|
|
@@ -88,11 +122,21 @@ function extractEnvelope(schema: Record<string, unknown>, meta: Record<string, u
|
|
|
88
122
|
const mcpServer = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabilities: { tools: {} } })
|
|
89
123
|
|
|
90
124
|
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
91
|
-
tools: Object.entries(toolMetas).map(([name, meta]) =>
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
125
|
+
tools: Object.entries(toolMetas).map(([name, meta]) => {
|
|
126
|
+
// BUG-APIGEN-019: publish the function's return-type schema (oneOf+discriminator
|
|
127
|
+
// for unions) as MCP's outputSchema — wrapped under \`result\` when it isn't
|
|
128
|
+
// top-level type:"object", since the MCP protocol requires that shape.
|
|
129
|
+
const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
|
|
130
|
+
return {
|
|
131
|
+
name,
|
|
132
|
+
// BUG-APIGEN-020: description baked at generate time by generate.ts —
|
|
133
|
+
// documents the "data" envelope calling convention (+ any envelope
|
|
134
|
+
// fields) so consumers don't have to discover it by trial and error.
|
|
135
|
+
description: (meta as any).description ?? name,
|
|
136
|
+
inputSchema: (meta.schema as any).input,
|
|
137
|
+
...(outputSchema ? { outputSchema } : {}),
|
|
138
|
+
}
|
|
139
|
+
}),
|
|
96
140
|
}))
|
|
97
141
|
|
|
98
142
|
mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
@@ -110,14 +154,35 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
|
110
154
|
envelope,
|
|
111
155
|
((args as any)['data'] ?? {}) as Record<string, unknown>,
|
|
112
156
|
)
|
|
113
|
-
|
|
157
|
+
// BUG-APIGEN-019: pair outputSchema with a matching structuredContent value.
|
|
158
|
+
const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
|
|
159
|
+
const structuredContent = wrapMcpStructuredContent(wrapped, result)
|
|
160
|
+
return {
|
|
161
|
+
content: [{ type: 'text', text: JSON.stringify(result) }],
|
|
162
|
+
...(structuredContent ? { structuredContent } : {}),
|
|
163
|
+
}
|
|
114
164
|
})
|
|
115
165
|
|
|
116
166
|
const mcpTransport = new ${e==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
|
|
117
167
|
const httpServer = createServer((req, res) => (mcpTransport as any).handleRequest(req, res))
|
|
118
168
|
httpServer.listen(${t}, () => console.error('MCP ${e} server on port ${t}'))
|
|
119
|
-
`}function
|
|
120
|
-
`)}function
|
|
121
|
-
`)}]}}function Il(e,t,n){var s,o;const r=(o=(s=n.http)==null?void 0:s.verb)==null?void 0:o[e];return r==="GET"||r==="POST"?r:t["x-apigen-safe"]?"GET":"POST"}function Wr(e,t){var o;const n=((o=e.input)==null?void 0:o.properties)??{},r=e["x-apigen-envelope"],s={};for(const i of Object.keys(n)){if(i==="data")continue;const a=(r==null?void 0:r[i])??"adhd",c=gt(a,i),u=t[c];u!==void 0&&(s[i]=u)}return s}function Cl(e){return e instanceof Kt?Hs[e.code]??500:500}async function Al(e){const t=e.options.port??3e3,n=e.options.host??"127.0.0.1",r=e.options.routePrefix??"",s=e.options.projection??{},o=e.logger??qt(),i=go({logger:o});i.setErrorHandler((c,u,l)=>{const f=Cl(c),h=c instanceof Kt?c.toJSON():{code:"internal",message:c.message??"Internal error"};l.status(f).send(h)});const a=[];for(const c of e.packages)for(const[u,l]of Object.entries(c.schemas)){const f=`${r}/${c.id}/${u}`,h=Il(`${c.id}:${u}`,l,s),{params:g,text:m}=yn(l);a.push({method:h,route:f,text:m,params:g}),h==="GET"?i.get(f,async v=>{const y=Wr(l,v.headers);return dt(c.fns,c.createClient,l,u,y,v.query)}):i.post(f,async v=>{const{data:y={}}=v.body,p=Wr(l,v.headers);return dt(c.fns,c.createClient,l,u,p,y)})}await i.listen({port:t,host:n}),o.info({host:n,port:t},`listening on http://${n}:${t}`);for(const c of a)o.info({method:c.method,route:c.route,body:{data:c.params}},`${c.method} ${c.route} body { data: {${c.text?` ${c.text} `:""}} }`);return new Promise(c=>{e.signal&&e.signal.addEventListener("abort",async()=>{await i.close(),c()})})}const Ml={id:"api-fastify",description:"Expose functions as Fastify HTTP POST routes",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(e){return Rl(e)},run(e){return Al(e)}};function xl(e,t,n){var s,o;const r=(o=(s=n.http)==null?void 0:s.verb)==null?void 0:o[e];return r==="GET"||r==="POST"?r:t["x-apigen-safe"]?"GET":"POST"}function ql(e){var s;const t=((s=e.input)==null?void 0:s.properties)??{},n=e["x-apigen-envelope"],r={};for(const o of Object.keys(t)){if(o==="data")continue;const i=(n==null?void 0:n[o])??"adhd";r[o]=gt(i,o)}return r}function Dl(e){const t=e.options.port??3e3,n=e.options.routePrefix??"",r=e.options.projection??{},s=["// Auto-generated by @adhd/apigen-cli — do not edit","import express, { Router } from 'express'","import { dispatch, buildFnTable } from '@adhd/apigen-runtime'"];for(const o of e.packages)s.push(`import * as ${o.id}_ns from '${o.importPath}'`),s.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);s.push(""),s.push(`const schemas: Record<string, unknown> = ${JSON.stringify(Object.fromEntries(e.packages.flatMap(o=>Object.entries(o.schemas).map(([i,a])=>[`${o.id}:${i}`,{schema:a,pkgId:o.id}]))),null,2)}`),s.push(""),s.push("const app = express()"),s.push("app.use(express.json())"),s.push("const router = Router()"),s.push("");for(const o of e.packages)for(const[i,a]of Object.entries(o.schemas)){const c=`${n}/${o.id}/${i}`,u=xl(`${o.id}:${i}`,a,r),l=ql(a),f=Object.entries(l);if(u==="GET"){if(s.push(`router.get('${c}', async (req, res) => {`),f.length>0){const h=f.map(([g,m])=>`'${g}': req.headers['${m}']`).join(", ");s.push(` const envelope: Record<string, unknown> = { ${h} }`)}else s.push(" const envelope: Record<string, unknown> = {}");s.push(` const result = await dispatch(${o.id}_fns as any, undefined, schemas['${o.id}:${i}']['schema'] as any, '${i}', envelope, req.query as any)`),s.push(" res.json(result)"),s.push("})")}else{if(s.push(`router.post('${c}', async (req, res) => {`),s.push(" const { data = {} } = req.body as Record<string, unknown>"),f.length>0){const h=f.map(([g,m])=>`'${g}': req.headers['${m}']`).join(", ");s.push(` const envelope: Record<string, unknown> = { ${h} }`)}else s.push(" const envelope: Record<string, unknown> = {}");s.push(` const result = await dispatch(${o.id}_fns as any, undefined, schemas['${o.id}:${i}']['schema'] as any, '${i}', envelope, data as any)`),s.push(" res.json(result)"),s.push("})")}}return s.push(""),s.push("app.use(router)"),s.push(`app.listen(${t})`),s.push(""),s.push("export default router"),{files:[{path:"routes.ts",content:s.join(`
|
|
122
|
-
`)}]}}function Fl(e,t,n){var s,o;const r=(o=(s=n.http)==null?void 0:s.verb)==null?void 0:o[e];return r==="GET"||r==="POST"?r:t["x-apigen-safe"]?"GET":"POST"}function Br(e,t){var o;const n=((o=e.input)==null?void 0:o.properties)??{},r=e["x-apigen-envelope"],s={};for(const i of Object.keys(n)){if(i==="data")continue;const a=(r==null?void 0:r[i])??"adhd",c=gt(a,i),u=t[c];u!==void 0&&(s[i]=u)}return s}function Vl(e){return e instanceof Kt?Hs[e.code]??500:500}async function zl(e){const t=e.options.port??3e3,n=e.options.host??"127.0.0.1",r=e.options.routePrefix??"",s=e.options.projection??{},o=e.logger??qt(),i=Qt();i.use(yo.pinoHttp({logger:o})),i.use(Qt.json());const a=Qt.Router(),c=[];for(const l of e.packages)for(const[f,h]of Object.entries(l.schemas)){const g=`${r}/${l.id}/${f}`,m=Fl(`${l.id}:${f}`,h,s),{params:v,text:y}=yn(h);c.push({method:m,route:g,text:y,params:v}),m==="GET"?a.get(g,async(p,_,E)=>{try{const j=Br(h,p.headers),N=await dt(l.fns,l.createClient,h,f,j,p.query);_.json(N)}catch(j){E(j)}}):a.post(g,async(p,_,E)=>{try{const{data:j={}}=p.body,N=Br(h,p.headers),q=await dt(l.fns,l.createClient,h,f,N,j);_.json(q)}catch(j){E(j)}})}i.use(a),i.use((l,f,h,g)=>{const m=Vl(l),v=l instanceof Kt?l.toJSON():{code:"internal",message:l.message??"Internal error"};h.status(m).json(v)});const u=await new Promise(l=>{const f=i.listen(t,n,()=>l(f))});o.info({host:n,port:t},`listening on http://${n}:${t}`);for(const l of c)o.info({method:l.method,route:l.route,body:{data:l.params}},`${l.method} ${l.route} body { data: {${l.text?` ${l.text} `:""}} }`);return new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{u.close(()=>l())})})}const Ll={id:"api-express",description:"Expose functions as Express HTTP POST routes",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(e){return Dl(e)},run(e){return zl(e)}};function Ul(e){var s;const t=((s=e.input)==null?void 0:s.properties)??{},n=e["x-apigen-envelope"],r=[];for(const o of Object.keys(t)){if(o==="data")continue;const i=(n==null?void 0:n[o])??"adhd";r.push({field:o,pluginId:i,flag:Yu(i,o),envVar:Zu(i,o)})}return r}function Kl(e){var s,o,i;const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-runtime'"];for(const a of e.packages)r.push(`import * as ${a.id}_ns from '${a.importPath}'`),r.push(`const ${a.id}_fns = buildFnTable(${a.id}_ns as Record<string, unknown>)`);r.push(""),r.push(`const schemas: Record<string, unknown> = ${JSON.stringify(Object.fromEntries(e.packages.flatMap(a=>Object.entries(a.schemas).map(([c,u])=>[`${a.id}:${c}`,u]))),null,2)}`),r.push(""),r.push(`const program = new Command().name('${t}').version('${n}')`),r.push("");for(const a of e.packages)for(const[c,u]of Object.entries(a.schemas)){const l=ss(u),f=rs(u,"session"),h=Ul(u),g=(o=(s=u.input)==null?void 0:s.properties)==null?void 0:o.data,m=(g==null?void 0:g.properties)??{},v=(g==null?void 0:g.required)??[];r.push("program"),r.push(` .command('${c}')`);for(const p of h){const _=p.flag.replace(/^--/,"");r.push(` .option('${p.flag} <${_}>', '${p.field} (env: ${p.envVar})')`)}f&&!h.some(p=>p.field==="session")&&r.push(" .option('--session <key>', 'Session key')");const y=p=>p.replace(/[A-Z]/g,_=>"-"+_.toLowerCase());for(const p of l){const _=y(p),E=((i=m[p])==null?void 0:i.type)==="boolean",j=v.includes(p);E?r.push(` .option('--${_}')`):j?r.push(` .requiredOption('--${_} <${_}>')`):r.push(` .option('--${_} <${_}>')`)}if(r.push(" .action(async (opts: Record<string, unknown>) => {"),r.push(` const domainArgs: Record<string, unknown> = { ${l.map(p=>`'${p}': opts['${p}']`).join(", ")} }`),h.length>0){const p=h.map(_=>{const j=_.flag.replace(/^--/,"").replace(/-([a-z])/g,(N,q)=>q.toUpperCase());return`'${_.field}': opts['${j}'] ?? process.env['${_.envVar}']`});r.push(` const envelope: Record<string, unknown> = { ${p.join(", ")} }`)}else f?r.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):r.push(" const envelope: Record<string, unknown> = {}");r.push(` const result = await dispatch(${a.id}_fns as any, undefined, schemas['${a.id}:${c}'] as any, '${c}', envelope, domainArgs)`),r.push(" console.log(JSON.stringify(result))"),r.push(" })")}return r.push(""),r.push("program.parseAsync()"),{files:[{path:"cli.ts",content:r.join(`
|
|
123
|
-
`)
|
|
169
|
+
`}function X$(e,t){const r=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const n of e)r.push(`import * as ${n.id}_ns from '${n.importPath}'`),r.push(`const ${n.id}_fns = buildFnTable(${n.id}_ns as Record<string, unknown>)`);r.push(""),r.push("export const toolMetas: Record<string, { group: string; schema: unknown; description: string }> = {");for(const n of e)for(const[o,s]of Object.entries(n.schemas)){const i=Cu(o,s,t[o]);r.push(` ${o}: { group: '${n.id}', schema: ${JSON.stringify(s)}, description: ${JSON.stringify(i)} },`)}r.push("}"),r.push(""),r.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const n of e)r.push(` '${n.id}': ${n.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);r.push("}"),r.push(""),r.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const n of e)r.push(` '${n.id}': undefined, // injected at startup if createClient provided`);return r.push("}"),r.join(`
|
|
170
|
+
`)}function ev(e){const t=e.options.transport??"stdio",r=e.options.port??3e3,n=e.options.toolDescriptions??{},o=X$(e.packages,n),s=t==="stdio"?Z$():Q$(t,r);return{files:[{path:"index.ts",content:o},{path:"server.ts",content:s}]}}const tv={"decimal.js":"Decimal"};function rv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(tv).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${rv(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function nv(e,t){return`x-${e}-${t}`}const ov=nv;function sv(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{},o=e["x-apigen-envelope"],s={};for(const i of Object.keys(n)){if(i==="data")continue;const a=(o==null?void 0:o[i])??"adhd",c=ov(a,i),u=t[c];u!==void 0&&(s[i]=u)}return s}function da(e,t){const r=e.options.toolDescriptions??{},n=new ld.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}}),o={};for(const s of e.packages)for(const i of Object.keys(s.schemas))o[i]={group:s.id,schema:s.schemas[i]};return n.setRequestHandler(Xs.ListToolsRequestSchema,async()=>({tools:Object.entries(o).map(([s,i])=>{const{outputSchema:a}=ua(i.schema.output);return{name:s,description:Cu(s,i.schema,r[s]),inputSchema:i.schema.input,...a?{outputSchema:a}:{}}})})),n.setRequestHandler(Xs.CallToolRequestSchema,async s=>{const{name:i,arguments:a={}}=s.params,c=a._meta??{},u=o[i];if(!u)throw new Error(`Unknown tool: ${i}`);const d=e.packages.find(y=>y.id===u.group);if(!d)throw new Error(`Package not found: ${u.group}`);const l=u.schema,p=sv(l,c),h=a.data??{},f=Date.now();try{if(!d.fns)throw new Error(`Package ${d.id} has no functions`);const y=await D$(d.fns,d.createClient,u.schema,i,p,h);t.info({tool:i,ms:Date.now()-f},`→ ${i}`);const{wrapped:$}=ua(l.output),g=Y$($,y);return{content:[{type:"text",text:JSON.stringify(y)}],...g?{structuredContent:g}:{}}}catch(y){throw t.error({tool:i,ms:Date.now()-f,err:y},`✗ ${i}`),y}}),{server:n,toolMetas:o}}async function iv(e){const t=e.options.transport??"stdio",r=e.options.port??3e3,n=e.options.host??"127.0.0.1",o=e.logger??M$();o.info(`mcp server starting (${t})`);const{server:s,toolMetas:i}=da(e,o),a=Object.keys(i);o.info({tools:a},`${a.length} tools available`);for(const[u,d]of Object.entries(i)){const{params:l,text:p}=F$(d.schema);o.info({tool:u,args:{data:l}},`tool: ${u} args { data: {${p?` ${p} `:""}} }`)}if(t==="stdio"){const u=new fd.StdioServerTransport;return await s.connect(u),o.info("stdio transport ready"),new Promise(d=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),d()})})}if(t==="sse"){const u=new Map,d=gn.createServer(async(l,p)=>{try{const h=l.url??"";if(l.method==="GET"&&h==="/sse"){const f=new pd.SSEServerTransport("/messages",p);u.set(f.sessionId,f),f.onclose=()=>u.delete(f.sessionId),await s.connect(f)}else if(l.method==="POST"&&h.startsWith("/messages")){const f=new URLSearchParams(h.split("?")[1]??"").get("sessionId"),y=f?u.get(f):void 0;if(!y){p.writeHead(404),p.end("Session not found");return}await y.handlePostMessage(l,p)}else p.writeHead(404),p.end("Not found")}catch(h){o.error({err:h},"sse request handler error"),p.headersSent||p.writeHead(500),p.writableEnded||p.end("Internal Server Error")}});return d.listen(r,n,()=>{o.info({host:n,port:r},`listening on http://${n}:${r}`)}),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),d.close(()=>l())})})}const c=gn.createServer(async(u,d)=>{const{server:l}=da(e,o),p=new md.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await l.connect(p),await p.handleRequest(u,d)});return c.listen(r,n,()=>{o.info({host:n,port:r},`listening on http://${n}:${r}`)}),new Promise(u=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),c.close(()=>u())})})}const av={id:"mcp",description:"Expose functions as MCP tools (stdio, SSE, or streaming-HTTP transport)",language:"ts",optionsSchema:{type:"object",properties:{transport:{type:"string",enum:["stdio","sse","streaming-http"]},port:{type:"number"},toolDescriptions:{type:"object",additionalProperties:{type:"string"}}}},generate(e){return ev(e)},run(e){return iv(e)}},cv={id:"jsonschema",description:"Emit one JSON Schema file per function per package",language:"ts",optionsSchema:{type:"object",properties:{pretty:{type:"boolean",description:"Pretty-print JSON (default: true)"}}},generate(e){const t=e.options.pretty!==!1,r=[];for(const n of e.packages)for(const[o,s]of Object.entries(n.schemas))r.push({path:N.join(n.id,`${o}.json`),content:JSON.stringify(s,null,t?2:0)});return{files:r}}},uv={"decimal.js":"Decimal"};function dv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(uv).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${dv(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Du(e,t,r){var n,o;const s=(o=(n=r.http)==null?void 0:n.verb)==null?void 0:o[e];return s==="GET"||s==="POST"?s:t["x-apigen-safe"]?"GET":"POST"}function Ru(e,t){return`x-${e}-${t}`}function la(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const lv=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],fv={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function xu(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&lv.includes(e.code)&&typeof e.toJSON=="function"}function pv(e){var t;const r=((t=e.input)==null?void 0:t.properties)??{},n=e["x-apigen-envelope"],o={};for(const s of Object.keys(r)){if(s==="data")continue;const i=(n==null?void 0:n[s])??"adhd";o[s]=Ru(i,s)}return o}function mv(e){const t=e.options.port??3e3,r=e.options.routePrefix??"",n=e.options.projection??{},o=["// Auto-generated by @adhd/apigen-cli — do not edit","import Fastify from 'fastify'","import { dispatch, buildFnTable, coerceQueryParams } from '@adhd/apigen-engine-runtime'"];for(const s of e.packages){const i=la(s.id);o.push(`import * as ${i}_ns from '${s.importPath}'`),o.push(`const ${i}_fns = buildFnTable(${i}_ns as Record<string, unknown>)`)}o.push(""),o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([i,a])=>[`${s.id}:${i}`,{schema:a,pkgId:s.id}]))),null,2)}`),o.push(""),o.push("const app = Fastify()"),o.push("");for(const s of e.packages){const i=la(s.id);for(const[a,c]of Object.entries(s.schemas)){const u=`${r}/${s.id}/${a}`,d=Du(`${s.id}:${a}`,c,n),l=pv(c),p=Object.entries(l);if(d==="GET"){if(o.push(`app.get('${u}', async (req) => {`),o.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas['${s.id}:${a}']['schema'] as any)`),p.length>0){const h=p.map(([f,y])=>`'${f}': (req.headers as Record<string, unknown>)['${y}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${h} }`)}else o.push(" const envelope: Record<string, unknown> = {}");o.push(` return dispatch(${i}_fns as any, undefined, schemas['${s.id}:${a}']['schema'] as any, '${a}', envelope, query as any)`),o.push("})")}else{if(o.push(`app.post('${u}', async (req) => {`),o.push(" const { data = {} } = req.body as Record<string, unknown>"),p.length>0){const h=p.map(([f,y])=>`'${f}': (req.headers as Record<string, unknown>)['${y}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${h} }`)}else o.push(" const envelope: Record<string, unknown> = {}");o.push(` return dispatch(${i}_fns as any, undefined, schemas['${s.id}:${a}']['schema'] as any, '${a}', envelope, data as any)`),o.push("})")}}}return o.push(""),o.push(`app.listen({ port: ${t} })`),{files:[{path:"routes.ts",content:o.join(`
|
|
171
|
+
`)}]}}const qn="$apigen";let fa=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function hv(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new fa(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const n of t.values())if(n.matches(r))return n},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),n={register(){throw new fa("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of r.values())if(s.matches(o))return s},get(o){return r.get(o)},ids(){return[...r.keys()]},freeze(){return n}};return n}}}const Es="x-apigen-logical",Ns="x-apigen-codec",Vn="x-apigen-ctor",Gn="x-apigen-tojson",yv="0.1.0";function pa(e,t){return{registry:e,resolve:r=>{throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function nt(e,t,r){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return nt(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Mu(e,s,t);return nt(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return an(e,t,r);const a=t.items;if(!a)return e.map(u=>ze(u));const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?ze(u):nt(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>nt(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return an(e,t,r);const a=t.properties;if(!a)return ze(e);const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=nt(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?an(e,t,r):ze(e)}function ot(e,t,r){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return ot(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Mu(e,s,t);return ot(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?u:ot(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>ot(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=ot(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?gv(e,r):e}function Mu(e,t,r,n){const o=r.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function an(e,t,r){for(const n of r.registry.ids()){const o=r.registry.get(n);if(o)try{const s=o.encode(e,o.schema,r);return{[qn]:n,v:s}}catch{}}return ze(e)}function gv(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&qn in e){const r=e,n=r[qn],o=t.registry.get(n);if(o)return o.decode(r.v,o.schema,t)}return e}function ze(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(ze);if(typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))n!==void 0&&(t[r]=ze(n));return t}return null}function $v(e){return{encode(t,r,n){const o=pa(e,n);return nt(t,r,o)},decode(t,r,n){const o=pa(e,n);return ot(t,r,o)}}}const Os={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,r){return e.toISOString()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${r.path}", got ${typeof e}`);return new Date(String(e))}if(r.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${r.path}": ${JSON.stringify(e)}`);return new Date(e)}},js={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,r){return String(e)},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${r.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(r.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},ks={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,r){return e},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e)}if(r.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${r.path}" is not a valid decimal string`);return e}},Ps={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,r){return Buffer.from(e).toString("base64")},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${r.path}", got ${typeof e}`);return new Uint8Array(0)}if(r.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${r.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},vv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,As={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,r){return e.toLowerCase()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e).toLowerCase()}if(r.mode==="strict"&&!vv.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Hn="NaN",Jn="Infinity",Kn="-Infinity",wv=new Set([Hn,Jn,Kn]),Ts={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,r){return Number.isNaN(e)?Hn:e===1/0?Jn:e===-1/0?Kn:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Hn)return NaN;if(e===Jn)return 1/0;if(e===Kn)return-1/0;const n=Number(e);if(!Number.isNaN(n))return n}if(r.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${r.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...wv].join(", ")}.`);return NaN}},_v=[Os,js,ks,Ps,As,Ts];function bv(e,t={}){for(const r of _v)e.register(r,{override:t.override??!1})}Os.id,js.id,ks.id,Ps.id,As.id,Ts.id;const Fu=hv();bv(Fu);const Uu=$v(Fu.freeze());function Sv(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function Ev(e){var t,r;const n=(r=(t=e.input)==null?void 0:t.properties)==null?void 0:r.data;return Object.keys((n==null?void 0:n.properties)??{})}function Nv(e,t){var r,n,o;const s=(o=(n=(r=e.input)==null?void 0:r.properties)==null?void 0:n.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function Ov(e,t){return t===void 0||e===void 0?e:Uu.decode(e,t)}function cn(e,t){const r=t.output;return!r||Object.keys(r).length===0?e:Uu.encode(e,r)}async function jv(e,t,r,n,o,s){const i=Ev(r).map(c=>Ov(s[c],Nv(r,c)));if(Sv(r,"session")&&t){const c=await t({session:o.session}),u=await e[n](c,...i);return cn(u,r)}if(r.hasCtx){const c=t?await t(o):void 0,u=await e[n](c,...i);return cn(u,r)}const a=await e[n](...i);return cn(a,r)}let un=class{constructor(){this._map=new Map}set(t,r){this._map.set(t,r)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function kv(e=[]){return async function(t,r,n){const o=n.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>jv(n.fns,n.createClient,o,t,r.envelope,r.domainArgs);return e.reduceRight((i,a)=>()=>a(r,i),s)()}}const Pv={"decimal.js":"Decimal"};function Av(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Pv).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Av(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Tv(e={}){const t=e.level??"info",r=typeof e.destination=="string"&&e.destination.length>0,n=!r&&!!process.stderr.isTTY,o=e.format??(n?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!r,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...r?{destination:e.destination,mkdir:!0}:{destination:2}}},te(s);const i=r?te.destination({dest:e.destination,mkdir:!0,sync:!0}):te.destination(2);return te(s,i)}function Lu(e){return e?e.type==="array"?`${Lu(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Iv(e){var t;const r=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,n=(r==null?void 0:r.properties)??{},o=new Set((r==null?void 0:r.required)??[]),s=Object.entries(n).map(([a,c])=>({name:a,type:Lu(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function Cv(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(r=>r==="number"||r==="integer"||r==="boolean")}function Dv(e,t){var r,n;const o=((n=(r=((t==null?void 0:t.input)??{}).properties)==null?void 0:r.data)==null?void 0:n.properties)??{},s={...e};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=Cv(a==null?void 0:a.type);if(u==="number"||u==="integer"){const d=Number(c);!Number.isNaN(d)&&c.trim()!==""&&(s[i]=d)}else u==="boolean"&&(c==="true"?s[i]=!0:c==="false"&&(s[i]=!1))}return s}let Rv=class extends Error{constructor(t,r,n){super(r),this.name="ApiError",this.code=t,this.details=n,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};const Pr=new Ft({allErrors:!0});Ut(Pr);for(const e of[Es,Ns,Vn,Gn,"discriminator"])Pr.addKeyword({keyword:e,valid:!0});Pr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function xv(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Mv(e){return async function(t,r){const n=t.operation.id,o=e[n];if(o===void 0)return r();const s={data:t.domainArgs,...t.envelope},i=Pr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Rv("invalid_argument",`Validation failed: ${xv(a)}`,a)}return r()}}class Ae extends Error{constructor(t,r){super(r),this.name="UnionCodecError",this.code=t}}function dn(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t;if(typeof r.propertyName!="string")return;const n=r.mapping;if(!(n===null||typeof n!="object"||Array.isArray(n)))return{propertyName:r.propertyName,mapping:n}}function zu(e,t){const r=e[Ns];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function Fv(e,t,r){const n=zu(t,r);return n?n.encode(e,t,r):e}function Uv(e,t,r){const n=zu(t,r);return n?n.decode(e,t,r):e}function Lv(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[Es]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:dn(n)!==void 0},encode(n,o,s){const i=dn(o);if(!i)throw new Ae("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=n[a];if(u==null)throw new Ae("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const d=String(u),l=c[d];if(!l)throw new Ae("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${d}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(l);return Fv(n,p,{...s,path:`${s.path}[${d}]`})},decode(n,o,s){if(n===null||typeof n!="object"||Array.isArray(n)){let f;throw n===null?f="null":Array.isArray(n)?f="array":f=typeof n,new Ae("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${f}.`)}const i=n,a=dn(o);if(!a)throw new Ae("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,d=i[c];if(d==null)throw new Ae("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const l=String(d),p=u[l];if(!p)throw new Ae("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Uv(n,h,{...s,path:`${s.path}[${l}]`})}}}const zv="x-apigen-instances";let er=class extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}};function ma(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function qv(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function ha(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function Vv(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function Gv(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[Es]==="nominal"?!0:o[Ns]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new er("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=ma(s),c=typeof s[Gn]=="string"?s[Gn]:"toJSON",u=o[c];if(typeof u=="function"){const f=u.call(o);if(f!==null&&typeof f=="object"&&!Array.isArray(f)){const y={};for(const[$,g]of Object.entries(f))y[$]=ha(g,a[$],{...i,path:`${i.path}/${$}`});return y}return f}const d={},l=Object.keys(a),p=o,h=l.length>0?l:Object.keys(p);for(const f of h){const y=p[f];y!==void 0&&(d[f]=ha(y,a[f],{...i,path:`${i.path}/${f}`}))}return d}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let d;throw o===null?d="null":Array.isArray(o)?d="array":d=typeof o,new er("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${d}.`)}const a=o;for(const d of qv(s))if(!(d in a))throw new er("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${d}" missing on the wire at "${i.path}".`);if(s[zv]===!1)throw new er("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=ma(s),u={};for(const[d,l]of Object.entries(a))u[d]=Vv(l,c[d],{...i,path:`${i.path}/${d}`});if(n){const d=typeof s[Vn]=="string"?s[Vn]:"fromJSON",l=n[d];if(typeof l=="function")return l.call(n,u);const p=n;return new p(u)}return u}}}const Hv=[Os,js,ks,Ps,As,Ts],Jv={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},ya=Gv({id:"ts.NominalSentinel",schema:Jv}),Kv={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ga=Lv({id:"ts.UnionSentinel",schema:Kv});function Bv(){const e=[...Hv.map(t=>[t.id,t]),[ya.id,ya],[ga.id,ga]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:yv,codecs:Bv()});function $a(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{},o=e["x-apigen-envelope"],s={};for(const i of Object.keys(n)){if(i==="data")continue;const a=(o==null?void 0:o[i])??"adhd",c=Ru(a,i),u=t[c];u!==void 0&&(s[i]=u)}return s}function Wv(e){return xu(e)?fv[e.code]??500:500}function Yv(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Zv(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Qv(e){return async function(t,r){const n=Object.assign(t,{data:t.domainArgs});return await e.layer(n,r)}}function Xv(e,t){var r;const n=[];for(const o of t){const s=(r=o.capabilities)==null?void 0:r.layer;s&&n.push(Qv(s))}return n.push(Mv(e)),kv(n)}function e0(e,t,r,n,o){var s;const i=[],a={host:r,operations:o};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const d=u.operations(a,t[c.id]);for(const l of d)l.transports&&!l.transports.includes("http")||i.push({route:`${n}/${l.id}`,handler:l.handler})}return i}function va(e,t){return e.type("application/json"),JSON.stringify(t===void 0?null:t)}async function t0(e){var t;const r=e.options.port??3e3,n=e.options.host??"127.0.0.1",o=e.options.routePrefix??"",s=e.options.projection??{},i=Yv(e.options),a=Zv(e.options),c=e.logger??Tv(),u=hd({logger:c});u.setErrorHandler((h,f,y)=>{const $=Wv(h),g=xu(h)?h.toJSON():{code:"internal",message:h.message??"Internal error"};y.status($).send(g)});const d=[];for(const h of e.packages){const f=Xv(h.schemas,i);if(!h.fns)throw new Error(`Package "${h.id}" is missing fns`);const y={fns:h.fns,createClient:h.createClient,schemas:h.schemas};for(const[$,g]of Object.entries(h.schemas)){const w=`${o}/${h.id}/${$}`,_=Du(`${h.id}:${$}`,g,s),{params:E,text:j}=Iv(g);d.push({method:_,route:w,text:j,params:E}),_==="GET"?u.get(w,async(I,x)=>{const V=$a(g,I.headers),D={operation:{id:$},ctx:new un,envelope:V,domainArgs:Dv(I.query,g),signal:e.signal};return va(x,await f($,D,y))}):u.post(w,async(I,x)=>{const{data:V={}}=I.body??{},D=$a(g,I.headers),U={operation:{id:$},ctx:new un,envelope:D,domainArgs:V,signal:e.signal};return va(x,await f($,U,y))})}}const l=((t=e.packages[0])==null?void 0:t.id)??"ts",p=e0(i,a,l,o,e.operations??[]);for(const h of p)d.push({method:"GET",route:h.route,text:"",params:[]}),u.get(h.route,async f=>{const y={operation:{id:h.route},data:{},envelope:{},ctx:new un,transport:"http",signal:e.signal??new AbortController().signal,raw:f};return h.handler(y)});await u.listen({port:r,host:n}),c.info({host:n,port:r},`listening on http://${n}:${r}`);for(const h of d)c.info({method:h.method,route:h.route,body:{data:h.params}},`${h.method} ${h.route} body { data: {${h.text?` ${h.text} `:""}} }`);return new Promise(h=>{e.signal&&e.signal.addEventListener("abort",async()=>{await u.close(),h()})})}const r0={id:"api-fastify",description:"Expose functions as Fastify HTTP POST routes",language:"ts",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(e){return mv(e)},run(e){return t0(e)}},n0={"decimal.js":"Decimal"};function o0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(n0).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${o0(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function qu(e,t,r){var n,o;const s=(o=(n=r.http)==null?void 0:n.verb)==null?void 0:o[e];return s==="GET"||s==="POST"?s:t["x-apigen-safe"]?"GET":"POST"}function Vu(e,t){return`x-${e}-${t}`}function wa(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const s0=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],i0={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function Gu(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&s0.includes(e.code)&&typeof e.toJSON=="function"}function a0(e){var t;const r=((t=e.input)==null?void 0:t.properties)??{},n=e["x-apigen-envelope"],o={};for(const s of Object.keys(r)){if(s==="data")continue;const i=(n==null?void 0:n[s])??"adhd";o[s]=Vu(i,s)}return o}function c0(e){const t=e.options.port??3e3,r=e.options.routePrefix??"",n=e.options.projection??{},o=["// Auto-generated by @adhd/apigen-cli — do not edit","import express, { Router } from 'express'","import { dispatch, buildFnTable, coerceQueryParams } from '@adhd/apigen-engine-runtime'"];for(const s of e.packages){const i=wa(s.id);o.push(`import * as ${i}_ns from '${s.importPath}'`),o.push(`const ${i}_fns = buildFnTable(${i}_ns as Record<string, unknown>)`)}o.push(""),o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([i,a])=>[`${s.id}:${i}`,{schema:a,pkgId:s.id}]))),null,2)}`),o.push(""),o.push("const app = express()"),o.push("app.use(express.json())"),o.push("const router = Router()"),o.push("");for(const s of e.packages){const i=wa(s.id);for(const[a,c]of Object.entries(s.schemas)){const u=`${r}/${s.id}/${a}`,d=qu(`${s.id}:${a}`,c,n),l=a0(c),p=Object.entries(l);if(d==="GET"){if(o.push(`router.get('${u}', async (req, res) => {`),p.length>0){const h=p.map(([f,y])=>`'${f}': req.headers['${y}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${h} }`)}else o.push(" const envelope: Record<string, unknown> = {}");o.push(` const domainArgs = coerceQueryParams(req.query as Record<string, unknown>, schemas['${s.id}:${a}']['schema'] as any)`),o.push(` const result = await dispatch(${i}_fns as any, undefined, schemas['${s.id}:${a}']['schema'] as any, '${a}', envelope, domainArgs as any)`),o.push(" res.json(result)"),o.push("})")}else{if(o.push(`router.post('${u}', async (req, res) => {`),o.push(" const { data = {} } = req.body as Record<string, unknown>"),p.length>0){const h=p.map(([f,y])=>`'${f}': req.headers['${y}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${h} }`)}else o.push(" const envelope: Record<string, unknown> = {}");o.push(` const result = await dispatch(${i}_fns as any, undefined, schemas['${s.id}:${a}']['schema'] as any, '${a}', envelope, data as any)`),o.push(" res.json(result)"),o.push("})")}}}return o.push(""),o.push("app.use(router)"),o.push(`app.listen(${t})`),o.push(""),o.push("export default router"),{files:[{path:"routes.ts",content:o.join(`
|
|
172
|
+
`)}]}}const Bn="$apigen";class _a extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function u0(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new _a(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const n of t.values())if(n.matches(r))return n},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),n={register(){throw new _a("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of r.values())if(s.matches(o))return s},get(o){return r.get(o)},ids(){return[...r.keys()]},freeze(){return n}};return n}}}const Is="x-apigen-logical",Cs="x-apigen-codec",Wn="x-apigen-ctor",Yn="x-apigen-tojson",d0="0.1.0";function ba(e,t){return{registry:e,resolve:r=>{throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function st(e,t,r){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return st(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Hu(e,s,t);return st(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return ln(e,t,r);const a=t.items;if(!a)return e.map(u=>qe(u));const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?qe(u):st(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>st(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return ln(e,t,r);const a=t.properties;if(!a)return qe(e);const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=st(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?ln(e,t,r):qe(e)}function it(e,t,r){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return it(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Hu(e,s,t);return it(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?u:it(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>it(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=it(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?l0(e,r):e}function Hu(e,t,r,n){const o=r.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function ln(e,t,r){for(const n of r.registry.ids()){const o=r.registry.get(n);if(o)try{const s=o.encode(e,o.schema,r);return{[Bn]:n,v:s}}catch{}}return qe(e)}function l0(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Bn in e){const r=e,n=r[Bn],o=t.registry.get(n);if(o)return o.decode(r.v,o.schema,t)}return e}function qe(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(qe);if(typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))n!==void 0&&(t[r]=qe(n));return t}return null}function f0(e){return{encode(t,r,n){const o=ba(e,n);return st(t,r,o)},decode(t,r,n){const o=ba(e,n);return it(t,r,o)}}}const Ds={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,r){return e.toISOString()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${r.path}", got ${typeof e}`);return new Date(String(e))}if(r.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${r.path}": ${JSON.stringify(e)}`);return new Date(e)}},Rs={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,r){return String(e)},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${r.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(r.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},xs={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,r){return e},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e)}if(r.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${r.path}" is not a valid decimal string`);return e}},Ms={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,r){return Buffer.from(e).toString("base64")},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${r.path}", got ${typeof e}`);return new Uint8Array(0)}if(r.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${r.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},p0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Fs={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,r){return e.toLowerCase()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e).toLowerCase()}if(r.mode==="strict"&&!p0.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Zn="NaN",Qn="Infinity",Xn="-Infinity",m0=new Set([Zn,Qn,Xn]),Us={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,r){return Number.isNaN(e)?Zn:e===1/0?Qn:e===-1/0?Xn:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Zn)return NaN;if(e===Qn)return 1/0;if(e===Xn)return-1/0;const n=Number(e);if(!Number.isNaN(n))return n}if(r.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${r.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...m0].join(", ")}.`);return NaN}},h0=[Ds,Rs,xs,Ms,Fs,Us];function y0(e,t={}){for(const r of h0)e.register(r,{override:t.override??!1})}Ds.id,Rs.id,xs.id,Ms.id,Fs.id,Us.id;const Ju=u0();y0(Ju);const Ku=f0(Ju.freeze());function g0(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function $0(e){var t,r;const n=(r=(t=e.input)==null?void 0:t.properties)==null?void 0:r.data;return Object.keys((n==null?void 0:n.properties)??{})}function v0(e,t){var r,n,o;const s=(o=(n=(r=e.input)==null?void 0:r.properties)==null?void 0:n.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function w0(e,t){return t===void 0||e===void 0?e:Ku.decode(e,t)}function fn(e,t){const r=t.output;return!r||Object.keys(r).length===0?e:Ku.encode(e,r)}async function _0(e,t,r,n,o,s){const i=$0(r).map(c=>w0(s[c],v0(r,c)));if(g0(r,"session")&&t){const c=await t({session:o.session}),u=await e[n](c,...i);return fn(u,r)}if(r.hasCtx){const c=t?await t(o):void 0,u=await e[n](c,...i);return fn(u,r)}const a=await e[n](...i);return fn(a,r)}let pn=class{constructor(){this._map=new Map}set(t,r){this._map.set(t,r)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function b0(e=[]){return async function(t,r,n){const o=n.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>_0(n.fns,n.createClient,o,t,r.envelope,r.domainArgs);return e.reduceRight((i,a)=>()=>a(r,i),s)()}}const S0={"decimal.js":"Decimal"};function E0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(S0).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${E0(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function N0(e={}){const t=e.level??"info",r=typeof e.destination=="string"&&e.destination.length>0,n=!r&&!!process.stderr.isTTY,o=e.format??(n?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!r,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...r?{destination:e.destination,mkdir:!0}:{destination:2}}},te(s);const i=r?te.destination({dest:e.destination,mkdir:!0,sync:!0}):te.destination(2);return te(s,i)}function Bu(e){return e?e.type==="array"?`${Bu(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function O0(e){var t;const r=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,n=(r==null?void 0:r.properties)??{},o=new Set((r==null?void 0:r.required)??[]),s=Object.entries(n).map(([a,c])=>({name:a,type:Bu(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function j0(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(r=>r==="number"||r==="integer"||r==="boolean")}function k0(e,t){var r,n;const o=((n=(r=((t==null?void 0:t.input)??{}).properties)==null?void 0:r.data)==null?void 0:n.properties)??{},s={...e};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=j0(a==null?void 0:a.type);if(u==="number"||u==="integer"){const d=Number(c);!Number.isNaN(d)&&c.trim()!==""&&(s[i]=d)}else u==="boolean"&&(c==="true"?s[i]=!0:c==="false"&&(s[i]=!1))}return s}class P0 extends Error{constructor(t,r,n){super(r),this.name="ApiError",this.code=t,this.details=n,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}const Ar=new Ft({allErrors:!0});Ut(Ar);for(const e of[Is,Cs,Wn,Yn,"discriminator"])Ar.addKeyword({keyword:e,valid:!0});Ar.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function A0(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function T0(e){return async function(t,r){const n=t.operation.id,o=e[n];if(o===void 0)return r();const s={data:t.domainArgs,...t.envelope},i=Ar.compile(o.input);if(!i(s)){const a=i.errors??[];throw new P0("invalid_argument",`Validation failed: ${A0(a)}`,a)}return r()}}let Te=class extends Error{constructor(t,r){super(r),this.name="UnionCodecError",this.code=t}};function mn(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t;if(typeof r.propertyName!="string")return;const n=r.mapping;if(!(n===null||typeof n!="object"||Array.isArray(n)))return{propertyName:r.propertyName,mapping:n}}function Wu(e,t){const r=e[Cs];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function I0(e,t,r){const n=Wu(t,r);return n?n.encode(e,t,r):e}function C0(e,t,r){const n=Wu(t,r);return n?n.decode(e,t,r):e}function D0(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[Is]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:mn(n)!==void 0},encode(n,o,s){const i=mn(o);if(!i)throw new Te("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=n[a];if(u==null)throw new Te("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const d=String(u),l=c[d];if(!l)throw new Te("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${d}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(l);return I0(n,p,{...s,path:`${s.path}[${d}]`})},decode(n,o,s){if(n===null||typeof n!="object"||Array.isArray(n)){let f;throw n===null?f="null":Array.isArray(n)?f="array":f=typeof n,new Te("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${f}.`)}const i=n,a=mn(o);if(!a)throw new Te("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,d=i[c];if(d==null)throw new Te("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const l=String(d),p=u[l];if(!p)throw new Te("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return C0(n,h,{...s,path:`${s.path}[${l}]`})}}}const R0="x-apigen-instances";let tr=class extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}};function Sa(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function x0(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function Ea(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function M0(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function F0(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[Is]==="nominal"?!0:o[Cs]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new tr("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Sa(s),c=typeof s[Yn]=="string"?s[Yn]:"toJSON",u=o[c];if(typeof u=="function"){const f=u.call(o);if(f!==null&&typeof f=="object"&&!Array.isArray(f)){const y={};for(const[$,g]of Object.entries(f))y[$]=Ea(g,a[$],{...i,path:`${i.path}/${$}`});return y}return f}const d={},l=Object.keys(a),p=o,h=l.length>0?l:Object.keys(p);for(const f of h){const y=p[f];y!==void 0&&(d[f]=Ea(y,a[f],{...i,path:`${i.path}/${f}`}))}return d}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let d;throw o===null?d="null":Array.isArray(o)?d="array":d=typeof o,new tr("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${d}.`)}const a=o;for(const d of x0(s))if(!(d in a))throw new tr("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${d}" missing on the wire at "${i.path}".`);if(s[R0]===!1)throw new tr("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Sa(s),u={};for(const[d,l]of Object.entries(a))u[d]=M0(l,c[d],{...i,path:`${i.path}/${d}`});if(n){const d=typeof s[Wn]=="string"?s[Wn]:"fromJSON",l=n[d];if(typeof l=="function")return l.call(n,u);const p=n;return new p(u)}return u}}}const U0=[Ds,Rs,xs,Ms,Fs,Us],L0={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Na=F0({id:"ts.NominalSentinel",schema:L0}),z0={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Oa=D0({id:"ts.UnionSentinel",schema:z0});function q0(){const e=[...U0.map(t=>[t.id,t]),[Na.id,Na],[Oa.id,Oa]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:d0,codecs:q0()});function ja(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{},o=e["x-apigen-envelope"],s={};for(const i of Object.keys(n)){if(i==="data")continue;const a=(o==null?void 0:o[i])??"adhd",c=Vu(a,i),u=t[c];u!==void 0&&(s[i]=u)}return s}function V0(e){return Gu(e)?i0[e.code]??500:500}function G0(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function H0(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function J0(e){return async function(t,r){const n=Object.assign(t,{data:t.domainArgs});return await e.layer(n,r)}}function K0(e,t){var r;const n=[];for(const o of t){const s=(r=o.capabilities)==null?void 0:r.layer;s&&n.push(J0(s))}return n.push(T0(e)),b0(n)}function B0(e,t,r,n,o){var s;const i=[],a={host:r,operations:o};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const d=u.operations(a,t[c.id]);for(const l of d)l.transports&&!l.transports.includes("http")||i.push({route:`${n}/${l.id}`,handler:l.handler})}return i}async function W0(e){var t;const r=e.options.port??3e3,n=e.options.host??"127.0.0.1",o=e.options.routePrefix??"",s=e.options.projection??{},i=G0(e.options),a=H0(e.options),c=e.logger??N0(),u=Br();u.use(yd.pinoHttp({logger:c})),u.use(Br.json());const d=Br.Router(),l=[];for(const y of e.packages){const $=K0(y.schemas,i);if(!y.fns)throw new Error(`Package "${y.id}" is missing fns`);const g={fns:y.fns,createClient:y.createClient,schemas:y.schemas};for(const[w,_]of Object.entries(y.schemas)){const E=`${o}/${y.id}/${w}`,j=qu(`${y.id}:${w}`,_,s),{params:I,text:x}=O0(_);l.push({method:j,route:E,text:x,params:I}),j==="GET"?d.get(E,async(V,D,U)=>{try{const H=ja(_,V.headers),J={operation:{id:w},ctx:new pn,envelope:H,domainArgs:k0(V.query,_),signal:e.signal},X=await $(w,J,g);D.json(X)}catch(H){U(H)}}):d.post(E,async(V,D,U)=>{try{const{data:H={}}=V.body??{},J=ja(_,V.headers),X={operation:{id:w},ctx:new pn,envelope:J,domainArgs:H,signal:e.signal},se=await $(w,X,g);D.json(se)}catch(H){U(H)}})}}const p=((t=e.packages[0])==null?void 0:t.id)??"ts",h=B0(i,a,p,o,e.operations??[]);for(const y of h)l.push({method:"GET",route:y.route,text:"",params:[]}),d.get(y.route,async($,g,w)=>{try{const _={operation:{id:y.route},data:{},envelope:{},ctx:new pn,transport:"http",signal:e.signal??new AbortController().signal,raw:$};g.json(await y.handler(_))}catch(_){w(_)}});u.use(d),u.use((y,$,g,w)=>{const _=V0(y),E=Gu(y)?y.toJSON():{code:"internal",message:y.message??"Internal error"};g.status(_).json(E)});const f=await new Promise(y=>{const $=u.listen(r,n,()=>y($))});c.info({host:n,port:r},`listening on http://${n}:${r}`);for(const y of l)c.info({method:y.method,route:y.route,body:{data:y.params}},`${y.method} ${y.route} body { data: {${y.text?` ${y.text} `:""}} }`);return new Promise(y=>{e.signal&&e.signal.addEventListener("abort",()=>{f.close(()=>y())})})}const Y0={id:"api-express",description:"Expose functions as Express HTTP POST routes",language:"ts",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(e){return c0(e)},run(e){return W0(e)}},eo="$apigen";let ka=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Z0(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new ka(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const n of t.values())if(n.matches(r))return n},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),n={register(){throw new ka("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of r.values())if(s.matches(o))return s},get(o){return r.get(o)},ids(){return[...r.keys()]},freeze(){return n}};return n}}}const Ls="x-apigen-logical",zs="x-apigen-codec",to="x-apigen-ctor",ro="x-apigen-tojson",Q0="0.1.0";function Pa(e,t){return{registry:e,resolve:r=>{throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function at(e,t,r){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return at(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Yu(e,s,t);return at(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return hn(e,t,r);const a=t.items;if(!a)return e.map(u=>Ve(u));const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?Ve(u):at(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>at(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return hn(e,t,r);const a=t.properties;if(!a)return Ve(e);const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=at(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?hn(e,t,r):Ve(e)}function ct(e,t,r){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return ct(e,a,r)}const s=t.oneOf;if(Array.isArray(s)){const a=Yu(e,s,t);return ct(e,a,r)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=r.path;return Array.isArray(a)?e.map((u,d)=>{const l=a[d];return l===void 0?u:ct(u,l,{...r,path:`${c}/${d}`})}):e.map((u,d)=>ct(u,a,{...r,path:`${c}/${d}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=r.path,u={};for(const[d,l]of Object.entries(a)){const p=e[d];p!==void 0&&(u[d]=ct(p,l,{...r,path:`${c}/${d}`}))}return u}return i==null?X0(e,r):e}function Yu(e,t,r,n){const o=r.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function hn(e,t,r){for(const n of r.registry.ids()){const o=r.registry.get(n);if(o)try{const s=o.encode(e,o.schema,r);return{[eo]:n,v:s}}catch{}}return Ve(e)}function X0(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&eo in e){const r=e,n=r[eo],o=t.registry.get(n);if(o)return o.decode(r.v,o.schema,t)}return e}function Ve(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Ve);if(typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))n!==void 0&&(t[r]=Ve(n));return t}return null}function ew(e){return{encode(t,r,n){const o=Pa(e,n);return at(t,r,o)},decode(t,r,n){const o=Pa(e,n);return ct(t,r,o)}}}const qs={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,r){return e.toISOString()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${r.path}", got ${typeof e}`);return new Date(String(e))}if(r.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${r.path}": ${JSON.stringify(e)}`);return new Date(e)}},Vs={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,r){return String(e)},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${r.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(r.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},Gs={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,r){return e},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e)}if(r.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${r.path}" is not a valid decimal string`);return e}},Hs={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,r){return Buffer.from(e).toString("base64")},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${r.path}", got ${typeof e}`);return new Uint8Array(0)}if(r.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${r.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},tw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Js={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,r){return e.toLowerCase()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e).toLowerCase()}if(r.mode==="strict"&&!tw.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},no="NaN",oo="Infinity",so="-Infinity",rw=new Set([no,oo,so]),Ks={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,r){return Number.isNaN(e)?no:e===1/0?oo:e===-1/0?so:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===no)return NaN;if(e===oo)return 1/0;if(e===so)return-1/0;const n=Number(e);if(!Number.isNaN(n))return n}if(r.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${r.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...rw].join(", ")}.`);return NaN}},nw=[qs,Vs,Gs,Hs,Js,Ks];function ow(e,t={}){for(const r of nw)e.register(r,{override:t.override??!1})}qs.id,Vs.id,Gs.id,Hs.id,Js.id,Ks.id;const Zu=Z0();ow(Zu);ew(Zu.freeze());function sw(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function Aa(e){var t,r;const n=(r=(t=e.input)==null?void 0:t.properties)==null?void 0:r.data;return Object.keys((n==null?void 0:n.properties)??{})}const iw={"decimal.js":"Decimal"};function aw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(iw).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${aw(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const Bs=new Ft({allErrors:!0});Ut(Bs);for(const e of[Ls,zs,to,ro,"discriminator"])Bs.addKeyword({keyword:e,valid:!0});Bs.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);let Ie=class extends Error{constructor(t,r){super(r),this.name="UnionCodecError",this.code=t}};function yn(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t;if(typeof r.propertyName!="string")return;const n=r.mapping;if(!(n===null||typeof n!="object"||Array.isArray(n)))return{propertyName:r.propertyName,mapping:n}}function Qu(e,t){const r=e[zs];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function cw(e,t,r){const n=Qu(t,r);return n?n.encode(e,t,r):e}function uw(e,t,r){const n=Qu(t,r);return n?n.decode(e,t,r):e}function dw(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[Ls]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:yn(n)!==void 0},encode(n,o,s){const i=yn(o);if(!i)throw new Ie("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=n[a];if(u==null)throw new Ie("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const d=String(u),l=c[d];if(!l)throw new Ie("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${d}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(l);return cw(n,p,{...s,path:`${s.path}[${d}]`})},decode(n,o,s){if(n===null||typeof n!="object"||Array.isArray(n)){let f;throw n===null?f="null":Array.isArray(n)?f="array":f=typeof n,new Ie("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${f}.`)}const i=n,a=yn(o);if(!a)throw new Ie("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,d=i[c];if(d==null)throw new Ie("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const l=String(d),p=u[l];if(!p)throw new Ie("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return uw(n,h,{...s,path:`${s.path}[${l}]`})}}}const lw="x-apigen-instances";let rr=class extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}};function Ta(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fw(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function Ia(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function pw(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function mw(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[Ls]==="nominal"?!0:o[zs]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new rr("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Ta(s),c=typeof s[ro]=="string"?s[ro]:"toJSON",u=o[c];if(typeof u=="function"){const f=u.call(o);if(f!==null&&typeof f=="object"&&!Array.isArray(f)){const y={};for(const[$,g]of Object.entries(f))y[$]=Ia(g,a[$],{...i,path:`${i.path}/${$}`});return y}return f}const d={},l=Object.keys(a),p=o,h=l.length>0?l:Object.keys(p);for(const f of h){const y=p[f];y!==void 0&&(d[f]=Ia(y,a[f],{...i,path:`${i.path}/${f}`}))}return d}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let d;throw o===null?d="null":Array.isArray(o)?d="array":d=typeof o,new rr("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${d}.`)}const a=o;for(const d of fw(s))if(!(d in a))throw new rr("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${d}" missing on the wire at "${i.path}".`);if(s[lw]===!1)throw new rr("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Ta(s),u={};for(const[d,l]of Object.entries(a))u[d]=pw(l,c[d],{...i,path:`${i.path}/${d}`});if(n){const d=typeof s[to]=="string"?s[to]:"fromJSON",l=n[d];if(typeof l=="function")return l.call(n,u);const p=n;return new p(u)}return u}}}const hw=[qs,Vs,Gs,Hs,Js,Ks],yw={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Ca=mw({id:"ts.NominalSentinel",schema:yw}),gw={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Da=dw({id:"ts.UnionSentinel",schema:gw});function $w(){const e=[...hw.map(t=>[t.id,t]),[Ca.id,Ca],[Da.id,Da]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Q0,codecs:$w()});const vw={"decimal.js":"Decimal"};function ww(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(vw).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ww(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function _w(e,t){return`--${e}-${t}`}function bw(e,t){const r=n=>n.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${r(t)}`:`APIGEN_${r(e)}_${r(t)}`}function Ra(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}function Sw(e){var t;const r=((t=e.input)==null?void 0:t.properties)??{},n=e["x-apigen-envelope"],o=[];for(const s of Object.keys(r)){if(s==="data")continue;const i=(n==null?void 0:n[s])??"adhd";o.push({field:s,pluginId:i,flag:_w(i,s),envVar:bw(i,s)})}return o}function Ew(e,t){if(!N.isAbsolute(t))return t;const r=N.relative(e,t);return!r.startsWith(".")&&!r.startsWith("/")?`./${r}`:r}function xa(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;if(e.anyOf){const t=e.anyOf.filter(r=>r.type!=="null");return t.length>0&&t.every(r=>r.type==="array"||r.type==="object")}return!1}const Nw=["function __apigenParseJsonArg(flag: string, raw: unknown): unknown {"," if (raw === undefined) return undefined"," if (typeof raw !== 'string') return raw"," try {"," return JSON.parse(raw)"," } catch (err) {"," throw new Error(`Invalid JSON for --${flag}: ${(err as Error).message}`)"," }","}"].join(`
|
|
173
|
+
`);function Ow(e){var t,r,n;const o=e.options.name??"cli",s=e.options.version??"0.1.0",i=e.packages.some(c=>Object.values(c.schemas).some(u=>{var d,l;const p=(l=(d=u.input)==null?void 0:d.properties)==null?void 0:l.data,h=(p==null?void 0:p.properties)??{};return Aa(u).some(f=>xa(h[f]))})),a=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const c of e.packages){const u=Ra(c.id),d=Ew(e.outputDir,c.importPath);a.push(`import * as ${u}_ns from '${d}'`),a.push(`const ${u}_fns = buildFnTable(${u}_ns as Record<string, unknown>)`)}a.push(""),i&&(a.push(Nw),a.push("")),a.push(`const schemas: Record<string, unknown> = ${JSON.stringify(Object.fromEntries(e.packages.flatMap(c=>Object.entries(c.schemas).map(([u,d])=>[`${c.id}:${u}`,d]))),null,2)}`),a.push(""),a.push(`const program = new Command().name('${o}').version('${s}')`),a.push("");for(const c of e.packages){const u=Ra(c.id);for(const[d,l]of Object.entries(c.schemas)){const p=Aa(l),h=sw(l,"session"),f=Sw(l),y=(r=(t=l.input)==null?void 0:t.properties)==null?void 0:r.data,$=(y==null?void 0:y.properties)??{},g=(y==null?void 0:y.required)??[],w=E=>{const j=$[E];if(!j)return!1;if(j.type==="boolean")return!0;if(j.anyOf){const I=j.anyOf.filter(x=>x.type!=="null");return I.length>0&&I.every(x=>x.type==="boolean")}return!1};a.push("program"),a.push(` .command('${d}')`);for(const E of f){const j=E.flag.replace(/^--/,"");a.push(` .option('${E.flag} <${j}>', '${E.field} (env: ${E.envVar})')`)}h&&!f.some(E=>E.field==="session")&&a.push(" .option('--session <key>', 'Session key')");const _=E=>E.replace(/[A-Z]/g,j=>"-"+j.toLowerCase());for(const E of p){const j=_(E),I=w(E),x=g.includes(E);I?(a.push(` .option('--${j}')`),((n=$[E])==null?void 0:n.default)===!0&&a.push(` .option('--no-${j}')`)):x?a.push(` .requiredOption('--${j} <${j}>')`):a.push(` .option('--${j} <${j}>')`)}if(a.push(" .action(async (opts: Record<string, unknown>) => {"),a.push(` const domainArgs: Record<string, unknown> = { ${p.map(E=>xa($[E])?`'${E}': __apigenParseJsonArg('${_(E)}', opts['${E}'])`:`'${E}': opts['${E}']`).join(", ")} }`),f.length>0){const E=f.map(j=>{const I=j.flag.replace(/^--/,"").replace(/-([a-z])/g,(x,V)=>V.toUpperCase());return`'${j.field}': opts['${I}'] ?? process.env['${j.envVar}']`});a.push(` const envelope: Record<string, unknown> = { ${E.join(", ")} }`)}else h?a.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):a.push(" const envelope: Record<string, unknown> = {}");a.push(` const result = await dispatch(${u}_fns as any, undefined, schemas['${c.id}:${d}'] as any, '${d}', envelope, domainArgs)`),a.push(" console.log(JSON.stringify(result))"),a.push(" })")}}return a.push(""),a.push("program.parseAsync()"),{files:[{path:"cli.ts",content:a.join(`
|
|
174
|
+
`)}]}}const Ma={id:"cli",description:"Emit a Commander CLI program where each exported function becomes a subcommand",language:"ts",optionsSchema:{type:"object",properties:{name:{type:"string",default:"cli"},version:{type:"string",default:"0.1.0"}}},generate(e){return Ow(e)}};function jw(e){const t=__dirname,r=N.resolve(t,"..","..","..","python");if(k.existsSync(N.join(r,"apigen_python")))return r;let n=t;for(let o=0;o<20;o++){const s=N.join(n,"packages","apigen","python");if(k.existsSync(N.join(s,"apigen_python")))return s;const i=N.dirname(n);if(i===n)break;n=i}return r}const Fa=["python3.13","python3.12","python3.11","python3"],Et=[3,11];function kw(e){const t=Q.spawnSync(e,["-c",'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")'],{encoding:"utf8",timeout:15e3});if(t.status!==0||!t.stdout)return;const[r,n]=t.stdout.trim().split(".").map(Number);if(!(!Number.isFinite(r)||!Number.isFinite(n)))return[r,n]}function Pw(){for(const e of Fa){const t=kw(e);if(t&&(t[0]>Et[0]||t[0]===Et[0]&&t[1]>=Et[1]))return e}throw new Error(`apigen-python-env: no Python >= ${Et.join(".")} found on PATH (tried: ${Fa.join(", ")}). Install Python ${Et.join(".")}+ or set APIGEN_PYTHON to a provisioned interpreter.`)}function Aw(e){return process.platform==="win32"?N.join(e,"Scripts","python.exe"):N.join(e,"bin","python3")}function Tw(e){const t=k.readFileSync(N.join(e,"pyproject.toml"));return ao.createHash("sha256").update(t).digest("hex")}function Ua(e){try{const t=JSON.parse(k.readFileSync(e,"utf8"));if(typeof t.pyprojectHash=="string"&&Array.isArray(t.extras))return t}catch{}}function Iw(e,t,r){const n=Date.now()+t;for(;;)try{k.mkdirSync(e,{recursive:!1});break}catch{if(Date.now()>n){try{k.rmdirSync(e)}catch{}continue}Q.spawnSync(process.execPath,["-e","setTimeout(()=>{}, 250)"],{timeout:5e3})}try{return r()}finally{try{k.rmdirSync(e)}catch{}}}function Cw(e={}){const t=jw(),r=process.env.APIGEN_PYTHON;if(r){if(!k.existsSync(r))throw new Error(`apigen-python-env: APIGEN_PYTHON points to a missing file: ${r}`);return{python:r,venvDir:"",pythonPkgDir:t}}const n=[...new Set(e.extras??[])].sort(),o=e.envHome??process.env.APIGEN_PYENV_HOME??N.join(Ge.homedir(),".adhd","apigen"),s=N.join(o,"pyvenv"),i=N.join(s,".apigen-stamp"),a=Tw(t),c=Aw(s),u=()=>{if(!k.existsSync(c))return!1;const p=Ua(i);return!p||p.pyprojectHash!==a?!1:n.every(h=>p.extras.includes(h))};if(u())return{python:c,venvDir:s,pythonPkgDir:t};k.mkdirSync(o,{recursive:!0});const d=N.join(o,"pyvenv.lock"),l=e.lockTimeoutMs??3e5;return Iw(d,l,()=>{if(u())return{python:c,venvDir:s,pythonPkgDir:t};const p=Ua(i),h=[...new Set([...(p==null?void 0:p.extras)??[],...n])].sort();k.rmSync(s,{recursive:!0,force:!0});const f=Pw(),y=Q.spawnSync(f,["-m","venv",s],{encoding:"utf8",timeout:12e4});if(y.status!==0)throw new Error(`apigen-python-env: "${f} -m venv" failed (exit ${y.status}):
|
|
175
|
+
${y.stderr}`);const $=N.join(t,"build");k.existsSync($)&&k.rmSync($,{recursive:!0,force:!0});for(const _ of k.readdirSync(t))_.endsWith(".egg-info")&&k.rmSync(N.join(t,_),{recursive:!0,force:!0});const g=k.mkdtempSync(N.join(Ge.tmpdir(),"apigen-python-wheel-"));try{const _=Q.spawnSync(c,["-m","pip","wheel","--no-deps","--wheel-dir",g,t],{encoding:"utf8",timeout:6e5});if(_.status!==0)throw new Error(`apigen-python-env: pip wheel failed (exit ${_.status}):
|
|
176
|
+
${_.stderr}
|
|
177
|
+
stdout:
|
|
178
|
+
${_.stdout}`);const E=k.readdirSync(g).filter(V=>V.endsWith(".whl"));if(E.length===0)throw new Error("apigen-python-env: pip wheel produced no .whl file");const j=N.join(g,E[0]),I=h.length?`${j}[${h.join(",")}]`:j,x=Q.spawnSync(c,["-m","pip","install","--quiet","--disable-pip-version-check",I],{encoding:"utf8",timeout:6e5});if(x.status!==0)throw new Error(`apigen-python-env: pip install "${I}" failed (exit ${x.status}):
|
|
179
|
+
${x.stderr}
|
|
180
|
+
stdout:
|
|
181
|
+
${x.stdout}`)}finally{k.rmSync(g,{recursive:!0,force:!0})}const w={pyprojectHash:a,extras:h};return k.writeFileSync(i,JSON.stringify(w)),{python:c,venvDir:s,pythonPkgDir:t}})}function Dw(e,t=1e4){return new Promise((r,n)=>{const o=uo.createInterface({input:e.stdout});let s=!1;function i(c){s||(s=!0,clearTimeout(a),o.close(),c())}const a=setTimeout(()=>{i(()=>n(new Error('py-flask: timed out waiting for {"ready":true}')))},t);o.on("line",c=>{const u=c.trim();try{JSON.parse(u).ready===!0&&i(()=>r())}catch{}}),e.on("exit",c=>{i(()=>n(new Error(`py-flask: python process exited prematurely (code ${c})`)))})})}async function Rw(e){const t=e.options.port??8e3,r=e.options.host??"127.0.0.1",n=e.packages[0];if(!n)throw new Error("py-flask plugin: no package in RunInput.packages");const o=e.options.namespace??n.id,s=n.importPath;if(!s.endsWith(".py"))throw new Error(`py-flask plugin: --source must point to a .py file, got: ${s}`);const i=Cw({}),a=Q.spawn(i.python,["-m","apigen_python.flask_server","--module",s,"--namespace",o,"--host",String(r),"--port",String(t)],{cwd:i.pythonPkgDir,env:{...process.env,PYTHONPATH:i.pythonPkgDir},stdio:["pipe","pipe","pipe"]});return a.stderr.on("data",c=>{process.stderr.write(c)}),await Dw(a),new Promise((c,u)=>{a.on("exit",d=>{d===0||d===null?c():u(new Error(`py-flask: python process exited with code ${d}`))}),e.signal&&e.signal.addEventListener("abort",()=>{a.kill("SIGTERM"),c()})})}const xw={id:"py-flask",description:"Serve Python functions over HTTP (stdlib http.server; Flask optional)",language:"py",optionsSchema:{type:"object",properties:{port:{type:"number",default:8e3},host:{type:"string",default:"127.0.0.1"},namespace:{type:"string"}}},generate(e){return{files:[]}},run:Rw};function Mw(e){const t=__dirname,r=N.resolve(t,"..","..","..","python");if(k.existsSync(N.join(r,"apigen_python")))return r;let n=t;for(let o=0;o<20;o++){const s=N.join(n,"packages","apigen","python");if(k.existsSync(N.join(s,"apigen_python")))return s;const i=N.dirname(n);if(i===n)break;n=i}return r}const La=["python3.13","python3.12","python3.11","python3"],Nt=[3,11];function Fw(e){const t=Q.spawnSync(e,["-c",'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")'],{encoding:"utf8",timeout:15e3});if(t.status!==0||!t.stdout)return;const[r,n]=t.stdout.trim().split(".").map(Number);if(!(!Number.isFinite(r)||!Number.isFinite(n)))return[r,n]}function Uw(){for(const e of La){const t=Fw(e);if(t&&(t[0]>Nt[0]||t[0]===Nt[0]&&t[1]>=Nt[1]))return e}throw new Error(`apigen-python-env: no Python >= ${Nt.join(".")} found on PATH (tried: ${La.join(", ")}). Install Python ${Nt.join(".")}+ or set APIGEN_PYTHON to a provisioned interpreter.`)}function Lw(e){return process.platform==="win32"?N.join(e,"Scripts","python.exe"):N.join(e,"bin","python3")}function zw(e){const t=k.readFileSync(N.join(e,"pyproject.toml"));return ao.createHash("sha256").update(t).digest("hex")}function za(e){try{const t=JSON.parse(k.readFileSync(e,"utf8"));if(typeof t.pyprojectHash=="string"&&Array.isArray(t.extras))return t}catch{}}function qw(e,t,r){const n=Date.now()+t;for(;;)try{k.mkdirSync(e,{recursive:!1});break}catch{if(Date.now()>n){try{k.rmdirSync(e)}catch{}continue}Q.spawnSync(process.execPath,["-e","setTimeout(()=>{}, 250)"],{timeout:5e3})}try{return r()}finally{try{k.rmdirSync(e)}catch{}}}function Vw(e={}){const t=Mw(),r=process.env.APIGEN_PYTHON;if(r){if(!k.existsSync(r))throw new Error(`apigen-python-env: APIGEN_PYTHON points to a missing file: ${r}`);return{python:r,venvDir:"",pythonPkgDir:t}}const n=[...new Set(e.extras??[])].sort(),o=e.envHome??process.env.APIGEN_PYENV_HOME??N.join(Ge.homedir(),".adhd","apigen"),s=N.join(o,"pyvenv"),i=N.join(s,".apigen-stamp"),a=zw(t),c=Lw(s),u=()=>{if(!k.existsSync(c))return!1;const p=za(i);return!p||p.pyprojectHash!==a?!1:n.every(h=>p.extras.includes(h))};if(u())return{python:c,venvDir:s,pythonPkgDir:t};k.mkdirSync(o,{recursive:!0});const d=N.join(o,"pyvenv.lock"),l=e.lockTimeoutMs??3e5;return qw(d,l,()=>{if(u())return{python:c,venvDir:s,pythonPkgDir:t};const p=za(i),h=[...new Set([...(p==null?void 0:p.extras)??[],...n])].sort();k.rmSync(s,{recursive:!0,force:!0});const f=Uw(),y=Q.spawnSync(f,["-m","venv",s],{encoding:"utf8",timeout:12e4});if(y.status!==0)throw new Error(`apigen-python-env: "${f} -m venv" failed (exit ${y.status}):
|
|
182
|
+
${y.stderr}`);const $=N.join(t,"build");k.existsSync($)&&k.rmSync($,{recursive:!0,force:!0});for(const _ of k.readdirSync(t))_.endsWith(".egg-info")&&k.rmSync(N.join(t,_),{recursive:!0,force:!0});const g=k.mkdtempSync(N.join(Ge.tmpdir(),"apigen-python-wheel-"));try{const _=Q.spawnSync(c,["-m","pip","wheel","--no-deps","--wheel-dir",g,t],{encoding:"utf8",timeout:6e5});if(_.status!==0)throw new Error(`apigen-python-env: pip wheel failed (exit ${_.status}):
|
|
183
|
+
${_.stderr}
|
|
184
|
+
stdout:
|
|
185
|
+
${_.stdout}`);const E=k.readdirSync(g).filter(V=>V.endsWith(".whl"));if(E.length===0)throw new Error("apigen-python-env: pip wheel produced no .whl file");const j=N.join(g,E[0]),I=h.length?`${j}[${h.join(",")}]`:j,x=Q.spawnSync(c,["-m","pip","install","--quiet","--disable-pip-version-check",I],{encoding:"utf8",timeout:6e5});if(x.status!==0)throw new Error(`apigen-python-env: pip install "${I}" failed (exit ${x.status}):
|
|
186
|
+
${x.stderr}
|
|
187
|
+
stdout:
|
|
188
|
+
${x.stdout}`)}finally{k.rmSync(g,{recursive:!0,force:!0})}const w={pyprojectHash:a,extras:h};return k.writeFileSync(i,JSON.stringify(w)),{python:c,venvDir:s,pythonPkgDir:t}})}function Gw(e,t=1e4){return new Promise((r,n)=>{const o=uo.createInterface({input:e.stdout});let s=!1;function i(c){s||(s=!0,clearTimeout(a),o.close(),c())}const a=setTimeout(()=>{i(()=>n(new Error('py-grpc: timed out waiting for {"ready":true}')))},t);o.on("line",c=>{const u=c.trim();try{JSON.parse(u).ready===!0&&i(()=>r())}catch{}}),e.on("exit",c=>{i(()=>n(new Error(`py-grpc: python process exited prematurely (code ${c})`)))})})}async function Hw(e){const t=e.options.port??50051,r=e.options.host??"127.0.0.1",n=e.packages[0];if(!n)throw new Error("py-grpc plugin: no package in RunInput.packages");const o=e.options.namespace??n.id,s=n.importPath;if(!s.endsWith(".py"))throw new Error(`py-grpc plugin: --source must point to a .py file, got: ${s}`);const i=Vw({extras:["grpc"]}),a=Q.spawn(i.python,["-m","apigen_python.grpc_server","--module",s,"--namespace",o,"--host",String(r),"--port",String(t)],{cwd:i.pythonPkgDir,env:{...process.env,PYTHONPATH:i.pythonPkgDir},stdio:["pipe","pipe","pipe"]});return a.stderr.on("data",c=>{process.stderr.write(c)}),await Gw(a),new Promise((c,u)=>{a.on("exit",d=>{d===0||d===null?c():u(new Error(`py-grpc: python process exited with code ${d}`))}),e.signal&&e.signal.addEventListener("abort",()=>{a.kill("SIGTERM"),c()})})}const Jw={id:"py-grpc",description:"Serve Python functions over gRPC (grpcio; in-memory descriptors; reflection enabled)",language:"py",optionsSchema:{type:"object",properties:{port:{type:"number",default:50051},host:{type:"string",default:"127.0.0.1"},namespace:{type:"string"}}},generate(e){return{files:[]}},run:Hw},zt={mcp:av,jsonschema:cv,"api-fastify":r0,"api-express":Y0,cli:Ma,"cli-output":Ma,"py-flask":xw,"py-grpc":Jw},Oe=new id.Command().name("apigen").version("0.1.0");zh(Oe);pg(Oe,zt);hg(Oe,zt);zg(Oe,zt);Gg(Oe,zt);w$(Oe);_$(Oe,zt);Oe.parseAsync();
|