@adhd/backlog 0.1.9 → 1.0.0
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 +80 -47
- package/README.md +332 -81
- package/api.d.ts +146 -0
- package/cli.d.ts +45 -18
- package/env.d.ts +23 -3
- package/envelope.d.ts +163 -0
- package/index.d.ts +11 -10
- package/index.js +531 -173
- package/index.mjs +30039 -15879
- package/install-skill.d.ts +23 -0
- package/package.json +50 -15
- package/query/card.d.ts +31 -0
- package/query/get.d.ts +11 -0
- package/query/index.d.ts +67 -0
- package/query/markdown.d.ts +11 -0
- package/query/query.d.ts +131 -0
- package/query/resolve.d.ts +123 -0
- package/query/types.d.ts +450 -0
- package/query/views/registry.d.ts +43 -0
- package/query/views/semantic.d.ts +101 -0
- package/query/views/stats.d.ts +109 -0
- package/search-shortcut.d.ts +79 -0
- package/serve.d.ts +18 -0
- package/server.d.ts +139 -4
- package/skill/SKILL.md +619 -138
- package/store/graph-backlog-store.d.ts +80 -17
- package/store/immediate-retry.d.ts +24 -13
- package/store/type-policy.d.ts +4 -0
- package/store/vocabulary-guard.d.ts +52 -0
- package/write/audit.d.ts +36 -0
- package/write/bootstrap.d.ts +123 -0
- package/write/catalog.d.ts +351 -0
- package/write/claim-lease.d.ts +21 -0
- package/write/claim.d.ts +80 -0
- package/write/create-issue.d.ts +250 -0
- package/write/delete.d.ts +39 -0
- package/write/embed-drain.d.ts +68 -0
- package/write/embedding-observer.d.ts +80 -0
- package/write/errors.d.ts +303 -0
- package/write/issue-status.d.ts +10 -0
- package/write/move.d.ts +70 -0
- package/write/relate.d.ts +52 -0
- package/write/transition.d.ts +60 -0
- package/write/tx.d.ts +344 -0
- package/write/update.d.ts +81 -0
- package/client.d.ts +0 -174
- package/markdown.d.ts +0 -75
- package/migration-admin.d.ts +0 -26
- package/model.d.ts +0 -437
- package/store/audit-log.d.ts +0 -16
- package/store/claim.d.ts +0 -24
- package/store/crud.d.ts +0 -62
- package/store/ids.d.ts +0 -24
- package/store/lifecycle.d.ts +0 -36
- package/store/mapping.d.ts +0 -101
- package/store/mutate-metadata.d.ts +0 -8
- package/store/query.d.ts +0 -68
- package/store/repo-migration.d.ts +0 -51
- package/store/serve-lock.d.ts +0 -42
- package/store/structure.d.ts +0 -66
package/index.js
CHANGED
|
@@ -1,211 +1,547 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var cm=Object.create;var tc=Object.defineProperty;var um=Object.getOwnPropertyDescriptor;var lm=Object.getOwnPropertyNames;var fm=Object.getPrototypeOf,dm=Object.prototype.hasOwnProperty;var pm=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lm(t))!dm.call(e,o)&&o!==n&&tc(e,o,{get:()=>t[o],enumerable:!(r=um(t,o))||r.enumerable});return e};var hm=(e,t,n)=>(n=e!=null?cm(fm(e)):{},pm(t||!e||!e.__esModule?tc(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("node:fs"),Ln=require("node:url"),xl=require("@adhd/sox-telemetry"),kn=require("ts-morph"),T=require("node:path"),bt=require("ts-json-schema-generator"),je=require("pino"),Pr=require("ajv"),Tr=require("ajv-formats"),Ko=require("@adhd/sox-store-adapter"),mm=require("@adhd/sox-graph-store"),Ue=require("node:os"),Un=require("node:crypto"),Pl=require("node:module"),gm=require("node:fs/promises"),ym=require("fastify"),nc=require("node:http"),$m=require("@modelcontextprotocol/sdk/server/index.js"),vm=require("@modelcontextprotocol/sdk/server/stdio.js"),wm=require("@modelcontextprotocol/sdk/server/sse.js"),bm=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),rc=require("@modelcontextprotocol/sdk/types.js"),oc=require("yaml");var re=typeof document<"u"?document.currentScript:null;function Tl(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 Go=Tl(T),Et=Tl(gm),Jo="$apigen";let sc=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Em(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new sc(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new sc("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Ws="x-apigen-logical",Ys="x-apigen-codec",Ho="x-apigen-ctor",zo="x-apigen-tojson",Sm="0.1.0";function ic(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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 Dt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Dt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Cl(e,s,t);return Dt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return $o(e,t,n);const a=t.items;if(!a)return e.map(u=>St(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?St(u):Dt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Dt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return $o(e,t,n);const a=t.properties;if(!a)return St(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Dt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?$o(e,t,n):St(e)}function Lt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Lt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Cl(e,s,t);return Lt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Lt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Lt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Lt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Nm(e,n):e}function Cl(e,t,n,r){const o=n.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 $o(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Jo]:r,v:s}}catch{}}return St(e)}function Nm(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Jo in e){const n=e,r=n[Jo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function St(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(St);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=St(r));return t}return null}function Om(e){return{encode(t,n,r){const o=ic(e,r);return Dt(t,n,o)},decode(t,n,r){const o=ic(e,r);return Lt(t,n,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,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},Zs={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.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,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},ei={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},km=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ti={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!km.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Wo="NaN",Yo="Infinity",Qo="-Infinity",_m=new Set([Wo,Yo,Qo]),ni={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Wo:e===1/0?Yo:e===-1/0?Qo:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Wo)return NaN;if(e===Yo)return 1/0;if(e===Qo)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[..._m].join(", ")}.`);return NaN}},Am=[Qs,Zs,Xs,ei,ti,ni];function jm(e,t={}){for(const n of Am)e.register(n,{override:t.override??!1})}const Im=12;function xm(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function ac(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function Pm(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function Tm(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function cc(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?_n(a,t,n+1):`<${i}>`}return s}function Cm(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[_n(r,t,n+1)]:[]}function _n(e,t=e??{},n=0){if(!e||n>Im)return null;if(typeof e.$ref=="string"){const o=xm(e.$ref,t);return o!==void 0?_n(o,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return cc({...e,properties:o,required:s},t,n)}const r=ac(e.oneOf)??ac(e.anyOf);if(r)return _n(r,t,n+1);switch(Pm(e)){case"object":return cc(e,t,n);case"array":return Cm(e,t,n);case"string":return Tm(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function Rm(e){if(!e)return;const t=_n(e);return`Example: ${JSON.stringify(t)}`}Qs.id,Zs.id,Xs.id,ei.id,ti.id,ni.id;const Rl=Em();jm(Rl);const Ml=Om(Rl.freeze());function Dl(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Zo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Mm(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function Dm(e,t){return t===void 0||e===void 0?e:Ml.decode(e,t)}function vo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Ml.encode(e,n)}async function Lm(e,t,n,r,o,s){const i=Zo(n).map(c=>Dm(s[c],Mm(n,c)));if(Dl(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return vo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return vo(u,n)}const a=await e[r](...i);return vo(a,n)}let Ll=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function Um(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>Lm(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const Bm={"decimal.js":"Decimal"};function Fm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Bm).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Fm(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function qm(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},je(s);const i=n?je.destination({dest:e.destination,mkdir:!0,sync:!0}):je.destination(2);return je(s,i)}function Ul(e){return e?e.type==="array"?`${Ul(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Vm(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:Ul(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let Km=class 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}};const Cr=new Pr({allErrors:!0});Tr(Cr);for(const e of[Ws,Ys,Ho,zo,"discriminator"])Cr.addKeyword({keyword:e,valid:!0});Cr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Gm(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Jm(e,t){const n=Rm(t),r=[`Validation failed: ${Gm(e)}`];return n&&r.push(n),r.join(" — ")}function Hm(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Cr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Km("invalid_argument",Jm(a,o.input),a)}return n()}}function zm(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let lt=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function wo(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Bl(e,t){const n=e[Ys];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Wm(e,t,n){const r=Bl(t,n);return r?r.encode(e,t,n):e}function Ym(e,t,n){const r=Bl(t,n);return r?r.decode(e,t,n):e}function Qm(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Ws]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:wo(r)!==void 0},encode(r,o,s){const i=wo(o);if(!i)throw new lt("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=r[a];if(u==null)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return Wm(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new lt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=wo(o);if(!a)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Ym(r,h,{...s,path:`${s.path}[${f}]`})}}}const Zm="x-apigen-instances";let Gn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function uc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Xm(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function lc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function eg(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function tg(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Ws]==="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 Gn("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=uc(s),c=typeof s[zo]=="string"?s[zo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=lc($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=lc(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Gn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of Xm(s))if(!(l in a))throw new Gn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Zm]===!1)throw new Gn("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=uc(s),u={};for(const[l,f]of Object.entries(a))u[l]=eg(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Ho]=="string"?s[Ho]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const ng=[Qs,Zs,Xs,ei,ti,ni],rg={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},fc=tg({id:"ts.NominalSentinel",schema:rg}),og={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},dc=Qm({id:"ts.UnionSentinel",schema:og});function sg(){const e=[...ng.map(t=>[t.id,t]),[fc.id,fc],[dc.id,dc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Sm,codecs:sg()});const pc=new Set(["string","number","boolean","integer"]);function ig(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:n}=t;return typeof n=="string"?pc.has(n):Array.isArray(n)?n.every(r=>pc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function ag(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(ig)}const cg={"decimal.js":"Decimal"};function ug(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(cg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ug(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function hc(e){return e.words.join("-")}function mc(e){return e.words.map(hg).join("")}function gc(e){return e.words.join("_")}function lg(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||ag(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>hc(h)).join("/"),c=o.map(h=>gc(h)).join("_"),u=o.map(h=>gc(h)).slice(0,-1).join("."),l=mc(o[o.length-2]??o[0]),f=mc(o[o.length-1]),p=o.map(h=>hc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function fg(e,t){return`x-${e}-${t}`}function dg(e,t){return`--${e}-${t}`}function pg(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function hg(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ri(e){return e.anyOf??e.oneOf}function mg(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=ri(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function gg(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=ri(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function yg(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=ri(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function $g(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function vg(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function yc(e){return typeof e.handler=="function"}function wg(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=fg(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:dg(i,s),envVar:pg(i,s)})}return o}function bg(e,t){const n=new Map,{props:r}=vg(e);for(const[o,s]of Object.entries(r)){let i="string";gg(s)?i="boolean":(mg(s)||yg(s))&&(i="json"),n.set($g(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Fl(e){const{op:t,schema:n,transport:r,projection:o}=e,s=lg(t,o),i=n?wg(n):[],a=n?bg(n,i):new Map,c=n?Vm(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:yc(t)};if(yc(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function Eg(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Sg(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Ng(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function bo(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(Ng(s))}return r.push(Hm(e)),Um(r)}function Og(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const kg={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function $c(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Ll};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Og(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:kg}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const _g={"decimal.js":"Decimal"};function Ag(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(_g).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ag(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function jg(e,t){return`--${e}-${t}`}function Ig(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Xo(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const xg=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],vc={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let br=class 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}};function wc(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&xg.includes(e.code)&&typeof e.toJSON=="function"}function ql(e){return e.anyOf??e.oneOf}function Pg(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd";o.push({field:s,pluginId:i,flag:jg(i,s),envVar:Ig(i,s)})}return o}function es(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=ql(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Tg(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=ql(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function bc(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Cg(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function Rg(e){const t=oi(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return t.length>0?t.toLowerCase():"branch"}function Eo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;if(!r)return;const o=r.oneOf,s=r.discriminator;if(!o||!s)return;const i=[];for(const[a,c]of Object.entries(s.mapping)){const u=Cg(c);if(u===void 0)continue;const l=o[u];if(!l)continue;const f=l.properties??{},p=l.required??[];i.push({value:a,commandName:Rg(a),props:f,required:p})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function oi(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Mg(e,t){if(!Go.isAbsolute(t))return t;const n=Go.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Dg=["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(`
|
|
3
|
-
`);function
|
|
4
|
-
`)}]}}function
|
|
5
|
-
`)}function
|
|
6
|
-
|
|
7
|
-
${Ec($)}`));return}const{entry:E,rest:b}=v,{plan:N,dispatch:j}=E,R=N.cli.path.join(" ");if(b.includes("--help")||b.includes("-h")){const U=Hl(N.params);console.log(`${R}${U?` { ${U} }`:""}`);return}const J={rest:b};try{if(N.streaming)throw new br("invalid_argument",`Command "${R}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const U=await c.readCall(J,N),q=Date.now(),Q=await j(U);await c.writeResult(J,Q,N),o.info({command:R,ms:Date.now()-q},`→ ${R}`)}catch(U){o.error({command:R,err:U},`✗ ${R}`),await c.writeError(J,U,N)}}const Qg={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"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(e){return Ug(e)},run(e){return Yg(e)}};let tt=class 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}};function Sc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Zg(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Sc(i),path:s.map(Sc),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}function Xg(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of t){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}const ey={"decimal.js":"Decimal"};function ty(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ey).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ty(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ny(e){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:e}},{type:"object",required:["index","status","chunks"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},chunks:{type:"array"}}},{type:"object",required:["index","status","reason"],properties:{index:{type:"integer"},status:{type:"string",enum:["rejected"]},reason:{},chunksDelivered:{type:"integer"}}}]}}function ry(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:ny(e.output)}}function oy(e,t={}){const n=new Set(t.exclude??[]),r=new Map;for(const o of e){if(n.has(o.id))continue;const s=r.get(o.kind);s?s.push(o):r.set(o.kind,[o])}return r}function Nc(e){return{type:"string",enum:[e]}}function Oc(e,t){return{type:"object",required:["operation","items"],properties:{operation:t,items:{type:"array",items:e.itemsSchema},concurrency:{type:"number"},mode:{type:"string",enum:["parallel","serial","chained"]},onItemError:{type:"string",enum:["continue","abort"]},itemTimeoutMs:{type:"number"}},additionalProperties:!0}}function sy(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(ry);if(e.length===1){const[o]=e,[s]=t;return{input:Oc(s,Nc(o.id)),output:{type:"array",items:s.resultSchema}}}const n=e.map((o,s)=>Oc(t[s],Nc(o.id))),r=Xg(n);return{input:{oneOf:n,...r?{discriminator:r}:{}},output:{oneOf:t.map(o=>({type:"array",items:o.resultSchema}))},...r?{discriminator:r}:{}}}function iy(e,t={}){const n=oy(e.operations,t),r=[];for(const[o,s]of n){const{input:i,output:a}=sy(s),c=Zg(`_batch/${o}`,e,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const ts="$apigen";let kc=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function ay(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new kc(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new kc("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const si="x-apigen-logical",ii="x-apigen-codec",ns="x-apigen-ctor",rs="x-apigen-tojson",cy="0.1.0";function _c(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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 Ut(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ut(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Wl(e,s,t);return Ut(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return So(e,t,n);const a=t.items;if(!a)return e.map(u=>Nt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Nt(u):Ut(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ut(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return So(e,t,n);const a=t.properties;if(!a)return Nt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ut(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?So(e,t,n):Nt(e)}function Bt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Bt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Wl(e,s,t);return Bt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Bt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Bt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Bt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?uy(e,n):e}function Wl(e,t,n,r){const o=n.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 So(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[ts]:r,v:s}}catch{}}return Nt(e)}function uy(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&ts in e){const n=e,r=n[ts],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Nt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Nt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Nt(r));return t}return null}function ly(e){return{encode(t,n,r){const o=_c(e,r);return Ut(t,n,o)},decode(t,n,r){const o=_c(e,r);return Bt(t,n,o)}}}const ai={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},ci={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},ui={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},li={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},fy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,fi={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!fy.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},os="NaN",ss="Infinity",is="-Infinity",dy=new Set([os,ss,is]),di={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?os:e===1/0?ss:e===-1/0?is:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===os)return NaN;if(e===ss)return 1/0;if(e===is)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...dy].join(", ")}.`);return NaN}},py=[ai,ci,ui,li,fi,di];function hy(e,t={}){for(const n of py)e.register(n,{override:t.override??!1})}ai.id,ci.id,ui.id,li.id,fi.id,di.id;const Yl=ay();hy(Yl);ly(Yl.freeze());let my=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};const gy={"decimal.js":"Decimal"};function yy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(gy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${yy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const $y=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let Ql=class 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}};function Zl(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&$y.includes(e.code)&&typeof e.toJSON=="function"}function Ac(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const pi=new Pr({allErrors:!0});Tr(pi);for(const e of[si,ii,ns,rs,"discriminator"])pi.addKeyword({keyword:e,valid:!0});pi.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function vy(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=Zl(n)?n:new Ql("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Ac("before-first-chunk",r)}:{ok:!1,carrier:Ac("after-first-chunk",r,t.length)}}}function wy(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let ft=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function No(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Xl(e,t){const n=e[ii];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function by(e,t,n){const r=Xl(t,n);return r?r.encode(e,t,n):e}function Ey(e,t,n){const r=Xl(t,n);return r?r.decode(e,t,n):e}function Sy(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[si]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:No(r)!==void 0},encode(r,o,s){const i=No(o);if(!i)throw new ft("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=r[a];if(u==null)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ft("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return by(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ft("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=No(o);if(!a)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ft("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Ey(r,h,{...s,path:`${s.path}[${f}]`})}}}const Ny="x-apigen-instances";let Hn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function jc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Oy(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ic(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function ky(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function _y(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[si]==="nominal"?!0:o[ii]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Hn("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=jc(s),c=typeof s[rs]=="string"?s[rs]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=Ic($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=Ic(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Hn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of Oy(s))if(!(l in a))throw new Hn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Ny]===!1)throw new Hn("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=jc(s),u={};for(const[l,f]of Object.entries(a))u[l]=ky(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[ns]=="string"?s[ns]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const Ay=[ai,ci,ui,li,fi,di],jy={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},xc=_y({id:"ts.NominalSentinel",schema:jy}),Iy={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Pc=Sy({id:"ts.UnionSentinel",schema:Iy});function xy(){const e=[...Ay.map(t=>[t.id,t]),[xc.id,xc],[Pc.id,Pc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:cy,codecs:xy()});const Py=4,Ty=32;function as(e){return Zl(e)?e:e instanceof Error?new Ql("internal",e.message):e}function Cy(e,t){if(e==="serial"||e==="chained")return 1;const n=t??Py;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Ty)}function Ry(){}function My(e,t){var n;if(!e&&!t)return{signal:void 0,dispose:Ry};const r=new AbortController,o=()=>{r.abort(e==null?void 0:e.reason)};e&&(e.aborted?r.abort(e.reason):e.addEventListener("abort",o,{once:!0}));let s;return t!==void 0&&!r.signal.aborted&&(s=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(n=s.unref)==null||n.call(s)),{signal:r.signal,dispose(){e&&e.removeEventListener("abort",o),s&&clearTimeout(s)}}}async function Tc(e,t,n,r,o,s){const i=My(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await e(t,a,o);if(wy(c)){const u=await vy(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:as(l.error),...l.phase==="after-first-chunk"?{chunksDelivered:l.chunksDelivered}:{}}}return{index:n,status:"fulfilled",value:c}}catch(a){return{index:n,status:"rejected",reason:as(a)}}finally{i.dispose()}}async function Dy(e,t,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=Cy(s,o.concurrency),c=new Array(n.length),u=d=>({index:d,status:"rejected",reason:as(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(s==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(s==="serial"||s==="chained"){let d=!1;for(let m=0;m<n.length;m++){if(d){c[m]=u(m);continue}const y=await Tc(e,t,m,n[m],r,o.itemTimeoutMs);c[m]=y,y.status==="rejected"&&(s==="chained"||i==="abort")&&(d=!0)}return c}let l=0,f=!1;const p=Math.max(1,Math.min(a,n.length)),h=Array.from({length:p},async()=>{for(;;){const d=l++;if(d>=n.length)return;if(f){c[d]=u(d);continue}const m=await Tc(e,t,d,n[d],r,o.itemTimeoutMs);c[d]=m,m.status==="rejected"&&i==="abort"&&(f=!0)}});return await Promise.all(h),c}const Ly={"decimal.js":"Decimal"};function Uy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ly).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Uy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function By(e,t){const n=e.operation;if(typeof n!="string"||n.length===0)throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "operation" must be a non-empty string naming the target operation id');if(!t.includes(n))throw new tt("invalid_argument",`@adhd/apigen-plugin-batch: "operation" ("${n}") is not one of this mount's batchable operations: ${t.join(", ")}`);const r=e.items;if(!Array.isArray(r))throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "items" must be an array');const o=e.concurrency;if(o!==void 0&&typeof o!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "concurrency" must be a number');const s=e.mode;if(s!==void 0&&s!=="parallel"&&s!=="serial"&&s!=="chained")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "mode" must be one of "parallel" | "serial" | "chained"');const i=e.onItemError;if(i!==void 0&&i!=="continue"&&i!=="abort")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "onItemError" must be one of "continue" | "abort"');const a=e.itemTimeoutMs;if(a!==void 0&&typeof a!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "itemTimeoutMs" must be a number');return{operation:n,items:r,concurrency:o,mode:s,onItemError:i,itemTimeoutMs:a}}function Fy(e,t){return async n=>{if(!t)throw new tt("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const r=By(n.data,e),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},s=r.items.map(i=>({operation:{id:r.operation},ctx:new my,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return Dy(t.invoke,r.operation,s,t.invokeOptions,o)}}function qy(e,t={},n){return iy(e,t).map(r=>({...r,handler:Fy(r.operationIds,n)}))}const cs={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(e,t,n){return qy(e,t,n)}}}},Cc=new Set(["string","number","boolean","integer"]);function Vy(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:n}=t;return typeof n=="string"?Cc.has(n):Array.isArray(n)?n.every(r=>Cc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Ky(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(Vy)}const Gy={"decimal.js":"Decimal"};function Jy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Gy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Jy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Rc(e){return e.words.join("-")}function Mc(e){return e.words.map(Hy).join("")}function Dc(e){return e.words.join("_")}function ef(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Ky(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Rc(h)).join("/"),c=o.map(h=>Dc(h)).join("_"),u=o.map(h=>Dc(h)).slice(0,-1).join("."),l=Mc(o[o.length-2]??o[0]),f=Mc(o[o.length-1]),p=o.map(h=>Rc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Hy(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}async function hi(e,t=5e3){if(e!==":memory:"&&C.mkdirSync(T.dirname(e),{recursive:!0}),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const n=await Ko.createStoreAdapter({dbPath:e},{migrateOnAdapterChange:e!==":memory:"&&C.existsSync(e)});await n.pragmaSet("busy_timeout",t);const r=mm.createGraphBackend(n);return await r.applySchema(),{adapter:n,graph:r}}async function tf(e){await e.adapter.close()}async function nf(e){if(e)try{await tf(e)}catch(t){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${t instanceof Error?t.message:String(t)}`)}}const us=["SIGINT","SIGTERM"];function rf(e,t=n=>process.exit(n)){let n=!1;const r=s=>{n||(n=!0,e().catch(i=>{console.error(`backlog: signal cleanup failed (${s}): ${i instanceof Error?i.message:String(i)}`)}).finally(()=>{o(),t(128+Ue.constants.signals[s])}))},o=()=>{for(const s of us)process.removeListener(s,r)};for(const s of us)process.on(s,r);return{dispose:o}}function zy(){return us.some(e=>process.listenerCount(e)>0)}const Wy=[".git",".adhd","adhd.environment.yaml"];function Oo(e){let t=T.resolve(e);const{root:n}=T.parse(t);for(;;){for(const o of Wy)if(C.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=T.dirname(t);if(r===t)return;t=r}}const Yy=new Set(["system","global","project"]);function Qy(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:Oo(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&Yy.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:Oo(n)??n}:{scope:s}}const o=Oo(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function Lc(e){return`.${e}`}function Zy(e){const t=Ue.homedir();if(process.platform==="darwin")return T.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??T.join(t,"AppData","Roaming");return T.join(r,e)}const n=process.env.XDG_DATA_HOME??T.join(t,".local","share");return T.join(n,e)}function Xy(e){const t=e.orgNamespace,n=e.adhdRoot??T.join(Ue.homedir(),Lc(t)),r=e.adhdRoot??Zy(t),o={system:T.join(r,e.project,e.namespace),global:T.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=T.join(e.projectRoot,Lc(t),e.project,e.namespace)),o}function of(e,t){return t==="project"?e.project??e.global:e[t]}function e$(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function t$(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}const oe={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},_={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},cr="tag:yaml.org,2002:",rt={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function Uc(e){const t=[0];let n=e.indexOf(`
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
2
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const J=require("node:fs"),mt=require("node:os"),L=require("node:path"),$s=require("node:url"),Lg=require("@adhd/sox-telemetry"),Ne=require("node:module"),pt=require("pino"),ia=require("ajv"),aa=require("ajv-formats"),pn=require("@adhd/sox-store-adapter"),tE=require("@adhd/sox-graph-store"),kn=require("node:crypto"),sl=require("node:fs/promises"),nE=require("fastify"),mp=require("node:http"),rE=require("@modelcontextprotocol/sdk/server/index.js"),oE=require("@modelcontextprotocol/sdk/server/stdio.js"),sE=require("@modelcontextprotocol/sdk/server/sse.js"),iE=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),gp=require("@modelcontextprotocol/sdk/types.js"),aE=require("@adhd/sox-hybrid-search");var D=typeof document<"u"?document.currentScript:null;function Dg(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Ic=Dg(L),or=Dg(sl),Pc="$apigen";let yp=class extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function cE(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new yp(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new yp("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const il="x-apigen-logical",al="x-apigen-codec",xc="x-apigen-ctor",Rc="x-apigen-tojson",uE="0.1.0";function wp(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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",...e}}function xr(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return xr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=Ug(t,s,e,n);return xr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return Mo(t,e,n);const a=e.items;if(!a)return t.map(u=>sr(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?sr(u):xr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>xr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return Mo(t,e,n);const a=e.properties;if(!a)return sr(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=xr(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?Mo(t,e,n):sr(t)}function Rr(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Rr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=Ug(t,s,e,n);return Rr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Rr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Rr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Rr(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Tc(t,n):t}function Ug(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=Mi(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=lE(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=Mi(u,r),d=Bg(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function Mi(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function vp(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function lE(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>Mi(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))vp(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?vp(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function dE(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function Bg(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=Bg(t,Mi(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=dE(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function Mo(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[Pc]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>Mo(o,{},n));if(Fg(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=Mo(i,{},n));return o}return sr(t)}function Fg(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Tc(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&Pc in t){const n=t,r=n[Pc],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Tc(n,e));if(Fg(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Tc(o,e);return n}return t}function sr(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(sr);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=sr(r));return e}return null}function fE(t){return{encode(e,n,r){const o=wp(t,r);return xr(e,n,o)},decode(e,n,r){const o=wp(t,r);return Rr(e,n,o)}}}const cl={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},ul={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},ll={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},dl={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},pE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,fl={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!pE.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},Cc="NaN",Mc="Infinity",Lc="-Infinity",hE=new Set([Cc,Mc,Lc]),pl={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?Cc:t===1/0?Mc:t===-1/0?Lc:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===Cc)return NaN;if(t===Mc)return 1/0;if(t===Lc)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...hE].join(", ")}.`);return NaN}},mE=[cl,ul,ll,dl,fl,pl];function gE(t,e={}){for(const n of mE)t.register(n,{override:e.override??!1})}const yE=12;function wE(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,r,o]=n,s=r==="$defs"?e.$defs:e.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function $p(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function vE(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function $E(t){switch(t.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function bp(t,e,n){const r=t.properties??{},o=t.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?ns(a,e,n+1):`<${i}>`}return s}function bE(t,e,n){const r=Array.isArray(t.items)?t.items[0]:t.items;return r?[ns(r,e,n+1)]:[]}function ns(t,e=t??{},n=0){if(!t||n>yE)return null;if(typeof t.$ref=="string"){const o=wE(t.$ref,e);return o!==void 0?ns(o,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const o={},s=[];for(const i of t.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return bp({...t,properties:o,required:s},e,n)}const r=$p(t.oneOf)??$p(t.anyOf);if(r)return ns(r,e,n+1);switch(vE(t)){case"object":return bp(t,e,n);case"array":return bE(t,e,n);case"string":return $E(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function EE(t){if(!t)return;const e=ns(t);return`Example: ${JSON.stringify(e)}`}cl.id,ul.id,ll.id,dl.id,fl.id,pl.id;const qg=cE();gE(qg);const Kg=fE(qg.freeze());function Vg(t,e){var n;const r=((n=t.input)==null?void 0:n.properties)??{};return e in r}function Dc(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function SE(t,e){var n,r,o;const s=(o=(r=(n=t.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[e];return i!==void 0?i:void 0}function _E(t,e){return e===void 0||t===void 0?t:Kg.decode(t,e)}function Ja(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:Kg.encode(t,n)}async function NE(t,e,n,r,o,s){const i=Dc(n).map(c=>_E(s[c],SE(n,c)));if(Vg(n,"session")&&e){const c=await e({session:o.session}),u=await t[r](c,...i);return Ja(u,n)}if(n.hasCtx){const c=e?await e(o):void 0,u=await t[r](c,...i);return Ja(u,n)}const a=await t[r](...i);return Ja(a,n)}let Gg=class{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function OE(t=[]){return async function(e,n,r){const o=r.schemas[e];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${e}"`);const s=()=>NE(r.fns,r.createClient,o,e,n.envelope,n.domainArgs);return t.reduceRight((i,a)=>()=>a(n,i),s)()}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const kE={"decimal.js":"Decimal"};function jE(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(kE).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${jE(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function AE(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,r=!n&&!!process.stderr.isTTY,o=t.format??(r?"pretty":"json"),s={level:e};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},pt(s);const i=n?pt.destination({dest:t.destination,mkdir:!0,sync:!0}):pt.destination(2);return pt(s,i)}function IE(t){if(!t||t.type!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([r,o])=>`${r}${n.has(r)?"":"?"}: ${ca(o)}`).join(", ")} }`}function PE(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function xE(t){const e=t.enum??[];return e.length===0?"unknown":e.map(PE).join("|")}function RE(t,e){return t.map(n=>ca(n,e)).join(" | ")}function ca(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${ca(t.items,0)}[]`;if(t.enum)return xE(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?RE(n,e-1):"union":e>=1&&t.type==="object"?IE(t)??"object":t.type??"object"}function TE(t){var e;const n=(e=((t==null?void 0:t.input)??{}).properties)==null?void 0:e.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:ca(c,2),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let CE=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};const ua=new ia({allErrors:!0});aa(ua);for(const t of[il,al,xc,Rc,"discriminator"])ua.addKeyword({keyword:t,valid:!0});ua.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function ME(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function LE(t,e){const n=EE(e),r=[`Validation failed: ${ME(t)}`];return n&&r.push(n),r.join(" — ")}function DE(t){return async function(e,n){const r=e.operation.id,o=t[r];if(o===void 0)return n();const s={data:e.domainArgs,...e.envelope},i=ua.compile(o.input);if(!i(s)){const a=i.errors??[];throw new CE("invalid_argument",LE(a,o.input),a)}return n()}}function UE(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}let qn=class extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}};function Qa(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function zg(t,e){const n=t[al];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function BE(t,e,n){const r=zg(e,n);return r?r.encode(t,e,n):t}function FE(t,e,n){const r=zg(e,n);return r?r.decode(t,e,n):t}function qE(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[il]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Qa(r)!==void 0},encode(r,o,s){const i=Qa(o);if(!i)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new qn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return BE(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new qn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=Qa(o);if(!a)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new qn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return FE(r,g,{...s,path:`${s.path}[${d}]`})}}}const KE="x-apigen-instances";let Rs=class extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}};function Ep(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function VE(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Sp(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function GE(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function zE(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[il]==="nominal"?!0:o[al]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Rs("E_NOMINAL_CYCLE",`[${e}] 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=Ep(s),c=typeof s[Rc]=="string"?s[Rc]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=Sp(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=Sp(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Rs("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of VE(s))if(!(l in a))throw new Rs("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[KE]===!1)throw new Rs("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Ep(s),u={};for(const[l,d]of Object.entries(a))u[l]=GE(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[xc]=="string"?s[xc]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const WE=[cl,ul,ll,dl,fl,pl],HE={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},_p=zE({id:"ts.NominalSentinel",schema:HE}),JE={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Np=qE({id:"ts.UnionSentinel",schema:JE});function QE(){const t=[...WE.map(e=>[e.id,e]),[_p.id,_p],[Np.id,Np]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:uE,codecs:QE()});Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Op=new Set(["string","number","boolean","integer"]);function YE(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Op.has(n):Array.isArray(n)?n.every(r=>Op.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function ZE(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(YE)}const XE={"decimal.js":"Decimal"};function eS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(XE).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${eS(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function kp(t){return t.words.join("-")}function jp(t){return t.words.map(sS).join("")}function Ap(t){return t.words.join("_")}function tS(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||ZE(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>kp(g)).join("/"),c=o.map(g=>Ap(g)).join("_"),u=o.map(g=>Ap(g)).slice(0,-1).join("."),l=jp(o[o.length-2]??o[0]),d=jp(o[o.length-1]),f=o.map(g=>kp(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function nS(t,e){return`x-${t}-${e}`}function rS(t,e){return`--${t}-${e}`}function oS(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function sS(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function hl(t){return t.anyOf??t.oneOf}function iS(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=hl(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function aS(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=hl(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function cS(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=hl(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function uS(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function lS(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Ip(t){return typeof t.handler=="function"}function dS(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=nS(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:rS(i,s),envVar:oS(i,s)})}return o}function fS(t,e,n,r){e===n||t.has(e)||t.set(e,{...r,aliasOf:n})}function pS(t,e){const n=new Map,{props:r}=lS(t);for(const[o,s]of Object.entries(r)){let i="string";aS(s)?i="boolean":(iS(s)||cS(s))&&(i="json");const a=uS(o),c={camelKey:o,kind:"domain",valueKind:i};n.set(a,c),fS(n,o,a,c)}for(const o of e){const s=o.cliFlag.replace(/^--/,""),i={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(s,i)}return n}function Wg(t){const{op:e,schema:n,transport:r,projection:o}=t,s=tS(e,o),i=n?dS(n):[],a=n?pS(n,i):new Map,c=n?TE(n).params:void 0,u={op:e,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:e.streaming,isMount:Ip(e)};if(Ip(e)){const l=e.handler;u.mountHandler=async d=>l(d)}return u}function hS(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function mS(t){const e=t.exitCode;return typeof e=="function"?e:void 0}function gS(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function yS(t){return async function(e,n){const r=Object.assign(e,{data:e.domainArgs});return await t.layer(r,n)}}function Ya(t,e){var n;const r=[];for(const o of e){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(yS(s))}return r.push(DE(t)),OE(r)}function wS(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const vS={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Pp(t,e,n,r){const o={...n,operation:{id:t.op.id},ctx:new Gg};if(t.isMount){const s=t.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const i={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:wS(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[t.op.id]:()=>s(i)},schemas:{[t.op.id]:vS}};return e(t.op.id,o,a)}return e(t.op.id,o,r)}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const $S={"decimal.js":"Decimal"};function bS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries($S).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${bS(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function ES(t,e){return`--${t}-${e}`}function SS(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function Uc(t){let e=t.replace(/[^a-zA-Z0-9_$]/g,"_");return(e===""||/^[0-9]/.test(e))&&(e=`_${e}`),e}const _S=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],xp={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let Li=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function Bc(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&_S.includes(t.code)&&typeof t.toJSON=="function"}function Hg(t){return t.anyOf??t.oneOf}function NS(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd";o.push({field:s,pluginId:i,flag:ES(i,s),envVar:SS(i,s)})}return o}function Fc(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=Hg(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function OS(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=Hg(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Rp(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function kS(t){const e=/^#\/oneOf\/(\d+)$/.exec(t);if(e)return Number(e[1])}function jS(t){const e=ml(t).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e.toLowerCase():"branch"}function Za(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;if(!r)return;const o=r.oneOf,s=r.discriminator;if(!o||!s)return;const i=[];for(const[a,c]of Object.entries(s.mapping)){const u=kS(c);if(u===void 0)continue;const l=o[u];if(!l)continue;const d=l.properties??{},f=l.required??[];i.push({value:a,commandName:jS(a),props:d,required:f})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function ml(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function AS(t,e){if(!Ic.isAbsolute(e))return e;const n=Ic.relative(t,e);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const IS=["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(`
|
|
3
|
+
`);function Jg(t,e,n){for(const r of e){const o=r.flag.replace(/^--/,"");t.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!e.some(r=>r.field==="session")&&t.push(" .option('--session <key>', 'Session key')")}function Qg(t,e,n,r){var o;for(const s of e){const i=ml(s),a=OS(n[s]),c=r.includes(s);a?(t.push(` .option('--${i}')`),((o=n[s])==null?void 0:o.default)===!0&&t.push(` .option('--no-${i}')`)):c?t.push(` .requiredOption('--${i} <${i}>')`):t.push(` .option('--${i} <${i}>')`)}}function Yg(t,e,n){return`${t}:${e}::${n}`}function Zg(t,e){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,paramNames:a,schemaProps:c,literalDomainArgs:u}=e,l=e.dispatchSchemaKey??`${r}:${o}`;t.push(" .action(async (opts: Record<string, unknown>) => {");const d=Object.entries(u??{}).map(([g,p])=>`'${g}': ${p}`),f=a.map(g=>Fc(c[g])?`'${g}': __apigenParseJsonArg('${ml(g)}', opts['${g}'])`:`'${g}': opts['${g}']`);if(t.push(` const domainArgs: Record<string, unknown> = { ${[...d,...f].join(", ")} }`),s.length>0){const g=s.map(p=>{const y=p.flag.replace(/^--/,"").replace(/-([a-z])/g,(w,h)=>h.toUpperCase());return`'${p.field}': opts['${y}'] ?? process.env['${p.envVar}']`});t.push(` const envelope: Record<string, unknown> = { ${g.join(", ")} }`)}else i?t.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):t.push(" const envelope: Record<string, unknown> = {}");t.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),t.push(" console.log(JSON.stringify(result))"),t.push(" })")}function PS(t,e){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,rootUnion:a}=e,c=Uc(`${r}_${o}_cmd`);t.push(`const ${c} = program.command('${o}')`);for(const u of a.branches){const l=Object.keys(u.props).filter(f=>f!==a.discriminatorProperty),d=u.required.filter(f=>f!==a.discriminatorProperty);t.push(`${c}`),t.push(` .command('${u.commandName}')`),Jg(t,s,i),Qg(t,l,u.props,d),Zg(t,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Yg(r,o,u.commandName),bindings:s,needsSession:i,paramNames:l,schemaProps:u.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(u.value)}})}}function xS(t){const e=t.options.name??"cli",n=t.options.version??"0.1.0",r=t.packages.some(i=>Object.values(i.schemas).some(a=>{const c=Za(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(d=>d!==c.discriminatorProperty).some(d=>Fc(l.props[d])));const{props:u}=Rp(a);return Dc(a).some(l=>Fc(u[l]))})),o=["#!/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 i of t.packages){const a=Uc(i.id),c=AS(t.outputDir,i.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),r&&(o.push(IS),o.push(""));const s=Object.fromEntries(t.packages.flatMap(i=>Object.entries(i.schemas).map(([a,c])=>[`${i.id}:${a}`,c])));for(const i of t.packages)for(const[a,c]of Object.entries(i.schemas)){const u=Za(c);if(u)for(const l of u.branches){const d=Yg(i.id,a,l.commandName);s[d]={input:{type:"object",properties:{data:{type:"object",properties:l.props,additionalProperties:!1,...l.required.length>0?{required:l.required}:{}}},required:["data"]},output:{},...c.hasCtx?{hasCtx:!0}:{}}}}o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(s,null,2)}`),o.push(""),o.push(`const program = new Command().name('${e}').version('${n}')`),o.push("");for(const i of t.packages){const a=Uc(i.id);for(const[c,u]of Object.entries(i.schemas)){const l=Vg(u,"session"),d=NS(u),f=Za(u);if(f){PS(o,{varName:a,pkgId:i.id,fnName:c,bindings:d,needsSession:l,rootUnion:f});continue}const g=Dc(u),{props:p,required:y}=Rp(u);o.push("program"),o.push(` .command('${c}')`),Jg(o,d,l),Qg(o,g,p,y),Zg(o,{varName:a,pkgId:i.id,fnName:c,bindings:d,needsSession:l,paramNames:g,schemaProps:p})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
|
|
4
|
+
`)}]}}function RS(t){return{props:t.properties??{},required:t.required??[]}}function TS(t){const e=t??{},n=Array.isArray(e.oneOf)&&e.oneOf.length>0?e.oneOf:[e],r={},o=new Map;for(const i of n){const{props:a,required:c}=RS(i);for(const[u,l]of Object.entries(a))u in r||(r[u]=l);for(const u of c)o.set(u,(o.get(u)??0)+1)}const s=[...o.entries()].filter(([,i])=>i===n.length).map(([i])=>i);return{input:{type:"object",properties:{data:{type:"object",properties:r,required:s}},required:["data"]},output:{}}}function CS(t){const e=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(t);)e.push(r[1]??r[2]??r[3]);return e}function MS(t){const e=t.argv;return Array.isArray(e)?e.map(String):typeof e=="string"?CS(e):process.argv.slice(2)}function LS(t,e){return{id:t,host:"ts",namespace:{raw:t,words:[t]},path:[],kind:"action",async:!1,streaming:!1,safe:e["x-apigen-safe"]??!1,input:e.input??{},output:e.output??{},envelope:{},typeText:null}}function DS(t){const e=new Map;for(const r of t.operations??[]){const o=r.path[r.path.length-1];o&&e.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of t.packages)for(const[o,s]of Object.entries(r.schemas)){const i=e.get(`${r.id}:${o}`)??LS(o,s),a=Wg({op:i,schema:s,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:r.id,fnName:o,schema:s,cliPath:c,plan:a})}return n}function US(t,e){let n=0;for(;n<t.length&&!t[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=e.get(t.slice(0,r).join(" "));if(o)return{entry:o,rest:t.slice(r)}}return null}function Xg(t){return!t||t.length===0?"":t.map(e=>`${e.name}${e.required?"":"?"}: ${e.type}`).join(", ")}function Tp(t){const e=["Available commands:",""],n=[...t.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const s=Xg(o.params);e.push(` ${r}${s?` { ${s} }`:""}`)}return e.join(`
|
|
5
|
+
`)}function Ts(t){return new Li("invalid_argument",t)}function BS(t,e){var n;const r={},o={};let s=0;for(;s<t.length;){const i=t[s];if(!i.startsWith("--"))throw Ts(`Unexpected positional argument: "${i}"`);let a=i.slice(2),c;const u=a.indexOf("=");u!==-1&&(c=a.slice(u+1),a=a.slice(0,u));let l=!1,d=a;a.startsWith("no-")&&((n=e.get(a.slice(3)))==null?void 0:n.valueKind)==="boolean"&&(l=!0,d=a.slice(3));const f=e.get(d);if(!f)throw Ts(`Unknown option: --${a}. Available: ${[...e.entries()].filter(([,p])=>p.aliasOf===void 0).map(([p])=>p).sort().map(p=>`--${p}`).join(", ")}`);s++;let g;if(f.valueKind==="boolean")l?g=!1:c===void 0?g=!0:g=c!=="false";else{const p=c!==void 0?c:t[s++];if(p===void 0)throw Ts(`Missing value for --${a}`);if(f.valueKind==="json")try{g=JSON.parse(p)}catch(y){throw Ts(`Invalid JSON for --${a}: ${y.message}`)}else g=p}f.kind==="domain"?r[f.camelKey]=g:o[f.camelKey]=g}for(const i of e.values()){if(i.kind!=="envelope"||!i.envVar||o[i.camelKey]!==void 0)continue;const a=process.env[i.envVar];a!==void 0&&(o[i.camelKey]=a)}return{domainArgs:r,envelope:o}}function ey(t){const e=Bc(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:String(t)};console.error(JSON.stringify(e)),process.exitCode=Bc(t)?xp[t.code]:xp.internal}function FS(t,e,n){if(Bc(n)&&n.code!=="internal"){t.error({command:e,code:n.code,message:n.message},`✗ ${e}`);return}t.error({command:e,err:n},`✗ ${e}`)}let qS=class{constructor(e,n){this.signal=e,this.exitCodeHook=n,this.routes=new Map}registerRoute(e,n){this.routes.set(e.cli.path.join(" "),{plan:e,dispatch:n})}routeTable(){return this.routes}readCall(e,n){const{domainArgs:r,envelope:o}=BS(e.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(e,n,r){var o;if(UE(n))throw new Li("invalid_argument",`Command "${r.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n));const s=(o=this.exitCodeHook)==null?void 0:o.call(this,n);typeof s=="number"&&s!==0&&(process.exitCode=s)}writeError(e,n,r){ey(n)}};function KS(t,e,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of t){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,e[c.id],o);for(const d of l)d.transports&&!d.transports.includes("cli")||i.push(d)}return i}async function VS(t){var e,n,r;const o=t.logger??AE();if((e=t.signal)!=null&&e.aborted){o.info("cli run: signal already aborted before dispatch — skipping");return}let s=MS(t.options);s[0]==="--"&&(s=s.slice(1));const i=hS(t.options),a=gS(t.options),c=new qS(t.signal,mS(t.options)),u=DS(t),l=new Map;for(const C of u.values()){const G=l.get(C.pkgId);G?G.push(C):l.set(C.pkgId,[C])}const d={},f={};for(const C of t.packages){const G=l.get(C.id);if(!G||G.length===0)continue;if(!C.fns)throw new Error(`apigen-plugin-cli-output: package "${C.id}" has no functions`);const H=C.fns,Z={},ue={};for(const pe of G)Z[pe.plan.op.id]=pe.schema,ue[pe.plan.op.id]=H[pe.fnName],d[pe.plan.op.id]=pe.schema,f[pe.plan.op.id]=H[pe.fnName];const fe=Ya(Z,i),he={fns:ue,createClient:C.createClient,schemas:Z};for(const pe of G)c.registerRoute(pe.plan,Oe=>Pp(pe.plan,fe,Oe,he))}const g=((n=t.packages[0])==null?void 0:n.id)??"ts",p=Ya(d,i),y={invoke:(C,G,H)=>p(C,{operation:{id:C},ctx:new Gg,domainArgs:G.domainArgs,envelope:G.envelope,signal:G.signal},H),invokeOptions:{fns:f,schemas:d,createClient:(r=t.packages[0])==null?void 0:r.createClient}},w=KS(i,a,g,t.operations??[],y);if(w.length>0){const C=Ya({},i),G={fns:{},schemas:{}};for(const H of w){const Z=Wg({op:H,schema:TS(H.input),transport:"cli"});c.registerRoute(Z,ue=>Pp(Z,C,ue,G))}}const h=c.routeTable();if(s.length===0||s[0]==="--help"||s[0]==="-h"){console.log(Tp(h));return}const v=US(s,h);if(!v){ey(new Li("not_found",`Unknown command: ${s.join(" ")}
|
|
6
|
+
|
|
7
|
+
${Tp(h)}`));return}const{entry:b,rest:E}=v,{plan:N,dispatch:j}=b,T=N.cli.path.join(" ");if(E.includes("--help")||E.includes("-h")){const C=Xg(N.params);console.log(`${T}${C?` { ${C} }`:""}`);return}const M={rest:E};try{if(N.streaming)throw new Li("invalid_argument",`Command "${T}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const C=await c.readCall(M,N),G=Date.now(),H=await j(C);await c.writeResult(M,H,N),o.info({command:T,ms:Date.now()-G},`→ ${T}`)}catch(C){FS(o,T,C),await c.writeError(M,C,N)}}const GS={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"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(t){return xS(t)},run(t){return VS(t)}};let qt=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function Cp(t){return{raw:t,words:t.split(/(?=[A-Z])|[-_]/).map(e=>e.toLowerCase()).filter(Boolean)}}function zS(t,e,n={}){const r=t.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${t}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:t,host:e.host,namespace:Cp(i),path:s.map(Cp),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);function WS(t){if(t.length<2)return;const e=[];for(const r of t){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;e.push(o)}const n=Object.keys(e[0]).filter(r=>e.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of e){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}const HS={"decimal.js":"Decimal"};function JS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(HS).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${JS(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function QS(t){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:t}},{type:"object",required:["index","status","chunks"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},chunks:{type:"array"}}},{type:"object",required:["index","status","reason"],properties:{index:{type:"integer"},status:{type:"string",enum:["rejected"]},reason:{},chunksDelivered:{type:"integer"}}}]}}function YS(t){return{operationConst:t.id,itemsSchema:t.input,resultSchema:QS(t.output)}}function ZS(t,e={}){const n=new Set(e.exclude??[]),r=new Map;for(const o of t){if(n.has(o.id))continue;const s=r.get(o.kind);s?s.push(o):r.set(o.kind,[o])}return r}function Mp(t){return{type:"string",enum:[t]}}function Lp(t,e){return{type:"object",required:["input"],properties:{input:{type:"object",required:["operation","items"],properties:{operation:e,items:{type:"array",items:t.itemsSchema},concurrency:{type:"number"},mode:{type:"string",enum:["parallel","serial","chained"]},onItemError:{type:"string",enum:["continue","abort"]},itemTimeoutMs:{type:"number"}},additionalProperties:!0}},additionalProperties:!1}}function Dp(t,e){const n={},r={},o=[["definitions",n],["$defs",r]];for(const s of t){const i=e(s);for(const[a,c]of o){const u=i[a];if(u)for(const[l,d]of Object.entries(u)){const f=c[l];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(d))throw new Error(`[apigen-core-client] _batch mount: operation "${s.id}" contributes a "${a}.${l}" definition that conflicts with an identically-named definition already hoisted from another batched operation. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one _batch/<kind> schema.`);c[l]=d}}}return{...Object.keys(n).length>0?{definitions:n}:{},...Object.keys(r).length>0?{$defs:r}:{}}}function XS(t){if(t.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const e=t.map(YS),n=Dp(t,i=>i.input),r=Dp(t,i=>i.output);if(t.length===1){const[i]=t,[a]=e;return{input:{...Lp(a,Mp(i.id)),...n},output:{type:"array",items:a.resultSchema,...r}}}const o=t.map((i,a)=>Lp(e[a],Mp(i.id))),s=WS(o);return{input:{oneOf:o,...s?{discriminator:s}:{},...n},output:{oneOf:e.map(i=>({type:"array",items:i.resultSchema})),...r},...s?{discriminator:s}:{}}}function e_(t,e={}){const n=ZS(t.operations,e),r=[];for(const[o,s]of n){const{input:i,output:a}=XS(s),c=zS(`_batch/${o}`,t,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const qc="$apigen";let Up=class extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function t_(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new Up(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new Up("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const gl="x-apigen-logical",yl="x-apigen-codec",Kc="x-apigen-ctor",Vc="x-apigen-tojson",n_="0.1.0";function Bp(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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",...e}}function Tr(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Tr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=ty(t,s,e,n);return Tr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return Lo(t,e,n);const a=e.items;if(!a)return t.map(u=>ir(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?ir(u):Tr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Tr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return Lo(t,e,n);const a=e.properties;if(!a)return ir(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Tr(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?Lo(t,e,n):ir(t)}function Cr(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Cr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=ty(t,s,e,n);return Cr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Cr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Cr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Cr(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Gc(t,n):t}function ty(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=Di(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=r_(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=Di(u,r),d=ny(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function Di(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function Fp(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function r_(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>Di(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))Fp(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?Fp(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function o_(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function ny(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=ny(t,Di(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=o_(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function Lo(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[qc]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>Lo(o,{},n));if(ry(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=Lo(i,{},n));return o}return ir(t)}function ry(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Gc(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&qc in t){const n=t,r=n[qc],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Gc(n,e));if(ry(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Gc(o,e);return n}return t}function ir(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(ir);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=ir(r));return e}return null}function s_(t){return{encode(e,n,r){const o=Bp(t,r);return Tr(e,n,o)},decode(e,n,r){const o=Bp(t,r);return Cr(e,n,o)}}}const wl={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},vl={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},$l={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},bl={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},i_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,El={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!i_.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},zc="NaN",Wc="Infinity",Hc="-Infinity",a_=new Set([zc,Wc,Hc]),Sl={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?zc:t===1/0?Wc:t===-1/0?Hc:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===zc)return NaN;if(t===Wc)return 1/0;if(t===Hc)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...a_].join(", ")}.`);return NaN}},c_=[wl,vl,$l,bl,El,Sl];function u_(t,e={}){for(const n of c_)t.register(n,{override:e.override??!1})}wl.id,vl.id,$l.id,bl.id,El.id,Sl.id;const oy=t_();u_(oy);s_(oy.freeze());let l_=class{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const d_={"decimal.js":"Decimal"};function f_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(d_).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${f_(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));const p_=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let sy=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function iy(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&p_.includes(t.code)&&typeof t.toJSON=="function"}function qp(t,e,n=0){return t==="before-first-chunk"?{phase:t,error:e}:{phase:t,error:e,chunksDelivered:n}}const _l=new ia({allErrors:!0});aa(_l);for(const t of[gl,yl,Kc,Vc,"discriminator"])_l.addKeyword({keyword:t,valid:!0});_l.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function h_(t){const e=[];try{for await(const n of t)e.push(n);return{ok:!0,chunks:e}}catch(n){const r=iy(n)?n:new sy("internal",n instanceof Error?n.message:String(n));return e.length===0?{ok:!1,carrier:qp("before-first-chunk",r)}:{ok:!1,carrier:qp("after-first-chunk",r,e.length)}}}function m_(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}let Kn=class extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}};function Xa(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function ay(t,e){const n=t[yl];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function g_(t,e,n){const r=ay(e,n);return r?r.encode(t,e,n):t}function y_(t,e,n){const r=ay(e,n);return r?r.decode(t,e,n):t}function w_(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[gl]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Xa(r)!==void 0},encode(r,o,s){const i=Xa(o);if(!i)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new Kn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return g_(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new Kn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=Xa(o);if(!a)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new Kn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return y_(r,g,{...s,path:`${s.path}[${d}]`})}}}const v_="x-apigen-instances";let Cs=class extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}};function Kp(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function $_(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Vp(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function b_(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function E_(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[gl]==="nominal"?!0:o[yl]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Cs("E_NOMINAL_CYCLE",`[${e}] 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=Kp(s),c=typeof s[Vc]=="string"?s[Vc]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=Vp(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=Vp(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Cs("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of $_(s))if(!(l in a))throw new Cs("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[v_]===!1)throw new Cs("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Kp(s),u={};for(const[l,d]of Object.entries(a))u[l]=b_(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Kc]=="string"?s[Kc]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const S_=[wl,vl,$l,bl,El,Sl],__={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Gp=E_({id:"ts.NominalSentinel",schema:__}),N_={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},zp=w_({id:"ts.UnionSentinel",schema:N_});function O_(){const t=[...S_.map(e=>[e.id,e]),[Gp.id,Gp],[zp.id,zp]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:n_,codecs:O_()});const k_=4,j_=32;function Jc(t){return iy(t)?t:t instanceof Error?new sy("internal",t.message):t}function A_(t,e){if(t==="serial"||t==="chained")return 1;const n=e??k_;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),j_)}function I_(){}function P_(t,e){var n;if(!t&&!e)return{signal:void 0,dispose:I_};const r=new AbortController,o=()=>{r.abort(t==null?void 0:t.reason)};t&&(t.aborted?r.abort(t.reason):t.addEventListener("abort",o,{once:!0}));let s;return e!==void 0&&!r.signal.aborted&&(s=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${e}ms`,"TimeoutError"))},e),(n=s.unref)==null||n.call(s)),{signal:r.signal,dispose(){t&&t.removeEventListener("abort",o),s&&clearTimeout(s)}}}async function Wp(t,e,n,r,o,s){const i=P_(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await t(e,a,o);if(m_(c)){const u=await h_(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:Jc(l.error),...l.phase==="after-first-chunk"?{chunksDelivered:l.chunksDelivered}:{}}}return{index:n,status:"fulfilled",value:c}}catch(a){return{index:n,status:"rejected",reason:Jc(a)}}finally{i.dispose()}}async function x_(t,e,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=A_(s,o.concurrency),c=new Array(n.length),u=p=>({index:p,status:"rejected",reason:Jc(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(s==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(s==="serial"||s==="chained"){let p=!1;for(let y=0;y<n.length;y++){if(p){c[y]=u(y);continue}const w=await Wp(t,e,y,n[y],r,o.itemTimeoutMs);c[y]=w,w.status==="rejected"&&(s==="chained"||i==="abort")&&(p=!0)}return c}let l=0,d=!1;const f=Math.max(1,Math.min(a,n.length)),g=Array.from({length:f},async()=>{for(;;){const p=l++;if(p>=n.length)return;if(d){c[p]=u(p);continue}const y=await Wp(t,e,p,n[p],r,o.itemTimeoutMs);c[p]=y,y.status==="rejected"&&i==="abort"&&(d=!0)}});return await Promise.all(g),c}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const R_={"decimal.js":"Decimal"};function T_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(R_).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${T_(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function C_(t,e){const n=t.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const r=n,o=r.operation;if(typeof o!="string"||o.length===0)throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!e.includes(o))throw new qt("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${o}") is not one of this mount's batchable operations: ${e.join(", ")}`);const s=r.items;if(!Array.isArray(s))throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const i=r.concurrency;if(i!==void 0&&typeof i!="number")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=r.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=r.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const u=r.itemTimeoutMs;if(u!==void 0&&typeof u!="number")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:o,items:s,concurrency:i,mode:a,onItemError:c,itemTimeoutMs:u}}function M_(t,e){return async n=>{if(!e)throw new qt("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const r=C_(n.data,t),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},s=r.items.map(i=>({operation:{id:r.operation},ctx:new l_,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return x_(e.invoke,r.operation,s,e.invokeOptions,o)}}function L_(t,e={},n){return e_(t,e).map(r=>({...r,handler:M_(r.operationIds,n)}))}const Ui={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(t,e,n){return L_(t,e,n)}}}};Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Hp=new Set(["string","number","boolean","integer"]);function D_(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Hp.has(n):Array.isArray(n)?n.every(r=>Hp.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function U_(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(D_)}const B_={"decimal.js":"Decimal"};function F_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(B_).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${F_(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Jp(t){return t.words.join("-")}function Qp(t){return t.words.map(q_).join("")}function Yp(t){return t.words.join("_")}function la(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||U_(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>Jp(g)).join("/"),c=o.map(g=>Yp(g)).join("_"),u=o.map(g=>Yp(g)).slice(0,-1).join("."),l=Qp(o[o.length-2]??o[0]),d=Qp(o[o.length-1]),f=o.map(g=>Jp(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function q_(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}const Zp={validateKind(){},validateRel(){},validateEdge(){}},K_=5,V_=20,G_=500;function z_(t){return pn.isBusyError(t)||pn.isConcurrentConflict(t)}function W_(t){return new Promise(e=>setTimeout(e,Math.max(0,Math.round(t))))}async function H_(t,e={}){const n=e.maxAttempts??K_;for(let r=0;;r++)try{return await t()}catch(o){if(!z_(o)||r>=n-1)throw o;const s=Math.min(G_,V_*2**r);await W_(s*(.5+Math.random()*.5))}}const Nl=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit"]);class cy extends Error{constructor(e,n){const r=e.length>0?e.map(o=>`${o.kind}=${o.count}`).join(", "):"(none)";super(`backlog: store vocabulary mismatch — refusing to read or write a store this build cannot address.
|
|
8
|
+
expected node kind(s): ${n.join(", ")}
|
|
9
|
+
found in store: ${r}
|
|
10
|
+
The store holds live node(s) but none of a kind this build recognizes, so every item read would match zero rows and report a misleading "0 items".
|
|
11
|
+
Likely cause: this store was written by a build with a different item vocabulary and was never converted to the one this build uses. Refusing rather than returning an empty result.`),this.observed=e,this.recognized=n,this.name="StoreVocabularyMismatchError"}}async function uy(t){const{rows:e}=await t.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=e.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,s)=>o+s.count,0),observed:n}}async function J_(t){const e=[...Nl],n=e.map(()=>"?").join(", "),{rows:r}=await t.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,e);return r.length>0}async function Ol(t){if(await J_(t))return;const{total:e,observed:n}=await uy(t);if(e!==0)throw new cy(n,[...Nl])}const Q_=3e4,Xp=new WeakMap;function Y_(t){let e=Xp.get(t);return e||(e=new Set,Xp.set(t,e)),e}function ly(t){const e=Y_(t);return{register(n){e.add(n);let r=!1;return()=>{r||(r=!0,e.delete(n))}},get size(){return e.size},snapshot(){return[...e]},async drain(n){const r=(n==null?void 0:n.timeoutMs)??Q_,o=Date.now()+r;let s=0;for(;;){const a=[...e].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=o-Date.now();if(c<=0)break;const u=await Z_(Promise.allSettled(a.map(l=>l.settled)),c);if(s+=a.filter(l=>l.outcome!=="pending").length,u==="timeout")break}const i=[...e];return{drained:s,stillPending:i.filter(a=>a.outcome==="pending"),recordedAsFailed:0,unrecorded:i.filter(a=>a.outcome==="unrecorded")}}}}async function Z_(t,e){let n;const r=new Promise(o=>{n=setTimeout(()=>o("timeout"),e),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([t,r])}finally{n!==void 0&&clearTimeout(n)}}class Ke extends Error{constructor(e,n=void 0,r){super(e),this.name=new.target.name,this.cause=n,this.retry_after_ms=r}}class dy extends Ke{constructor(e,n){super(`Write contention: exhausted the retry budget (last backoff ${e}ms)`,n,e),this.code="E_CONTENTION",this.retryable=!0}}class kl extends Ke{constructor(e){super("Write I/O failure: an unclassified driver/connection error surfaced from the underlying transaction",e),this.code="E_IO",this.retryable=!0}}class da extends Ke{constructor(e,n){super(n===void 0?`Issue "${e}" was already superseded by a concurrent write; re-get and retry`:`Issue "${e}" was superseded by a body edit and is no longer the live issue; it now lives under "${n}"`),this.uid=e,this.successorUid=n,this.code="E_CONSTRAINT",this.retryable=!1}}class Xe extends Ke{constructor(e,n){super(`${e} "${n}" was not found`),this.catalogKind=e,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class oe extends Ke{constructor(e,n){super(n?`Invalid argument "${e}": ${n}`:`Invalid argument "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}class fa extends Ke{constructor(e){super(`No live issue found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class Bi extends Ke{constructor(e,n){super(`Claim already held by "${e}" since ${n}`),this.heldBy=e,this.heldSince=n,this.code="E_VALIDATION",this.retryable=!1}}class fy extends Ke{constructor(e,n){super(`Issue "${e}" is in terminal status "${n}" and cannot be claimed; re-open it via "transition" first`),this.uid=e,this.status=n,this.code="E_VALIDATION",this.retryable=!1}}class Qc extends Ke{constructor(e){const n=e.side==="source"?`"${e.rel}" already has a single target (${e.conflictingUid}) for source "${e.cappedUid}"`:`"${e.rel}" already has a single source (${e.conflictingUid}) for target "${e.cappedUid}"`;super(n),this.code="E_VALIDATION",this.retryable=!1,this.side=e.side,this.cappedUid=e.cappedUid,this.rel=e.rel,this.conflictingUid=e.conflictingUid}}class jl extends Ke{constructor(e){super(`Citation target "${e}" could not be verified and this project requires a real sha`),this.target=e,this.code="E_VALIDATION",this.retryable=!1}}class py extends Ke{constructor(e){super(`A note is required to transition issue "${e}" (project_policy.transition_requires_note)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class hy extends Ke{constructor(e){super(`At least one citation is required to close issue "${e}" (project_policy.citation_required)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class Er extends Ke{constructor(e,n){super(n?`Invalid "${e}": ${n}`:`Invalid "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}function X_(t){const e=t instanceof Error?t.message:String(t);return pn.isBusyError(t)||pn.isConcurrentConflict(t)?{code:"E_CONTENTION",retryable:!0,message:e,cause:t}:pn.isUniqueConstraintError(t)||pn.isForeignKeyError(t)?{code:"E_CONSTRAINT",retryable:!1,message:e,cause:t}:pn.isDatabaseError(t)?{code:"E_IO",retryable:!0,message:e,cause:t}:{code:"E_IO",retryable:!1,message:e,cause:t}}const eN=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function jt(t,e){if(eN.has(e.trim().toLowerCase()))throw new oe(t,`"${e}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}function my(t){if(t!=null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function gy(t){return{rowid:t.rowid,uid:t.uid,kind:t.kind,name:t.name,content:t.content??"",metadata:my(t.meta),tInvalid:t.t_invalid,isSuperseded:t.is_superseded===1}}function He(){return new Date().toISOString()}function Al(t){return kn.createHash("sha256").update(t).digest("hex")}function yy(t){return JSON.stringify(Yc(t))}function Yc(t){if(Array.isArray(t))return t.map(Yc);if(t!==null&&typeof t=="object"){const e=t,n={};for(const r of Object.keys(e).sort())e[r]!==void 0&&(n[r]=Yc(e[r]));return n}return t}async function pa(t,e){const n=await t.executeGet("SELECT * FROM node WHERE uid = ?",[e]);return n?gy(n):null}async function _n(t,e){const n=await pa(t,e);if(!n||n.kind!=="issue"||n.tInvalid!==null)throw new fa(e);if(n.isSuperseded)throw new da(e);return n}async function sn(t,e){const n=await t.executeGet("SELECT * FROM node WHERE rowid = ?",[e]);return n?gy(n):null}const tN=["off","on"];function nN(){const t=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(t===void 0)return"off";if(tN.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_DEDUPE_MODE="${t}" is not a recognized dedupe mode (expected "off" or "on"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "off" so a mistyped negative control can never pass for the wrong reason.`)}async function ct(t,e){const n=e.at??He(),r=e.content??e.name??"",o=Al(r.trim().toLowerCase());if(nN()==="on"){const c=await t.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const s=kn.randomUUID(),i=e.metadata!==void 0?JSON.stringify(e.metadata):null,a=await t.executeGet(`INSERT INTO node (uid, kind, content, name, summary, topic, tags, importance,
|
|
12
|
+
confidence, content_hash, namespace, meta, agent_id, session_id, source,
|
|
13
|
+
project_path, t_occurred, t_expires, t_created, t_valid)
|
|
14
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
15
|
+
RETURNING rowid`,[s,e.kind,r,e.name??null,null,null,null,1,null,o,"global",i,null,null,null,null,n,null,n,n]);if(!a)throw new Error(`writeNodeTx: INSERT returned no rowid for kind="${e.kind}" name="${e.name??""}"`);return{rowid:a.rowid,uid:s}}async function rN(t,e){const{multiplicity:n}=e.rule;if(n==="n:m")return;if(n==="n:1"){const o=await t.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.dst
|
|
16
|
+
WHERE e.src = ? AND e.rel = ? AND e.dst != ? AND e.t_invalid IS NULL LIMIT 1`,[e.srcRowid,e.rel,e.dstRowid]);if(o)throw new Qc({side:"source",cappedUid:e.srcUid,rel:e.rel,conflictingUid:o.uid});return}const r=await t.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.src
|
|
17
|
+
WHERE e.dst = ? AND e.rel = ? AND e.src != ? AND e.t_invalid IS NULL LIMIT 1`,[e.dstRowid,e.rel,e.srcRowid]);if(r)throw new Qc({side:"target",cappedUid:e.dstUid,rel:e.rel,conflictingUid:r.uid})}async function Re(t,e){const{rule:n}=e;if(n.sourceKind!=="*"&&n.sourceKind!==e.srcKind)throw new eh(e.rel,"source",n.sourceKind,e.srcKind);if(n.targetKind!==e.dstKind)throw new eh(e.rel,"target",n.targetKind,e.dstKind);await rN(t,e),e.typePolicy.validateEdge?e.typePolicy.validateEdge(e.srcKind,e.rel,e.dstKind):e.typePolicy.validateRel(e.rel);const r=e.at??He(),o=e.metadata!==void 0?JSON.stringify(e.metadata):null;await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
|
|
18
|
+
VALUES (?, ?, ?, ?, 'user_asserted', ?, ?, ?)
|
|
19
|
+
ON CONFLICT(src, dst, rel) DO UPDATE SET
|
|
20
|
+
meta = excluded.meta, weight = excluded.weight,
|
|
21
|
+
t_invalid = NULL, t_valid = excluded.t_valid`,[e.srcRowid,e.dstRowid,e.rel,e.weight??1,o,r,r])}class eh extends Ke{constructor(e,n,r,o){super(`"${e}" requires a ${n} of kind "${r}", got "${o}"`),this.code="E_VALIDATION",this.retryable=!1}}async function Sr(t,e){const n=await t.executeGet("SELECT rowid, meta FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e.srcRowid,e.dstRowid,e.rel]);if(!n)return;const r=e.at??He(),o={...my(n.meta)??{},invalidatedAt:r,...e.reason!==void 0?{invalidatedReason:e.reason}:{}};await t.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[r,JSON.stringify(o),n.rowid])}const Ms=[250,500];function oN(t){return new Promise(e=>setTimeout(e,t))}const sN=["immediate","deferred"];function iN(){const t=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(t===void 0)return"immediate";if(sN.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_TX_MODE="${t}" is not a recognized transaction mode (expected "immediate" or "deferred"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "immediate" so a mistyped negative control can never pass for the wrong reason.`)}async function lt(t,e){let n=0;for(;;)try{return await t.adapter.transaction(e,{mode:iN()})}catch(r){if(r instanceof Ke)throw r;const o=X_(r);if(o.code==="E_CONTENTION"){if(n<Ms.length){const s=Ms[n];n+=1,await oN(s);continue}throw new dy(Ms[Ms.length-1],r)}throw o.code==="E_IO"&&o.retryable?new kl(r):r}}function Il(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}const aN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _r(t){return aN.test(t)}async function bs(t,e,n){const r=await pa(t,n);if(!r||r.tInvalid!==null||r.kind!==e)throw new Xe(e,n);const{name:o}=r;if(o===null)throw new Xe(e,n);return{...r,name:o}}async function rs(t,e){if(_r(e)){const o=await bs(t,"project",e);return{rowid:o.rowid,uid:o.uid,name:o.name,metadata:o.metadata}}const n=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[e]);if(!n)throw new Xe("project",e);let r;if(n.meta!==null)try{r=JSON.parse(n.meta)}catch{r=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??e,metadata:r}}async function Pl(t,e){var r;if(_r(e.ref)){const o=await bs(t,"component",e.ref);if(((r=o.metadata)==null?void 0:r.projectUid)!==e.projectUid)throw new Xe("component",e.ref);return{rowid:o.rowid,uid:o.uid,name:o.name}}const n=await t.executeGet(`SELECT rowid, uid, name FROM node
|
|
22
|
+
WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
|
|
23
|
+
AND json_extract(meta, '$.projectUid') = ?
|
|
24
|
+
LIMIT 1`,[e.ref,e.projectUid]);if(!n)throw new Xe("component",e.ref);return{rowid:n.rowid,uid:n.uid,name:n.name??e.ref}}async function wy(t,e){const n=await t.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
|
|
25
|
+
FROM edge e JOIN node c ON c.rowid = e.dst
|
|
26
|
+
WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
|
|
27
|
+
AND c.name = '(root)' AND c.t_invalid IS NULL
|
|
28
|
+
LIMIT 1`,[e.projectRowid]);if(!n)throw new Xe("component","(root)");return{rowid:n.rowid,uid:n.uid,name:n.name??"(root)"}}async function mn(t,e){if(_r(e.ref)){const s=await bs(t,e.catalogKind,e.ref);return{rowid:s.rowid,uid:s.uid,name:s.name}}const n=await t.executeGet("SELECT rowid, uid, name FROM node WHERE kind = ? AND name = ? AND t_invalid IS NULL LIMIT 1",[e.catalogKind,e.ref]);if(n)return{rowid:n.rowid,uid:n.uid,name:n.name??e.ref};const r=e.mintMetadata?await e.mintMetadata(t):{},o=await ct(t,{kind:e.catalogKind,name:e.ref,metadata:r,at:e.at});return{rowid:o.rowid,uid:o.uid,name:e.ref}}async function vy(t){const e=await t.executeGet("SELECT MAX(CAST(json_extract(meta, '$.rank') AS INTEGER)) AS maxRank FROM node WHERE kind = 'priority' AND t_invalid IS NULL"),n=(e==null?void 0:e.maxRank)??null;return n===null?0:n+1}const cN=[{rel:"owns_project",sourceKind:"project",targetKind:"component",multiplicity:"1:n"},{rel:"owns_component",sourceKind:"component",targetKind:"issue",multiplicity:"1:n"},{rel:"has_kind",sourceKind:"issue",targetKind:"kind",multiplicity:"n:1"},{rel:"has_status",sourceKind:"issue",targetKind:"status",multiplicity:"n:1"},{rel:"has_priority",sourceKind:"issue",targetKind:"priority",multiplicity:"n:1"},{rel:"authored_by",sourceKind:"issue",targetKind:"agent",multiplicity:"n:1"},{rel:"has_note",sourceKind:"issue",targetKind:"note",multiplicity:"1:n"},{rel:"has_citation",sourceKind:"issue",targetKind:"citation",multiplicity:"1:n"},{rel:"has_transition",sourceKind:"issue",targetKind:"transition",multiplicity:"1:n"},{rel:"audits",sourceKind:"*",targetKind:"audit",multiplicity:"1:n"},{rel:"depends_on",sourceKind:"component",targetKind:"component",multiplicity:"n:m"},{rel:"has_location",sourceKind:"component",targetKind:"location",multiplicity:"1:n"},{rel:"relates_to",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"supersedes",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"blocks",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"duplicate_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"part_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"}],th=new Map(cN.map(t=>[t.rel,t]));async function Te(t,e){const n=await t.executeGet("SELECT rowid, meta FROM node WHERE kind = 'edge_kind' AND name = ? AND t_invalid IS NULL ORDER BY rowid ASC LIMIT 1",[e]);if(n){const o=Il(n.meta)??{},s=typeof o.source_kind=="string"?o.source_kind:void 0,i=typeof o.target_kind=="string"?o.target_kind:void 0,a=o.multiplicity;if(s&&i&&a)return{rel:e,sourceKind:s,targetKind:i,multiplicity:a};const c=th.get(e);if(!c)throw new Xe("edge_kind",e);return await t.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[He(),n.rowid]),await ct(t,{kind:"edge_kind",name:e,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const r=th.get(e);if(!r)throw new Xe("edge_kind",e);return await ct(t,{kind:"edge_kind",name:e,metadata:{source_kind:r.sourceKind,target_kind:r.targetKind,multiplicity:r.multiplicity}}),r}const It=Object.freeze({transitionRequiresNote:!0,citationRequired:!1,citationRequiresSha:!0,dedupeScanEnabled:!0,dedupeThreshold:.8,claimStaleAfterMin:30,allowedStatuses:[],allowedKinds:[],requiredFields:[]});function Lt(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}function Zr(t){var r;const e=(r=t.metadata)==null?void 0:r.policy;if(e===null||typeof e!="object")return{...It};const n=e;return{transitionRequiresNote:n.transitionRequiresNote??It.transitionRequiresNote,citationRequired:n.citationRequired??It.citationRequired,citationRequiresSha:n.citationRequiresSha??It.citationRequiresSha,defaultStatus:n.defaultStatus,defaultKind:n.defaultKind,dedupeScanEnabled:n.dedupeScanEnabled??It.dedupeScanEnabled,dedupeThreshold:n.dedupeThreshold??It.dedupeThreshold,claimStaleAfterMin:n.claimStaleAfterMin??It.claimStaleAfterMin,allowedStatuses:n.allowedStatuses??It.allowedStatuses,allowedKinds:n.allowedKinds??It.allowedKinds,requiredFields:n.requiredFields??It.requiredFields}}function ha(t){var n;const e=(n=t.metadata)==null?void 0:n.path;return typeof e=="string"&&e.length>0}function Fi(t,e){const n={...t};for(const[r,o]of Object.entries(e))o!==void 0&&(n[r]=o);return n}async function uN(t,e){return Lt("name",e.name),Lt("by",e.by),jt("by",e.by),lt(t,n=>lN(n,t,e))}async function lN(t,e,n){const r=He(),o=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[n.name]),s={path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description};if(o){const l=Fi(Il(o.meta)??{},s);return await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),o.rowid]),await Pe({tx:t,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:n.by,action:"updated",at:r}),{uid:o.uid,created:!1,project:{uid:o.uid,name:o.name??n.name,path:l.path,repoUrl:l.repoUrl,monorepo:l.monorepo,description:l.description}}}const i=Fi({},s),a=await ct(t,{kind:"project",name:n.name,metadata:i,at:r}),c=await ct(t,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:r}),u=await Te(t,"owns_project");return await Re(t,{at:r,srcRowid:a.rowid,srcUid:a.uid,srcKind:"project",dstRowid:c.rowid,dstUid:c.uid,dstKind:"component",rel:"owns_project",rule:u,typePolicy:e.typePolicy}),await Pe({tx:t,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:r}),{uid:a.uid,created:!0,project:{uid:a.uid,name:n.name,path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description}}}async function dN(t,e){return Lt("project",e.project),Lt("name",e.name),Lt("by",e.by),jt("by",e.by),lt(t,n=>fN(n,t,e))}async function fN(t,e,n){const r=He(),o=await rs(t,n.project),s=await t.executeGet(`SELECT rowid, uid, name, meta FROM node
|
|
29
|
+
WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
|
|
30
|
+
AND json_extract(meta, '$.projectUid') = ?
|
|
31
|
+
LIMIT 1`,[n.name,o.uid]),i={path:n.path,description:n.description};let a,c,u,l,d;if(s)d=Fi({...Il(s.meta)??{},projectUid:o.uid},i),await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(d),s.rowid]),a=s.rowid,c=s.uid,u=s.name??n.name,l=!1;else{d=Fi({projectUid:o.uid},i);const g=await ct(t,{kind:"component",name:n.name,metadata:d,at:r});a=g.rowid,c=g.uid,u=n.name,l=!0}const f=await Te(t,"owns_project");return await Re(t,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:e.typePolicy}),await Pe({tx:t,typePolicy:e.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:r}),{uid:c,created:l,component:{uid:c,name:u,projectUid:o.uid,path:d.path,description:d.description}}}const nh=["path","url","tool"];async function pN(t,e){if(Lt("component",e.component),Lt("value",e.value),Lt("by",e.by),jt("by",e.by),!nh.includes(e.locType))throw new oe("locType",`must be one of ${nh.join(", ")}`);return lt(t,async n=>{const r=He();let o;if(_r(e.component)){const u=await bs(n,"component",e.component);o={rowid:u.rowid,uid:u.uid,name:u.name}}else{if(e.project===void 0||e.project.trim().length===0)throw new oe("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const u=await rs(n,e.project);o=await Pl(n,{projectUid:u.uid,ref:e.component})}const s=await n.executeGet(`SELECT rowid, uid FROM node
|
|
32
|
+
WHERE kind = 'location' AND t_invalid IS NULL
|
|
33
|
+
AND json_extract(meta, '$.componentUid') = ?
|
|
34
|
+
AND json_extract(meta, '$.locType') = ?
|
|
35
|
+
AND json_extract(meta, '$.value') = ?
|
|
36
|
+
LIMIT 1`,[o.uid,e.locType,e.value]);if(s)return{uid:s.uid,created:!1,location:{uid:s.uid,locType:e.locType,value:e.value,componentUid:o.uid}};const i={componentUid:o.uid,locType:e.locType,value:e.value},a=await ct(n,{kind:"location",name:e.value,metadata:i,at:r}),c=await Te(n,"has_location");return await Re(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:t.typePolicy}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:e.by,action:"created",at:r}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:e.locType,value:e.value,componentUid:o.uid}}})}async function hN(t,e){return Lt("uid",e.uid),Lt("by",e.by),jt("by",e.by),lt(t,async n=>{var c;const r=He(),o=await bs(n,"location",e.uid),s={...o.metadata??{},...e.reason!==void 0?{invalidatedReason:e.reason}:{},invalidatedAt:r},i=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[r,JSON.stringify(s),o.rowid]);if(i.rowsAffected!==1)throw new Error(`rmLocation: invalidate UPDATE affected ${i.rowsAffected} rows for uid="${e.uid}", expected exactly 1.`);const a=typeof((c=o.metadata)==null?void 0:c.componentUid)=="string"?o.metadata.componentUid:void 0;if(a!==void 0){const u=await pa(n,a);u&&u.tInvalid===null&&await Sr(n,{srcRowid:u.rowid,dstRowid:o.rowid,rel:"has_location",reason:e.reason,at:r})}return await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"location",actor:e.by,action:"deleted",note:e.reason,at:r}),{uid:o.uid,invalidated:!0}})}async function Pe(t){const e=t.at??He(),n={actor:t.actor,action:t.action,target_uid:t.subjectUid,from:t.from??null,to:t.to??null,note:t.note??null,at:e},r=Al(yy(n)),o={...n,sha:r},s=await ct(t.tx,{at:e,kind:"audit",name:t.action,content:t.note??t.action,metadata:o}),i=await Te(t.tx,"audits");return await Re(t.tx,{at:e,srcRowid:t.subjectRowid,srcUid:t.subjectUid,srcKind:t.subjectKind,dstRowid:s.rowid,dstUid:s.uid,dstKind:"audit",rel:"audits",rule:i,typePolicy:t.typePolicy}),{rowid:s.rowid,uid:s.uid,sha:r}}const mN="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function xl(t,e){return`${t}
|
|
37
|
+
${e}`.trim()}function qi(t,e){const n=t.embedding;if(!n)return Promise.resolve();const r=gN(t,n,e),o={subjectRowid:e.subjectRowid,subjectUid:e.subjectUid,actor:e.actor,action:e.action,settled:r,outcome:"pending"},s=ly(t.adapter).register(o);return r.then(i=>{o.outcome=i,i!=="unrecorded"&&s()},()=>{o.outcome="unrecorded"}),r.then(()=>{})}async function gN(t,e,n){let r,o;try{if(n.action==="upsert"){const s=await e.embedDocument(n.content);await e.upsertVector(n.subjectRowid,s),r="embedding_upserted"}else await e.deleteVector(n.subjectRowid),r="embedding_deleted"}catch(s){r="embedding_failed",o=s instanceof Error?s.message:String(s),console.error(`scheduleIssueEmbedding: embed round-trip failed for issue uid="${n.subjectUid}" (action="${n.action}") — degrading to an "embedding_failed" audit row.`,s)}try{await lt(t,async s=>{await Pe({tx:s,typePolicy:t.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:r,note:o})})}catch(s){return console.error(`scheduleIssueEmbedding: failed to persist "${r}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,s),"unrecorded"}switch(r){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function yN(t,e){const n=[],r=[];for(const o of e)try{await lt(t,async s=>{await Pe({tx:s,typePolicy:t.typePolicy,subjectRowid:o.subjectRowid,subjectUid:o.subjectUid,subjectKind:"issue",actor:o.actor,action:"embedding_failed",note:mN})}),o.outcome="failed",n.push(o)}catch(s){o.outcome="unrecorded",r.push(o),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${o.subjectUid}" — this embed outcome is UNRECORDED.`,s)}return{recorded:n,unrecorded:r}}async function Ki(t,e=5e3){if(t!==":memory:"&&J.mkdirSync(L.dirname(t),{recursive:!0}),!Number.isInteger(e)||e<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${e}`);const n=await pn.createStoreAdapter({dbPath:t});await n.pragmaSet("busy_timeout",e);const r=tE.createGraphBackend(n,{typePolicy:Zp});await H_(()=>r.applySchema());try{await Ol(n)}catch(s){throw await n.close().catch(()=>{}),s}return{adapter:n,graph:r,typePolicy:Zp,flushEmbeds:s=>ly(n).drain(s)}}async function $y(t,e){const n=await t.flushEmbeds(e);let r=0,o=[...n.unrecorded];try{if(n.stillPending.length>0){const s=await yN(t,n.stillPending);r=s.recorded.length,o=[...o,...s.unrecorded]}}finally{await t.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:r,unrecorded:o}}async function Zc(t){if(!t)return;let e;try{e=await $y(t)}catch(n){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${n instanceof Error?n.message:String(n)}`);return}e.unrecorded.length>0?(console.error(`backlog: ${e.unrecorded.length} scheduled embed(s) died UNRECORDED — the store closed before they settled and the embedding_failed audit row could not be written. The subject write(s) are durable; the vector(s) are missing. Re-run the embedding backfill.`),process.exitCode||(process.exitCode=1)):e.stillPending.length>0&&console.error(`backlog: ${e.stillPending.length} scheduled embed(s) did not settle before close — recorded as embedding_failed. The subject write(s) are durable.`)}const Xc=["SIGINT","SIGTERM"];function by(t,e=n=>process.exit(n)){let n=!1;const r=s=>{n||(n=!0,t().catch(i=>{console.error(`backlog: signal cleanup failed (${s}): ${i instanceof Error?i.message:String(i)}`)}).finally(()=>{o(),e(128+mt.constants.signals[s])}))},o=()=>{for(const s of Xc)process.removeListener(s,r)};for(const s of Xc)process.on(s,r);return{dispose:o}}function wN(){return Xc.some(t=>process.listenerCount(t)>0)}const vN=[".git",".adhd","adhd.environment.yaml"];function ec(t){let e=L.resolve(t);const{root:n}=L.parse(e);for(;;){for(const o of vN)if(J.existsSync(`${e}/${o}`))return e;if(e===n)return;const r=L.dirname(e);if(r===e)return;e=r}}const $N=new Set(["system","global","project"]);function bN(t,e){const n=t.cwd??process.cwd();if(t.scope)return t.scope==="project"?{scope:"project",projectRoot:ec(n)??n}:{scope:t.scope};const r=e.ADHD_ENV_SCOPE;if(r!==void 0&&$N.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:ec(n)??n}:{scope:s}}const o=ec(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function rh(t){return`.${t}`}function EN(t){const e=mt.homedir();if(process.platform==="darwin")return L.join(e,"Library","Application Support",t);if(process.platform==="win32"){const r=process.env.APPDATA??L.join(e,"AppData","Roaming");return L.join(r,t)}const n=process.env.XDG_DATA_HOME??L.join(e,".local","share");return L.join(n,t)}function SN(t){const e=t.orgNamespace,n=t.adhdRoot??L.join(mt.homedir(),rh(e)),r=t.adhdRoot??EN(e),o={system:L.join(r,t.project,t.namespace),global:L.join(n,t.project,t.namespace)};return t.projectRoot&&(o.project=L.join(t.projectRoot,rh(e),t.project,t.namespace)),o}function Ey(t,e){return e==="project"?t.project??t.global:t[e]}function _N(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function NN(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return t[r]}})}),n}const ke={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},I={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},di="tag:yaml.org,2002:",gn={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function oh(t){const e=[0];let n=t.indexOf(`
|
|
38
|
+
`);for(;n!==-1;)n+=1,e.push(n),n=t.indexOf(`
|
|
39
|
+
`,n);return e}function Sy(t){let e,n;return typeof t=="string"?(e=oh(t),n=t):(Array.isArray(t)&&(t=t[0]),t&&t.context&&(t.lineStarts||(t.lineStarts=oh(t.context.src)),e=t.lineStarts,n=t.context.src)),{lineStarts:e,src:n}}function eu(t,e){if(typeof t!="number"||t<0)return null;const{lineStarts:n,src:r}=Sy(e);if(!n||!r||t>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(t<i)return{line:s,col:t-n[s-1]+1};if(t===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:t-n[o-1]+1}}function ON(t,e){const{lineStarts:n,src:r}=Sy(e);if(!n||!(t>=1)||t>n.length)return null;const o=n[t-1];let s=n[t];for(;s&&s>o&&r[s-1]===`
|
|
40
|
+
`;)--s;return r.slice(o,s)}function kN({start:t,end:e},n,r=80){let o=ON(t.line,n);if(!o)return null;let{col:s}=t;if(o.length>r)if(s<=r-10)o=o.substr(0,r-1)+"…";else{const l=Math.round(r/2);o.length>s+l&&(o=o.substr(0,s+l-1)+"…"),s-=o.length-r,o="…"+o.substr(1-r)}let i=1,a="";e&&(e.line===t.line&&s+(e.col-t.col)<=r+1?i=e.col-t.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
|
|
41
|
+
${c}${u}${a}`}let be=class _y{static copy(e){return new _y(e.start,e.end)}constructor(e,n){this.start=e,this.end=n||e}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(e,n){const{start:r,end:o}=this;if(e.length===0||o<=e[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<e.length&&!(e[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<e.length&&!(e[s]>=o);)++s;return this.origEnd=o+s,i}},B=class Kt{static addStringTerminator(e,n,r){if(r[r.length-1]===`
|
|
42
|
+
`)return r;const o=Kt.endOfWhiteSpace(e,n);return o>=e.length||e[o]===`
|
|
13
43
|
`?r+`
|
|
14
|
-
`:r}static atDocumentBoundary(
|
|
15
|
-
`)return!1;if(r){if(o!==r)return!1}else if(o!==
|
|
16
|
-
`||c===" "||c===" "}static endOfIdentifier(
|
|
44
|
+
`:r}static atDocumentBoundary(e,n,r){const o=e[n];if(!o)return!0;const s=e[n-1];if(s&&s!==`
|
|
45
|
+
`)return!1;if(r){if(o!==r)return!1}else if(o!==ke.DIRECTIVES_END&&o!==ke.DOCUMENT_END)return!1;const i=e[n+1],a=e[n+2];if(i!==o||a!==o)return!1;const c=e[n+3];return!c||c===`
|
|
46
|
+
`||c===" "||c===" "}static endOfIdentifier(e,n){let r=e[n];const o=r==="<",s=o?[`
|
|
17
47
|
`," "," ",">"]:[`
|
|
18
|
-
`," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=
|
|
19
|
-
`;)r=
|
|
48
|
+
`," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=e[n+=1];return o&&r===">"&&(n+=1),n}static endOfIndent(e,n){let r=e[n];for(;r===" ";)r=e[n+=1];return n}static endOfLine(e,n){let r=e[n];for(;r&&r!==`
|
|
49
|
+
`;)r=e[n+=1];return n}static endOfWhiteSpace(e,n){let r=e[n];for(;r===" "||r===" ";)r=e[n+=1];return n}static startOfLine(e,n){let r=e[n-1];if(r===`
|
|
20
50
|
`)return n;for(;r&&r!==`
|
|
21
|
-
`;)r=
|
|
22
|
-
`)return s}return null}static atBlank(
|
|
23
|
-
`||o===" "||o===" "||r&&!o}static nextNodeIsIndented(
|
|
24
|
-
`&&
|
|
25
|
-
`?n-1:
|
|
51
|
+
`;)r=e[n-=1];return n+1}static endOfBlockIndent(e,n,r){const o=Kt.endOfIndent(e,r);if(o>r+n)return o;{const s=Kt.endOfWhiteSpace(e,o),i=e[s];if(!i||i===`
|
|
52
|
+
`)return s}return null}static atBlank(e,n,r){const o=e[n];return o===`
|
|
53
|
+
`||o===" "||o===" "||r&&!o}static nextNodeIsIndented(e,n,r){return!e||n<0?!1:n>0?!0:r&&e==="-"}static normalizeOffset(e,n){const r=e[n];return r?r!==`
|
|
54
|
+
`&&e[n-1]===`
|
|
55
|
+
`?n-1:Kt.endOfWhiteSpace(e,n):n}static foldNewline(e,n,r){let o=0,s=!1,i="",a=e[n+1];for(;a===" "||a===" "||a===`
|
|
26
56
|
`;){switch(a){case`
|
|
27
57
|
`:o=0,n+=1,i+=`
|
|
28
|
-
`;break;case" ":o<=r&&(s=!0),n=
|
|
29
|
-
`):null}commentHasRequiredWhitespace(
|
|
30
|
-
`)return!0;return!1}parseComment(
|
|
58
|
+
`;break;case" ":o<=r&&(s=!0),n=Kt.endOfWhiteSpace(e,n+2)-1;break;case" ":o+=1,n+=1;break}a=e[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(e,n,r){Object.defineProperty(this,"context",{value:r||null,writable:!0}),this.error=null,this.range=null,this.valueRange=null,this.props=n||[],this.type=e,this.value=null}getPropValue(e,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[e];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,ke.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const e=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,ke.COMMENT,!0);r!=null&&e.push(r)}return e.length>0?e.join(`
|
|
59
|
+
`):null}commentHasRequiredWhitespace(e){const{src:n}=this.context;if(this.header&&e===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return e!==r||Kt.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]===ke.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]!==ke.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[I.FLOW_MAP,I.FLOW_SEQ,I.QUOTE_DOUBLE,I.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const e=eu(this.range.start,this.context.root);if(!e)return;const n=eu(this.range.end,this.context.root);return{start:e,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:e,end:n}=this.valueRange;return this.context.src.slice(e,n)}get tag(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,ke.TAG,!1);if(n!=null){if(n[1]==="<")return{verbatim:n.slice(2,-1)};{const[r,o,s]=n.match(/^(.*!)([^!]*)$/);return{handle:o,suffix:s}}}}return null}get valueRangeContainsNewline(){if(!this.valueRange||!this.context)return!1;const{start:e,end:n}=this.valueRange,{src:r}=this.context;for(let o=e;o<n;++o)if(r[o]===`
|
|
60
|
+
`)return!0;return!1}parseComment(e){const{src:n}=this.context;if(n[e]===ke.COMMENT){const r=Kt.endOfLine(n,e+1),o=new be(e,r);return this.props.push(o),r}return e}setOrigRanges(e,n){return this.range&&(n=this.range.setOrigRange(e,n)),this.valueRange&&this.valueRange.setOrigRange(e,n),this.props.forEach(r=>r.setOrigRange(e,n)),n}toString(){const{context:{src:e},range:n,value:r}=this;if(r!=null)return r;const o=e.slice(n.start,n.end);return Kt.addStringTerminator(e,n.end,o)}},hr=class extends Error{constructor(e,n,r){if(!r||!(n instanceof B))throw new Error(`Invalid arguments for new ${e}`);super(),this.name=e,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const e=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new be(this.offset,this.offset+1);const n=e&&eu(this.offset,e);if(n){const r={line:n.line,col:n.col+1};this.linePos={start:n,end:r}}delete this.offset}else this.range=this.source.range,this.linePos=this.source.rangeAsLinePos;if(this.linePos){const{line:n,col:r}=this.linePos.start;this.message+=` at line ${n}, column ${r}`;const o=e&&kN(this.linePos,e);o&&(this.message+=`:
|
|
31
61
|
|
|
32
62
|
${o}
|
|
33
|
-
`)}delete this.source}},
|
|
34
|
-
`&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=
|
|
35
|
-
`||i===" "||i===" "||r&&i===",")||(o===" "||o===" ")&&i==="#")break;s+=1,o=i}return s}get strValue(){if(!this.valueRange||!this.context)return null;let{start:
|
|
36
|
-
`||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=
|
|
37
|
-
`){const{fold:u,offset:l}=
|
|
38
|
-
`&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[
|
|
39
|
-
`&&!
|
|
40
|
-
`?s=c:(i=
|
|
41
|
-
`&&(s=
|
|
42
|
-
`||u==="#";){if(u==="#"){const
|
|
43
|
-
`&&
|
|
44
|
-
`?!1:
|
|
63
|
+
`)}delete this.source}},os=class extends hr{constructor(e,n){super("YAMLReferenceError",e,n)}},X=class extends hr{constructor(e,n){super("YAMLSemanticError",e,n)}},Fe=class extends hr{constructor(e,n){super("YAMLSyntaxError",e,n)}},co=class extends hr{constructor(e,n){super("YAMLWarning",e,n)}};function ze(t,e,n){return(e=AN(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function jN(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function AN(t){var e=jN(t,"string");return typeof e=="symbol"?e:e+""}let Ny=class tu extends B{static endOfLine(e,n,r){let o=e[n],s=n;for(;o&&o!==`
|
|
64
|
+
`&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=e[s+1];if(o===":"&&(!i||i===`
|
|
65
|
+
`||i===" "||i===" "||r&&i===",")||(o===" "||o===" ")&&i==="#")break;s+=1,o=i}return s}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;e<n&&(o===`
|
|
66
|
+
`||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=e;a<n;++a){const c=r[a];if(c===`
|
|
67
|
+
`){const{fold:u,offset:l}=B.foldNewline(r,a,-1);s+=u,a=l}else if(c===" "||c===" "){const u=a;let l=r[a+1];for(;a<n&&(l===" "||l===" ");)a+=1,l=r[a+1];l!==`
|
|
68
|
+
`&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[e];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new X(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new X(this,a)],str:s}}default:return s}}parseBlockValue(e){const{indent:n,inFlow:r,src:o}=this.context;let s=e,i=e;for(let a=o[s];a===`
|
|
69
|
+
`&&!B.atDocumentBoundary(o,s+1);a=o[s]){const c=B.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
|
|
70
|
+
`?s=c:(i=tu.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=e),this.valueRange.end=i,i}parse(e,n){this.context=e;const{inFlow:r,src:o}=e;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
|
|
71
|
+
`&&(s=tu.endOfLine(o,n,r)),this.valueRange=new be(n,s),s=B.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}},ss=class extends B{constructor(){super(I.BLANK_LINE)}get includesTrailingLines(){return!0}parse(e,n){return this.context=e,this.range=new be(n,n+1),n+1}},Rl=class extends B{constructor(e,n){super(e,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{atLineStart:s,lineStart:i}=e;!s&&this.type===I.SEQ_ITEM&&(this.error=new X(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:e.indent;let c=B.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",d=[];let f=null;for(;u===`
|
|
72
|
+
`||u==="#";){if(u==="#"){const p=B.endOfLine(o,c+1);d.push(new be(c,p)),c=p}else{s=!0,i=c+1;const p=B.endOfWhiteSpace(o,i);o[p]===`
|
|
73
|
+
`&&d.length===0&&(f=new ss,i=f.parse({src:o},i)),c=B.endOfIndent(o,i)}u=o[c]}if(B.nextNodeIsIndented(u,c-(i+a),this.type!==I.SEQ_ITEM)?this.node=r({atLineStart:s,inCollection:!1,indent:a,lineStart:i,parent:this},c):u&&i>n+1&&(c=i-1),this.node){if(f){const p=e.parent.items||e.parent.contents;p&&p.push(f)}d.length&&Array.prototype.push.apply(this.props,d),c=this.node.range.end}else if(l){const p=d[0];this.props.push(p),c=p.end}else c=B.endOfLine(o,n+1);const g=this.node?this.node.valueRange.end:c;return this.valueRange=new be(n,g),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.node?this.node.setOrigRanges(e,n):n}toString(){const{context:{src:e},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?e.slice(r.start,n.range.start)+String(n):e.slice(r.start,r.end);return B.addStringTerminator(e,r.end,s)}},Do=class extends B{constructor(){super(I.COMMENT)}parse(e,n){this.context=e;const r=this.parseComment(n);return this.range=new be(n,r),r}};function nu(t){let e=t;for(;e instanceof Rl;)e=e.node;if(!(e instanceof Oy))return null;const n=e.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=e.items[i];if(a.type===I.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===I.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=e.items.splice(r,n-r),s=o[0].range.start;for(;e.range.end=s,e.valueRange&&e.valueRange.end>s&&(e.valueRange.end=s),e!==t;)e=e.context.parent;return o}let Oy=class ru extends B{static nextContentHasIndent(e,n,r){const o=B.endOfLine(e,n)+1;n=B.endOfWhiteSpace(e,o);const s=e[n];return s?n>=o+r?!0:s!=="#"&&s!==`
|
|
74
|
+
`?!1:ru.nextContentHasIndent(e,n,r):!1}constructor(e){super(e.type===I.SEQ_ITEM?I.SEQ:I.MAP);for(let r=e.props.length-1;r>=0;--r)if(e.props[r].start<e.context.lineStart){this.props=e.props.slice(0,r+1),e.props=e.props.slice(r+1);const o=e.props[0]||e.valueRange;e.range.start=o.start;break}this.items=[e];const n=nu(e);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let s=B.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=be.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=B.normalizeOffset(o,c);let u=o[c],l=B.endOfWhiteSpace(o,s)===c,d=!1;for(;u;){for(;u===`
|
|
45
75
|
`||u==="#";){if(l&&u===`
|
|
46
|
-
`&&!
|
|
47
|
-
`||
|
|
48
|
-
`||
|
|
49
|
-
`&&(s=
|
|
50
|
-
`&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(
|
|
51
|
-
`&&o!=="#";)o=n[r+=1];return this.valueRange=new
|
|
52
|
-
`?r:n}constructor(){super(
|
|
53
|
-
`:if(r){const i=new
|
|
54
|
-
`:if(i){const a=new
|
|
55
|
-
`:s+=1;break;case void 0:break;default:this.error=new
|
|
56
|
-
`),o+=
|
|
76
|
+
`&&!d){const p=new ss;if(c=p.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(p),c-=1}else if(u==="#"){if(c<s+a&&!ru.nextContentHasIndent(o,c,a))return c;const p=new Do;if(c=p.parse({indent:a,lineStart:s,src:o},c),this.items.push(p),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=B.endOfIndent(o,s),B.atBlank(o,c)){const p=B.endOfWhiteSpace(o,c),y=o[p];(!y||y===`
|
|
77
|
+
`||y==="#")&&(c=p)}u=o[c],l=!0}if(!u)break;if(c!==s+a&&(l||u!==":")){if(c<s+a){s>n&&(c=s);break}else if(!this.error){const p="All collection items must start at the same column";this.error=new Fe(this,p)}}if(i.type===I.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const p=o[c+1];if(!p||p===`
|
|
78
|
+
`||p===" "||p===" "){const y="A collection cannot be both a mapping and a sequence";this.error=new Fe(this,y)}}const f=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!f)return c;if(this.items.push(f),this.valueRange.end=f.valueRange.end,c=B.normalizeOffset(o,f.range.end),u=o[c],l=!1,d=f.includesTrailingLines,u){let p=c-1,y=o[p];for(;y===" "||y===" ";)y=o[--p];y===`
|
|
79
|
+
`&&(s=p+1,l=!0)}const g=nu(f);g&&Array.prototype.push.apply(this.items,g)}return c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{n=r.setOrigRanges(e,n)}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;let s=e.slice(r.start,n[0].range.start)+String(n[0]);for(let i=1;i<n.length;++i){const a=n[i],{atLineStart:c,indent:u}=a.context;if(c)for(let l=0;l<u;++l)s+=" ";s+=String(a)}return B.addStringTerminator(e,r.end,s)}};class IN extends B{constructor(){super(I.DIRECTIVE),this.name=null}get parameters(){const e=this.rawValue;return e?e.trim().split(/[ \t]+/):[]}parseName(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
|
|
80
|
+
`&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(e,r),r}parseParameters(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
|
|
81
|
+
`&&o!=="#";)o=n[r+=1];return this.valueRange=new be(e,r),r}parse(e,n){this.context=e;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new be(n,r),r}}let PN=class ou extends B{static startCommentOrEndBlankLine(e,n){const r=B.endOfWhiteSpace(e,n),o=e[r];return o==="#"||o===`
|
|
82
|
+
`?r:n}constructor(){super(I.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(e){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=e;for(;!B.atDocumentBoundary(n,s,ke.DIRECTIVES_END);)switch(s=ou.startCommentOrEndBlankLine(n,s),n[s]){case`
|
|
83
|
+
`:if(r){const i=new ss;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new Do;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new IN;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new X(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new be(s,s+3),s+3):(o?this.error=new X(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(e){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=e;for(;r[o-1]==="-";)o-=1;let s=B.endOfWhiteSpace(r,e),i=o===e;for(this.valueRange=new be(s);!B.atDocumentBoundary(r,s,ke.DOCUMENT_END);){switch(r[s]){case`
|
|
84
|
+
`:if(i){const a=new ss;s=a.parse({src:r},s),s<r.length&&this.contents.push(a)}else s+=1,i=!0;o=s;break;case"#":{const a=new Do;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=B.endOfIndent(r,s),c=n({atLineStart:i,indent:-1,inFlow:!1,inCollection:!1,lineStart:o,parent:this},a);if(!c)return this.valueRange.end=a;this.contents.push(c),s=c.range.end,i=!1;const u=nu(c);u&&Array.prototype.push.apply(this.contents,u)}}s=ou.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new be(s,s+3),s+=3,r[s])){if(s=B.endOfWhiteSpace(r,s),r[s]==="#"){const a=new Do;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
|
|
85
|
+
`:s+=1;break;case void 0:break;default:this.error=new Fe(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(e,n){e.root=this,this.context=e;const{src:r}=e;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.directives.forEach(r=>{n=r.setOrigRanges(e,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(e,n)),this.contents.forEach(r=>{n=r.setOrigRanges(e,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(e,n)),n}toString(){const{contents:e,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return e.length>0&&((n.length>0||e[0].type===I.COMMENT)&&(o+=`---
|
|
86
|
+
`),o+=e.join("")),o[o.length-1]!==`
|
|
57
87
|
`&&(o+=`
|
|
58
|
-
`),o}},
|
|
59
|
-
`||i===" "||i===" ";){if(n-=1,n<=
|
|
60
|
-
`&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===
|
|
61
|
-
`)
|
|
62
|
-
`?
|
|
63
|
-
`:
|
|
64
|
-
`;else{const
|
|
65
|
-
`:!
|
|
66
|
-
`&&(
|
|
67
|
-
|
|
68
|
-
`),f
|
|
69
|
-
`,
|
|
70
|
-
`}parseBlockHeader(
|
|
71
|
-
`&&(s+=1,!
|
|
72
|
-
`&&
|
|
73
|
-
`){if(
|
|
74
|
-
`?s=u:s=i=
|
|
75
|
-
`:{i=c+1;const u=
|
|
76
|
-
`){const l=new
|
|
77
|
-
`||u===" "||u===" "||u===","||a===":"&&this.prevNodeIsJsonLike()){this.items.push({char:a,offset:c}),c+=1;break}}default:{const u=r({atLineStart:!1,inCollection:!1,inFlow:!0,indent:-1,lineStart:i,parent:this},c);if(!u)return this.valueRange=new
|
|
78
|
-
`&&
|
|
79
|
-
`&&
|
|
80
|
-
`&&(a+=1)}),i+=
|
|
81
|
-
`){
|
|
82
|
-
`;break;case"r":i+="\r";break;case"t":i+=" ";break;case"v":i+="\v";break;case"N":i+="
";break;case"_":i+=" ";break;case"L":i+="\u2028";break;case"P":i+="\u2029";break;case" ":i+=" ";break;case'"':i+='"';break;case"/":i+="/";break;case"\\":i+="\\";break;case" ":i+=" ";break;case"x":i+=this.parseCharCode(a+1,2,
|
|
83
|
-
`:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:
|
|
84
|
-
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return
|
|
85
|
-
`){
|
|
86
|
-
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return
|
|
88
|
+
`),o}},xN=class extends B{parse(t,e){this.context=t;const{src:n}=t;let r=B.endOfIdentifier(n,e+1);return this.valueRange=new be(e+1,r),r=B.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const an={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class RN extends B{constructor(e,n){super(e,n),this.blockIndent=null,this.chomping=an.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===an.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{indent:r,src:o}=this.context;if(this.valueRange.isEmpty())return"";let s=null,i=o[n-1];for(;i===`
|
|
89
|
+
`||i===" "||i===" ";){if(n-=1,n<=e){if(this.chomping===an.KEEP)break;return""}i===`
|
|
90
|
+
`&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===an.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===I.BLOCK_FOLDED;let l=!0,d="",f="",g=!1;for(let p=e;p<n;++p){for(let w=0;w<c&&o[p]===" ";++w)p+=1;const y=o[p];if(y===`
|
|
91
|
+
`)f===`
|
|
92
|
+
`?d+=`
|
|
93
|
+
`:f=`
|
|
94
|
+
`;else{const w=B.endOfLine(o,p),h=o.slice(p,w);p=w,u&&(y===" "||y===" ")&&p<a?(f===" "?f=`
|
|
95
|
+
`:!g&&!l&&f===`
|
|
96
|
+
`&&(f=`
|
|
97
|
+
|
|
98
|
+
`),d+=f+h,f=w<n&&o[w]||"",g=!0):(d+=f+h,f=u&&p<a?" ":`
|
|
99
|
+
`,g=!1),l&&h!==""&&(l=!1)}}return this.chomping===an.STRIP?d:d+`
|
|
100
|
+
`}parseBlockHeader(e){const{src:n}=this.context;let r=e+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=an.STRIP;break;case"+":this.chomping=an.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o+=s;break;default:return this.blockIndent=Number(o)||null,this.header=new be(e,r),r}r+=1}}parseBlockValue(e){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=e,i=e,a=1;for(let c=r[s];c===`
|
|
101
|
+
`&&(s+=1,!B.atDocumentBoundary(r,s));c=r[s]){const u=B.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],d=u-(s+n);if(this.blockIndent){if(l&&l!==`
|
|
102
|
+
`&&d<this.blockIndent){if(r[u]==="#")break;if(!this.error){const f=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new X(this,f)}}}else if(r[u]!==`
|
|
103
|
+
`){if(d<a){const f="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new X(this,f)}this.blockIndent=d}else d>a&&(a=d);r[u]===`
|
|
104
|
+
`?s=u:s=i=B.endOfLine(r,u)}return this.chomping!==an.KEEP&&(s=r[i]?i+1:i),this.valueRange=new be(e+1,s),s}parse(e,n){this.context=e;const{src:r}=e;let o=this.parseBlockHeader(n);return o=B.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.header?this.header.setOrigRange(e,n):n}}class TN extends B{constructor(e,n){super(e,n),this.items=null}prevNodeIsJsonLike(e=this.items.length){const n=this.items[e-1];return!!n&&(n.jsonLike||n.type===I.COMMENT&&this.prevNodeIsJsonLike(e-1))}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{indent:s,lineStart:i}=e,a=o[n];this.items=[{char:a,offset:n}];let c=B.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
|
|
105
|
+
`:{i=c+1;const u=B.endOfWhiteSpace(o,i);if(o[u]===`
|
|
106
|
+
`){const l=new ss;i=l.parse({src:o},i),this.items.push(l)}if(c=B.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new X(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new Do;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
|
|
107
|
+
`||u===" "||u===" "||u===","||a===":"&&this.prevNodeIsJsonLike()){this.items.push({char:a,offset:c}),c+=1;break}}default:{const u=r({atLineStart:!1,inCollection:!1,inFlow:!0,indent:-1,lineStart:i,parent:this},c);if(!u)return this.valueRange=new be(n,c),c;this.items.push(u),c=B.normalizeOffset(o,u.range.end)}}c=B.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new be(n,c+1),a&&(this.items.push({char:a,offset:c}),c=B.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{if(r instanceof B)n=r.setOrigRanges(e,n);else if(e.length===0)r.origOffset=r.offset;else{let o=n;for(;o<e.length&&!(e[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof B);let i="",a=r.start;return s.forEach(c=>{const u=e.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
|
|
108
|
+
`&&e[a-1]!==`
|
|
109
|
+
`&&e[a]===`
|
|
110
|
+
`&&(a+=1)}),i+=e.slice(a,r.end),B.addStringTerminator(e,r.end,i)}}let CN=class ky extends B{static endOfQuote(e,n){let r=e[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=e[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&e.push(new Fe(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
|
|
111
|
+
`){B.atDocumentBoundary(s,a+1)&&e.push(new X(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=B.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new X(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(c==="\\")switch(a+=1,s[a]){case"0":i+="\0";break;case"a":i+="\x07";break;case"b":i+="\b";break;case"e":i+="\x1B";break;case"f":i+="\f";break;case"n":i+=`
|
|
112
|
+
`;break;case"r":i+="\r";break;case"t":i+=" ";break;case"v":i+="\v";break;case"N":i+="
";break;case"_":i+=" ";break;case"L":i+="\u2028";break;case"P":i+="\u2029";break;case" ":i+=" ";break;case'"':i+='"';break;case"/":i+="/";break;case"\\":i+="\\";break;case" ":i+=" ";break;case"x":i+=this.parseCharCode(a+1,2,e),a+=2;break;case"u":i+=this.parseCharCode(a+1,4,e),a+=4;break;case"U":i+=this.parseCharCode(a+1,8,e),a+=8;break;case`
|
|
113
|
+
`:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:e.push(new Fe(this,`Invalid escape sequence ${s.substr(a-1,2)}`)),i+="\\"+s[a]}else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
|
|
114
|
+
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parseCharCode(e,n,r){const{src:o}=this.context,s=o.substr(e,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new Fe(this,`Invalid escape sequence ${o.substr(e-2,n+2)}`)),o.substr(e-2,n+2)):String.fromCodePoint(i)}parse(e,n){this.context=e;const{src:r}=e;let o=ky.endOfQuote(r,n+1);return this.valueRange=new be(n,o),o=B.endOfWhiteSpace(r,o),o=this.parseComment(o),o}},MN=class jy extends B{static endOfQuote(e,n){let r=e[n];for(;r;)if(r==="'"){if(e[n+1]!=="'")break;r=e[n+=2]}else r=e[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&e.push(new Fe(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
|
|
115
|
+
`){B.atDocumentBoundary(s,a+1)&&e.push(new X(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=B.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new X(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&e.push(new Fe(this,"Unescaped single quote? This should not happen."));else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
|
|
116
|
+
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parse(e,n){this.context=e;const{src:r}=e;let o=jy.endOfQuote(r,n+1);return this.valueRange=new be(n,o),o=B.endOfWhiteSpace(r,o),o=this.parseComment(o),o}};function LN(t,e){switch(t){case I.ALIAS:return new xN(t,e);case I.BLOCK_FOLDED:case I.BLOCK_LITERAL:return new RN(t,e);case I.FLOW_MAP:case I.FLOW_SEQ:return new TN(t,e);case I.MAP_KEY:case I.MAP_VALUE:case I.SEQ_ITEM:return new Rl(t,e);case I.COMMENT:case I.PLAIN:return new Ny(t,e);case I.QUOTE_DOUBLE:return new CN(t,e);case I.QUOTE_SINGLE:return new MN(t,e);default:return null}}let DN=class fi{static parseType(e,n,r){switch(e[n]){case"*":return I.ALIAS;case">":return I.BLOCK_FOLDED;case"|":return I.BLOCK_LITERAL;case"{":return I.FLOW_MAP;case"[":return I.FLOW_SEQ;case"?":return!r&&B.atBlank(e,n+1,!0)?I.MAP_KEY:I.PLAIN;case":":return!r&&B.atBlank(e,n+1,!0)?I.MAP_VALUE:I.PLAIN;case"-":return!r&&B.atBlank(e,n+1,!0)?I.SEQ_ITEM:I.PLAIN;case'"':return I.QUOTE_DOUBLE;case"'":return I.QUOTE_SINGLE;default:return I.PLAIN}}constructor(e={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){ze(this,"parseNode",(c,u)=>{if(B.atDocumentBoundary(this.src,u))return null;const l=new fi(this,c),{props:d,type:f,valueStart:g}=l.parseProps(u),p=LN(f,d);let y=u;try{y=p.parse(l,g)}catch(w){const h=w instanceof Error?w.message:String(w);p.error||(p.error=new Fe(p,h))}if(p.range=new be(u,y),y<=u&&(p.error||(p.error=new Error("Node#parse consumed no characters")),p.error.parseEnd=y,p.error.source=p,p.range.end=u+1),l.nodeStartsCollection(p)){!p.error&&!l.atLineStart&&l.parent.type===I.DOCUMENT&&(p.error=new Fe(p,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const w=new Oy(p);return y=w.parse(new fi(l),y),w.range=new be(u,y),w}return p}),this.atLineStart=n??(e.atLineStart||!1),this.inCollection=r??(e.inCollection||!1),this.inFlow=o??(e.inFlow||!1),this.indent=s??e.indent,this.lineStart=i??e.lineStart,this.parent=a??(e.parent||{}),this.root=e.root,this.src=e.src}nodeStartsCollection(e){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(e instanceof Rl)return!0;let s=e.range.end;return o[s]===`
|
|
87
117
|
`||o[s-1]===`
|
|
88
|
-
`?!1:(s=
|
|
118
|
+
`?!1:(s=B.endOfWhiteSpace(o,s),o[s]===":")}parseProps(e){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;e=this.atLineStart?B.endOfIndent(o,e):B.endOfWhiteSpace(o,e);let a=o[e];for(;a===ke.ANCHOR||a===ke.COMMENT||a===ke.TAG||a===`
|
|
89
119
|
`;){if(a===`
|
|
90
|
-
`){let u=
|
|
91
|
-
`);const
|
|
92
|
-
`)));const n=[];let r=0;do{const o=new
|
|
93
|
-
`),n}function
|
|
94
|
-
${
|
|
95
|
-
`)===-1?`${
|
|
96
|
-
`+n.replace(/^/gm,`${
|
|
97
|
-
`)&&(
|
|
98
|
-
${u}${c}${
|
|
99
|
-
`;
|
|
100
|
-
${c}${v}`}else
|
|
120
|
+
`){let u=e,l;do l=u+1,u=B.endOfIndent(o,l);while(o[u]===`
|
|
121
|
+
`);const d=u-(l+this.indent),f=r.type===I.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!B.nextNodeIsIndented(o[u],d,!f))break;this.atLineStart=!0,this.lineStart=l,i=!1,e=u}else if(a===ke.COMMENT){const u=B.endOfLine(o,e+1);s.push(new be(e,u)),e=u}else{let u=B.endOfIdentifier(o,e+1);a===ke.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(e+1,u+13))&&(u=B.endOfIdentifier(o,u+5)),s.push(new be(e,u)),i=!0,e=B.endOfWhiteSpace(o,u)}a=o[e]}i&&a===":"&&B.atBlank(o,e+1,!0)&&(e-=1);const c=fi.parseType(o,e,n);return{props:s,type:c,valueStart:e}}};function Tl(t){const e=[];t.indexOf("\r")!==-1&&(t=t.replace(/\r\n?/g,(o,s)=>(o.length>1&&e.push(s),`
|
|
122
|
+
`)));const n=[];let r=0;do{const o=new PN,s=new DN({src:t});r=o.parse(s,r),n.push(o)}while(r<t.length);return n.setOrigRanges=()=>{if(e.length===0)return!1;for(let s=1;s<e.length;++s)e[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(e,o);return e.splice(0,e.length),!0},n.toString=()=>n.join(`...
|
|
123
|
+
`),n}function UN(t,e,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${e}#`)}
|
|
124
|
+
${e}${t}`:t}function qr(t,e,n){return n?n.indexOf(`
|
|
125
|
+
`)===-1?`${t} #${n}`:`${t}
|
|
126
|
+
`+n.replace(/^/gm,`${e||""}#`):t}let nt=class{};function _t(t,e,n){if(Array.isArray(t))return t.map((r,o)=>_t(r,String(o),n));if(t&&typeof t.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(t);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=t.toJSON(e,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof t=="bigint"?Number(t):t}let me=class extends nt{constructor(e){super(),this.value=e}toJSON(e,n){return n&&n.keep?this.value:_t(this.value,e,n)}toString(){return String(this.value)}};function sh(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){const s=e[o];if(Number.isInteger(s)&&s>=0){const i=[];i[s]=r,r=i}else{const i={};Object.defineProperty(i,s,{value:r,writable:!0,enumerable:!0,configurable:!0}),r=i}}return t.createNode(r,!1)}const ko=t=>t==null||typeof t=="object"&&t[Symbol.iterator]().next().done;let Ue=class Jn extends nt{constructor(e){super(),ze(this,"items",[]),this.schema=e}addIn(e,n){if(ko(e))this.add(n);else{const[r,...o]=e,s=this.get(r,!0);if(s instanceof Jn)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,sh(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([e,...n]){if(n.length===0)return this.delete(e);const r=this.get(e,!0);if(r instanceof Jn)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}getIn([e,...n],r){const o=this.get(e,!0);return n.length===0?!r&&o instanceof me?o.value:o:o instanceof Jn?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(e=>{if(!e||e.type!=="PAIR")return!1;const n=e.value;return n==null||n instanceof me&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([e,...n]){if(n.length===0)return this.has(e);const r=this.get(e,!0);return r instanceof Jn?r.hasIn(n):!1}setIn([e,...n],r){if(n.length===0)this.set(e,r);else{const o=this.get(e,!0);if(o instanceof Jn)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(e,sh(this.schema,n,r));else throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}}toJSON(){return null}toString(e,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=e,d=this.type===I.FLOW_MAP||this.type===I.FLOW_SEQ||e.inFlow;d&&(s+=u);const f=o&&this.hasAllNullValues();e=Object.assign({},e,{allNullValues:f,indent:s,inFlow:d,type:null});let g=!1,p=!1;const y=this.items.reduce((h,v,b)=>{let E;v&&(!g&&v.spaceBefore&&h.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(j=>{h.push({type:"comment",str:`#${j}`})}),v.comment&&(E=v.comment),d&&(!g&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(p=!0)),g=!1;let N=l(v,e,()=>E=null,()=>g=!0);return d&&!p&&N.includes(`
|
|
127
|
+
`)&&(p=!0),d&&b<this.items.length-1&&(N+=","),N=qr(N,s,E),g&&(E||d)&&(g=!1),h.push({type:"item",str:N}),h},[]);let w;if(y.length===0)w=r.start+r.end;else if(d){const{start:h,end:v}=r,b=y.map(E=>E.str);if(p||b.reduce((E,N)=>E+N.length+2,2)>Jn.maxFlowStringSingleLineLength){w=h;for(const E of b)w+=E?`
|
|
128
|
+
${u}${c}${E}`:`
|
|
129
|
+
`;w+=`
|
|
130
|
+
${c}${v}`}else w=`${h} ${b.join(" ")} ${v}`}else{const h=y.map(n);w=h.shift();for(const v of h)w+=v?`
|
|
101
131
|
${c}${v}`:`
|
|
102
|
-
`}return this.comment?(
|
|
103
|
-
`+this.comment.replace(/^/gm,`${c}#`),i&&i()):
|
|
104
|
-
${
|
|
105
|
-
`),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${
|
|
106
|
-
${N}`}v=c.comment}else c&&typeof c=="object"&&(c=
|
|
107
|
-
${
|
|
108
|
-
`))&&(
|
|
109
|
-
${
|
|
110
|
-
`&&(
|
|
111
|
-
`);n=e
|
|
112
|
-
`)n===
|
|
113
|
-
`&&
|
|
114
|
-
`&&
|
|
115
|
-
${
|
|
116
|
-
${
|
|
117
|
-
`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function
|
|
132
|
+
`}return this.comment?(w+=`
|
|
133
|
+
`+this.comment.replace(/^/gm,`${c}#`),i&&i()):g&&a&&a(),w}};ze(Ue,"maxFlowStringSingleLineLength",60);function Ls(t){let e=t instanceof me?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),Number.isInteger(e)&&e>=0?e:null}let Dt=class extends Ue{add(e){this.items.push(e)}delete(e){const n=Ls(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){const r=Ls(e);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof me?o.value:o}has(e){const n=Ls(e);return typeof n=="number"&&n<this.items.length}set(e,n){const r=Ls(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);this.items[r]=n}toJSON(e,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(_t(s,String(o++),n));return r}toString(e,n,r){return e?super.toString(e,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(e.indent||"")+" "},n,r):JSON.stringify(this)}};const BN=(t,e,n)=>e===null?"":typeof e!="object"?String(e):t instanceof nt&&n&&n.doc?t.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(e);let le=class Ay extends nt{constructor(e,n=null){super(),this.key=e,this.value=n,this.type=Ay.Type.PAIR}get commentBefore(){return this.key instanceof nt?this.key.commentBefore:void 0}set commentBefore(e){if(this.key==null&&(this.key=new me(null)),this.key instanceof nt)this.key.commentBefore=e;else{const n="Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.";throw new Error(n)}}addToJSMap(e,n){const r=_t(this.key,"",e);if(n instanceof Map){const o=_t(this.value,r,e);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=BN(this.key,r,e),s=_t(this.value,o,e);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(e,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(e,n,r){if(!e||!e.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=e.doc.options;let{key:a,value:c}=this,u=a instanceof nt&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof Ue){const N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let l=!i&&(!a||u||(a instanceof nt?a instanceof Ue||a.type===I.BLOCK_FOLDED||a.type===I.BLOCK_LITERAL:typeof a=="object"));const{doc:d,indent:f,indentStep:g,stringify:p}=e;e=Object.assign({},e,{implicitKey:!l,indent:f+g});let y=!1,w=p(a,e,()=>u=null,()=>y=!0);if(w=qr(w,e.indent,u),!l&&w.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(e.allNullValues&&!i)return this.comment?(w=qr(w,e.indent,this.comment),n&&n()):y&&!u&&r&&r(),e.inFlow&&!l?w:`? ${w}`;w=l?`? ${w}
|
|
134
|
+
${f}:`:`${w}:`,this.comment&&(w=qr(w,e.indent,this.comment),n&&n());let h="",v=null;if(c instanceof nt){if(c.spaceBefore&&(h=`
|
|
135
|
+
`),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${e.indent}#`);h+=`
|
|
136
|
+
${N}`}v=c.comment}else c&&typeof c=="object"&&(c=d.schema.createNode(c,!0));e.implicitKey=!1,!l&&!this.comment&&c instanceof me&&(e.indentAtStart=w.length+1),y=!1,!s&&o>=2&&!e.inFlow&&!l&&c instanceof Dt&&c.type!==I.FLOW_SEQ&&!c.tag&&!d.anchors.getName(c)&&(e.indent=e.indent.substr(2));const b=p(c,e,()=>v=null,()=>y=!0);let E=" ";return h||this.comment?E=`${h}
|
|
137
|
+
${e.indent}`:!l&&c instanceof Ue?(!(b[0]==="["||b[0]==="{")||b.includes(`
|
|
138
|
+
`))&&(E=`
|
|
139
|
+
${e.indent}`):b[0]===`
|
|
140
|
+
`&&(E=""),y&&!v&&r&&r(),qr(w+E+b,e.indent,v)}};ze(le,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const pi=(t,e)=>{if(t instanceof tn){const n=e.get(t.source);return n.count*n.aliasCount}else if(t instanceof Ue){let n=0;for(const r of t.items){const o=pi(r,e);o>n&&(n=o)}return n}else if(t instanceof le){const n=pi(t.key,e),r=pi(t.value,e);return Math.max(n,r)}return 1};let tn=class Iy extends nt{static stringify({range:e,source:n},{anchors:r,doc:o,implicitKey:s,inStringifyKey:i}){let a=Object.keys(r).find(u=>r[u]===n);if(!a&&i&&(a=o.anchors.getName(n)||o.anchors.newName()),a)return`*${a}${s?" ":""}`;const c=o.anchors.getName(n)?"Alias node must be after source node":"Source node not found for alias node";throw new Error(`${c} [${e}]`)}constructor(e){super(),this.source=e,this.type=I.ALIAS}set tag(e){throw new Error("Alias nodes cannot have tags")}toJSON(e,n){if(!n)return _t(this.source,e,n);const{anchors:r,maxAliasCount:o}=n,s=r.get(this.source);if(!s||s.res===void 0){const i="This should not happen: Alias anchor was not resolved?";throw this.cstNode?new os(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=pi(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new os(this.cstNode,i):new ReferenceError(i)}return s.res}toString(e){return Iy.stringify(this,e)}};ze(tn,"default",!0);function ar(t,e){const n=e instanceof me?e.value:e;for(const r of t)if(r instanceof le&&(r.key===e||r.key===n||r.key&&r.key.value===n))return r}let ot=class extends Ue{add(e,n){e?e instanceof le||(e=new le(e.key||e,e.value)):e=new le(e);const r=ar(this.items,e.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=e.value;else throw new Error(`Key ${e.key} already set`);else if(o){const s=this.items.findIndex(i=>o(e,i)<0);s===-1?this.items.push(e):this.items.splice(s,0,e)}else this.items.push(e)}delete(e){const n=ar(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){const r=ar(this.items,e),o=r&&r.value;return!n&&o instanceof me?o.value:o}has(e){return!!ar(this.items,e)}set(e,n){this.add(new le(e,n),!0)}toJSON(e,n,r){const o=r?new r:n&&n.mapAsMap?new Map:{};n&&n.onCreate&&n.onCreate(o);for(const s of this.items)s.addToJSMap(n,o);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof le))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(e,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:e.indent||""},n,r)}};const Py="<<";let xy=class extends le{constructor(e){if(e instanceof le){let n=e.value;n instanceof Dt||(n=new Dt,n.items.push(e.value),n.range=e.value.range),super(e.key,n),this.range=e.range}else super(new me(Py),new Dt);this.type=le.Type.MERGE_PAIR}addToJSMap(e,n){for(const{source:r}of this.value.items){if(!(r instanceof ot))throw new Error("Merge sources must be maps");const o=r.toJSON(null,e,Map);for(const[s,i]of o)n instanceof Map?n.has(s)||n.set(s,i):n instanceof Set?n.add(s):Object.prototype.hasOwnProperty.call(n,s)||Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return n}toString(e,n){const r=this.value;if(r.items.length>1)return super.toString(e,n);this.value=r.items[0];const o=super.toString(e,n);return this.value=r,o}};const Uo={defaultType:I.BLOCK_LITERAL,lineWidth:76},Wt={trueStr:"true",falseStr:"false"},Nn={asBigInt:!1},Xr={nullStr:"null"},nn={defaultType:I.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function Cl(t,e,n){for(const{format:r,test:o,resolve:s}of e)if(o){const i=t.match(o);if(i){let a=s.apply(null,i);return a instanceof me||(a=new me(a)),r&&(a.format=r),a}}return n&&(t=n(t)),new me(t)}const Ry="flow",su="block",hi="quoted",ih=(t,e)=>{let n=t[e+1];for(;n===" "||n===" ";){do n=t[e+=1];while(n&&n!==`
|
|
141
|
+
`);n=t[e+1]}return e};function ma(t,e,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return t;const c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;const u=[],l={};let d=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):d=o-r);let f,g,p=!1,y=-1,w=-1,h=-1;n===su&&(y=ih(t,y),y!==-1&&(d=y+c));for(let b;b=t[y+=1];){if(n===hi&&b==="\\"){switch(w=y,t[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}h=y}if(b===`
|
|
142
|
+
`)n===su&&(y=ih(t,y)),d=y+c,f=void 0;else{if(b===" "&&g&&g!==" "&&g!==`
|
|
143
|
+
`&&g!==" "){const E=t[y+1];E&&E!==" "&&E!==`
|
|
144
|
+
`&&E!==" "&&(f=y)}if(y>=d)if(f)u.push(f),d=f+c,f=void 0;else if(n===hi){for(;g===" "||g===" ";)g=b,b=t[y+=1],p=!0;const E=y>h+1?y-2:w-1;if(l[E])return t;u.push(E),l[E]=!0,d=E+c,f=void 0}else p=!0}g=b}if(p&&a&&a(),u.length===0)return t;i&&i();let v=t.slice(0,u[0]);for(let b=0;b<u.length;++b){const E=u[b],N=u[b+1]||t.length;E===0?v=`
|
|
145
|
+
${e}${t.slice(0,N)}`:(n===hi&&l[E]&&(v+=`${t[E]}\\`),v+=`
|
|
146
|
+
${e}${t.slice(E+1,N)}`)}return v}const Ml=({indentAtStart:t})=>t?Object.assign({indentAtStart:t},nn.fold):nn.fold,ga=t=>/^(%|---|\.\.\.)/m.test(t);function FN(t,e,n){if(!e||e<0)return!1;const r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`
|
|
147
|
+
`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function dr(t,e){const{implicitKey:n}=e,{jsonEncoding:r,minMultiLineLength:o}=nn.doubleQuoted,s=JSON.stringify(t);if(r)return s;const i=e.indent||(ga(t)?" ":"");let a="",c=0;for(let u=0,l=s[u];l;l=s[++u])if(l===" "&&s[u+1]==="\\"&&s[u+2]==="n"&&(a+=s.slice(c,u)+"\\ ",u+=1,c=u,l="\\"),l==="\\")switch(s[u+1]){case"u":{a+=s.slice(c,u);const d=s.substr(u+2,4);switch(d){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:d.substr(0,2)==="00"?a+="\\x"+d.substr(2):a+=s.substr(u,6)}u+=5,c=u+1}break;case"n":if(n||s[u+2]==='"'||s.length<o)u+=1;else{for(a+=s.slice(c,u)+`
|
|
118
148
|
|
|
119
149
|
`;s[u+2]==="\\"&&s[u+3]==="n"&&s[u+4]!=='"';)a+=`
|
|
120
|
-
`,u+=2;a+=i,s[u+2]===" "&&(a+="\\"),u+=1,c=u+1}break;default:u+=1}return a=c?a+s.slice(c):s,n?a:
|
|
121
|
-
${n}`)+"'";return
|
|
122
|
-
`;let l="",
|
|
123
|
-
`);return
|
|
124
|
-
${i}${
|
|
125
|
-
${i}${l}${n}${
|
|
126
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const
|
|
127
|
-
${i}${
|
|
128
|
-
`)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?
|
|
129
|
-
`)!==-1)return
|
|
130
|
-
${u}`);if(a){const{tags:
|
|
150
|
+
`,u+=2;a+=i,s[u+2]===" "&&(a+="\\"),u+=1,c=u+1}break;default:u+=1}return a=c?a+s.slice(c):s,n?a:ma(a,i,hi,Ml(e))}function Ty(t,e){if(e.implicitKey){if(/\n/.test(t))return dr(t,e)}else if(/[ \t]\n|\n[ \t]/.test(t))return dr(t,e);const n=e.indent||(ga(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
151
|
+
${n}`)+"'";return e.implicitKey?r:ma(r,n,Ry,Ml(e))}function mi({comment:t,type:e,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return dr(n,r);const i=r.indent||(r.forceBlockIndent||ga(n)?" ":""),a=i?"2":"1",c=e===I.BLOCK_FOLDED?!1:e===I.BLOCK_LITERAL?!0:!FN(n,nn.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
|
|
152
|
+
`;let l="",d="";if(n=n.replace(/[\n\t ]*$/,g=>{const p=g.indexOf(`
|
|
153
|
+
`);return p===-1?u+="-":(n===g||p!==g.length-1)&&(u+="+",s&&s()),d=g.replace(/\n$/,""),""}).replace(/^[\n ]*/,g=>{g.indexOf(" ")!==-1&&(u+=a);const p=g.match(/ +$/);return p?(l=g.slice(0,-p[0].length),p[0]):(l=g,"")}),d&&(d=d.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),t&&(u+=" #"+t.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
|
|
154
|
+
${i}${d}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
|
|
155
|
+
${i}${l}${n}${d}`;n=n.replace(/\n+/g,`
|
|
156
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const f=ma(`${l}${n}${d}`,i,su,nn.fold);return`${u}
|
|
157
|
+
${i}${f}`}function qN(t,e,n,r){const{comment:o,type:s,value:i}=t,{actualString:a,implicitKey:c,indent:u,inFlow:l}=e;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return dr(i,e);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
|
|
158
|
+
`)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?Ty(i,e):dr(i,e):mi(t,e,n,r);if(!c&&!l&&s!==I.PLAIN&&i.indexOf(`
|
|
159
|
+
`)!==-1)return mi(t,e,n,r);if(u===""&&ga(i))return e.forceBlockIndent=!0,mi(t,e,n,r);const d=i.replace(/\n+/g,`$&
|
|
160
|
+
${u}`);if(a){const{tags:g}=e.doc.schema;if(typeof Cl(d,g,g.scalarFallback).value!="string")return dr(i,e)}const f=c?d:ma(d,u,Ry,Ml(e));return o&&!l&&(f.indexOf(`
|
|
131
161
|
`)!==-1||o.indexOf(`
|
|
132
|
-
`)!==-1)?(n&&n(),
|
|
133
|
-
`&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";
|
|
134
|
-
`+o:s.commentBefore=o):o!==void 0&&(
|
|
135
|
-
`+o:
|
|
162
|
+
`)!==-1)?(n&&n(),UN(f,u,o)):f}function Ll(t,e,n,r){const{defaultType:o}=nn,{implicitKey:s,inFlow:i}=e;let{type:a,value:c}=t;typeof c!="string"&&(c=String(c),t=Object.assign({},t,{value:c}));const u=d=>{switch(d){case I.BLOCK_FOLDED:case I.BLOCK_LITERAL:return mi(t,e,n,r);case I.QUOTE_DOUBLE:return dr(c,e);case I.QUOTE_SINGLE:return Ty(c,e);case I.PLAIN:return qN(t,e,n,r);default:return null}};(a!==I.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===I.BLOCK_FOLDED||a===I.BLOCK_LITERAL))&&(a=I.QUOTE_DOUBLE);let l=u(a);if(l===null&&(l=u(o),l===null))throw new Error(`Unsupported default string type ${o}`);return l}function Ht({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=e-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function Cy(t,e){let n,r;switch(e.type){case I.FLOW_MAP:n="}",r="flow map";break;case I.FLOW_SEQ:n="]",r="flow sequence";break;default:t.push(new X(e,"Not a flow collection!?"));return}let o;for(let s=e.items.length-1;s>=0;--s){const i=e.items[s];if(!i||i.type!==I.COMMENT){o=i;break}}if(o&&o.char!==n){const s=`Expected ${r} to end with ${n}`;let i;typeof o.offset=="number"?(i=new X(e,s),i.offset=o.offset+1):(i=new X(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),t.push(i)}}function My(t,e){const n=e.context.src[e.range.start-1];if(n!==`
|
|
163
|
+
`&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";t.push(new X(e,r))}}function Ly(t,e){const n=String(e),r=n.substr(0,8)+"..."+n.substr(-8);return new X(t,`The "${r}" key is too long`)}function Dy(t,e){for(const{afterKey:n,before:r,comment:o}of e){let s=t.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
|
|
164
|
+
`+o:s.commentBefore=o):o!==void 0&&(t.comment?t.comment+=`
|
|
165
|
+
`+o:t.comment=o)}}function Es(t,e){const n=e.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=e),t.errors.push(r)}),n.str):""}function KN(t,e){const{handle:n,suffix:r}=e.tag;let o=t.tagPrefixes.find(s=>s.handle===n);if(!o){const s=t.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new X(e,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new X(e,`The ${n} tag has no suffix.`);if(n==="!"&&(t.version||t.options.version)==="1.0"){if(r[0]==="^")return t.warnings.push(new co(e,"YAML 1.0 ^ tag expansion is not supported")),r;if(/[:/]/.test(r)){const s=r.match(/^([a-z0-9-]+)\/(.*)/i);return s?`tag:${s[1]}.yaml.org,2002:${s[2]}`:`tag:${r}`}}return o.prefix+decodeURIComponent(r)}function VN(t,e){const{tag:n,type:r}=e;let o=!1;if(n){const{handle:s,suffix:i,verbatim:a}=n;if(a){if(a!=="!"&&a!=="!!")return a;const c=`Verbatim tags aren't resolved, so ${a} is invalid.`;t.errors.push(new X(e,c))}else if(s==="!"&&!i)o=!0;else try{return KN(t,e)}catch(c){t.errors.push(c)}}switch(r){case I.BLOCK_FOLDED:case I.BLOCK_LITERAL:case I.QUOTE_DOUBLE:case I.QUOTE_SINGLE:return gn.STR;case I.FLOW_MAP:case I.MAP:return gn.MAP;case I.FLOW_SEQ:case I.SEQ:return gn.SEQ;case I.PLAIN:return o?gn.STR:null;default:return null}}function ah(t,e,n){const{tags:r}=t.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(t,e);return a instanceof Ue?a:new me(a)}const s=Es(t,e);return typeof s=="string"&&o.length>0?Cl(s,o,r.scalarFallback):null}function GN({type:t}){switch(t){case I.FLOW_MAP:case I.MAP:return gn.MAP;case I.FLOW_SEQ:case I.SEQ:return gn.SEQ;default:return gn.STR}}function zN(t,e,n){try{const r=ah(t,e,n);if(r)return n&&e.tag&&(r.tag=n),r}catch(r){if(r instanceof hr)r.source||(r.source=e),t.errors.push(r);else{const o=r instanceof Error?r.message:String(r);t.errors.push(new X(e,o))}return null}try{const r=GN(e);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;t.warnings.push(new co(e,o));const s=ah(t,e,r);return s.tag=n,s}catch(r){const o=new os(e,r.message);return o.stack=r.stack,t.errors.push(o),null}}const WN=t=>{if(!t)return!1;const{type:e}=t;return e===I.MAP_KEY||e===I.MAP_VALUE||e===I.SEQ_ITEM};function HN(t,e){const n={before:[],after:[]};let r=!1,o=!1;const s=WN(e.context.parent)?e.context.parent.props.concat(e.props):e.props;for(const{start:i,end:a}of s)switch(e.context.src[i]){case ke.COMMENT:{if(!e.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";t.push(new X(e,l))}const{header:c,valueRange:u}=e;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(e.context.src.slice(i+1,a));break}case ke.ANCHOR:if(r){const c="A node can have at most one anchor";t.push(new X(e,c))}r=!0;break;case ke.TAG:if(o){const c="A node can have at most one tag";t.push(new X(e,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function JN(t,e){const{anchors:n,errors:r,schema:o}=t;if(e.type===I.ALIAS){const i=e.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new os(e,u)),null}const c=new tn(a);return n._cstAliases.push(c),c}const s=VN(t,e);if(s)return zN(t,e,s);if(e.type!==I.PLAIN){const i=`Failed to resolve ${e.type} node here`;return r.push(new Fe(e,i)),null}try{const i=Es(t,e);return Cl(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=e),r.push(i),null}}function $n(t,e){if(!e)return null;e.error&&t.errors.push(e.error);const{comments:n,hasAnchor:r,hasTag:o}=HN(t.errors,e);if(r){const{anchors:i}=t,a=e.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=e}if(e.type===I.ALIAS&&(r||o)){const i="An alias node must not specify any properties";t.errors.push(new X(e,i))}const s=JN(t,e);if(s){s.range=[e.range.start,e.range.end],t.options.keepCstNodes&&(s.cstNode=e),t.options.keepNodeTypes&&(s.type=e.type);const i=n.before.join(`
|
|
136
166
|
`);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
|
|
137
167
|
${i}`:i);const a=n.after.join(`
|
|
138
168
|
`);a&&(s.comment=s.comment?`${s.comment}
|
|
139
|
-
${a}`:a)}return
|
|
140
|
-
`)return!1;return!0};function
|
|
141
|
-
`){const
|
|
142
|
-
`:" ")}return
|
|
169
|
+
${a}`:a)}return e.resolved=s}function Uy(t,e){if(e.type!==I.MAP&&e.type!==I.FLOW_MAP){const i=`A ${e.type} node cannot be resolved as a mapping`;return t.errors.push(new Fe(e,i)),null}const{comments:n,items:r}=e.type===I.FLOW_MAP?XN(t,e):ZN(t,e),o=new ot;o.items=r,Dy(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof Ue&&(s=!0),t.schema.merge&&a&&a.value===Py){r[i]=new xy(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof tn){const{type:d}=l.source;return d===I.MAP||d===I.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&t.errors.push(new X(e,u))}else for(let c=i+1;c<r.length;++c){const{key:u}=r[c];if(a===u||a&&u&&Object.prototype.hasOwnProperty.call(a,"value")&&a.value===u.value){const l=`Map keys must be unique; "${a}" is repeated`;t.errors.push(new X(e,l));break}}}if(s&&!t.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new co(e,i))}return e.resolved=o,o}const QN=({context:{lineStart:t,node:e,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(e&&o>e.valueRange.start||n[o]!==ke.COMMENT)return!1;for(let s=t;s<o;++s)if(n[s]===`
|
|
170
|
+
`)return!1;return!0};function YN(t,e){if(!QN(t))return;const n=t.getPropValue(0,ke.COMMENT,!0);let r=!1;const o=e.value.commentBefore;if(o&&o.startsWith(n))e.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=e.value.comment;!t.node&&s&&s.startsWith(n)&&(e.value.comment=s.substr(n.length+1),r=!0)}r&&(e.comment=n)}function ZN(t,e){const n=[],r=[];let o,s=null;for(let i=0;i<e.items.length;++i){const a=e.items[i];switch(a.type){case I.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case I.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case I.MAP_KEY:o!==void 0&&r.push(new le(o)),a.error&&t.errors.push(a.error),o=$n(t,a.node),s=null;break;case I.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&t.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===I.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";t.errors.push(new X(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new Ny(I.PLAIN,[]),c.context={parent:a,src:a.context.src};const l=a.range.start+1;if(c.range={start:l,end:l},c.valueRange={start:l,end:l},typeof a.range.origStart=="number"){const d=a.range.origStart+1;c.range.origStart=c.range.origEnd=d,c.valueRange.origStart=c.valueRange.origEnd=d}}const u=new le(o,$n(t,c));YN(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&t.errors.push(Ly(e,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new le(o)),o=$n(t,a),s=a.range.start,a.error&&t.errors.push(a.error);e:for(let c=i+1;;++c){const u=e.items[c];switch(u&&u.type){case I.BLANK_LINE:case I.COMMENT:continue e;case I.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";t.errors.push(new X(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";t.errors.push(new X(a,c))}}}return o!==void 0&&r.push(new le(o)),{comments:n,items:r}}function XN(t,e){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<e.items.length;++a){const c=e.items[a];if(typeof c.char=="string"){const{char:u,offset:l}=c;if(u==="?"&&o===void 0&&!s){s=!0,i=":";continue}if(u===":"){if(o===void 0&&(o=null),i===":"){i=",";continue}}else if(s&&(o===void 0&&u!==","&&(o=null),s=!1),o!==void 0&&(r.push(new le(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===e.items.length-1)continue}else if(u===i){i=":";continue}const d=`Flow map contains an unexpected ${u}`,f=new Fe(e,d);f.offset=l,t.errors.push(f)}else c.type===I.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===I.COMMENT?(My(t.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&t.errors.push(new X(c,"Separator , missing in flow map")),o=$n(t,c)):(i!==","&&t.errors.push(new X(c,"Indicator : missing in flow map entry")),r.push(new le(o,$n(t,c))),o=void 0,s=!1)}return Cy(t.errors,e),o!==void 0&&r.push(new le(o)),{comments:n,items:r}}function By(t,e){if(e.type!==I.SEQ&&e.type!==I.FLOW_SEQ){const s=`A ${e.type} node cannot be resolved as a sequence`;return t.errors.push(new Fe(e,s)),null}const{comments:n,items:r}=e.type===I.FLOW_SEQ?tO(t,e):eO(t,e),o=new Dt;if(o.items=r,Dy(o,n),!t.options.mapAsMap&&r.some(s=>s instanceof le&&s.key instanceof Ue)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new co(e,s))}return e.resolved=o,o}function eO(t,e){const n=[],r=[];for(let o=0;o<e.items.length;++o){const s=e.items[o];switch(s.type){case I.BLANK_LINE:n.push({before:r.length});break;case I.COMMENT:n.push({comment:s.comment,before:r.length});break;case I.SEQ_ITEM:if(s.error&&t.errors.push(s.error),r.push($n(t,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";t.errors.push(new X(s,i))}break;default:s.error&&t.errors.push(s.error),t.errors.push(new Fe(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function tO(t,e){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<e.items.length;++u){const l=e.items[u];if(typeof l.char=="string"){const{char:d,offset:f}=l;if(d!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new le(s)),o=!1,s=void 0,i=null),d===a)a=null;else if(!a&&d==="?")o=!0;else if(a!=="["&&d===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof le){const g="Chaining flow sequence pairs is invalid",p=new X(e,g);p.offset=f,t.errors.push(p)}if(!o&&typeof i=="number"){const g=l.range?l.range.start:l.offset;g>i+1024&&t.errors.push(Ly(e,s));const{src:p}=c.context;for(let y=i;y<g;++y)if(p[y]===`
|
|
171
|
+
`){const w="Implicit keys of flow sequence pairs need to be on a single line";t.errors.push(new X(c,w));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||d!=="]"||u<e.items.length-1){const g=`Flow sequence contains an unexpected ${d}`,p=new Fe(e,g);p.offset=f,t.errors.push(p)}}else if(l.type===I.BLANK_LINE)n.push({before:r.length});else if(l.type===I.COMMENT)My(t.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const f=`Expected a ${a} in flow sequence`;t.errors.push(new X(l,f))}const d=$n(t,l);s===void 0?(r.push(d),c=l):(r.push(new le(s,d)),s=void 0),i=l.range.start,a=","}}return Cy(t.errors,e),s!==void 0&&r.push(new le(s)),{comments:n,items:r}}const Fy={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(t,e)=>{const n=Es(t,e);if(typeof Buffer=="function")return Buffer.from(n,"base64");if(typeof atob=="function"){const r=atob(n.replace(/[\n\r]/g,"")),o=new Uint8Array(r.length);for(let s=0;s<r.length;++s)o[s]=r.charCodeAt(s);return o}else{const r="This environment does not support reading binary tags; either Buffer or atob is required";return t.errors.push(new os(e,r)),null}},options:Uo,stringify:({comment:t,type:e,value:n},r,o,s)=>{let i;if(typeof Buffer=="function")i=n instanceof Buffer?n.toString("base64"):Buffer.from(n.buffer).toString("base64");else if(typeof btoa=="function"){let a="";for(let c=0;c<n.length;++c)a+=String.fromCharCode(n[c]);i=btoa(a)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e||(e=Uo.defaultType),e===I.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=Uo,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,d=0;l<c;++l,d+=a)u[l]=i.substr(d,a);n=u.join(e===I.BLOCK_LITERAL?`
|
|
172
|
+
`:" ")}return Ll({comment:t,type:e,value:n},r,o,s)}};function qy(t,e){const n=By(t,e);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof le)){if(o instanceof ot){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new X(e,i)}const s=o.items[0]||new le;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
|
|
143
173
|
${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
|
|
144
|
-
${s.comment}`:o.comment),o=s}n.items[r]=o instanceof H?o:new H(o)}}return n}function Nf(e,t,n){const r=new Le(e);r.tag="tag:yaml.org,2002:pairs";for(const o of t){let s,i;if(Array.isArray(o))if(o.length===2)s=o[0],i=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const c=Object.keys(o);if(c.length===1)s=c[0],i=o[s];else throw new TypeError(`Expected { key: value } tuple: ${o}`)}else s=o;const a=e.createPair(s,i,n);r.items.push(a)}return r}const Of={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Sf,createNode:Nf};let Dr=class kf extends Le{constructor(){super(),me(this,"add",be.prototype.add.bind(this)),me(this,"delete",be.prototype.delete.bind(this)),me(this,"get",be.prototype.get.bind(this)),me(this,"has",be.prototype.has.bind(this)),me(this,"set",be.prototype.set.bind(this)),this.tag=kf.tag}toJSON(t,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof H?(s=Te(o.key,"",n),i=Te(o.value,s,n)):s=Te(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};me(Dr,"tag","tag:yaml.org,2002:omap");function j$(e,t){const n=Sf(e,t),r=[];for(const{key:o}of n.items)if(o instanceof Y)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new F(t,s)}else r.push(o.value);return Object.assign(new Dr,n)}function I$(e,t,n){const r=Nf(e,t,n),o=new Dr;return o.items=r.items,o}const _f={identify:e=>e instanceof Map,nodeClass:Dr,default:!1,tag:"tag:yaml.org,2002:omap",resolve:j$,createNode:I$};let Lr=class Af extends be{constructor(){super(),this.tag=Af.tag}add(t){const n=t instanceof H?t:new H(t);Ot(this.items,n.key)||this.items.push(n)}get(t,n){const r=Ot(this.items,t);return!n&&r instanceof H?r.key instanceof Y?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=Ot(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new H(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(t,n,r);throw new Error("Set items must all have null values")}};me(Lr,"tag","tag:yaml.org,2002:set");function x$(e,t){const n=wf(e,t);if(!n.hasAllNullValues())throw new F(t,"Set items must all have null values");return Object.assign(new Lr,n)}function P$(e,t,n){const r=new Lr;for(const o of t)r.items.push(e.createPair(o,null,n));return r}const jf={identify:e=>e instanceof Set,nodeClass:Lr,default:!1,tag:"tag:yaml.org,2002:set",resolve:x$,createNode:P$},Ei=(e,t)=>{const n=t.split(":").reduce((r,o)=>r*60+Number(o),0);return e==="-"?-n:n},If=({value:e})=>{if(isNaN(e)||!isFinite(e))return He(e);let t="";e<0&&(t="-",e=Math.abs(e));const n=[e%60];return e<60?n.unshift(0):(e=Math.round((e-n[0])/60),n.unshift(e%60),e>=60&&(e=Math.round((e-n[0])/60),n.unshift(e))),t+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},xf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(e,t,n)=>Ei(t,n.replace(/_/g,"")),stringify:If},Pf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(e,t,n)=>Ei(t,n.replace(/_/g,"")),stringify:If},Tf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?)$"),resolve:(e,t,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(t,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=Ei(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function Cf(e){const t=typeof process<"u"&&process.env||{};return e?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!t.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!t.YAML_SILENCE_WARNINGS}function Rf(e,t){if(Cf(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(e,t):console.warn(t?`${t}: ${e}`:e)}}const Vc={};function T$(e,t){if(!Vc[e]&&Cf(!0)){Vc[e]=!0;let n=`The option '${e}' will be removed in a future release`;n+=`, use '${t}' instead.`,Rf(n,"DeprecationWarning")}}function C$(e,t,n){const r=new be(e);if(t instanceof Map)for(const[o,s]of t)r.items.push(e.createPair(o,s,n));else if(t&&typeof t=="object")for(const o of Object.keys(t))r.items.push(e.createPair(o,t[o],n));return typeof e.sortMapEntries=="function"&&r.items.sort(e.sortMapEntries),r}const In={createNode:C$,default:!0,nodeClass:be,tag:"tag:yaml.org,2002:map",resolve:wf};function R$(e,t,n){const r=new Le(e);if(t&&t[Symbol.iterator])for(const o of t){const s=e.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const Ur={createNode:R$,default:!0,nodeClass:Le,tag:"tag:yaml.org,2002:seq",resolve:bf},M$={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Bn,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),bi(e,t,n,r)},options:Qe},Si=[In,Ur,M$],Br=e=>typeof e=="bigint"||Number.isInteger(e),Ni=(e,t,n)=>at.asBigInt?BigInt(e):parseInt(t,n);function Mf(e,t,n){const{value:r}=e;return Br(r)&&r>=0?n+r.toString(t):He(e)}const Df={identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Zt,stringify:()=>Zt.nullStr},Lf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>e[0]==="t"||e[0]==="T",options:Je,stringify:({value:e})=>e?Je.trueStr:Je.falseStr},Uf={identify:e=>Br(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(e,t)=>Ni(e,t,8),options:at,stringify:e=>Mf(e,8,"0o")},Bf={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:e=>Ni(e,e,10),options:at,stringify:He},Ff={identify:e=>Br(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(e,t)=>Ni(e,t,16),options:at,stringify:e=>Mf(e,16,"0x")},qf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:He},Vf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify:({value:e})=>Number(e).toExponential()},Kf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(e,t,n){const r=t||n,o=new Y(parseFloat(e));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:He},D$=Si.concat([Df,Lf,Uf,Bf,Ff,qf,Vf,Kf]),Kc=e=>typeof e=="bigint"||Number.isInteger(e),Wn=({value:e})=>JSON.stringify(e),Gf=[In,Ur,{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Bn,stringify:Wn},{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Wn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:Wn},{identify:Kc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:e=>at.asBigInt?BigInt(e):parseInt(e,10),stringify:({value:e})=>Kc(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Wn}];Gf.scalarFallback=e=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(e)}`)};const Gc=({value:e})=>e?Je.trueStr:Je.falseStr,mn=e=>typeof e=="bigint"||Number.isInteger(e);function Yn(e,t,n){let r=t.replace(/_/g,"");if(at.asBigInt){switch(n){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}const s=BigInt(r);return e==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return e==="-"?-1*o:o}function ko(e,t,n){const{value:r}=e;if(mn(r)){const o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return He(e)}const L$=Si.concat([{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Zt,stringify:()=>Zt.nullStr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Je,stringify:Gc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>!1,options:Je,stringify:Gc},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(e,t,n)=>Yn(t,n,2),stringify:e=>ko(e,2,"0b")},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(e,t,n)=>Yn(t,n,8),stringify:e=>ko(e,8,"0")},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(e,t,n)=>Yn(t,n,10),stringify:He},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(e,t,n)=>Yn(t,n,16),stringify:e=>ko(e,16,"0x")},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:He},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify:({value:e})=>Number(e).toExponential()},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(e,t){const n=new Y(parseFloat(e.replace(/_/g,"")));if(t){const r=t.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:He}],Ef,_f,Of,jf,xf,Pf,Tf),U$={core:D$,failsafe:Si,json:Gf,yaml11:L$},B$={binary:Ef,bool:Lf,float:Kf,floatExp:Vf,floatNaN:qf,floatTime:Pf,int:Bf,intHex:Ff,intOct:Uf,intTime:xf,map:In,null:Df,omap:_f,pairs:Of,seq:Ur,set:jf,timestamp:Tf};function F$(e,t,n){if(t){const r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>(r.identify&&r.identify(e)||r.class&&e instanceof r.class)&&!r.format)}function q$(e,t,n){if(e instanceof we)return e;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;t&&t.startsWith("!!")&&(t=r+t.slice(2));let c=F$(e,t,i.tags);if(!c){if(typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object")return a?new Y(e):e;c=e instanceof Map?In:e[Symbol.iterator]?Ur:In}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(e&&typeof e=="object"&&s){const l=s.get(e);if(l){const f=new Ye(l);return n.aliasNodes.push(f),f}u.value=e,s.set(e,u)}return u.node=c.createNode?c.createNode(n.schema,e,n):a?new Y(e):e,t&&u.node instanceof we&&(u.node.tag=t),u.node}function V$(e,t,n,r){let o=e[r.replace(/\W/g,"")];if(!o){const s=Object.keys(e).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${r}"; use one of ${s}`)}if(Array.isArray(n))for(const s of n)o=o.concat(s);else typeof n=="function"&&(o=n(o.slice()));for(let s=0;s<o.length;++s){const i=o[s];if(typeof i=="string"){const a=t[i];if(!a){const c=Object.keys(t).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const K$=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;let xn=class Jf{constructor({customTags:t,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?K$:o||null,!t&&s&&T$("tags","customTags"),this.tags=V$(U$,B$,t||s,r)}createNode(t,n,r,o){const s={defaultPrefix:Jf.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return q$(t,r,i)}createPair(t,n,r){r||(r={wrapScalars:!0});const o=this.createNode(t,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new H(o,s)}};me(xn,"defaultPrefix",cr);me(xn,"defaultTags",rt);const Er={anchorPrefix:"a",customTags:null,indent:2,indentSeq:!0,keepCstNodes:!1,keepNodeTypes:!0,keepBlobsInJSON:!0,mapAsMap:!1,maxAliasCount:100,prettyErrors:!1,simpleKeys:!1,version:"1.2"},G$={get binary(){return wn},set binary(e){Object.assign(wn,e)},get bool(){return Je},set bool(e){Object.assign(Je,e)},get int(){return at},set int(e){Object.assign(at,e)},get null(){return Zt},set null(e){Object.assign(Zt,e)},get str(){return Qe},set str(e){Object.assign(Qe,e)}},Hf={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:cr},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:cr}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:cr}]}};function Jc(e,t){if((e.version||e.options.version)==="1.0"){const o=t.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=t.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${t.replace(/^tag:/,"")}`}let n=e.tagPrefixes.find(o=>t.indexOf(o.prefix)===0);if(!n){const o=e.getDefaults().tagPrefixes;n=o&&o.find(s=>t.indexOf(s.prefix)===0)}if(!n)return t[0]==="!"?t:`!<${t}>`;const r=t.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function J$(e,t){if(t instanceof Ye)return Ye;if(t.tag){const o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)||o[0]}let n,r;if(t instanceof Y){r=t.value;const o=e.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===t.format)||o.find(s=>!s.format)}else r=t,n=e.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){const o=r&&r.constructor?r.constructor.name:typeof r;throw new Error(`Tag not resolved for ${o} value`)}return n}function H$(e,t,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(e);return s&&(n[s]=e,o.push(`&${s}`)),e.tag?o.push(Jc(r,e.tag)):t.default||o.push(Jc(r,t.tag)),o.join(" ")}function Qn(e,t,n,r){const{anchors:o,schema:s}=t.doc;let i;if(!(e instanceof we)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};e=s.createNode(e,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let f=o.getName(l.source);f||(f=o.newName(),o.map[f]=l.source)}}if(e instanceof H)return e.toString(t,n,r);i||(i=J$(s.tags,e));const a=H$(e,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(e,t,n,r):e instanceof Y?bi(e,t,n,r):e.toString(t,n,r);return a?e instanceof Y||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
|
|
145
|
-
${
|
|
146
|
-
`),n.before=[]));if(
|
|
174
|
+
${s.comment}`:o.comment),o=s}n.items[r]=o instanceof le?o:new le(o)}}return n}function Ky(t,e,n){const r=new Dt(t);r.tag="tag:yaml.org,2002:pairs";for(const o of e){let s,i;if(Array.isArray(o))if(o.length===2)s=o[0],i=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const c=Object.keys(o);if(c.length===1)s=c[0],i=o[s];else throw new TypeError(`Expected { key: value } tuple: ${o}`)}else s=o;const a=t.createPair(s,i,n);r.items.push(a)}return r}const Vy={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qy,createNode:Ky};let ya=class Gy extends Dt{constructor(){super(),ze(this,"add",ot.prototype.add.bind(this)),ze(this,"delete",ot.prototype.delete.bind(this)),ze(this,"get",ot.prototype.get.bind(this)),ze(this,"has",ot.prototype.has.bind(this)),ze(this,"set",ot.prototype.set.bind(this)),this.tag=Gy.tag}toJSON(e,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof le?(s=_t(o.key,"",n),i=_t(o.value,s,n)):s=_t(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};ze(ya,"tag","tag:yaml.org,2002:omap");function nO(t,e){const n=qy(t,e),r=[];for(const{key:o}of n.items)if(o instanceof me)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new X(e,s)}else r.push(o.value);return Object.assign(new ya,n)}function rO(t,e,n){const r=Ky(t,e,n),o=new ya;return o.items=r.items,o}const zy={identify:t=>t instanceof Map,nodeClass:ya,default:!1,tag:"tag:yaml.org,2002:omap",resolve:nO,createNode:rO};let wa=class Wy extends ot{constructor(){super(),this.tag=Wy.tag}add(e){const n=e instanceof le?e:new le(e);ar(this.items,n.key)||this.items.push(n)}get(e,n){const r=ar(this.items,e);return!n&&r instanceof le?r.key instanceof me?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=ar(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new le(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(e,n,r);throw new Error("Set items must all have null values")}};ze(wa,"tag","tag:yaml.org,2002:set");function oO(t,e){const n=Uy(t,e);if(!n.hasAllNullValues())throw new X(e,"Set items must all have null values");return Object.assign(new wa,n)}function sO(t,e,n){const r=new wa;for(const o of e)r.items.push(t.createPair(o,null,n));return r}const Hy={identify:t=>t instanceof Set,nodeClass:wa,default:!1,tag:"tag:yaml.org,2002:set",resolve:oO,createNode:sO},Dl=(t,e)=>{const n=e.split(":").reduce((r,o)=>r*60+Number(o),0);return t==="-"?-n:n},Jy=({value:t})=>{if(isNaN(t)||!isFinite(t))return Ht(t);let e="";t<0&&(e="-",t=Math.abs(t));const n=[t%60];return t<60?n.unshift(0):(t=Math.round((t-n[0])/60),n.unshift(t%60),t>=60&&(t=Math.round((t-n[0])/60),n.unshift(t))),e+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},Qy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(t,e,n)=>Dl(e,n.replace(/_/g,"")),stringify:Jy},Yy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(t,e,n)=>Dl(e,n.replace(/_/g,"")),stringify:Jy},Zy={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?)$"),resolve:(t,e,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(e,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=Dl(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function Xy(t){const e=typeof process<"u"&&process.env||{};return t?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!e.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!e.YAML_SILENCE_WARNINGS}function ew(t,e){if(Xy(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(t,e):console.warn(e?`${e}: ${t}`:t)}}const ch={};function iO(t,e){if(!ch[t]&&Xy(!0)){ch[t]=!0;let n=`The option '${t}' will be removed in a future release`;n+=`, use '${e}' instead.`,ew(n,"DeprecationWarning")}}function aO(t,e,n){const r=new ot(t);if(e instanceof Map)for(const[o,s]of e)r.items.push(t.createPair(o,s,n));else if(e&&typeof e=="object")for(const o of Object.keys(e))r.items.push(t.createPair(o,e[o],n));return typeof t.sortMapEntries=="function"&&r.items.sort(t.sortMapEntries),r}const is={createNode:aO,default:!0,nodeClass:ot,tag:"tag:yaml.org,2002:map",resolve:Uy};function cO(t,e,n){const r=new Dt(t);if(e&&e[Symbol.iterator])for(const o of e){const s=t.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const va={createNode:cO,default:!0,nodeClass:Dt,tag:"tag:yaml.org,2002:seq",resolve:By},uO={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Es,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),Ll(t,e,n,r)},options:nn},Ul=[is,va,uO],$a=t=>typeof t=="bigint"||Number.isInteger(t),Bl=(t,e,n)=>Nn.asBigInt?BigInt(t):parseInt(e,n);function tw(t,e,n){const{value:r}=t;return $a(r)&&r>=0?n+r.toString(e):Ht(t)}const nw={identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new me(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Xr,stringify:()=>Xr.nullStr},rw={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>t[0]==="t"||t[0]==="T",options:Wt,stringify:({value:t})=>t?Wt.trueStr:Wt.falseStr},ow={identify:t=>$a(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(t,e)=>Bl(t,e,8),options:Nn,stringify:t=>tw(t,8,"0o")},sw={identify:$a,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:t=>Bl(t,t,10),options:Nn,stringify:Ht},iw={identify:t=>$a(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(t,e)=>Bl(t,e,16),options:Nn,stringify:t=>tw(t,16,"0x")},aw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ht},cw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify:({value:t})=>Number(t).toExponential()},uw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(t,e,n){const r=e||n,o=new me(parseFloat(t));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Ht},lO=Ul.concat([nw,rw,ow,sw,iw,aw,cw,uw]),uh=t=>typeof t=="bigint"||Number.isInteger(t),Ds=({value:t})=>JSON.stringify(t),lw=[is,va,{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Es,stringify:Ds},{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new me(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ds},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:t=>t==="true",stringify:Ds},{identify:uh,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:t=>Nn.asBigInt?BigInt(t):parseInt(t,10),stringify:({value:t})=>uh(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Ds}];lw.scalarFallback=t=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(t)}`)};const lh=({value:t})=>t?Wt.trueStr:Wt.falseStr,jo=t=>typeof t=="bigint"||Number.isInteger(t);function Us(t,e,n){let r=e.replace(/_/g,"");if(Nn.asBigInt){switch(n){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}const s=BigInt(r);return t==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return t==="-"?-1*o:o}function tc(t,e,n){const{value:r}=t;if(jo(r)){const o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return Ht(t)}const dO=Ul.concat([{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new me(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Xr,stringify:()=>Xr.nullStr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Wt,stringify:lh},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>!1,options:Wt,stringify:lh},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(t,e,n)=>Us(e,n,2),stringify:t=>tc(t,2,"0b")},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(t,e,n)=>Us(e,n,8),stringify:t=>tc(t,8,"0")},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(t,e,n)=>Us(e,n,10),stringify:Ht},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(t,e,n)=>Us(e,n,16),stringify:t=>tc(t,16,"0x")},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ht},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify:({value:t})=>Number(t).toExponential()},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(t,e){const n=new me(parseFloat(t.replace(/_/g,"")));if(e){const r=e.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Ht}],Fy,zy,Vy,Hy,Qy,Yy,Zy),fO={core:lO,failsafe:Ul,json:lw,yaml11:dO},pO={binary:Fy,bool:rw,float:uw,floatExp:cw,floatNaN:aw,floatTime:Yy,int:sw,intHex:iw,intOct:ow,intTime:Qy,map:is,null:nw,omap:zy,pairs:Vy,seq:va,set:Hy,timestamp:Zy};function hO(t,e,n){if(e){const r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>(r.identify&&r.identify(t)||r.class&&t instanceof r.class)&&!r.format)}function mO(t,e,n){if(t instanceof nt)return t;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;e&&e.startsWith("!!")&&(e=r+e.slice(2));let c=hO(t,e,i.tags);if(!c){if(typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object")return a?new me(t):t;c=t instanceof Map?is:t[Symbol.iterator]?va:is}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(t&&typeof t=="object"&&s){const l=s.get(t);if(l){const d=new tn(l);return n.aliasNodes.push(d),d}u.value=t,s.set(t,u)}return u.node=c.createNode?c.createNode(n.schema,t,n):a?new me(t):t,e&&u.node instanceof nt&&(u.node.tag=e),u.node}function gO(t,e,n,r){let o=t[r.replace(/\W/g,"")];if(!o){const s=Object.keys(t).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${r}"; use one of ${s}`)}if(Array.isArray(n))for(const s of n)o=o.concat(s);else typeof n=="function"&&(o=n(o.slice()));for(let s=0;s<o.length;++s){const i=o[s];if(typeof i=="string"){const a=e[i];if(!a){const c=Object.keys(e).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const yO=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0;let as=class dw{constructor({customTags:e,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?yO:o||null,!e&&s&&iO("tags","customTags"),this.tags=gO(fO,pO,e||s,r)}createNode(e,n,r,o){const s={defaultPrefix:dw.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return mO(e,r,i)}createPair(e,n,r){r||(r={wrapScalars:!0});const o=this.createNode(e,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new le(o,s)}};ze(as,"defaultPrefix",di);ze(as,"defaultTags",gn);const Vi={anchorPrefix:"a",customTags:null,indent:2,indentSeq:!0,keepCstNodes:!1,keepNodeTypes:!0,keepBlobsInJSON:!0,mapAsMap:!1,maxAliasCount:100,prettyErrors:!1,simpleKeys:!1,version:"1.2"},wO={get binary(){return Uo},set binary(t){Object.assign(Uo,t)},get bool(){return Wt},set bool(t){Object.assign(Wt,t)},get int(){return Nn},set int(t){Object.assign(Nn,t)},get null(){return Xr},set null(t){Object.assign(Xr,t)},get str(){return nn},set str(t){Object.assign(nn,t)}},fw={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:di},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:di}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:di}]}};function dh(t,e){if((t.version||t.options.version)==="1.0"){const o=e.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=e.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${e.replace(/^tag:/,"")}`}let n=t.tagPrefixes.find(o=>e.indexOf(o.prefix)===0);if(!n){const o=t.getDefaults().tagPrefixes;n=o&&o.find(s=>e.indexOf(s.prefix)===0)}if(!n)return e[0]==="!"?e:`!<${e}>`;const r=e.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function vO(t,e){if(e instanceof tn)return tn;if(e.tag){const o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)||o[0]}let n,r;if(e instanceof me){r=e.value;const o=t.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===e.format)||o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){const o=r&&r.constructor?r.constructor.name:typeof r;throw new Error(`Tag not resolved for ${o} value`)}return n}function $O(t,e,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(t);return s&&(n[s]=t,o.push(`&${s}`)),t.tag?o.push(dh(r,t.tag)):e.default||o.push(dh(r,e.tag)),o.join(" ")}function Bs(t,e,n,r){const{anchors:o,schema:s}=e.doc;let i;if(!(t instanceof nt)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};t=s.createNode(t,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let d=o.getName(l.source);d||(d=o.newName(),o.map[d]=l.source)}}if(t instanceof le)return t.toString(e,n,r);i||(i=vO(s.tags,t));const a=$O(t,i,e);a.length>0&&(e.indentAtStart=(e.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(t,e,n,r):t instanceof me?Ll(t,e,n,r):t.toString(e,n,r);return a?t instanceof me||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
|
|
175
|
+
${e.indent}${c}`:c}class Fl{static validAnchorNode(e){return e instanceof me||e instanceof Dt||e instanceof ot}constructor(e){ze(this,"map",Object.create(null)),this.prefix=e}createAlias(e,n){return this.setAnchor(e,n),new tn(e)}createMergePair(...e){const n=new xy;return n.value.items=e.map(r=>{if(r instanceof tn){if(r.source instanceof ot)return r}else if(r instanceof ot)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(e){const{map:n}=this;return Object.keys(n).find(r=>n[r]===e)}getNames(){return Object.keys(this.map)}getNode(e){return this.map[e]}newName(e){e||(e=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${e}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:e,_cstAliases:n}=this;Object.keys(e).forEach(r=>{e[r]=e[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(e,n){if(e!=null&&!Fl.validAnchorNode(e))throw new Error("Anchors may only be set for Scalar, Seq and Map nodes");if(n&&/[\x00-\x19\s,[\]{}]/.test(n))throw new Error("Anchor names must not contain whitespace or control characters");const{map:r}=this,o=e&&Object.keys(r).find(s=>r[s]===e);if(o)if(n)o!==n&&(delete r[o],r[n]=e);else return o;else{if(!n){if(!e)return null;n=this.newName()}r[n]=e}return n}}const gi=(t,e)=>{if(t&&typeof t=="object"){const{tag:n}=t;t instanceof Ue?(n&&(e[n]=!0),t.items.forEach(r=>gi(r,e))):t instanceof le?(gi(t.key,e),gi(t.value,e)):t instanceof me&&n&&(e[n]=!0)}return e},bO=t=>Object.keys(gi(t,{}));function EO(t,e){const n={before:[],after:[]};let r,o=!1;for(const s of e)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";t.errors.push(new Fe(s,a));break}const i=$n(t,s);o&&(i.spaceBefore=!0,o=!1),r=i}else s.comment!==null?(r===void 0?n.before:n.after).push(s.comment):s.type===I.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!t.commentBefore&&(t.commentBefore=n.before.join(`
|
|
176
|
+
`),n.before=[]));if(t.contents=r||null,!r)t.comment=n.before.concat(n.after).join(`
|
|
147
177
|
`)||null;else{const s=n.before.join(`
|
|
148
|
-
`);if(s){const i=r instanceof
|
|
149
|
-
${i.commentBefore}`:s}
|
|
150
|
-
`)||null}}function
|
|
151
|
-
`)||null}function
|
|
178
|
+
`);if(s){const i=r instanceof Ue&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
|
|
179
|
+
${i.commentBefore}`:s}t.comment=n.after.join(`
|
|
180
|
+
`)||null}}function SO({tagPrefixes:t},e){const[n,r]=e.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new X(e,o)}if(t.some(o=>o.handle===n)){const o="The %TAG directive must only be given at most once per handle in the same document.";throw new X(e,o)}return{handle:n,prefix:r}}function _O(t,e){let[n]=e.parameters;if(e.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new X(e,r)}if(!fw[n]){const r=`Document will be parsed as YAML ${t.version||t.options.version} rather than YAML ${n}`;t.warnings.push(new co(e,r))}return n}function NO(t,e,n){const r=[];let o=!1;for(const s of e){const{comment:i,name:a}=s;switch(a){case"TAG":try{t.tagPrefixes.push(SO(t,s))}catch(c){t.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(t.version){const c="The %YAML directive must only be given at most once per document.";t.errors.push(new X(s,c))}try{t.version=_O(t,s)}catch(c){t.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;t.warnings.push(new co(s,c))}}i&&r.push(i)}if(n&&!o&&(t.version||n.version||t.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});t.tagPrefixes=n.tagPrefixes.map(s),t.version=n.version}t.commentBefore=r.join(`
|
|
181
|
+
`)||null}function Or(t){if(t instanceof Ue)return!0;throw new Error("Expected a YAML collection as document contents")}let ql=class iu{constructor(e){this.anchors=new Fl(e.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=e,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(e){return Or(this.contents),this.contents.add(e)}addIn(e,n){Or(this.contents),this.contents.addIn(e,n)}delete(e){return Or(this.contents),this.contents.delete(e)}deleteIn(e){return ko(e)?this.contents==null?!1:(this.contents=null,!0):(Or(this.contents),this.contents.deleteIn(e))}getDefaults(){return iu.defaults[this.version]||iu.defaults[this.options.version]||{}}get(e,n){return this.contents instanceof Ue?this.contents.get(e,n):void 0}getIn(e,n){return ko(e)?!n&&this.contents instanceof me?this.contents.value:this.contents:this.contents instanceof Ue?this.contents.getIn(e,n):void 0}has(e){return this.contents instanceof Ue?this.contents.has(e):!1}hasIn(e){return ko(e)?this.contents!==void 0:this.contents instanceof Ue?this.contents.hasIn(e):!1}set(e,n){Or(this.contents),this.contents.set(e,n)}setIn(e,n){ko(e)?this.contents=n:(Or(this.contents),this.contents.setIn(e,n))}setSchema(e,n){if(!e&&!n&&this.schema)return;typeof e=="number"&&(e=e.toFixed(1)),e==="1.0"||e==="1.1"||e==="1.2"?(this.version?this.version=e:this.options.version=e,delete this.options.schema):e&&typeof e=="string"&&(this.options.schema=e),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new as(r)}parse(e,n){this.options.keepCstNodes&&(this.cstNode=e),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=e;if(i&&(i.source||(i.source=this),this.errors.push(i)),NO(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],EO(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof hr&&c.makePretty();for(const c of this.warnings)c instanceof hr&&c.makePretty()}return this}listNonDefaultTags(){return bO(this.contents).filter(e=>e.indexOf(as.defaultPrefix)!==0)}setTagPrefix(e,n){if(e[0]!=="!"||e[e.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===e);r?r.prefix=n:this.tagPrefixes.push({handle:e,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==e)}toJSON(e,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof e!="string"||!(this.contents instanceof me)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Bs},c=Object.keys(this.anchors.map);c.length>0&&(a.anchors=new Map(c.map(l=>[this.anchors.map[l],{alias:[],aliasCount:0,count:1}])));const u=_t(this.contents,e,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:d}of a.anchors.values())n(d,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const e=this.options.indent;if(!Number.isInteger(e)||e<=0){const c=JSON.stringify(e);throw new Error(`"indent" option must be a positive integer, not ${c}`)}this.setSchema();const n=[];let r=!1;if(this.version){let c="%YAML 1.2";this.schema.name==="yaml-1.1"&&(this.version==="1.0"?c="%YAML:1.0":this.version==="1.1"&&(c="%YAML 1.1")),n.push(c),r=!0}const o=this.listNonDefaultTags();this.tagPrefixes.forEach(({handle:c,prefix:u})=>{o.some(l=>l.indexOf(u)===0)&&(n.push(`%TAG ${c} ${u}`),r=!0)}),(r||this.directivesEndMarker)&&n.push("---"),this.commentBefore&&((r||!this.directivesEndMarker)&&n.unshift(""),n.unshift(this.commentBefore.replace(/^/gm,"#")));const s={anchors:Object.create(null),doc:this,indent:"",indentStep:" ".repeat(e),stringify:Bs};let i=!1,a=null;if(this.contents){this.contents instanceof nt&&(this.contents.spaceBefore&&(r||this.directivesEndMarker)&&n.push(""),this.contents.commentBefore&&n.push(this.contents.commentBefore.replace(/^/gm,"#")),s.forceBlockIndent=!!this.comment,a=this.contents.comment);const c=a?null:()=>i=!0,u=Bs(this.contents,s,()=>a=null,c);n.push(qr(u,"",a))}else this.contents!==void 0&&n.push(Bs(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
|
|
152
182
|
`)+`
|
|
153
|
-
`}};
|
|
154
|
-
`}return`sha256-${
|
|
155
|
-
`);return`sha256-${Yf(t)}`}function mv(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function gv(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function yv(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],s=r.split(".");let i=t;s.forEach((a,c)=>{if(c===s.length-1){i.properties[a]=$v(o);return}const u=i.properties[a];if(u===void 0){const l={type:"object",properties:{}};i.properties[a]=l,i=l}else i=u})}return t}function $v(e){const t={type:e.type};return e.default!==void 0&&e.secret!==!0&&(t.default=e.default),e.description!==void 0&&(t.description=e.description),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.enum!==void 0&&(t.enum=e.enum),e.pattern!==void 0&&(t.pattern=e.pattern),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.items!==void 0&&(t.items=e.items),t}const vv="adhd-env-ref:";function wv(e){return`${vv}${e}`}const bv=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Ev=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Re(e,t){return(e>>>t|e<<32-t)>>>0}function Sv(e){const t=Uint32Array.from(Ev),n=e.length*8;let r=e.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(e),o[e.length]=128;const s=Math.floor(n/4294967296),i=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,s,!1),a.setUint32(r-4,i,!1);const c=new Uint32Array(64);for(let f=0;f<r;f+=64){for(let b=0;b<16;b++)c[b]=a.getUint32(f+b*4,!1);for(let b=16;b<64;b++){const N=c[b-15],j=c[b-2],R=Re(N,7)^Re(N,18)^N>>>3,J=Re(j,17)^Re(j,19)^j>>>10;c[b]=c[b-16]+R+c[b-7]+J>>>0}let p=t[0],h=t[1],d=t[2],m=t[3],y=t[4],$=t[5],v=t[6],E=t[7];for(let b=0;b<64;b++){const N=Re(y,6)^Re(y,11)^Re(y,25),j=y&$^~y&v,R=E+N+j+bv[b]+c[b]>>>0,J=Re(p,2)^Re(p,13)^Re(p,22),U=p&h^p&d^h&d,q=J+U>>>0;E=v,v=$,$=y,y=m+R>>>0,m=d,d=h,h=p,p=R+q>>>0}t[0]=t[0]+p>>>0,t[1]=t[1]+h>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+m>>>0,t[4]=t[4]+y>>>0,t[5]=t[5]+$>>>0,t[6]=t[6]+v>>>0,t[7]=t[7]+E>>>0}const u=new Uint8Array(32),l=new DataView(u.buffer);for(let f=0;f<8;f++)l.setUint32(f*4,t[f],!1);return u}function Nv(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function Yf(e){const t=new TextEncoder().encode(e);return Nv(Sv(t))}function Qf(e,t=""){const n={};if(e===null||typeof e!="object"||Array.isArray(e))return t&&(n[t]=e),n;for(const[r,o]of Object.entries(e)){const s=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,Qf(o,s)):n[s]=o}return n}function Zn(e){if(C.existsSync(e))try{const t=C.readFileSync(e,"utf8"),n=iv.parse(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:Qf(n)}catch{return}}function Ov(e){return{system:Zn(T.join(e.system,_o)),global:Zn(T.join(e.global,_o)),project:e.project?Zn(T.join(e.project,_o)):void 0,local:e.project?Zn(T.join(e.project,fv)):void 0}}function kv(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function ys(e,t){if(e===void 0)return e;switch(t){case"integer":{if(typeof e=="number")return e;const n=parseInt(String(e),10);return Number.isNaN(n)?e:n}case"number":{if(typeof e=="number")return e;const n=parseFloat(String(e));return Number.isNaN(n)?e:n}case"boolean":{if(typeof e=="boolean")return e;const n=String(e).toLowerCase();return n==="true"?!0:n==="false"?!1:e}case"array":return Array.isArray(e)?e:typeof e=="string"?e.length===0?[]:e.split(",").map(n=>n.trim()):e;case"string":return typeof e=="string"?e:String(e);default:return e}}function Zf(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((s,i)=>{if(i===r.length-1){o[s]=e[n];return}const a=o[s];(typeof a!="object"||a===null||Array.isArray(a))&&(o[s]={}),o=o[s]})}return t}const _v=[["system","system"],["global","global"],["project","project"],["local","local"]];function Av(e,t,n,r){const o={},s={},i={},a={};for(const c of Object.keys(e)){const u=e[c],l=u.env&&u.env!==""?u.env:gv(r.prefix,c),f=u.at==="runtime"||u.secret===!0,p=u.scope??r.activeScope;let h=u.default,d="default";for(const[E,b]of _v){const N=t[E];N&&Object.prototype.hasOwnProperty.call(N,c)&&(h=ys(N[c],u.type),d=b)}const m=n[l];let y,$,v;m!==void 0?(y=ys(m,u.type),$="env",v=l):(y=h,$=d),o[c]=f?wv(l):y,s[c]=y,i[c]=kv(f?{source:"env",scope:p,env:l}:{source:$,scope:p,env:v}),a[c]={...u,env:l,live:f,fallbackValue:h}}return{raw:o,nested:Zf(o),typedRaw:s,provenance:i,fields:a}}function jv(e,t){return e.replace(/\$\{HOME\}/g,Ue.homedir()).replace(/\$HOME\b/g,Ue.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function Iv(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=o.scope??t.activeScope,i=o.share??dv[o.kind],a=o.path?jv(o.path,t):T.join(of(t.roots,s),r),c=i==="per-instance"?T.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function xv(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=t[o.in];if(!s)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:T.join(s.path,o.name),share:o.share??"shared"}}return n}var $s={exports:{}},Xf={},Ce={},Xt={},Fn={},G={},Pn={};(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(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((E,b)=>`${E}${b}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((E,b)=>(b instanceof n&&(E[b.str]=(E[b.str]||0)+1),E),{})}}e._Code=r,e.nil=new r("");function o($,...v){const E=[$[0]];let b=0;for(;b<v.length;)a(E,v[b]),E.push($[++b]);return new r(E)}e._=o;const s=new r("+");function i($,...v){const E=[h($[0])];let b=0;for(;b<v.length;)E.push(s),a(E,v[b]),E.push(s,h($[++b]));return c(E),new r(E)}e.str=i;function a($,v){v instanceof r?$.push(...v._items):v instanceof n?$.push(v):$.push(f(v))}e.addCodeArg=a;function c($){let v=1;for(;v<$.length-1;){if($[v]===s){const E=u($[v-1],$[v+1]);if(E!==void 0){$.splice(v-1,3,E);continue}$[v++]="+"}v++}}function u($,v){if(v==='""')return $;if($==='""')return v;if(typeof $=="string")return v instanceof n||$[$.length-1]!=='"'?void 0:typeof v!="string"?`${$.slice(0,-1)}${v}"`:v[0]==='"'?$.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!($ instanceof n))return`"${$}${v.slice(1)}`}function l($,v){return v.emptyStr()?$:$.emptyStr()?v:i`${$}${v}`}e.strConcat=l;function f($){return typeof $=="number"||typeof $=="boolean"||$===null?$:h(Array.isArray($)?$.join(","):$)}function p($){return new r(h($))}e.stringify=p;function h($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function d($){return typeof $=="string"&&e.IDENTIFIER.test($)?new r(`.${$}`):o`[${$}]`}e.getProperty=d;function m($){if(typeof $=="string"&&e.IDENTIFIER.test($))return new r(`${$}`);throw new Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}e.getEsmExportName=m;function y($){return new r($.toString())}e.regexpCode=y})(Pn);var vs={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Pn;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 o{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=o;class s 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=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,l){var f;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:h}=p,d=(f=l.key)!==null&&f!==void 0?f:l.ref;let m=this._values[h];if(m){const v=m.get(d);if(v)return v}else m=this._values[h]=new Map;m.set(d,p);const y=this._scope[h]||(this._scope[h]=[]),$=y.length;return y[$]=l.ref,p.setValue(l,{property:h,itemIndex:$}),p}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,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,f)}_reduceValues(u,l,f={},p){let h=t.nil;for(const d in u){const m=u[d];if(!m)continue;const y=f[d]=f[d]||new Map;m.forEach($=>{if(y.has($))return;y.set($,r.Started);let v=l($);if(v){const E=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${E} ${$} = ${v};${this.opts._n}`}else if(v=p==null?void 0:p($))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new n($);y.set($,r.Completed)})}return h}}e.ValueScope=a})(vs);(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=Pn,n=vs;var r=Pn;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 o=vs;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(g,w){return this}}class i extends s{constructor(g,w,k){super(),this.varKind=g,this.name=w,this.rhs=k}render({es5:g,_n:w}){const k=g?n.varKinds.var:this.varKind,D=this.rhs===void 0?"":` = ${this.rhs}`;return`${k} ${this.name}${D};`+w}optimizeNames(g,w){if(g[this.name.str])return this.rhs&&(this.rhs=_e(this.rhs,g,w)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(g,w,k){super(),this.lhs=g,this.rhs=w,this.sideEffects=k}render({_n:g}){return`${this.lhs} = ${this.rhs};`+g}optimizeNames(g,w){if(!(this.lhs instanceof t.Name&&!g[this.lhs.str]&&!this.sideEffects))return this.rhs=_e(this.rhs,g,w),this}get names(){const g=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ye(g,this.rhs)}}class c extends a{constructor(g,w,k,D){super(g,k,D),this.op=w}render({_n:g}){return`${this.lhs} ${this.op}= ${this.rhs};`+g}}class u extends s{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`${this.label}:`+g}}class l extends s{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`break${this.label?` ${this.label}`:""};`+g}}class f extends s{constructor(g){super(),this.error=g}render({_n:g}){return`throw ${this.error};`+g}get names(){return this.error.names}}class p extends s{constructor(g){super(),this.code=g}render({_n:g}){return`${this.code};`+g}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(g,w){return this.code=_e(this.code,g,w),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(g=[]){super(),this.nodes=g}render(g){return this.nodes.reduce((w,k)=>w+k.render(g),"")}optimizeNodes(){const{nodes:g}=this;let w=g.length;for(;w--;){const k=g[w].optimizeNodes();Array.isArray(k)?g.splice(w,1,...k):k?g[w]=k:g.splice(w,1)}return g.length>0?this:void 0}optimizeNames(g,w){const{nodes:k}=this;let D=k.length;for(;D--;){const L=k[D];L.optimizeNames(g,w)||(Ve(g,L.names),k.splice(D,1))}return k.length>0?this:void 0}get names(){return this.nodes.reduce((g,w)=>Z(g,w.names),{})}}class d extends h{render(g){return"{"+g._n+super.render(g)+"}"+g._n}}class m extends h{}class y extends d{}y.kind="else";class $ extends d{constructor(g,w){super(w),this.condition=g}render(g){let w=`if(${this.condition})`+super.render(g);return this.else&&(w+="else "+this.else.render(g)),w}optimizeNodes(){super.optimizeNodes();const g=this.condition;if(g===!0)return this.nodes;let w=this.else;if(w){const k=w.optimizeNodes();w=this.else=Array.isArray(k)?new y(k):k}if(w)return g===!1?w instanceof $?w:w.nodes:this.nodes.length?this:new $(pe(g),w instanceof $?[w]:w.nodes);if(!(g===!1||!this.nodes.length))return this}optimizeNames(g,w){var k;if(this.else=(k=this.else)===null||k===void 0?void 0:k.optimizeNames(g,w),!!(super.optimizeNames(g,w)||this.else))return this.condition=_e(this.condition,g,w),this}get names(){const g=super.names;return ye(g,this.condition),this.else&&Z(g,this.else.names),g}}$.kind="if";class v extends d{}v.kind="for";class E extends v{constructor(g){super(),this.iteration=g}render(g){return`for(${this.iteration})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iteration=_e(this.iteration,g,w),this}get names(){return Z(super.names,this.iteration.names)}}class b extends v{constructor(g,w,k,D){super(),this.varKind=g,this.name=w,this.from=k,this.to=D}render(g){const w=g.es5?n.varKinds.var:this.varKind,{name:k,from:D,to:L}=this;return`for(${w} ${k}=${D}; ${k}<${L}; ${k}++)`+super.render(g)}get names(){const g=ye(super.names,this.from);return ye(g,this.to)}}class N extends v{constructor(g,w,k,D){super(),this.loop=g,this.varKind=w,this.name=k,this.iterable=D}render(g){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iterable=_e(this.iterable,g,w),this}get names(){return Z(super.names,this.iterable.names)}}class j extends d{constructor(g,w,k){super(),this.name=g,this.args=w,this.async=k}render(g){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(g)}}j.kind="func";class R extends h{render(g){return"return "+super.render(g)}}R.kind="return";class J extends d{render(g){let w="try"+super.render(g);return this.catch&&(w+=this.catch.render(g)),this.finally&&(w+=this.finally.render(g)),w}optimizeNodes(){var g,w;return super.optimizeNodes(),(g=this.catch)===null||g===void 0||g.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(g,w){var k,D;return super.optimizeNames(g,w),(k=this.catch)===null||k===void 0||k.optimizeNames(g,w),(D=this.finally)===null||D===void 0||D.optimizeNames(g,w),this}get names(){const g=super.names;return this.catch&&Z(g,this.catch.names),this.finally&&Z(g,this.finally.names),g}}class U extends d{constructor(g){super(),this.error=g}render(g){return`catch(${this.error})`+super.render(g)}}U.kind="catch";class q extends d{render(g){return"finally"+super.render(g)}}q.kind="finally";class Q{constructor(g,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
156
|
-
`:""},this._extScope=g,this._scope=new n.Scope({parent:g}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(g){return this._scope.name(g)}scopeName(g){return this._extScope.name(g)}scopeValue(g,w){const k=this._extScope.value(g,w);return(this._values[k.prefix]||(this._values[k.prefix]=new Set)).add(k),k}getScopeValue(g,w){return this._extScope.getValue(g,w)}scopeRefs(g){return this._extScope.scopeRefs(g,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(g,w,k,D){const L=this._scope.toName(w);return k!==void 0&&D&&(this._constants[L.str]=k),this._leafNode(new i(g,L,k)),L}const(g,w,k){return this._def(n.varKinds.const,g,w,k)}let(g,w,k){return this._def(n.varKinds.let,g,w,k)}var(g,w,k){return this._def(n.varKinds.var,g,w,k)}assign(g,w,k){return this._leafNode(new a(g,w,k))}add(g,w){return this._leafNode(new c(g,e.operators.ADD,w))}code(g){return typeof g=="function"?g():g!==t.nil&&this._leafNode(new p(g)),this}object(...g){const w=["{"];for(const[k,D]of g)w.length>1&&w.push(","),w.push(k),(k!==D||this.opts.es5)&&(w.push(":"),(0,t.addCodeArg)(w,D));return w.push("}"),new t._Code(w)}if(g,w,k){if(this._blockNode(new $(g)),w&&k)this.code(w).else().code(k).endIf();else if(w)this.code(w).endIf();else if(k)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(g){return this._elseNode(new $(g))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode($,y)}_for(g,w){return this._blockNode(g),w&&this.code(w).endFor(),this}for(g,w){return this._for(new E(g),w)}forRange(g,w,k,D,L=this.opts.es5?n.varKinds.var:n.varKinds.let){const W=this._scope.toName(g);return this._for(new b(L,W,w,k),()=>D(W))}forOf(g,w,k,D=n.varKinds.const){const L=this._scope.toName(g);if(this.opts.es5){const W=w instanceof t.Name?w:this.var("_arr",w);return this.forRange("_i",0,(0,t._)`${W}.length`,z=>{this.var(L,(0,t._)`${W}[${z}]`),k(L)})}return this._for(new N("of",D,L,w),()=>k(L))}forIn(g,w,k,D=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(g,(0,t._)`Object.keys(${w})`,k);const L=this._scope.toName(g);return this._for(new N("in",D,L,w),()=>k(L))}endFor(){return this._endBlockNode(v)}label(g){return this._leafNode(new u(g))}break(g){return this._leafNode(new l(g))}return(g){const w=new R;if(this._blockNode(w),this.code(g),w.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(R)}try(g,w,k){if(!w&&!k)throw new Error('CodeGen: "try" without "catch" and "finally"');const D=new J;if(this._blockNode(D),this.code(g),w){const L=this.name("e");this._currNode=D.catch=new U(L),w(L)}return k&&(this._currNode=D.finally=new q,this.code(k)),this._endBlockNode(U,q)}throw(g){return this._leafNode(new f(g))}block(g,w){return this._blockStarts.push(this._nodes.length),g&&this.code(g).endBlock(w),this}endBlock(g){const w=this._blockStarts.pop();if(w===void 0)throw new Error("CodeGen: not in self-balancing block");const k=this._nodes.length-w;if(k<0||g!==void 0&&k!==g)throw new Error(`CodeGen: wrong number of nodes: ${k} vs ${g} expected`);return this._nodes.length=w,this}func(g,w=t.nil,k,D){return this._blockNode(new j(g,w,k)),D&&this.code(D).endFunc(),this}endFunc(){return this._endBlockNode(j)}optimize(g=1){for(;g-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(g){return this._currNode.nodes.push(g),this}_blockNode(g){this._currNode.nodes.push(g),this._nodes.push(g)}_endBlockNode(g,w){const k=this._currNode;if(k instanceof g||w&&k instanceof w)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${w?`${g.kind}/${w.kind}`:g.kind}"`)}_elseNode(g){const w=this._currNode;if(!(w instanceof $))throw new Error('CodeGen: "else" without "if"');return this._currNode=w.else=g,this}get _root(){return this._nodes[0]}get _currNode(){const g=this._nodes;return g[g.length-1]}set _currNode(g){const w=this._nodes;w[w.length-1]=g}}e.CodeGen=Q;function Z(O,g){for(const w in g)O[w]=(O[w]||0)+(g[w]||0);return O}function ye(O,g){return g instanceof t._CodeOrName?Z(O,g.names):O}function _e(O,g,w){if(O instanceof t.Name)return k(O);if(!D(O))return O;return new t._Code(O._items.reduce((L,W)=>(W instanceof t.Name&&(W=k(W)),W instanceof t._Code?L.push(...W._items):L.push(W),L),[]));function k(L){const W=w[L.str];return W===void 0||g[L.str]!==1?L:(delete g[L.str],W)}function D(L){return L instanceof t._Code&&L._items.some(W=>W instanceof t.Name&&g[W.str]===1&&w[W.str]!==void 0)}}function Ve(O,g){for(const w in g)O[w]=(O[w]||0)-(g[w]||0)}function pe(O){return typeof O=="boolean"||typeof O=="number"||O===null?!O:(0,t._)`!${A(O)}`}e.not=pe;const cn=S(e.operators.AND);function no(...O){return O.reduce(cn)}e.and=no;const Kn=S(e.operators.OR);function x(...O){return O.reduce(Kn)}e.or=x;function S(O){return(g,w)=>g===t.nil?w:w===t.nil?g:(0,t._)`${A(g)} ${O} ${A(w)}`}function A(O){return O instanceof t.Name?O:(0,t._)`(${O})`}})(G);var P={};Object.defineProperty(P,"__esModule",{value:!0});P.checkStrictMode=P.getErrorPath=P.Type=P.useFunc=P.setEvaluated=P.evaluatedPropsToName=P.mergeEvaluated=P.eachItem=P.unescapeJsonPointer=P.escapeJsonPointer=P.escapeFragment=P.unescapeFragment=P.schemaRefOrVal=P.schemaHasRulesButRef=P.schemaHasRules=P.checkUnknownRules=P.alwaysValidSchema=P.toHash=void 0;const X=G,Pv=Pn;function Tv(e){const t={};for(const n of e)t[n]=!0;return t}P.toHash=Tv;function Cv(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(ed(e,t),!td(t,e.self.RULES.all))}P.alwaysValidSchema=Cv;function ed(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const o=r.RULES.keywords;for(const s in t)o[s]||od(e,`unknown keyword: "${s}"`)}P.checkUnknownRules=ed;function td(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}P.schemaHasRules=td;function Rv(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}P.schemaHasRulesButRef=Rv;function Mv({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,X._)`${n}`}return(0,X._)`${e}${t}${(0,X.getProperty)(r)}`}P.schemaRefOrVal=Mv;function Dv(e){return nd(decodeURIComponent(e))}P.unescapeFragment=Dv;function Lv(e){return encodeURIComponent(_i(e))}P.escapeFragment=Lv;function _i(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}P.escapeJsonPointer=_i;function nd(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}P.unescapeJsonPointer=nd;function Uv(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}P.eachItem=Uv;function Yc({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof X.Name?(s instanceof X.Name?e(o,s,i):t(o,s,i),i):s instanceof X.Name?(t(o,i,s),s):n(s,i);return a===X.Name&&!(c instanceof X.Name)?r(o,c):c}}P.mergeEvaluated={props:Yc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,X._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,X._)`${n} || {}`).code((0,X._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,X._)`${n} || {}`),Ai(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:rd}),items:Yc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,X._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,X._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function rd(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,X._)`{}`);return t!==void 0&&Ai(e,n,t),n}P.evaluatedPropsToName=rd;function Ai(e,t,n){Object.keys(n).forEach(r=>e.assign((0,X._)`${t}${(0,X.getProperty)(r)}`,!0))}P.setEvaluated=Ai;const Qc={};function Bv(e,t){return e.scopeValue("func",{ref:t,code:Qc[t.code]||(Qc[t.code]=new Pv._Code(t.code))})}P.useFunc=Bv;var ws;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ws||(P.Type=ws={}));function Fv(e,t,n){if(e instanceof X.Name){const r=t===ws.Num;return n?r?(0,X._)`"[" + ${e} + "]"`:(0,X._)`"['" + ${e} + "']"`:r?(0,X._)`"/" + ${e}`:(0,X._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,X.getProperty)(e).toString():"/"+_i(e)}P.getErrorPath=Fv;function od(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}P.checkStrictMode=od;var Fe={};Object.defineProperty(Fe,"__esModule",{value:!0});const he=G,qv={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};Fe.default=qv;(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=G,n=P,r=Fe;e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:$})=>$?(0,t.str)`"${y}" keyword must be ${$} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,$=e.keywordError,v,E){const{it:b}=y,{gen:N,compositeRule:j,allErrors:R}=b,J=f(y,$,v);E??(j||R)?c(N,J):u(b,(0,t._)`[${J}]`)}e.reportError=o;function s(y,$=e.keywordError,v){const{it:E}=y,{gen:b,compositeRule:N,allErrors:j}=E,R=f(y,$,v);c(b,R),N||j||u(E,r.default.vErrors)}e.reportExtraError=s;function i(y,$){y.assign(r.default.errors,$),y.if((0,t._)`${r.default.vErrors} !== null`,()=>y.if($,()=>y.assign((0,t._)`${r.default.vErrors}.length`,$),()=>y.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:y,keyword:$,schemaValue:v,data:E,errsCount:b,it:N}){if(b===void 0)throw new Error("ajv implementation error");const j=y.name("err");y.forRange("i",b,r.default.errors,R=>{y.const(j,(0,t._)`${r.default.vErrors}[${R}]`),y.if((0,t._)`${j}.instancePath === undefined`,()=>y.assign((0,t._)`${j}.instancePath`,(0,t.strConcat)(r.default.instancePath,N.errorPath))),y.assign((0,t._)`${j}.schemaPath`,(0,t.str)`${N.errSchemaPath}/${$}`),N.opts.verbose&&(y.assign((0,t._)`${j}.schema`,v),y.assign((0,t._)`${j}.data`,E))})}e.extendErrors=a;function c(y,$){const v=y.const("err",$);y.if((0,t._)`${r.default.vErrors} === null`,()=>y.assign(r.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${r.default.vErrors}.push(${v})`),y.code((0,t._)`${r.default.errors}++`)}function u(y,$){const{gen:v,validateName:E,schemaEnv:b}=y;b.$async?v.throw((0,t._)`new ${y.ValidationError}(${$})`):(v.assign((0,t._)`${E}.errors`,$),v.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,$,v){const{createErrors:E}=y.it;return E===!1?(0,t._)`{}`:p(y,$,v)}function p(y,$,v={}){const{gen:E,it:b}=y,N=[h(b,v),d(y,v)];return m(y,$,N),E.object(...N)}function h({errorPath:y},{instancePath:$}){const v=$?(0,t.str)`${y}${(0,n.getErrorPath)($,n.Type.Str)}`:y;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,v)]}function d({keyword:y,it:{errSchemaPath:$}},{schemaPath:v,parentSchema:E}){let b=E?$:(0,t.str)`${$}/${y}`;return v&&(b=(0,t.str)`${b}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,b]}function m(y,{params:$,message:v},E){const{keyword:b,data:N,schemaValue:j,it:R}=y,{opts:J,propertyName:U,topSchemaRef:q,schemaPath:Q}=R;E.push([l.keyword,b],[l.params,typeof $=="function"?$(y):$||(0,t._)`{}`]),J.messages&&E.push([l.message,typeof v=="function"?v(y):v]),J.verbose&&E.push([l.schema,j],[l.parentSchema,(0,t._)`${q}${Q}`],[r.default.data,N]),U&&E.push([l.propertyName,U])}})(Fn);Object.defineProperty(Xt,"__esModule",{value:!0});Xt.boolOrEmptySchema=Xt.topBoolOrEmptySchema=void 0;const Vv=Fn,Kv=G,Gv=Fe,Jv={message:"boolean schema is false"};function Hv(e){const{gen:t,schema:n,validateName:r}=e;n===!1?sd(e,!1):typeof n=="object"&&n.$async===!0?t.return(Gv.default.data):(t.assign((0,Kv._)`${r}.errors`,null),t.return(!0))}Xt.topBoolOrEmptySchema=Hv;function zv(e,t){const{gen:n,schema:r}=e;r===!1?(n.var(t,!1),sd(e)):n.var(t,!0)}Xt.boolOrEmptySchema=zv;function sd(e,t){const{gen:n,data:r}=e,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Vv.reportError)(o,Jv,void 0,t)}var ie={},It={};Object.defineProperty(It,"__esModule",{value:!0});It.getRules=It.isJSONType=void 0;const Wv=["string","number","integer","boolean","null","object","array"],Yv=new Set(Wv);function Qv(e){return typeof e=="string"&&Yv.has(e)}It.isJSONType=Qv;function Zv(){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:{}}}It.getRules=Zv;var ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.shouldUseRule=ze.shouldUseGroup=ze.schemaHasRulesForType=void 0;function Xv({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&id(e,r)}ze.schemaHasRulesForType=Xv;function id(e,t){return t.rules.some(n=>ad(e,n))}ze.shouldUseGroup=id;function ad(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}ze.shouldUseRule=ad;Object.defineProperty(ie,"__esModule",{value:!0});ie.reportTypeError=ie.checkDataTypes=ie.checkDataType=ie.coerceAndCheckDataType=ie.getJSONTypes=ie.getSchemaTypes=ie.DataType=void 0;const e0=It,t0=ze,n0=Fn,V=G,cd=P;var Wt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Wt||(ie.DataType=Wt={}));function r0(e){const t=ud(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}ie.getSchemaTypes=r0;function ud(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(e0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ie.getJSONTypes=ud;function o0(e,t){const{gen:n,data:r,opts:o}=e,s=s0(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,t0.schemaHasRulesForType)(e,t[0]));if(i){const a=ji(t,r,o.strictNumbers,Wt.Wrong);n.if(a,()=>{s.length?i0(e,t,s):Ii(e)})}return i}ie.coerceAndCheckDataType=o0;const ld=new Set(["string","number","integer","boolean","null"]);function s0(e,t){return t?e.filter(n=>ld.has(n)||t==="array"&&n==="array"):[]}function i0(e,t,n){const{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,V._)`typeof ${o}`),a=r.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&r.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(ji(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,V._)`${a} !== undefined`);for(const u of n)(ld.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Ii(e),r.endIf(),r.if((0,V._)`${a} !== undefined`,()=>{r.assign(o,a),a0(e,a)});function c(u){switch(u){case"string":r.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":r.elseIf((0,V._)`${i} == "boolean" || ${o} === null
|
|
157
|
-
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,
|
|
158
|
-
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,
|
|
159
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function a0({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,V._)`${t} !== undefined`,()=>e.assign((0,V._)`${t}[${n}]`,r))}function bs(e,t,n,r=Wt.Correct){const o=r===Wt.Correct?V.operators.EQ:V.operators.NEQ;let s;switch(e){case"null":return(0,V._)`${t} ${o} null`;case"array":s=(0,V._)`Array.isArray(${t})`;break;case"object":s=(0,V._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,V._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${t} ${o} ${e}`}return r===Wt.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${t} == "number"`,a,n?(0,V._)`isFinite(${t})`:V.nil)}}ie.checkDataType=bs;function ji(e,t,n,r){if(e.length===1)return bs(e[0],t,n,r);let o;const s=(0,cd.toHash)(e);if(s.array&&s.object){const i=(0,V._)`typeof ${t} != "object"`;o=s.null?i:(0,V._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(const i in s)o=(0,V.and)(o,bs(i,t,n,r));return o}ie.checkDataTypes=ji;const c0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,V._)`{type: ${e}}`:(0,V._)`{type: ${t}}`};function Ii(e){const t=u0(e);(0,n0.reportError)(t,c0)}ie.reportTypeError=Ii;function u0(e){const{gen:t,data:n,schema:r}=e,o=(0,cd.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var qr={};Object.defineProperty(qr,"__esModule",{value:!0});qr.assignDefaults=void 0;const Rt=G,l0=P;function f0(e,t){const{properties:n,items:r}=e.schema;if(t==="object"&&n)for(const o in n)Zc(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Zc(e,s,o.default))}qr.assignDefaults=f0;function Zc(e,t,n){const{gen:r,compositeRule:o,data:s,opts:i}=e;if(n===void 0)return;const a=(0,Rt._)`${s}${(0,Rt.getProperty)(t)}`;if(o){(0,l0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Rt._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Rt._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Rt._)`${a} = ${(0,Rt.stringify)(n)}`)}var De={},K={};Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;const ee=G,xi=P,Xe=Fe,d0=P;function p0(e,t){const{gen:n,data:r,it:o}=e;n.if(Ti(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=p0;function h0({gen:e,data:t,it:{opts:n}},r,o){return(0,ee.or)(...r.map(s=>(0,ee.and)(Ti(e,t,s,n.ownProperties),(0,ee._)`${o} = ${s}`)))}K.checkMissingProp=h0;function m0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=m0;function fd(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=fd;function Pi(e,t,n){return(0,ee._)`${fd(e)}.call(${t}, ${n})`}K.isOwnProperty=Pi;function g0(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} !== undefined`;return r?(0,ee._)`${o} && ${Pi(e,t,n)}`:o}K.propertyInData=g0;function Ti(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} === undefined`;return r?(0,ee.or)(o,(0,ee.not)(Pi(e,t,n))):o}K.noPropertyInData=Ti;function dd(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=dd;function y0(e,t){return dd(t).filter(n=>!(0,xi.alwaysValidSchema)(e,t[n]))}K.schemaProperties=y0;function $0({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,ee._)`${e}, ${t}, ${r}${o}`:t,f=[[Xe.default.instancePath,(0,ee.strConcat)(Xe.default.instancePath,s)],[Xe.default.parentData,i.parentData],[Xe.default.parentDataProperty,i.parentDataProperty],[Xe.default.rootData,Xe.default.rootData]];i.opts.dynamicRef&&f.push([Xe.default.dynamicAnchors,Xe.default.dynamicAnchors]);const p=(0,ee._)`${l}, ${n.object(...f)}`;return c!==ee.nil?(0,ee._)`${a}.call(${c}, ${p})`:(0,ee._)`${a}(${p})`}K.callValidateCode=$0;const v0=(0,ee._)`new RegExp`;function w0({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ee._)`${o.code==="new RegExp"?v0:(0,d0.useFunc)(e,o)}(${n}, ${r})`})}K.usePattern=w0;function b0(e){const{gen:t,data:n,keyword:r,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,ee._)`${n}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:r,dataProp:u,dataPropType:xi.Type.Num},s),t.if((0,ee.not)(s),a)})}}K.validateArray=b0;function E0(e){const{gen:t,schema:n,keyword:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,xi.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=t.let("valid",!1),i=t.name("_valid");t.block(()=>n.forEach((a,c)=>{const u=e.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);t.assign(s,(0,ee._)`${s} || ${i}`),e.mergeValidEvaluated(u,i)||t.if((0,ee.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=E0;Object.defineProperty(De,"__esModule",{value:!0});De.validateKeywordUsage=De.validSchemaType=De.funcKeywordCode=De.macroKeywordCode=void 0;const $e=G,$t=Fe,S0=K,N0=Fn;function O0(e,t){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=pd(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");e.subschema({schema:a,schemaPath:$e.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}De.macroKeywordCode=O0;function k0(e,t){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;A0(c,t);const u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=pd(r,o,u),f=r.let("valid");e.block$data(f,p),e.ok((n=t.valid)!==null&&n!==void 0?n:f);function p(){if(t.errors===!1)m(),t.modifying&&Xc(e),y(()=>e.error());else{const $=t.async?h():d();t.modifying&&Xc(e),y(()=>_0(e,$))}}function h(){const $=r.let("ruleErrs",null);return r.try(()=>m((0,$e._)`await `),v=>r.assign(f,!1).if((0,$e._)`${v} instanceof ${c.ValidationError}`,()=>r.assign($,(0,$e._)`${v}.errors`),()=>r.throw(v))),$}function d(){const $=(0,$e._)`${l}.errors`;return r.assign($,null),m($e.nil),$}function m($=t.async?(0,$e._)`await `:$e.nil){const v=c.opts.passContext?$t.default.this:$t.default.self,E=!("compile"in t&&!a||t.schema===!1);r.assign(f,(0,$e._)`${$}${(0,S0.callValidateCode)(e,l,v,E)}`,t.modifying)}function y($){var v;r.if((0,$e.not)((v=t.valid)!==null&&v!==void 0?v:f),$)}}De.funcKeywordCode=k0;function Xc(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,$e._)`${r.parentData}[${r.parentDataProperty}]`))}function _0(e,t){const{gen:n}=e;n.if((0,$e._)`Array.isArray(${t})`,()=>{n.assign($t.default.vErrors,(0,$e._)`${$t.default.vErrors} === null ? ${t} : ${$t.default.vErrors}.concat(${t})`).assign($t.default.errors,(0,$e._)`${$t.default.vErrors}.length`),(0,N0.extendErrors)(e)},()=>e.error())}function A0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function pd(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,$e.stringify)(n)})}function j0(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}De.validSchemaType=j0;function I0({schema:e,opts:t,self:n,errSchemaPath:r},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 a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}De.validateKeywordUsage=I0;var it={};Object.defineProperty(it,"__esModule",{value:!0});it.extendSubschemaMode=it.extendSubschemaData=it.getSubschema=void 0;const Me=G,hd=P;function x0(e,{keyword:t,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){const a=e.schema[t];return n===void 0?{schema:a,schemaPath:(0,Me._)`${e.schemaPath}${(0,Me.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,Me._)`${e.schemaPath}${(0,Me.getProperty)(t)}${(0,Me.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,hd.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}it.getSubschema=x0;function P0(e,t,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=t;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:f}=t,p=a.let("data",(0,Me._)`${t.data}${(0,Me.getProperty)(n)}`,!0);c(p),e.errorPath=(0,Me.str)`${u}${(0,hd.getErrorPath)(n,r,f.jsPropertySyntax)}`,e.parentDataProperty=(0,Me._)`${n}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){const u=o instanceof Me.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]}}it.extendSubschemaData=P0;function T0(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(e.compositeRule=r),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}it.extendSubschemaMode=T0;var le={},md=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,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))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(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n},gd={exports:{}},ot=gd.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};pr(t,r,o,e,"",e)};ot.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ot.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ot.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ot.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 pr(e,t,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,i,a,c,u);for(var l in r){var f=r[l];if(Array.isArray(f)){if(l in ot.arrayKeywords)for(var p=0;p<f.length;p++)pr(e,t,n,f[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in ot.propsKeywords){if(f&&typeof f=="object")for(var h in f)pr(e,t,n,f[h],o+"/"+l+"/"+C0(h),s,o,l,r,h)}else(l in ot.keywords||e.allKeys&&!(l in ot.skipKeywords))&&pr(e,t,n,f,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function C0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var R0=gd.exports;Object.defineProperty(le,"__esModule",{value:!0});le.getSchemaRefs=le.resolveUrl=le.normalizeId=le._getFullPath=le.getFullPath=le.inlineRef=void 0;const M0=P,D0=md,L0=R0,U0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function B0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Es(e):t?yd(e)<=t:!1}le.inlineRef=B0;const F0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Es(e){for(const t in e){if(F0.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(Es)||typeof n=="object"&&Es(n))return!0}return!1}function yd(e){let t=0;for(const n in e)if(n==="$ref"||(t++,!U0.has(n)&&(typeof e[n]=="object"&&(0,M0.eachItem)(e[n],r=>t+=yd(r)),t===1/0)))return 1/0;return t}function $d(e,t="",n){n!==!1&&(t=Yt(t));const r=e.parse(t);return vd(e,r)}le.getFullPath=$d;function vd(e,t){return e.serialize(t).split("#")[0]+"#"}le._getFullPath=vd;const q0=/#\/?$/;function Yt(e){return e?e.replace(q0,""):""}le.normalizeId=Yt;function V0(e,t,n){return n=Yt(n),e.resolve(t,n)}le.resolveUrl=V0;const K0=/^[a-z_][-a-z0-9._]*$/i;function G0(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Yt(e[n]||t),s={"":o},i=$d(r,o,!1),a={},c=new Set;return L0(e,{allKeys:!0},(f,p,h,d)=>{if(d===void 0)return;const m=i+p;let y=s[d];typeof f[n]=="string"&&(y=$.call(this,f[n])),v.call(this,f.$anchor),v.call(this,f.$dynamicAnchor),s[p]=y;function $(E){const b=this.opts.uriResolver.resolve;if(E=Yt(y?b(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!==Yt(m)&&(E[0]==="#"?(u(f,a[E],E),a[E]=f):this.refs[E]=m),E}function v(E){if(typeof E=="string"){if(!K0.test(E))throw new Error(`invalid anchor "${E}"`);$.call(this,`#${E}`)}}}),a;function u(f,p,h){if(p!==void 0&&!D0(f,p))throw l(h)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}le.getSchemaRefs=G0;Object.defineProperty(Ce,"__esModule",{value:!0});Ce.getData=Ce.KeywordCxt=Ce.validateFunctionCode=void 0;const wd=Xt,eu=ie,Ci=ze,Sr=ie,J0=qr,bn=De,Ao=it,M=G,B=Fe,H0=le,We=P,ln=Fn;function z0(e){if(Sd(e)&&(Nd(e),Ed(e))){Q0(e);return}bd(e,()=>(0,wd.topBoolOrEmptySchema)(e))}Ce.validateFunctionCode=z0;function bd({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,M._)`${B.default.data}, ${B.default.valCxt}`,r.$async,()=>{e.code((0,M._)`"use strict"; ${tu(n,o)}`),Y0(e,o),e.code(s)}):e.func(t,(0,M._)`${B.default.data}, ${W0(o)}`,r.$async,()=>e.code(tu(n,o)).code(s))}function W0(e){return(0,M._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${e.dynamicRef?(0,M._)`, ${B.default.dynamicAnchors}={}`:M.nil}}={}`}function Y0(e,t){e.if(B.default.valCxt,()=>{e.var(B.default.instancePath,(0,M._)`${B.default.valCxt}.${B.default.instancePath}`),e.var(B.default.parentData,(0,M._)`${B.default.valCxt}.${B.default.parentData}`),e.var(B.default.parentDataProperty,(0,M._)`${B.default.valCxt}.${B.default.parentDataProperty}`),e.var(B.default.rootData,(0,M._)`${B.default.valCxt}.${B.default.rootData}`),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,M._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{e.var(B.default.instancePath,(0,M._)`""`),e.var(B.default.parentData,(0,M._)`undefined`),e.var(B.default.parentDataProperty,(0,M._)`undefined`),e.var(B.default.rootData,B.default.data),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,M._)`{}`)})}function Q0(e){const{schema:t,opts:n,gen:r}=e;bd(e,()=>{n.$comment&&t.$comment&&kd(e),nw(e),r.let(B.default.vErrors,null),r.let(B.default.errors,0),n.unevaluated&&Z0(e),Od(e),sw(e)})}function Z0(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,M._)`${n}.evaluated`),t.if((0,M._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,M._)`${e.evaluated}.props`,(0,M._)`undefined`)),t.if((0,M._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,M._)`${e.evaluated}.items`,(0,M._)`undefined`))}function tu(e,t){const n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,M._)`/*# sourceURL=${n} */`:M.nil}function X0(e,t){if(Sd(e)&&(Nd(e),Ed(e))){ew(e,t);return}(0,wd.boolOrEmptySchema)(e,t)}function Ed({schema:e,self:t}){if(typeof e=="boolean")return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function Sd(e){return typeof e.schema!="boolean"}function ew(e,t){const{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&kd(e),rw(e),ow(e);const s=r.const("_errs",B.default.errors);Od(e,s),r.var(t,(0,M._)`${s} === ${B.default.errors}`)}function Nd(e){(0,We.checkUnknownRules)(e),tw(e)}function Od(e,t){if(e.opts.jtd)return nu(e,[],!1,t);const n=(0,eu.getSchemaTypes)(e.schema),r=(0,eu.coerceAndCheckDataType)(e,n);nu(e,n,!r,t)}function tw(e){const{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,We.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function nw(e){const{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,We.checkStrictMode)(e,"default is ignored in the schema root")}function rw(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,H0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ow(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function kd({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)e.code((0,M._)`${B.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,M.str)`${r}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,M._)`${B.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function sw(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,M._)`${B.default.errors} === 0`,()=>t.return(B.default.data),()=>t.throw((0,M._)`new ${o}(${B.default.vErrors})`)):(t.assign((0,M._)`${r}.errors`,B.default.vErrors),s.unevaluated&&iw(e),t.return((0,M._)`${B.default.errors} === 0`))}function iw({gen:e,evaluated:t,props:n,items:r}){n instanceof M.Name&&e.assign((0,M._)`${t}.props`,n),r instanceof M.Name&&e.assign((0,M._)`${t}.items`,r)}function nu(e,t,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,We.schemaHasRulesButRef)(s,l))){o.block(()=>jd(e,"$ref",l.all.$ref.definition));return}c.jtd||aw(e,t),o.block(()=>{for(const p of l.rules)f(p);f(l.post)});function f(p){(0,Ci.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Sr.checkDataType)(p.type,i,c.strictNumbers)),ru(e,p),t.length===1&&t[0]===p.type&&n&&(o.else(),(0,Sr.reportTypeError)(e)),o.endIf()):ru(e,p),a||o.if((0,M._)`${B.default.errors} === ${r||0}`))}}function ru(e,t){const{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,J0.assignDefaults)(e,t.type),n.block(()=>{for(const s of t.rules)(0,Ci.shouldUseRule)(r,s)&&jd(e,s.keyword,s.definition,t.type)})}function aw(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(cw(e,t),e.opts.allowUnionTypes||uw(e,t),lw(e,e.dataTypes))}function cw(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{_d(e.dataTypes,n)||Ri(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),dw(e,t)}}function uw(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ri(e,"use allowUnionTypes to allow union type keyword")}function lw(e,t){const n=e.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,Ci.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>fw(t,i))&&Ri(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function fw(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function _d(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function dw(e,t){const n=[];for(const r of e.dataTypes)_d(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function Ri(e,t){const n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,We.checkStrictMode)(e,t,e.opts.strictTypes)}class Ad{constructor(t,n,r){if((0,bn.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,We.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",Id(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,bn.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",B.default.errors))}result(t,n,r){this.failResult((0,M.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,M.not)(t),void 0,n)}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:n}=this;this.fail((0,M._)`${n} !== undefined && (${(0,M.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?ln.reportExtraError:ln.reportError)(this,this.def.error,n)}$dataError(){(0,ln.reportError)(this,this.def.$dataError||ln.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ln.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=M.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=M.nil,n=M.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,M.or)((0,M._)`${o} === undefined`,n)),t!==M.nil&&r.assign(t,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==M.nil&&r.assign(t,!1)),r.else()}invalid$data(){const{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,M.or)(i(),a());function i(){if(r.length){if(!(n instanceof M.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,M._)`${(0,Sr.checkDataTypes)(c,n,s.opts.strictNumbers,Sr.DataType.Wrong)}`}return M.nil}function a(){if(o.validateSchema){const c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,M._)`!${c}(${n})`}return M.nil}}subschema(t,n){const r=(0,Ao.getSubschema)(this.it,t);(0,Ao.extendSubschemaData)(r,this.it,t),(0,Ao.extendSubschemaMode)(r,t);const o={...this.it,...r,items:void 0,props:void 0};return X0(o,n),o}mergeEvaluated(t,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=We.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=We.mergeEvaluated.items(o,t.items,r.items,n)))}mergeValidEvaluated(t,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(t,M.Name)),!0}}Ce.KeywordCxt=Ad;function jd(e,t,n,r){const o=new Ad(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,bn.funcKeywordCode)(o,n):"macro"in n?(0,bn.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,bn.funcKeywordCode)(o,n)}const pw=/^\/(?:[^~]|~0|~1)*$/,hw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Id(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return B.default.rootData;if(e[0]==="/"){if(!pw.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=B.default.rootData}else{const u=hw.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return r[t-l]}if(l>t)throw new Error(c("data",l));if(s=n[t-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,M._)`${s}${(0,M.getProperty)((0,We.unescapeJsonPointer)(u))}`,i=(0,M._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}Ce.getData=Id;var qn={};Object.defineProperty(qn,"__esModule",{value:!0});let mw=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};qn.default=mw;var on={};Object.defineProperty(on,"__esModule",{value:!0});const jo=le;class gw extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,jo.resolveUrl)(t,n,r),this.missingSchema=(0,jo.normalizeId)((0,jo.getFullPath)(t,this.missingRef))}}on.default=gw;var Ee={};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.resolveSchema=Ee.getCompilingSchema=Ee.resolveRef=Ee.compileSchema=Ee.SchemaEnv=void 0;const Ie=G,yw=qn,dt=Fe,Pe=le,ou=P,$w=Ce;class Vr{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,Pe.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={}}}Ee.SchemaEnv=Vr;function Mi(e){const t=xd.call(this,e);if(t)return t;const n=(0,Pe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ie.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:yw.default,code:(0,Ie._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:dt.default.data,parentData:dt.default.parentData,parentDataProperty:dt.default.parentDataProperty,dataNames:[dt.default.data],dataPathArr:[Ie.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ie.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ie.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ie._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,$w.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(dt.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const p=new Function(`${dt.default.self}`,`${dt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){const{props:h,items:d}=u;p.evaluated={props:h instanceof Ie.Name?void 0:h,items:d instanceof Ie.Name?void 0:d,dynamicProps:h instanceof Ie.Name,dynamicItems:d instanceof Ie.Name},p.source&&(p.source.evaluated=(0,Ie.stringify)(p.evaluated))}return e.validate=p,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)}}Ee.compileSchema=Mi;function vw(e,t,n){var r;n=(0,Pe.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=Ew.call(this,e,n);if(s===void 0){const i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Vr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=ww.call(this,s)}Ee.resolveRef=vw;function ww(e){return(0,Pe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Mi.call(this,e)}function xd(e){for(const t of this._compilations)if(bw(t,e))return t}Ee.getCompilingSchema=xd;function bw(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Ew(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Kr.call(this,e,t)}function Kr(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Pe._getFullPath)(this.opts.uriResolver,n);let o=(0,Pe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return Io.call(this,n,e);const s=(0,Pe.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Kr.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:Io.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||Mi.call(this,i),s===(0,Pe.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pe.resolveUrl)(this.opts.uriResolver,o,u)),new Vr({schema:a,schemaId:c,root:e,baseId:o})}return Io.call(this,n,i)}}Ee.resolveSchema=Kr;const Sw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Io(e,{baseId:t,schema:n,root:r}){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 n=="boolean")return;const c=n[(0,ou.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!Sw.has(a)&&u&&(t=(0,Pe.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,ou.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Pe.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Kr.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Vr({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const Nw="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Ow="Meta-schema for $data reference (JSON AnySchema extension proposal)",kw="object",_w=["$data"],Aw={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},jw=!1,Iw={$id:Nw,description:Ow,type:kw,required:_w,properties:Aw,additionalProperties:jw};var Di={},Gr={exports:{}};const xw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Pd=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),Li=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Td=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Pw=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Cd(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 Tw=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function su(e){return e.length=0,!0}function Cw(e,t,n){if(e.length){const r=Cd(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function Rw(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=Cw;for(let c=0;c<e.length;c++){const u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=su}else{o.push(u);continue}}return o.length&&(a===su?n.zone=o.join(""):i?r.push(o.join("")):r.push(Cd(o))),n.address=r.join(""),n}function Rd(e){if(Mw(e,":")<2)return{host:e,isIPV6:!1};const t=Rw(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 Mw(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function Dw(e){let t=e;const n=[];let r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.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]==="/")){n.push("/");break}}else if(o===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 Lw={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Uw=/[@/?#:]/g,Bw=/[@/?#]/g;function Md(e,t){const n=t?Bw:Uw;return n.lastIndex=0,e.replace(n,r=>Lw[r])}function Fw(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 o=e.slice(r+1,r+3);if(Li(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Td(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function qw(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(Li(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Td(s)?t+=s:t+="%"+o,n+=2;continue}}Pw(e[n])?t+=e[n]:t+=escape(e[n])}return t}function Vw(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(Li(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function Kw(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!Pd(n)){const r=Rd(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Md(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 Dd={nonSimpleDomain:Tw,recomposeAuthority:Kw,reescapeHostDelimiters:Md,normalizePercentEncoding:Fw,normalizePathEncoding:qw,escapePreservingEscapes:Vw,removeDotSegments:Dw,isIPv4:Pd,isUUID:xw,normalizeIPv6:Rd};const{isUUID:Gw}=Dd,Jw=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function Ld(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 Ud(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Bd(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 Hw(e){return e.secure=Ld(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function zw(e){if((e.port===(Ld(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 Ww(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(Jw);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=`${r}:${t.nid||e.nid}`,s=Ui(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Yw(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(),o=`${n}:${t.nid||r}`,s=Ui(o);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${r||t.nid}:${a}`,t.skipEscape=!0,i}function Qw(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!Gw(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Zw(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Fd={scheme:"http",domainHost:!0,parse:Ud,serialize:Bd},Xw={scheme:"https",domainHost:Fd.domainHost,parse:Ud,serialize:Bd},hr={scheme:"ws",domainHost:!0,parse:Hw,serialize:zw},eb={scheme:"wss",domainHost:hr.domainHost,parse:hr.parse,serialize:hr.serialize},tb={scheme:"urn",parse:Ww,serialize:Yw,skipNormalize:!0},nb={scheme:"urn:uuid",parse:Qw,serialize:Zw,skipNormalize:!0},Nr={http:Fd,https:Xw,ws:hr,wss:eb,urn:tb,"urn:uuid":nb};Object.setPrototypeOf(Nr,null);function Ui(e){return e&&(Nr[e]||Nr[e.toLowerCase()])||void 0}var rb={SCHEMES:Nr,getSchemeHandler:Ui};const{normalizeIPv6:ob,removeDotSegments:gn,recomposeAuthority:sb,normalizePercentEncoding:ib,normalizePathEncoding:ab,escapePreservingEscapes:cb,reescapeHostDelimiters:ub,isIPv4:lb,nonSimpleDomain:fb}=Dd,{SCHEMES:db,getSchemeHandler:qd}=rb;function pb(e,t){return typeof e=="string"?e=vb(e,t):typeof e=="object"&&(e=en(xt(e,t),t)),e}function hb(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Vd(en(e,r),en(t,r),r,!0);return r.skipEscape=!0,xt(o,r)}function Vd(e,t,n,r){const o={};return r||(e=en(xt(e,n),n),t=en(xt(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=gn(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=gn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=gn(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=gn(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 mb(e,t,n){const r=iu(e,n),o=iu(t,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function xt(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),o=[],s=qd(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=ib(n.path):(n.path=cb(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=sb(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=gn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const gb=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,yb=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function $b(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 Kd(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 o=!1,s=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);const i=e.match(yb);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=e.match(gb);if(a){r.scheme=a[1],r.userinfo=a[3],r.host=a[4],r.port=parseInt(a[5],10),r.path=a[6]||"",r.query=a[7],r.fragment=a[8],isNaN(r.port)&&(r.port=a[5]);const c=$b(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(lb(r.host)===!1){const l=ob(r.host);r.host=l.host.toLowerCase(),s=l.isIPV6}else s=!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 u=qd(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&fb(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(l){r.error=r.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=ub(unescape(r.host),s))),r.path&&(r.path=ab(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}u&&u.parse&&u.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function en(e,t){return Kd(e,t).parsed}function vb(e,t){return Gd(e,t).normalized}function Gd(e,t){const{parsed:n,malformedAuthorityOrPort:r}=Kd(e,t);return{normalized:r?e:xt(n,t),malformedAuthorityOrPort:r}}function iu(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=Gd(e,t);return r?void 0:n}if(typeof e=="object")return xt(e,t)}const Bi={SCHEMES:db,normalize:pb,resolve:hb,resolveComponent:Vd,equal:mb,serialize:xt,parse:en};Gr.exports=Bi;Gr.exports.default=Bi;Gr.exports.fastUri=Bi;var wb=Gr.exports;Object.defineProperty(Di,"__esModule",{value:!0});const Jd=wb;Jd.code='require("ajv/dist/runtime/uri").default';Di.default=Jd;(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=Ce;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G;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=qn,o=on,s=It,i=Ee,a=G,c=le,u=ie,l=P,f=Iw,p=Di,h=(x,S)=>new RegExp(x,S);h.code="new RegExp";const d=["removeAdditional","useDefaults","coerceTypes"],m=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."},$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function E(x){var S,A,O,g,w,k,D,L,W,z,ce,Tt,ro,oo,so,io,ao,co,uo,lo,fo,po,ho,mo,go;const un=x.strict,yo=(S=x.code)===null||S===void 0?void 0:S.optimize,Xa=yo===!0||yo===void 0?1:yo||0,ec=(O=(A=x.code)===null||A===void 0?void 0:A.regExp)!==null&&O!==void 0?O:h,am=(g=x.uriResolver)!==null&&g!==void 0?g:p.default;return{strictSchema:(k=(w=x.strictSchema)!==null&&w!==void 0?w:un)!==null&&k!==void 0?k:!0,strictNumbers:(L=(D=x.strictNumbers)!==null&&D!==void 0?D:un)!==null&&L!==void 0?L:!0,strictTypes:(z=(W=x.strictTypes)!==null&&W!==void 0?W:un)!==null&&z!==void 0?z:"log",strictTuples:(Tt=(ce=x.strictTuples)!==null&&ce!==void 0?ce:un)!==null&&Tt!==void 0?Tt:"log",strictRequired:(oo=(ro=x.strictRequired)!==null&&ro!==void 0?ro:un)!==null&&oo!==void 0?oo:!1,code:x.code?{...x.code,optimize:Xa,regExp:ec}:{optimize:Xa,regExp:ec},loopRequired:(so=x.loopRequired)!==null&&so!==void 0?so:v,loopEnum:(io=x.loopEnum)!==null&&io!==void 0?io:v,meta:(ao=x.meta)!==null&&ao!==void 0?ao:!0,messages:(co=x.messages)!==null&&co!==void 0?co:!0,inlineRefs:(uo=x.inlineRefs)!==null&&uo!==void 0?uo:!0,schemaId:(lo=x.schemaId)!==null&&lo!==void 0?lo:"$id",addUsedSchema:(fo=x.addUsedSchema)!==null&&fo!==void 0?fo:!0,validateSchema:(po=x.validateSchema)!==null&&po!==void 0?po:!0,validateFormats:(ho=x.validateFormats)!==null&&ho!==void 0?ho:!0,unicodeRegExp:(mo=x.unicodeRegExp)!==null&&mo!==void 0?mo:!0,int32range:(go=x.int32range)!==null&&go!==void 0?go:!0,uriResolver:am}}class b{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...E(S)};const{es5:A,lines:O}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:m,es5:A,lines:O}),this.logger=Z(S.logger);const g=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,y,S,"NOT SUPPORTED"),N.call(this,$,S,"DEPRECATED","warn"),this._metaOpts=q.call(this),S.formats&&J.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&U.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),R.call(this),S.validateFormats=g}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:A,schemaId:O}=this.opts;let g=f;O==="id"&&(g={...f},g.id=g.$id,delete g.$id),A&&S&&this.addMetaSchema(g,g[O],!1)}defaultMeta(){const{meta:S,schemaId:A}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[A]||S:void 0}validate(S,A){let O;if(typeof S=="string"){if(O=this.getSchema(S),!O)throw new Error(`no schema with key or ref "${S}"`)}else O=this.compile(S);const g=O(A);return"$async"in O||(this.errors=O.errors),g}compile(S,A){const O=this._addSchema(S,A);return O.validate||this._compileSchemaEnv(O)}compileAsync(S,A){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:O}=this.opts;return g.call(this,S,A);async function g(z,ce){await w.call(this,z.$schema);const Tt=this._addSchema(z,ce);return Tt.validate||k.call(this,Tt)}async function w(z){z&&!this.getSchema(z)&&await g.call(this,{$ref:z},!0)}async function k(z){try{return this._compileSchemaEnv(z)}catch(ce){if(!(ce instanceof o.default))throw ce;return D.call(this,ce),await L.call(this,ce.missingSchema),k.call(this,z)}}function D({missingSchema:z,missingRef:ce}){if(this.refs[z])throw new Error(`AnySchema ${z} is loaded but ${ce} cannot be resolved`)}async function L(z){const ce=await W.call(this,z);this.refs[z]||await w.call(this,ce.$schema),this.refs[z]||this.addSchema(ce,z,A)}async function W(z){const ce=this._loading[z];if(ce)return ce;try{return await(this._loading[z]=O(z))}finally{delete this._loading[z]}}}addSchema(S,A,O,g=this.opts.validateSchema){if(Array.isArray(S)){for(const k of S)this.addSchema(k,void 0,O,g);return this}let w;if(typeof S=="object"){const{schemaId:k}=this.opts;if(w=S[k],w!==void 0&&typeof w!="string")throw new Error(`schema ${k} must be string`)}return A=(0,c.normalizeId)(A||w),this._checkUnique(A),this.schemas[A]=this._addSchema(S,O,A,g,!0),this}addMetaSchema(S,A,O=this.opts.validateSchema){return this.addSchema(S,A,!0,O),this}validateSchema(S,A){if(typeof S=="boolean")return!0;let O;if(O=S.$schema,O!==void 0&&typeof O!="string")throw new Error("$schema must be a string");if(O=O||this.opts.defaultMeta||this.defaultMeta(),!O)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const g=this.validate(O,S);if(!g&&A){const w="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(w);else throw new Error(w)}return g}getSchema(S){let A;for(;typeof(A=j.call(this,S))=="string";)S=A;if(A===void 0){const{schemaId:O}=this.opts,g=new i.SchemaEnv({schema:{},schemaId:O});if(A=i.resolveSchema.call(this,g,S),!A)return;this.refs[S]=A}return A.validate||this._compileSchemaEnv(A)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const A=j.call(this,S);return typeof A=="object"&&this._cache.delete(A.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const A=S;this._cache.delete(A);let O=S[this.opts.schemaId];return O&&(O=(0,c.normalizeId)(O),delete this.schemas[O],delete this.refs[O]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const A of S)this.addKeyword(A);return this}addKeyword(S,A){let O;if(typeof S=="string")O=S,typeof A=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),A.keyword=O);else if(typeof S=="object"&&A===void 0){if(A=S,O=A.keyword,Array.isArray(O)&&!O.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(_e.call(this,O,A),!A)return(0,l.eachItem)(O,w=>Ve.call(this,w)),this;cn.call(this,A);const g={...A,type:(0,u.getJSONTypes)(A.type),schemaType:(0,u.getJSONTypes)(A.schemaType)};return(0,l.eachItem)(O,g.type.length===0?w=>Ve.call(this,w,g):w=>g.type.forEach(k=>Ve.call(this,w,g,k))),this}getKeyword(S){const A=this.RULES.all[S];return typeof A=="object"?A.definition:!!A}removeKeyword(S){const{RULES:A}=this;delete A.keywords[S],delete A.all[S];for(const O of A.rules){const g=O.rules.findIndex(w=>w.keyword===S);g>=0&&O.rules.splice(g,1)}return this}addFormat(S,A){return typeof A=="string"&&(A=new RegExp(A)),this.formats[S]=A,this}errorsText(S=this.errors,{separator:A=", ",dataVar:O="data"}={}){return!S||S.length===0?"No errors":S.map(g=>`${O}${g.instancePath} ${g.message}`).reduce((g,w)=>g+A+w)}$dataMetaSchema(S,A){const O=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const g of A){const w=g.split("/").slice(1);let k=S;for(const D of w)k=k[D];for(const D in O){const L=O[D];if(typeof L!="object")continue;const{$data:W}=L.definition,z=k[D];W&&z&&(k[D]=Kn(z))}}return S}_removeAllSchemas(S,A){for(const O in S){const g=S[O];(!A||A.test(O))&&(typeof g=="string"?delete S[O]:g&&!g.meta&&(this._cache.delete(g.schema),delete S[O]))}}_addSchema(S,A,O,g=this.opts.validateSchema,w=this.opts.addUsedSchema){let k;const{schemaId:D}=this.opts;if(typeof S=="object")k=S[D];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let L=this._cache.get(S);if(L!==void 0)return L;O=(0,c.normalizeId)(k||O);const W=c.getSchemaRefs.call(this,S,O);return L=new i.SchemaEnv({schema:S,schemaId:D,meta:A,baseId:O,localRefs:W}),this._cache.set(L.schema,L),w&&!O.startsWith("#")&&(O&&this._checkUnique(O),this.refs[O]=L),g&&this.validateSchema(S,!0),L}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):i.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const A=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=A}}}b.ValidationError=r.default,b.MissingRefError=o.default,e.default=b;function N(x,S,A,O="error"){for(const g in x){const w=g;w in S&&this.logger[O](`${A}: option ${g}. ${x[w]}`)}}function j(x){return x=(0,c.normalizeId)(x),this.schemas[x]||this.refs[x]}function R(){const x=this.opts.schemas;if(x)if(Array.isArray(x))this.addSchema(x);else for(const S in x)this.addSchema(x[S],S)}function J(){for(const x in this.opts.formats){const S=this.opts.formats[x];S&&this.addFormat(x,S)}}function U(x){if(Array.isArray(x)){this.addVocabulary(x);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in x){const A=x[S];A.keyword||(A.keyword=S),this.addKeyword(A)}}function q(){const x={...this.opts};for(const S of d)delete x[S];return x}const Q={log(){},warn(){},error(){}};function Z(x){if(x===!1)return Q;if(x===void 0)return console;if(x.log&&x.warn&&x.error)return x;throw new Error("logger must implement log, warn and error methods")}const ye=/^[a-z_$][a-z0-9_$:-]*$/i;function _e(x,S){const{RULES:A}=this;if((0,l.eachItem)(x,O=>{if(A.keywords[O])throw new Error(`Keyword ${O} is already defined`);if(!ye.test(O))throw new Error(`Keyword ${O} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function Ve(x,S,A){var O;const g=S==null?void 0:S.post;if(A&&g)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:w}=this;let k=g?w.post:w.rules.find(({type:L})=>L===A);if(k||(k={type:A,rules:[]},w.rules.push(k)),w.keywords[x]=!0,!S)return;const D={keyword:x,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?pe.call(this,k,D,S.before):k.rules.push(D),w.all[x]=D,(O=S.implements)===null||O===void 0||O.forEach(L=>this.addKeyword(L))}function pe(x,S,A){const O=x.rules.findIndex(g=>g.keyword===A);O>=0?x.rules.splice(O,0,S):(x.rules.push(S),this.logger.warn(`rule ${A} is not defined`))}function cn(x){let{metaSchema:S}=x;S!==void 0&&(x.$data&&this.opts.$data&&(S=Kn(S)),x.validateSchema=this.compile(S,!0))}const no={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Kn(x){return{anyOf:[x,no]}}})(Xf);var Fi={},qi={},Vi={};Object.defineProperty(Vi,"__esModule",{value:!0});const bb={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Vi.default=bb;var Pt={};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.callRef=Pt.getValidate=void 0;const Eb=on,au=K,ve=G,Mt=Fe,cu=Ee,Xn=P,Sb={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return f();const l=cu.resolveRef.call(c,u,o,n);if(l===void 0)throw new Eb.default(r.opts.uriResolver,o,n);if(l instanceof cu.SchemaEnv)return p(l);return h(l);function f(){if(s===u)return mr(e,i,s,s.$async);const d=t.scopeValue("root",{ref:u});return mr(e,(0,ve._)`${d}.validate`,u,u.$async)}function p(d){const m=Hd(e,d);mr(e,m,d,d.$async)}function h(d){const m=t.scopeValue("schema",a.code.source===!0?{ref:d,code:(0,ve.stringify)(d)}:{ref:d}),y=t.name("valid"),$=e.subschema({schema:d,dataTypes:[],schemaPath:ve.nil,topSchemaRef:m,errSchemaPath:n},y);e.mergeEvaluated($),e.ok(y)}}};function Hd(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,ve._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Pt.getValidate=Hd;function mr(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Mt.default.this:ve.nil;r?l():f();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const d=o.let("valid");o.try(()=>{o.code((0,ve._)`await ${(0,au.callValidateCode)(e,t,u)}`),h(t),i||o.assign(d,!0)},m=>{o.if((0,ve._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(d,!1)}),e.ok(d)}function f(){e.result((0,au.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(d){const m=(0,ve._)`${d}.errors`;o.assign(Mt.default.vErrors,(0,ve._)`${Mt.default.vErrors} === null ? ${m} : ${Mt.default.vErrors}.concat(${m})`),o.assign(Mt.default.errors,(0,ve._)`${Mt.default.vErrors}.length`)}function h(d){var m;if(!s.opts.unevaluated)return;const y=(m=n==null?void 0:n.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Xn.mergeEvaluated.props(o,y.props,s.props));else{const $=o.var("props",(0,ve._)`${d}.evaluated.props`);s.props=Xn.mergeEvaluated.props(o,$,s.props,ve.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Xn.mergeEvaluated.items(o,y.items,s.items));else{const $=o.var("items",(0,ve._)`${d}.evaluated.items`);s.items=Xn.mergeEvaluated.items(o,$,s.items,ve.Name)}}}Pt.callRef=mr;Pt.default=Sb;Object.defineProperty(qi,"__esModule",{value:!0});const Nb=Vi,Ob=Pt,kb=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Nb.default,Ob.default];qi.default=kb;var Ki={},Gi={};Object.defineProperty(Gi,"__esModule",{value:!0});const Or=G,et=Or.operators,kr={maximum:{okStr:"<=",ok:et.LTE,fail:et.GT},minimum:{okStr:">=",ok:et.GTE,fail:et.LT},exclusiveMaximum:{okStr:"<",ok:et.LT,fail:et.GTE},exclusiveMinimum:{okStr:">",ok:et.GT,fail:et.LTE}},_b={message:({keyword:e,schemaCode:t})=>(0,Or.str)`must be ${kr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Or._)`{comparison: ${kr[e].okStr}, limit: ${t}}`},Ab={keyword:Object.keys(kr),type:"number",schemaType:"number",$data:!0,error:_b,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,Or._)`${n} ${kr[t].fail} ${r} || isNaN(${n})`)}};Gi.default=Ab;var Ji={};Object.defineProperty(Ji,"__esModule",{value:!0});const En=G,jb={message:({schemaCode:e})=>(0,En.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,En._)`{multipleOf: ${e}}`},Ib={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:jb,code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,En._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,En._)`${i} !== parseInt(${i})`;e.fail$data((0,En._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Ji.default=Ib;var Hi={},zi={};Object.defineProperty(zi,"__esModule",{value:!0});function zd(e){const t=e.length;let n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}zi.default=zd;zd.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(Hi,"__esModule",{value:!0});const vt=G,xb=P,Pb=zi,Tb={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,vt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,vt._)`{limit: ${e}}`},Cb={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Tb,code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?vt.operators.GT:vt.operators.LT,i=o.opts.unicode===!1?(0,vt._)`${n}.length`:(0,vt._)`${(0,xb.useFunc)(e.gen,Pb.default)}(${n})`;e.fail$data((0,vt._)`${i} ${s} ${r}`)}};Hi.default=Cb;var Wi={};Object.defineProperty(Wi,"__esModule",{value:!0});const Rb=K,Mb=P,Ht=G,Db={message:({schemaCode:e})=>(0,Ht.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Ht._)`{pattern: ${e}}`},Lb={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Db,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Ht._)`new RegExp`:(0,Mb.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,Ht._)`${u}(${s}, ${a}).test(${n})`),()=>t.assign(l,!1)),e.fail$data((0,Ht._)`!${l}`)}else{const c=(0,Rb.usePattern)(e,o);e.fail$data((0,Ht._)`!${c}.test(${n})`)}}};Wi.default=Lb;var Yi={};Object.defineProperty(Yi,"__esModule",{value:!0});const Sn=G,Ub={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,Sn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,Sn._)`{limit: ${e}}`},Bb={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Ub,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?Sn.operators.GT:Sn.operators.LT;e.fail$data((0,Sn._)`Object.keys(${n}).length ${o} ${r}`)}};Yi.default=Bb;var Qi={};Object.defineProperty(Qi,"__esModule",{value:!0});const fn=K,Nn=G,Fb=P,qb={message:({params:{missingProperty:e}})=>(0,Nn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Nn._)`{missingProperty: ${e}}`},Vb={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qb,code(e){const{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const h=e.parentSchema.properties,{definedProperties:d}=e.it;for(const m of n)if((h==null?void 0:h[m])===void 0&&!d.has(m)){const y=i.schemaEnv.baseId+i.errSchemaPath,$=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,Fb.checkStrictMode)(i,$,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(Nn.nil,f);else for(const h of n)(0,fn.checkReportMissingProp)(e,h)}function l(){const h=t.let("missing");if(c||s){const d=t.let("valid",!0);e.block$data(d,()=>p(h,d)),e.ok(d)}else t.if((0,fn.checkMissingProp)(e,n,h)),(0,fn.reportMissingProp)(e,h),t.else()}function f(){t.forOf("prop",r,h=>{e.setParams({missingProperty:h}),t.if((0,fn.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,d){e.setParams({missingProperty:h}),t.forOf(h,r,()=>{t.assign(d,(0,fn.propertyInData)(t,o,h,a.ownProperties)),t.if((0,Nn.not)(d),()=>{e.error(),t.break()})},Nn.nil)}}};Qi.default=Vb;var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0});const On=G,Kb={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,On.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,On._)`{limit: ${e}}`},Gb={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Kb,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?On.operators.GT:On.operators.LT;e.fail$data((0,On._)`${n}.length ${o} ${r}`)}};Zi.default=Gb;var Xi={},Vn={};Object.defineProperty(Vn,"__esModule",{value:!0});const Wd=md;Wd.code='require("ajv/dist/runtime/equal").default';Vn.default=Wd;Object.defineProperty(Xi,"__esModule",{value:!0});const xo=ie,ue=G,Jb=P,Hb=Vn,zb={message:({params:{i:e,j:t}})=>(0,ue.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ue._)`{i: ${e}, j: ${t}}`},Wb={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:zb,code(e){const{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!r&&!o)return;const c=t.let("valid"),u=s.items?(0,xo.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,ue._)`${i} === false`),e.ok(c);function l(){const d=t.let("i",(0,ue._)`${n}.length`),m=t.let("j");e.setParams({i:d,j:m}),t.assign(c,!0),t.if((0,ue._)`${d} > 1`,()=>(f()?p:h)(d,m))}function f(){return u.length>0&&!u.some(d=>d==="object"||d==="array")}function p(d,m){const y=t.name("item"),$=(0,xo.checkDataTypes)(u,y,a.opts.strictNumbers,xo.DataType.Wrong),v=t.const("indices",(0,ue._)`{}`);t.for((0,ue._)`;${d}--;`,()=>{t.let(y,(0,ue._)`${n}[${d}]`),t.if($,(0,ue._)`continue`),u.length>1&&t.if((0,ue._)`typeof ${y} == "string"`,(0,ue._)`${y} += "_"`),t.if((0,ue._)`typeof ${v}[${y}] == "number"`,()=>{t.assign(m,(0,ue._)`${v}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,ue._)`${v}[${y}] = ${d}`)})}function h(d,m){const y=(0,Jb.useFunc)(t,Hb.default),$=t.name("outer");t.label($).for((0,ue._)`;${d}--;`,()=>t.for((0,ue._)`${m} = ${d}; ${m}--;`,()=>t.if((0,ue._)`${y}(${n}[${d}], ${n}[${m}])`,()=>{e.error(),t.assign(c,!1).break($)})))}}};Xi.default=Wb;var ea={};Object.defineProperty(ea,"__esModule",{value:!0});const Ss=G,Yb=P,Qb=Vn,Zb={message:"must be equal to constant",params:({schemaCode:e})=>(0,Ss._)`{allowedValue: ${e}}`},Xb={keyword:"const",$data:!0,error:Zb,code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,Ss._)`!${(0,Yb.useFunc)(t,Qb.default)}(${n}, ${o})`):e.fail((0,Ss._)`${s} !== ${n}`)}};ea.default=Xb;var ta={};Object.defineProperty(ta,"__esModule",{value:!0});const yn=G,eE=P,tE=Vn,nE={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,yn._)`{allowedValues: ${e}}`},rE={keyword:"enum",schemaType:"array",$data:!0,error:nE,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e;if(!r&&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,eE.useFunc)(t,tE.default));let l;if(a||r)l=t.let("valid"),e.block$data(l,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const h=t.const("vSchema",s);l=(0,yn.or)(...o.map((d,m)=>p(h,m)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",s,h=>t.if((0,yn._)`${u()}(${n}, ${h})`,()=>t.assign(l,!0).break()))}function p(h,d){const m=o[d];return typeof m=="object"&&m!==null?(0,yn._)`${u()}(${n}, ${h}[${d}])`:(0,yn._)`${n} === ${m}`}}};ta.default=rE;Object.defineProperty(Ki,"__esModule",{value:!0});const oE=Gi,sE=Ji,iE=Hi,aE=Wi,cE=Yi,uE=Qi,lE=Zi,fE=Xi,dE=ea,pE=ta,hE=[oE.default,sE.default,iE.default,aE.default,cE.default,uE.default,lE.default,fE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dE.default,pE.default];Ki.default=hE;var na={},sn={};Object.defineProperty(sn,"__esModule",{value:!0});sn.validateAdditionalItems=void 0;const wt=G,Ns=P,mE={message:({params:{len:e}})=>(0,wt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,wt._)`{limit: ${e}}`},gE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:mE,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,Ns.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Yd(e,r)}};function Yd(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,wt._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,wt._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,Ns.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,wt._)`${a} <= ${t.length}`);n.if((0,wt.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Ns.Type.Num},u),i.allErrors||n.if((0,wt.not)(u),()=>n.break())})}}sn.validateAdditionalItems=Yd;sn.default=gE;var ra={},an={};Object.defineProperty(an,"__esModule",{value:!0});an.validateTuple=void 0;const uu=G,gr=P,yE=K,$E={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return Qd(e,"additionalItems",t);n.items=!0,!(0,gr.alwaysValidSchema)(n,t)&&e.ok((0,yE.validateArray)(e))}};function Qd(e,t,n=e.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=gr.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,uu._)`${s}.length`);n.forEach((f,p)=>{(0,gr.alwaysValidSchema)(a,f)||(r.if((0,uu._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(f){const{opts:p,errSchemaPath:h}=a,d=n.length,m=d===f.minItems&&(d===f.maxItems||f[t]===!1);if(p.strictTuples&&!m){const y=`"${i}" is ${d}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,gr.checkStrictMode)(a,y,p.strictTuples)}}}an.validateTuple=Qd;an.default=$E;Object.defineProperty(ra,"__esModule",{value:!0});const vE=an,wE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,vE.validateTuple)(e,"items")};ra.default=wE;var oa={};Object.defineProperty(oa,"__esModule",{value:!0});const lu=G,bE=P,EE=K,SE=sn,NE={message:({params:{len:e}})=>(0,lu.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,lu._)`{limit: ${e}}`},OE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:NE,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,bE.alwaysValidSchema)(r,t)&&(o?(0,SE.validateAdditionalItems)(e,o):e.ok((0,EE.validateArray)(e)))}};oa.default=OE;var sa={};Object.defineProperty(sa,"__esModule",{value:!0});const Ae=G,er=P,kE={message:({params:{min:e,max:t}})=>t===void 0?(0,Ae.str)`must contain at least ${e} valid item(s)`:(0,Ae.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ae._)`{minContains: ${e}}`:(0,Ae._)`{minContains: ${e}, maxContains: ${t}}`},_E={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:kE,code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=t.const("len",(0,Ae._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,er.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,er.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,er.alwaysValidSchema)(s,n)){let m=(0,Ae._)`${l} >= ${i}`;a!==void 0&&(m=(0,Ae._)`${m} && ${l} <= ${a}`),e.pass(m);return}s.items=!0;const f=t.name("valid");a===void 0&&i===1?h(f,()=>t.if(f,()=>t.break())):i===0?(t.let(f,!0),a!==void 0&&t.if((0,Ae._)`${o}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset());function p(){const m=t.name("_valid"),y=t.let("count",0);h(m,()=>t.if(m,()=>d(y)))}function h(m,y){t.forRange("i",0,l,$=>{e.subschema({keyword:"contains",dataProp:$,dataPropType:er.Type.Num,compositeRule:!0},m),y()})}function d(m){t.code((0,Ae._)`${m}++`),a===void 0?t.if((0,Ae._)`${m} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,Ae._)`${m} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,Ae._)`${m} >= ${i}`,()=>t.assign(f,!0)))}}};sa.default=_E;var Zd={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=G,n=P,r=K;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},
|
|
160
|
-
missingProperty: ${
|
|
183
|
+
`}};ze(ql,"defaults",fw);function OO(t,e=!0,n){n===void 0&&typeof e=="string"&&(n=e,e=!0);const r=Object.assign({},ql.defaults[Vi.version],Vi);return new as(r).createNode(t,e,n)}let ba=class extends ql{constructor(e){super(Object.assign({},Vi,e))}};function kO(t,e){const n=[];let r;for(const o of Tl(t)){const s=new ba(e);s.parse(o,r),n.push(s),r=s}return n}function pw(t,e){const n=Tl(t),r=new ba(e).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new X(n[1],o))}return r}function jO(t,e){const n=pw(t,e);if(n.warnings.forEach(r=>ew(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function AO(t,e){const n=new ba(e);return n.contents=t,String(n)}const IO={createNode:OO,defaultOptions:Vi,Document:ba,parse:jO,parseAllDocuments:kO,parseCST:Tl,parseDocument:pw,scalarOptions:wO,stringify:AO},PO=Object.freeze(Object.defineProperty({__proto__:null,YAML:IO},Symbol.toStringTag,{value:"Module"})),xO=NN(PO);var RO=xO.YAML;const TO="1.0.0-redesign.1",CO="adhd",MO="default",LO="adhd-environment.json",nc="config.yaml",DO="config.local.yaml",UO={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};let fh=class extends Error{constructor(e,n){super(`contentHash: lone surrogate in ${e} (not well-formed Unicode)`),this.location=e,this.offending=n,this.name="LoneSurrogateError"}};function ph(t){for(let e=0;e<t.length;e++){const n=t.charCodeAt(e);if(n>=55296&&n<=56319){const r=e+1<t.length?t.charCodeAt(e+1):0;if(r<56320||r>57343)return!0;e++}else if(n>=56320&&n<=57343)return!0}return!1}function hw(t,e){const n=Array.from(t),r=Array.from(e),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){const i=n[s].codePointAt(0)??0,a=r[s].codePointAt(0)??0;if(i!==a)return i<a?-1:1}return n.length===r.length?0:n.length<r.length?-1:1}function hh(t){return new TextEncoder().encode(t).length}function BO(t){const e=Object.keys(t).sort(hw);let n="";for(const r of e){const o=t[r];if(ph(r))throw new fh("key",r);if(ph(o))throw new fh("value",o);n+=`${hh(r)}:${r}=${hh(o)}:${o}
|
|
184
|
+
`}return`sha256-${mw(n)}`}function FO(t){const e=[...t].sort((n,r)=>hw(n.name,r.name)).map(n=>`${n.name}:${n.kind}:${n.scope}`).join(`
|
|
185
|
+
`);return`sha256-${mw(e)}`}function qO(t){return`ADHD_${t.toUpperCase().replace(/[.-]/g,"_")}`}function KO(t,e){return`${t}_${e.toUpperCase().replace(/[.-]/g,"_")}`}function VO(t){const e={type:"object",properties:{}},n=t;for(const r of Object.keys(n)){const o=n[r],s=r.split(".");let i=e;s.forEach((a,c)=>{if(c===s.length-1){i.properties[a]=GO(o);return}const u=i.properties[a];if(u===void 0){const l={type:"object",properties:{}};i.properties[a]=l,i=l}else i=u})}return e}function GO(t){const e={type:t.type};return t.default!==void 0&&t.secret!==!0&&(e.default=t.default),t.description!==void 0&&(e.description=t.description),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.enum!==void 0&&(e.enum=t.enum),t.pattern!==void 0&&(e.pattern=t.pattern),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.items!==void 0&&(e.items=t.items),e}const zO="adhd-env-ref:";function WO(t){return`${zO}${t}`}const HO=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],JO=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Pt(t,e){return(t>>>e|t<<32-e)>>>0}function QO(t){const e=Uint32Array.from(JO),n=t.length*8;let r=t.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(t),o[t.length]=128;const s=Math.floor(n/4294967296),i=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,s,!1),a.setUint32(r-4,i,!1);const c=new Uint32Array(64);for(let d=0;d<r;d+=64){for(let E=0;E<16;E++)c[E]=a.getUint32(d+E*4,!1);for(let E=16;E<64;E++){const N=c[E-15],j=c[E-2],T=Pt(N,7)^Pt(N,18)^N>>>3,M=Pt(j,17)^Pt(j,19)^j>>>10;c[E]=c[E-16]+T+c[E-7]+M>>>0}let f=e[0],g=e[1],p=e[2],y=e[3],w=e[4],h=e[5],v=e[6],b=e[7];for(let E=0;E<64;E++){const N=Pt(w,6)^Pt(w,11)^Pt(w,25),j=w&h^~w&v,T=b+N+j+HO[E]+c[E]>>>0,M=Pt(f,2)^Pt(f,13)^Pt(f,22),C=f&g^f&p^g&p,G=M+C>>>0;b=v,v=h,h=w,w=y+T>>>0,y=p,p=g,g=f,f=T+G>>>0}e[0]=e[0]+f>>>0,e[1]=e[1]+g>>>0,e[2]=e[2]+p>>>0,e[3]=e[3]+y>>>0,e[4]=e[4]+w>>>0,e[5]=e[5]+h>>>0,e[6]=e[6]+v>>>0,e[7]=e[7]+b>>>0}const u=new Uint8Array(32),l=new DataView(u.buffer);for(let d=0;d<8;d++)l.setUint32(d*4,e[d],!1);return u}function YO(t){let e="";for(const n of t)e+=n.toString(16).padStart(2,"0");return e}function mw(t){const e=new TextEncoder().encode(t);return YO(QO(e))}function gw(t,e=""){const n={};if(t===null||typeof t!="object"||Array.isArray(t))return e&&(n[e]=t),n;for(const[r,o]of Object.entries(t)){const s=e?`${e}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,gw(o,s)):n[s]=o}return n}function Fs(t){if(J.existsSync(t))try{const e=J.readFileSync(t,"utf8"),n=RO.parse(e);return n===null||typeof n!="object"||Array.isArray(n)?void 0:gw(n)}catch{return}}function ZO(t){return{system:Fs(L.join(t.system,nc)),global:Fs(L.join(t.global,nc)),project:t.project?Fs(L.join(t.project,nc)):void 0,local:t.project?Fs(L.join(t.project,DO)):void 0}}function XO(t){const e={source:t.source,scope:t.scope};return t.source==="env"&&t.env!==void 0&&(e.env=t.env),e}function au(t,e){if(t===void 0)return t;switch(e){case"integer":{if(typeof t=="number")return t;const n=parseInt(String(t),10);return Number.isNaN(n)?t:n}case"number":{if(typeof t=="number")return t;const n=parseFloat(String(t));return Number.isNaN(n)?t:n}case"boolean":{if(typeof t=="boolean")return t;const n=String(t).toLowerCase();return n==="true"?!0:n==="false"?!1:t}case"array":return Array.isArray(t)?t:typeof t=="string"?t.length===0?[]:t.split(",").map(n=>n.trim()):t;case"string":return typeof t=="string"?t:String(t);default:return t}}function yw(t){const e={};for(const n of Object.keys(t)){const r=n.split(".");let o=e;r.forEach((s,i)=>{if(i===r.length-1){o[s]=t[n];return}const a=o[s];(typeof a!="object"||a===null||Array.isArray(a))&&(o[s]={}),o=o[s]})}return e}const ek=[["system","system"],["global","global"],["project","project"],["local","local"]];function tk(t,e,n,r){const o={},s={},i={},a={};for(const c of Object.keys(t)){const u=t[c],l=u.env&&u.env!==""?u.env:KO(r.prefix,c),d=u.at==="runtime"||u.secret===!0,f=u.scope??r.activeScope;let g=u.default,p="default";for(const[b,E]of ek){const N=e[b];N&&Object.prototype.hasOwnProperty.call(N,c)&&(g=au(N[c],u.type),p=E)}const y=n[l];let w,h,v;y!==void 0?(w=au(y,u.type),h="env",v=l):(w=g,h=p),o[c]=d?WO(l):w,s[c]=w,i[c]=XO(d?{source:"env",scope:f,env:l}:{source:h,scope:f,env:v}),a[c]={...u,env:l,live:d,fallbackValue:g}}return{raw:o,nested:yw(o),typedRaw:s,provenance:i,fields:a}}function nk(t,e){return t.replace(/\$\{HOME\}/g,mt.homedir()).replace(/\$HOME\b/g,mt.homedir()).replace(/\$\{PROJECT_ROOT\}/g,e.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,e.namespace)}function rk(t,e){const n={};for(const[r,o]of Object.entries(t??{})){const s=o.scope??e.activeScope,i=o.share??UO[o.kind],a=o.path?nk(o.path,e):L.join(Ey(e.roots,s),r),c=i==="per-instance"?L.join(a,e.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function ok(t,e){const n={};for(const[r,o]of Object.entries(t??{})){const s=e[o.in];if(!s)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:L.join(s.path,o.name),share:o.share??"shared"}}return n}var cu={exports:{}},ww={},Nt={},eo={},Ss={},ae={},cs={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class r extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((b,E)=>`${b}${E}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((b,E)=>(E instanceof n&&(b[E.str]=(b[E.str]||0)+1),b),{})}}t._Code=r,t.nil=new r("");function o(h,...v){const b=[h[0]];let E=0;for(;E<v.length;)a(b,v[E]),b.push(h[++E]);return new r(b)}t._=o;const s=new r("+");function i(h,...v){const b=[g(h[0])];let E=0;for(;E<v.length;)b.push(s),a(b,v[E]),b.push(s,g(h[++E]));return c(b),new r(b)}t.str=i;function a(h,v){v instanceof r?h.push(...v._items):v instanceof n?h.push(v):h.push(d(v))}t.addCodeArg=a;function c(h){let v=1;for(;v<h.length-1;){if(h[v]===s){const b=u(h[v-1],h[v+1]);if(b!==void 0){h.splice(v-1,3,b);continue}h[v++]="+"}v++}}function u(h,v){if(v==='""')return h;if(h==='""')return v;if(typeof h=="string")return v instanceof n||h[h.length-1]!=='"'?void 0:typeof v!="string"?`${h.slice(0,-1)}${v}"`:v[0]==='"'?h.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(h instanceof n))return`"${h}${v.slice(1)}`}function l(h,v){return v.emptyStr()?h:h.emptyStr()?v:i`${h}${v}`}t.strConcat=l;function d(h){return typeof h=="number"||typeof h=="boolean"||h===null?h:g(Array.isArray(h)?h.join(","):h)}function f(h){return new r(g(h))}t.stringify=f;function g(h){return JSON.stringify(h).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=g;function p(h){return typeof h=="string"&&t.IDENTIFIER.test(h)?new r(`.${h}`):o`[${h}]`}t.getProperty=p;function y(h){if(typeof h=="string"&&t.IDENTIFIER.test(h))return new r(`${h}`);throw new Error(`CodeGen: invalid export name: ${h}, use explicit $id name mapping`)}t.getEsmExportName=y;function w(h){return new r(h.toString())}t.regexpCode=w})(cs);var uu={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=cs;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||(t.UsedValueState=r={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.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}}}t.Scope=o;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;const i=(0,e._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const f=this.toName(u),{prefix:g}=f,p=(d=l.key)!==null&&d!==void 0?d:l.ref;let y=this._values[g];if(y){const v=y.get(p);if(v)return v}else y=this._values[g]=new Map;y.set(p,f);const w=this._scope[g]||(this._scope[g]=[]),h=w.length;return w[h]=l.ref,f.setValue(l,{property:g,itemIndex:h}),f}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},l,d)}_reduceValues(u,l,d={},f){let g=e.nil;for(const p in u){const y=u[p];if(!y)continue;const w=d[p]=d[p]||new Map;y.forEach(h=>{if(w.has(h))return;w.set(h,r.Started);let v=l(h);if(v){const b=this.opts.es5?t.varKinds.var:t.varKinds.const;g=(0,e._)`${g}${b} ${h} = ${v};${this.opts._n}`}else if(v=f==null?void 0:f(h))g=(0,e._)`${g}${v}${this.opts._n}`;else throw new n(h);w.set(h,r.Completed)})}return g}}t.ValueScope=a})(uu);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=cs,n=uu;var r=cs;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}});var o=uu;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(m,$){return this}}class i extends s{constructor(m,$,O){super(),this.varKind=m,this.name=$,this.rhs=O}render({es5:m,_n:$}){const O=m?n.varKinds.var:this.varKind,x=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${x};`+$}optimizeNames(m,$){if(m[this.name.str])return this.rhs&&(this.rhs=fe(this.rhs,m,$)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(m,$,O){super(),this.lhs=m,this.rhs=$,this.sideEffects=O}render({_n:m}){return`${this.lhs} = ${this.rhs};`+m}optimizeNames(m,$){if(!(this.lhs instanceof e.Name&&!m[this.lhs.str]&&!this.sideEffects))return this.rhs=fe(this.rhs,m,$),this}get names(){const m=this.lhs instanceof e.Name?{}:{...this.lhs.names};return ue(m,this.rhs)}}class c extends a{constructor(m,$,O,x){super(m,O,x),this.op=$}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 l extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`break${this.label?` ${this.label}`:""};`+m}}class d extends s{constructor(m){super(),this.error=m}render({_n:m}){return`throw ${this.error};`+m}get names(){return this.error.names}}class f extends s{constructor(m){super(),this.code=m}render({_n:m}){return`${this.code};`+m}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(m,$){return this.code=fe(this.code,m,$),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class g extends s{constructor(m=[]){super(),this.nodes=m}render(m){return this.nodes.reduce(($,O)=>$+O.render(m),"")}optimizeNodes(){const{nodes:m}=this;let $=m.length;for(;$--;){const O=m[$].optimizeNodes();Array.isArray(O)?m.splice($,1,...O):O?m[$]=O:m.splice($,1)}return m.length>0?this:void 0}optimizeNames(m,$){const{nodes:O}=this;let x=O.length;for(;x--;){const R=O[x];R.optimizeNames(m,$)||(he(m,R.names),O.splice(x,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((m,$)=>Z(m,$.names),{})}}class p extends g{render(m){return"{"+m._n+super.render(m)+"}"+m._n}}class y extends g{}class w extends p{}w.kind="else";class h extends p{constructor(m,$){super($),this.condition=m}render(m){let $=`if(${this.condition})`+super.render(m);return this.else&&($+="else "+this.else.render(m)),$}optimizeNodes(){super.optimizeNodes();const m=this.condition;if(m===!0)return this.nodes;let $=this.else;if($){const O=$.optimizeNodes();$=this.else=Array.isArray(O)?new w(O):O}if($)return m===!1?$ instanceof h?$:$.nodes:this.nodes.length?this:new h(pe(m),$ instanceof h?[$]:$.nodes);if(!(m===!1||!this.nodes.length))return this}optimizeNames(m,$){var O;if(this.else=(O=this.else)===null||O===void 0?void 0:O.optimizeNames(m,$),!!(super.optimizeNames(m,$)||this.else))return this.condition=fe(this.condition,m,$),this}get names(){const m=super.names;return ue(m,this.condition),this.else&&Z(m,this.else.names),m}}h.kind="if";class v extends p{}v.kind="for";class b extends v{constructor(m){super(),this.iteration=m}render(m){return`for(${this.iteration})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iteration=fe(this.iteration,m,$),this}get names(){return Z(super.names,this.iteration.names)}}class E extends v{constructor(m,$,O,x){super(),this.varKind=m,this.name=$,this.from=O,this.to=x}render(m){const $=m.es5?n.varKinds.var:this.varKind,{name:O,from:x,to:R}=this;return`for(${$} ${O}=${x}; ${O}<${R}; ${O}++)`+super.render(m)}get names(){const m=ue(super.names,this.from);return ue(m,this.to)}}class N extends v{constructor(m,$,O,x){super(),this.loop=m,this.varKind=$,this.name=O,this.iterable=x}render(m){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iterable=fe(this.iterable,m,$),this}get names(){return Z(super.names,this.iterable.names)}}class j extends p{constructor(m,$,O){super(),this.name=m,this.args=$,this.async=O}render(m){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(m)}}j.kind="func";class T extends g{render(m){return"return "+super.render(m)}}T.kind="return";class M extends p{render(m){let $="try"+super.render(m);return this.catch&&($+=this.catch.render(m)),this.finally&&($+=this.finally.render(m)),$}optimizeNodes(){var m,$;return super.optimizeNodes(),(m=this.catch)===null||m===void 0||m.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(m,$){var O,x;return super.optimizeNames(m,$),(O=this.catch)===null||O===void 0||O.optimizeNames(m,$),(x=this.finally)===null||x===void 0||x.optimizeNames(m,$),this}get names(){const m=super.names;return this.catch&&Z(m,this.catch.names),this.finally&&Z(m,this.finally.names),m}}class C extends p{constructor(m){super(),this.error=m}render(m){return`catch(${this.error})`+super.render(m)}}C.kind="catch";class G extends p{render(m){return"finally"+super.render(m)}}G.kind="finally";class H{constructor(m,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
186
|
+
`:""},this._extScope=m,this._scope=new n.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,$){const O=this._extScope.value(m,$);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(m,$){return this._extScope.getValue(m,$)}scopeRefs(m){return this._extScope.scopeRefs(m,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(m,$,O,x){const R=this._scope.toName($);return O!==void 0&&x&&(this._constants[R.str]=O),this._leafNode(new i(m,R,O)),R}const(m,$,O){return this._def(n.varKinds.const,m,$,O)}let(m,$,O){return this._def(n.varKinds.let,m,$,O)}var(m,$,O){return this._def(n.varKinds.var,m,$,O)}assign(m,$,O){return this._leafNode(new a(m,$,O))}add(m,$){return this._leafNode(new c(m,t.operators.ADD,$))}code(m){return typeof m=="function"?m():m!==e.nil&&this._leafNode(new f(m)),this}object(...m){const $=["{"];for(const[O,x]of m)$.length>1&&$.push(","),$.push(O),(O!==x||this.opts.es5)&&($.push(":"),(0,e.addCodeArg)($,x));return $.push("}"),new e._Code($)}if(m,$,O){if(this._blockNode(new h(m)),$&&O)this.code($).else().code(O).endIf();else if($)this.code($).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(m){return this._elseNode(new h(m))}else(){return this._elseNode(new w)}endIf(){return this._endBlockNode(h,w)}_for(m,$){return this._blockNode(m),$&&this.code($).endFor(),this}for(m,$){return this._for(new b(m),$)}forRange(m,$,O,x,R=this.opts.es5?n.varKinds.var:n.varKinds.let){const U=this._scope.toName(m);return this._for(new E(R,U,$,O),()=>x(U))}forOf(m,$,O,x=n.varKinds.const){const R=this._scope.toName(m);if(this.opts.es5){const U=$ instanceof e.Name?$:this.var("_arr",$);return this.forRange("_i",0,(0,e._)`${U}.length`,q=>{this.var(R,(0,e._)`${U}[${q}]`),O(R)})}return this._for(new N("of",x,R,$),()=>O(R))}forIn(m,$,O,x=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(m,(0,e._)`Object.keys(${$})`,O);const R=this._scope.toName(m);return this._for(new N("in",x,R,$),()=>O(R))}endFor(){return this._endBlockNode(v)}label(m){return this._leafNode(new u(m))}break(m){return this._leafNode(new l(m))}return(m){const $=new T;if(this._blockNode($),this.code(m),$.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(m,$,O){if(!$&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');const x=new M;if(this._blockNode(x),this.code(m),$){const R=this.name("e");this._currNode=x.catch=new C(R),$(R)}return O&&(this._currNode=x.finally=new G,this.code(O)),this._endBlockNode(C,G)}throw(m){return this._leafNode(new d(m))}block(m,$){return this._blockStarts.push(this._nodes.length),m&&this.code(m).endBlock($),this}endBlock(m){const $=this._blockStarts.pop();if($===void 0)throw new Error("CodeGen: not in self-balancing block");const O=this._nodes.length-$;if(O<0||m!==void 0&&O!==m)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${m} expected`);return this._nodes.length=$,this}func(m,$=e.nil,O,x){return this._blockNode(new j(m,$,O)),x&&this.code(x).endFunc(),this}endFunc(){return this._endBlockNode(j)}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,$){const O=this._currNode;if(O instanceof m||$&&O instanceof $)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${$?`${m.kind}/${$.kind}`:m.kind}"`)}_elseNode(m){const $=this._currNode;if(!($ instanceof h))throw new Error('CodeGen: "else" without "if"');return this._currNode=$.else=m,this}get _root(){return this._nodes[0]}get _currNode(){const m=this._nodes;return m[m.length-1]}set _currNode(m){const $=this._nodes;$[$.length-1]=m}}t.CodeGen=H;function Z(_,m){for(const $ in m)_[$]=(_[$]||0)+(m[$]||0);return _}function ue(_,m){return m instanceof e._CodeOrName?Z(_,m.names):_}function fe(_,m,$){if(_ instanceof e.Name)return O(_);if(!x(_))return _;return new e._Code(_._items.reduce((R,U)=>(U instanceof e.Name&&(U=O(U)),U instanceof e._Code?R.push(...U._items):R.push(U),R),[]));function O(R){const U=$[R.str];return U===void 0||m[R.str]!==1?R:(delete m[R.str],U)}function x(R){return R instanceof e._Code&&R._items.some(U=>U instanceof e.Name&&m[U.str]===1&&$[U.str]!==void 0)}}function he(_,m){for(const $ in m)_[$]=(_[$]||0)-(m[$]||0)}function pe(_){return typeof _=="boolean"||typeof _=="number"||_===null?!_:(0,e._)`!${k(_)}`}t.not=pe;const Oe=S(t.operators.AND);function gt(..._){return _.reduce(Oe)}t.and=gt;const ut=S(t.operators.OR);function A(..._){return _.reduce(ut)}t.or=A;function S(_){return(m,$)=>m===e.nil?$:$===e.nil?m:(0,e._)`${k(m)} ${_} ${k($)}`}function k(_){return _ instanceof e.Name?_:(0,e._)`(${_})`}})(ae);var K={};Object.defineProperty(K,"__esModule",{value:!0});K.checkStrictMode=K.getErrorPath=K.Type=K.useFunc=K.setEvaluated=K.evaluatedPropsToName=K.mergeEvaluated=K.eachItem=K.unescapeJsonPointer=K.escapeJsonPointer=K.escapeFragment=K.unescapeFragment=K.schemaRefOrVal=K.schemaHasRulesButRef=K.schemaHasRules=K.checkUnknownRules=K.alwaysValidSchema=K.toHash=void 0;const ye=ae,sk=cs;function ik(t){const e={};for(const n of t)e[n]=!0;return e}K.toHash=ik;function ak(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(vw(t,e),!$w(e,t.self.RULES.all))}K.alwaysValidSchema=ak;function vw(t,e=t.schema){const{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;const o=r.RULES.keywords;for(const s in e)o[s]||Sw(t,`unknown keyword: "${s}"`)}K.checkUnknownRules=vw;function $w(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(e[n])return!0;return!1}K.schemaHasRules=$w;function ck(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}K.schemaHasRulesButRef=ck;function uk({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ye._)`${n}`}return(0,ye._)`${t}${e}${(0,ye.getProperty)(r)}`}K.schemaRefOrVal=uk;function lk(t){return bw(decodeURIComponent(t))}K.unescapeFragment=lk;function dk(t){return encodeURIComponent(Kl(t))}K.escapeFragment=dk;function Kl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}K.escapeJsonPointer=Kl;function bw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}K.unescapeJsonPointer=bw;function fk(t,e){if(Array.isArray(t))for(const n of t)e(n);else e(t)}K.eachItem=fk;function mh({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof ye.Name?(s instanceof ye.Name?t(o,s,i):e(o,s,i),i):s instanceof ye.Name?(e(o,i,s),s):n(s,i);return a===ye.Name&&!(c instanceof ye.Name)?r(o,c):c}}K.mergeEvaluated={props:mh({mergeNames:(t,e,n)=>t.if((0,ye._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,ye._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,ye._)`${n} || {}`).code((0,ye._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,ye._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,ye._)`${n} || {}`),Vl(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ew}),items:mh({mergeNames:(t,e,n)=>t.if((0,ye._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,ye._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,ye._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,ye._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Ew(t,e){if(e===!0)return t.var("props",!0);const n=t.var("props",(0,ye._)`{}`);return e!==void 0&&Vl(t,n,e),n}K.evaluatedPropsToName=Ew;function Vl(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ye._)`${e}${(0,ye.getProperty)(r)}`,!0))}K.setEvaluated=Vl;const gh={};function pk(t,e){return t.scopeValue("func",{ref:e,code:gh[e.code]||(gh[e.code]=new sk._Code(e.code))})}K.useFunc=pk;var lu;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(lu||(K.Type=lu={}));function hk(t,e,n){if(t instanceof ye.Name){const r=e===lu.Num;return n?r?(0,ye._)`"[" + ${t} + "]"`:(0,ye._)`"['" + ${t} + "']"`:r?(0,ye._)`"/" + ${t}`:(0,ye._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ye.getProperty)(t).toString():"/"+Kl(t)}K.getErrorPath=hk;function Sw(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}K.checkStrictMode=Sw;var Bt={};Object.defineProperty(Bt,"__esModule",{value:!0});const Ve=ae,mk={data:new Ve.Name("data"),valCxt:new Ve.Name("valCxt"),instancePath:new Ve.Name("instancePath"),parentData:new Ve.Name("parentData"),parentDataProperty:new Ve.Name("parentDataProperty"),rootData:new Ve.Name("rootData"),dynamicAnchors:new Ve.Name("dynamicAnchors"),vErrors:new Ve.Name("vErrors"),errors:new Ve.Name("errors"),this:new Ve.Name("this"),self:new Ve.Name("self"),scope:new Ve.Name("scope"),json:new Ve.Name("json"),jsonPos:new Ve.Name("jsonPos"),jsonLen:new Ve.Name("jsonLen"),jsonPart:new Ve.Name("jsonPart")};Bt.default=mk;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=ae,n=K,r=Bt;t.keywordError={message:({keyword:w})=>(0,e.str)`must pass "${w}" keyword validation`},t.keyword$DataError={message:({keyword:w,schemaType:h})=>h?(0,e.str)`"${w}" keyword must be ${h} ($data)`:(0,e.str)`"${w}" keyword is invalid ($data)`};function o(w,h=t.keywordError,v,b){const{it:E}=w,{gen:N,compositeRule:j,allErrors:T}=E,M=d(w,h,v);b??(j||T)?c(N,M):u(E,(0,e._)`[${M}]`)}t.reportError=o;function s(w,h=t.keywordError,v){const{it:b}=w,{gen:E,compositeRule:N,allErrors:j}=b,T=d(w,h,v);c(E,T),N||j||u(b,r.default.vErrors)}t.reportExtraError=s;function i(w,h){w.assign(r.default.errors,h),w.if((0,e._)`${r.default.vErrors} !== null`,()=>w.if(h,()=>w.assign((0,e._)`${r.default.vErrors}.length`,h),()=>w.assign(r.default.vErrors,null)))}t.resetErrorsCount=i;function a({gen:w,keyword:h,schemaValue:v,data:b,errsCount:E,it:N}){if(E===void 0)throw new Error("ajv implementation error");const j=w.name("err");w.forRange("i",E,r.default.errors,T=>{w.const(j,(0,e._)`${r.default.vErrors}[${T}]`),w.if((0,e._)`${j}.instancePath === undefined`,()=>w.assign((0,e._)`${j}.instancePath`,(0,e.strConcat)(r.default.instancePath,N.errorPath))),w.assign((0,e._)`${j}.schemaPath`,(0,e.str)`${N.errSchemaPath}/${h}`),N.opts.verbose&&(w.assign((0,e._)`${j}.schema`,v),w.assign((0,e._)`${j}.data`,b))})}t.extendErrors=a;function c(w,h){const v=w.const("err",h);w.if((0,e._)`${r.default.vErrors} === null`,()=>w.assign(r.default.vErrors,(0,e._)`[${v}]`),(0,e._)`${r.default.vErrors}.push(${v})`),w.code((0,e._)`${r.default.errors}++`)}function u(w,h){const{gen:v,validateName:b,schemaEnv:E}=w;E.$async?v.throw((0,e._)`new ${w.ValidationError}(${h})`):(v.assign((0,e._)`${b}.errors`,h),v.return(!1))}const l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(w,h,v){const{createErrors:b}=w.it;return b===!1?(0,e._)`{}`:f(w,h,v)}function f(w,h,v={}){const{gen:b,it:E}=w,N=[g(E,v),p(w,v)];return y(w,h,N),b.object(...N)}function g({errorPath:w},{instancePath:h}){const v=h?(0,e.str)`${w}${(0,n.getErrorPath)(h,n.Type.Str)}`:w;return[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,v)]}function p({keyword:w,it:{errSchemaPath:h}},{schemaPath:v,parentSchema:b}){let E=b?h:(0,e.str)`${h}/${w}`;return v&&(E=(0,e.str)`${E}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,E]}function y(w,{params:h,message:v},b){const{keyword:E,data:N,schemaValue:j,it:T}=w,{opts:M,propertyName:C,topSchemaRef:G,schemaPath:H}=T;b.push([l.keyword,E],[l.params,typeof h=="function"?h(w):h||(0,e._)`{}`]),M.messages&&b.push([l.message,typeof v=="function"?v(w):v]),M.verbose&&b.push([l.schema,j],[l.parentSchema,(0,e._)`${G}${H}`],[r.default.data,N]),C&&b.push([l.propertyName,C])}})(Ss);Object.defineProperty(eo,"__esModule",{value:!0});eo.boolOrEmptySchema=eo.topBoolOrEmptySchema=void 0;const gk=Ss,yk=ae,wk=Bt,vk={message:"boolean schema is false"};function $k(t){const{gen:e,schema:n,validateName:r}=t;n===!1?_w(t,!1):typeof n=="object"&&n.$async===!0?e.return(wk.default.data):(e.assign((0,yk._)`${r}.errors`,null),e.return(!0))}eo.topBoolOrEmptySchema=$k;function bk(t,e){const{gen:n,schema:r}=t;r===!1?(n.var(e,!1),_w(t)):n.var(e,!0)}eo.boolOrEmptySchema=bk;function _w(t,e){const{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,gk.reportError)(o,vk,void 0,e)}var Ae={},mr={};Object.defineProperty(mr,"__esModule",{value:!0});mr.getRules=mr.isJSONType=void 0;const Ek=["string","number","integer","boolean","null","object","array"],Sk=new Set(Ek);function _k(t){return typeof t=="string"&&Sk.has(t)}mr.isJSONType=_k;function Nk(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}mr.getRules=Nk;var Jt={};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.shouldUseRule=Jt.shouldUseGroup=Jt.schemaHasRulesForType=void 0;function Ok({schema:t,self:e},n){const r=e.RULES.types[n];return r&&r!==!0&&Nw(t,r)}Jt.schemaHasRulesForType=Ok;function Nw(t,e){return e.rules.some(n=>Ow(t,n))}Jt.shouldUseGroup=Nw;function Ow(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Jt.shouldUseRule=Ow;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.reportTypeError=Ae.checkDataTypes=Ae.checkDataType=Ae.coerceAndCheckDataType=Ae.getJSONTypes=Ae.getSchemaTypes=Ae.DataType=void 0;const kk=mr,jk=Jt,Ak=Ss,te=ae,kw=K;var zr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(zr||(Ae.DataType=zr={}));function Ik(t){const e=jw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ae.getSchemaTypes=Ik;function jw(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(kk.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ae.getJSONTypes=jw;function Pk(t,e){const{gen:n,data:r,opts:o}=t,s=xk(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,jk.schemaHasRulesForType)(t,e[0]));if(i){const a=Gl(e,r,o.strictNumbers,zr.Wrong);n.if(a,()=>{s.length?Rk(t,e,s):zl(t)})}return i}Ae.coerceAndCheckDataType=Pk;const Aw=new Set(["string","number","integer","boolean","null"]);function xk(t,e){return e?t.filter(n=>Aw.has(n)||e==="array"&&n==="array"):[]}function Rk(t,e,n){const{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,te._)`typeof ${o}`),a=r.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&r.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(Gl(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,te._)`${a} !== undefined`);for(const u of n)(Aw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),zl(t),r.endIf(),r.if((0,te._)`${a} !== undefined`,()=>{r.assign(o,a),Tk(t,a)});function c(u){switch(u){case"string":r.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":r.elseIf((0,te._)`${i} == "boolean" || ${o} === null
|
|
187
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,te._)`+${o}`);return;case"integer":r.elseIf((0,te._)`${i} === "boolean" || ${o} === null
|
|
188
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,te._)`+${o}`);return;case"boolean":r.elseIf((0,te._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,te._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,te._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,te._)`${i} === "string" || ${i} === "number"
|
|
189
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function Tk({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${n}]`,r))}function du(t,e,n,r=zr.Correct){const o=r===zr.Correct?te.operators.EQ:te.operators.NEQ;let s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return r===zr.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,n?(0,te._)`isFinite(${e})`:te.nil)}}Ae.checkDataType=du;function Gl(t,e,n,r){if(t.length===1)return du(t[0],e,n,r);let o;const s=(0,kw.toHash)(t);if(s.array&&s.object){const i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(const i in s)o=(0,te.and)(o,du(i,e,n,r));return o}Ae.checkDataTypes=Gl;const Ck={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function zl(t){const e=Mk(t);(0,Ak.reportError)(e,Ck)}Ae.reportTypeError=zl;function Mk(t){const{gen:e,data:n,schema:r}=t,o=(0,kw.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0});Ea.assignDefaults=void 0;const kr=ae,Lk=K;function Dk(t,e){const{properties:n,items:r}=t.schema;if(e==="object"&&n)for(const o in n)yh(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>yh(t,s,o.default))}Ea.assignDefaults=Dk;function yh(t,e,n){const{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;const a=(0,kr._)`${s}${(0,kr.getProperty)(e)}`;if(o){(0,Lk.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,kr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,kr._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,kr._)`${a} = ${(0,kr.stringify)(n)}`)}var Tt={},se={};Object.defineProperty(se,"__esModule",{value:!0});se.validateUnion=se.validateArray=se.usePattern=se.callValidateCode=se.schemaProperties=se.allSchemaProperties=se.noPropertyInData=se.propertyInData=se.isOwnProperty=se.hasPropFunc=se.reportMissingProp=se.checkMissingProp=se.checkReportMissingProp=void 0;const ve=ae,Wl=K,cn=Bt,Uk=K;function Bk(t,e){const{gen:n,data:r,it:o}=t;n.if(Jl(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ve._)`${e}`},!0),t.error()})}se.checkReportMissingProp=Bk;function Fk({gen:t,data:e,it:{opts:n}},r,o){return(0,ve.or)(...r.map(s=>(0,ve.and)(Jl(t,e,s,n.ownProperties),(0,ve._)`${o} = ${s}`)))}se.checkMissingProp=Fk;function qk(t,e){t.setParams({missingProperty:e},!0),t.error()}se.reportMissingProp=qk;function Iw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ve._)`Object.prototype.hasOwnProperty`})}se.hasPropFunc=Iw;function Hl(t,e,n){return(0,ve._)`${Iw(t)}.call(${e}, ${n})`}se.isOwnProperty=Hl;function Kk(t,e,n,r){const o=(0,ve._)`${e}${(0,ve.getProperty)(n)} !== undefined`;return r?(0,ve._)`${o} && ${Hl(t,e,n)}`:o}se.propertyInData=Kk;function Jl(t,e,n,r){const o=(0,ve._)`${e}${(0,ve.getProperty)(n)} === undefined`;return r?(0,ve.or)(o,(0,ve.not)(Hl(t,e,n))):o}se.noPropertyInData=Jl;function Pw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}se.allSchemaProperties=Pw;function Vk(t,e){return Pw(e).filter(n=>!(0,Wl.alwaysValidSchema)(t,e[n]))}se.schemaProperties=Vk;function Gk({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,ve._)`${t}, ${e}, ${r}${o}`:e,d=[[cn.default.instancePath,(0,ve.strConcat)(cn.default.instancePath,s)],[cn.default.parentData,i.parentData],[cn.default.parentDataProperty,i.parentDataProperty],[cn.default.rootData,cn.default.rootData]];i.opts.dynamicRef&&d.push([cn.default.dynamicAnchors,cn.default.dynamicAnchors]);const f=(0,ve._)`${l}, ${n.object(...d)}`;return c!==ve.nil?(0,ve._)`${a}.call(${c}, ${f})`:(0,ve._)`${a}(${f})`}se.callValidateCode=Gk;const zk=(0,ve._)`new RegExp`;function Wk({gen:t,it:{opts:e}},n){const r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ve._)`${o.code==="new RegExp"?zk:(0,Uk.useFunc)(t,o)}(${n}, ${r})`})}se.usePattern=Wk;function Hk(t){const{gen:e,data:n,keyword:r,it:o}=t,s=e.name("valid");if(o.allErrors){const a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){const c=e.const("len",(0,ve._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Wl.Type.Num},s),e.if((0,ve.not)(s),a)})}}se.validateArray=Hk;function Jk(t){const{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,Wl.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=e.let("valid",!1),i=e.name("_valid");e.block(()=>n.forEach((a,c)=>{const u=t.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);e.assign(s,(0,ve._)`${s} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,ve.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}se.validateUnion=Jk;Object.defineProperty(Tt,"__esModule",{value:!0});Tt.validateKeywordUsage=Tt.validSchemaType=Tt.funcKeywordCode=Tt.macroKeywordCode=void 0;const Ye=ae,Zn=Bt,Qk=se,Yk=Ss;function Zk(t,e){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=xw(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");t.subschema({schema:a,schemaPath:Ye.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Tt.macroKeywordCode=Zk;function Xk(t,e){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;t1(c,e);const u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=xw(r,o,u),d=r.let("valid");t.block$data(d,f),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function f(){if(e.errors===!1)y(),e.modifying&&wh(t),w(()=>t.error());else{const h=e.async?g():p();e.modifying&&wh(t),w(()=>e1(t,h))}}function g(){const h=r.let("ruleErrs",null);return r.try(()=>y((0,Ye._)`await `),v=>r.assign(d,!1).if((0,Ye._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(h,(0,Ye._)`${v}.errors`),()=>r.throw(v))),h}function p(){const h=(0,Ye._)`${l}.errors`;return r.assign(h,null),y(Ye.nil),h}function y(h=e.async?(0,Ye._)`await `:Ye.nil){const v=c.opts.passContext?Zn.default.this:Zn.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,Ye._)`${h}${(0,Qk.callValidateCode)(t,l,v,b)}`,e.modifying)}function w(h){var v;r.if((0,Ye.not)((v=e.valid)!==null&&v!==void 0?v:d),h)}}Tt.funcKeywordCode=Xk;function wh(t){const{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Ye._)`${r.parentData}[${r.parentDataProperty}]`))}function e1(t,e){const{gen:n}=t;n.if((0,Ye._)`Array.isArray(${e})`,()=>{n.assign(Zn.default.vErrors,(0,Ye._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,Ye._)`${Zn.default.vErrors}.length`),(0,Yk.extendErrors)(t)},()=>t.error())}function t1({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function xw(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Ye.stringify)(n)})}function n1(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Tt.validSchemaType=n1;function r1({schema:t,opts:e,self:n,errSchemaPath:r},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(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){const a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}Tt.validateKeywordUsage=r1;var bn={};Object.defineProperty(bn,"__esModule",{value:!0});bn.extendSubschemaMode=bn.extendSubschemaData=bn.getSubschema=void 0;const xt=ae,Rw=K;function o1(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,xt._)`${t.schemaPath}${(0,xt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,xt._)`${t.schemaPath}${(0,xt.getProperty)(e)}${(0,xt.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Rw.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}bn.getSubschema=o1;function s1(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,xt._)`${e.data}${(0,xt.getProperty)(n)}`,!0);c(f),t.errorPath=(0,xt.str)`${u}${(0,Rw.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,xt._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){const u=o instanceof xt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}bn.extendSubschemaData=s1;function i1(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}bn.extendSubschemaMode=i1;var Le={},Tw=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n},Cw={exports:{}},yn=Cw.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};yi(e,r,o,t,"",t)};yn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yn.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 yi(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in yn.arrayKeywords)for(var f=0;f<d.length;f++)yi(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in yn.propsKeywords){if(d&&typeof d=="object")for(var g in d)yi(t,e,n,d[g],o+"/"+l+"/"+a1(g),s,o,l,r,g)}else(l in yn.keywords||t.allKeys&&!(l in yn.skipKeywords))&&yi(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function a1(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var c1=Cw.exports;Object.defineProperty(Le,"__esModule",{value:!0});Le.getSchemaRefs=Le.resolveUrl=Le.normalizeId=Le._getFullPath=Le.getFullPath=Le.inlineRef=void 0;const u1=K,l1=Tw,d1=c1,f1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function p1(t,e=!0){return typeof t=="boolean"?!0:e===!0?!fu(t):e?Mw(t)<=e:!1}Le.inlineRef=p1;const h1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function fu(t){for(const e in t){if(h1.has(e))return!0;const n=t[e];if(Array.isArray(n)&&n.some(fu)||typeof n=="object"&&fu(n))return!0}return!1}function Mw(t){let e=0;for(const n in t)if(n==="$ref"||(e++,!f1.has(n)&&(typeof t[n]=="object"&&(0,u1.eachItem)(t[n],r=>e+=Mw(r)),e===1/0)))return 1/0;return e}function Lw(t,e="",n){n!==!1&&(e=Wr(e));const r=t.parse(e);return Dw(t,r)}Le.getFullPath=Lw;function Dw(t,e){return t.serialize(e).split("#")[0]+"#"}Le._getFullPath=Dw;const m1=/#\/?$/;function Wr(t){return t?t.replace(m1,""):""}Le.normalizeId=Wr;function g1(t,e,n){return n=Wr(n),t.resolve(e,n)}Le.resolveUrl=g1;const y1=/^[a-z_][-a-z0-9._]*$/i;function w1(t,e){if(typeof t=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Wr(t[n]||e),s={"":o},i=Lw(r,o,!1),a={},c=new Set;return d1(t,{allKeys:!0},(d,f,g,p)=>{if(p===void 0)return;const y=i+f;let w=s[p];typeof d[n]=="string"&&(w=h.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=w;function h(b){const E=this.opts.uriResolver.resolve;if(b=Wr(w?E(w,b):b),c.has(b))throw l(b);c.add(b);let N=this.refs[b];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(d,N.schema,b):b!==Wr(y)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=y),b}function v(b){if(typeof b=="string"){if(!y1.test(b))throw new Error(`invalid anchor "${b}"`);h.call(this,`#${b}`)}}}),a;function u(d,f,g){if(f!==void 0&&!l1(d,f))throw l(g)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Le.getSchemaRefs=w1;Object.defineProperty(Nt,"__esModule",{value:!0});Nt.getData=Nt.KeywordCxt=Nt.validateFunctionCode=void 0;const Uw=eo,vh=Ae,Ql=Jt,Gi=Ae,v1=Ea,Bo=Tt,rc=bn,z=ae,Q=Bt,$1=Le,Qt=K,$o=Ss;function b1(t){if(qw(t)&&(Kw(t),Fw(t))){_1(t);return}Bw(t,()=>(0,Uw.topBoolOrEmptySchema)(t))}Nt.validateFunctionCode=b1;function Bw({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,z._)`${Q.default.data}, ${Q.default.valCxt}`,r.$async,()=>{t.code((0,z._)`"use strict"; ${$h(n,o)}`),S1(t,o),t.code(s)}):t.func(e,(0,z._)`${Q.default.data}, ${E1(o)}`,r.$async,()=>t.code($h(n,o)).code(s))}function E1(t){return(0,z._)`{${Q.default.instancePath}="", ${Q.default.parentData}, ${Q.default.parentDataProperty}, ${Q.default.rootData}=${Q.default.data}${t.dynamicRef?(0,z._)`, ${Q.default.dynamicAnchors}={}`:z.nil}}={}`}function S1(t,e){t.if(Q.default.valCxt,()=>{t.var(Q.default.instancePath,(0,z._)`${Q.default.valCxt}.${Q.default.instancePath}`),t.var(Q.default.parentData,(0,z._)`${Q.default.valCxt}.${Q.default.parentData}`),t.var(Q.default.parentDataProperty,(0,z._)`${Q.default.valCxt}.${Q.default.parentDataProperty}`),t.var(Q.default.rootData,(0,z._)`${Q.default.valCxt}.${Q.default.rootData}`),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,z._)`${Q.default.valCxt}.${Q.default.dynamicAnchors}`)},()=>{t.var(Q.default.instancePath,(0,z._)`""`),t.var(Q.default.parentData,(0,z._)`undefined`),t.var(Q.default.parentDataProperty,(0,z._)`undefined`),t.var(Q.default.rootData,Q.default.data),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,z._)`{}`)})}function _1(t){const{schema:e,opts:n,gen:r}=t;Bw(t,()=>{n.$comment&&e.$comment&&Gw(t),A1(t),r.let(Q.default.vErrors,null),r.let(Q.default.errors,0),n.unevaluated&&N1(t),Vw(t),x1(t)})}function N1(t){const{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,z._)`${n}.evaluated`),e.if((0,z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,z._)`${t.evaluated}.props`,(0,z._)`undefined`)),e.if((0,z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,z._)`${t.evaluated}.items`,(0,z._)`undefined`))}function $h(t,e){const n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${n} */`:z.nil}function O1(t,e){if(qw(t)&&(Kw(t),Fw(t))){k1(t,e);return}(0,Uw.boolOrEmptySchema)(t,e)}function Fw({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const n in t)if(e.RULES.all[n])return!0;return!1}function qw(t){return typeof t.schema!="boolean"}function k1(t,e){const{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Gw(t),I1(t),P1(t);const s=r.const("_errs",Q.default.errors);Vw(t,s),r.var(e,(0,z._)`${s} === ${Q.default.errors}`)}function Kw(t){(0,Qt.checkUnknownRules)(t),j1(t)}function Vw(t,e){if(t.opts.jtd)return bh(t,[],!1,e);const n=(0,vh.getSchemaTypes)(t.schema),r=(0,vh.coerceAndCheckDataType)(t,n);bh(t,n,!r,e)}function j1(t){const{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Qt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function A1(t){const{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Qt.checkStrictMode)(t,"default is ignored in the schema root")}function I1(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,$1.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function P1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gw({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)t.code((0,z._)`${Q.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,z.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${Q.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function x1(t){const{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,z._)`${Q.default.errors} === 0`,()=>e.return(Q.default.data),()=>e.throw((0,z._)`new ${o}(${Q.default.vErrors})`)):(e.assign((0,z._)`${r}.errors`,Q.default.vErrors),s.unevaluated&&R1(t),e.return((0,z._)`${Q.default.errors} === 0`))}function R1({gen:t,evaluated:e,props:n,items:r}){n instanceof z.Name&&t.assign((0,z._)`${e}.props`,n),r instanceof z.Name&&t.assign((0,z._)`${e}.items`,r)}function bh(t,e,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Qt.schemaHasRulesButRef)(s,l))){o.block(()=>Hw(t,"$ref",l.all.$ref.definition));return}c.jtd||T1(t,e),o.block(()=>{for(const f of l.rules)d(f);d(l.post)});function d(f){(0,Ql.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Gi.checkDataType)(f.type,i,c.strictNumbers)),Eh(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,Gi.reportTypeError)(t)),o.endIf()):Eh(t,f),a||o.if((0,z._)`${Q.default.errors} === ${r||0}`))}}function Eh(t,e){const{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,v1.assignDefaults)(t,e.type),n.block(()=>{for(const s of e.rules)(0,Ql.shouldUseRule)(r,s)&&Hw(t,s.keyword,s.definition,e.type)})}function T1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(C1(t,e),t.opts.allowUnionTypes||M1(t,e),L1(t,t.dataTypes))}function C1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{zw(t.dataTypes,n)||Yl(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),U1(t,e)}}function M1(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Yl(t,"use allowUnionTypes to allow union type keyword")}function L1(t,e){const n=t.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,Ql.shouldUseRule)(t.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>D1(e,i))&&Yl(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function D1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function zw(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function U1(t,e){const n=[];for(const r of t.dataTypes)zw(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Yl(t,e){const n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Qt.checkStrictMode)(t,e,t.opts.strictTypes)}let Ww=class{constructor(e,n,r){if((0,Bo.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Qt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Jw(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Bo.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Q.default.errors))}result(e,n,r){this.failResult((0,z.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,z.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:n}=this;this.fail((0,z._)`${n} !== undefined && (${(0,z.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?$o.reportExtraError:$o.reportError)(this,this.def.error,n)}$dataError(){(0,$o.reportError)(this,this.def.$dataError||$o.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$o.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=z.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=z.nil,n=z.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,z.or)((0,z._)`${o} === undefined`,n)),e!==z.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,z.or)(i(),a());function i(){if(r.length){if(!(n instanceof z.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,z._)`${(0,Gi.checkDataTypes)(c,n,s.opts.strictNumbers,Gi.DataType.Wrong)}`}return z.nil}function a(){if(o.validateSchema){const c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,z._)`!${c}(${n})`}return z.nil}}subschema(e,n){const r=(0,rc.getSubschema)(this.it,e);(0,rc.extendSubschemaData)(r,this.it,e),(0,rc.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return O1(o,n),o}mergeEvaluated(e,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Qt.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Qt.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,z.Name)),!0}};Nt.KeywordCxt=Ww;function Hw(t,e,n,r){const o=new Ww(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Bo.funcKeywordCode)(o,n):"macro"in n?(0,Bo.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Bo.funcKeywordCode)(o,n)}const B1=/^\/(?:[^~]|~0|~1)*$/,F1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Jw(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return Q.default.rootData;if(t[0]==="/"){if(!B1.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=Q.default.rootData}else{const u=F1.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,z._)`${s}${(0,z.getProperty)((0,Qt.unescapeJsonPointer)(u))}`,i=(0,z._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Nt.getData=Jw;var _s={};Object.defineProperty(_s,"__esModule",{value:!0});let q1=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_s.default=q1;var uo={};Object.defineProperty(uo,"__esModule",{value:!0});const oc=Le;let K1=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,oc.resolveUrl)(e,n,r),this.missingSchema=(0,oc.normalizeId)((0,oc.getFullPath)(e,this.missingRef))}};uo.default=K1;var st={};Object.defineProperty(st,"__esModule",{value:!0});st.resolveSchema=st.getCompilingSchema=st.resolveRef=st.compileSchema=st.SchemaEnv=void 0;const wt=ae,V1=_s,Vn=Bt,Et=Le,Sh=K,G1=Nt;let Sa=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Et.normalizeId)(r==null?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r==null?void 0:r.$async,this.refs={}}};st.SchemaEnv=Sa;function Zl(t){const e=Qw.call(this,t);if(e)return e;const n=(0,Et.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new wt.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;t.$async&&(a=i.scopeValue("Error",{ref:V1.default,code:(0,wt._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");t.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:Vn.default.data,parentData:Vn.default.parentData,parentDataProperty:Vn.default.parentDataProperty,dataNames:[Vn.default.data],dataPathArr:[wt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,wt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:wt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wt._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(t),(0,G1.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const d=i.toString();l=`${i.scopeRefs(Vn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));const f=new Function(`${Vn.default.self}`,`${Vn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){const{props:g,items:p}=u;f.evaluated={props:g instanceof wt.Name?void 0:g,items:p instanceof wt.Name?void 0:p,dynamicProps:g instanceof wt.Name,dynamicItems:p instanceof wt.Name},f.source&&(f.source.evaluated=(0,wt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}st.compileSchema=Zl;function z1(t,e,n){var r;n=(0,Et.resolveUrl)(this.opts.uriResolver,e,n);const o=t.refs[n];if(o)return o;let s=J1.call(this,t,n);if(s===void 0){const i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Sa({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=W1.call(this,s)}st.resolveRef=z1;function W1(t){return(0,Et.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Zl.call(this,t)}function Qw(t){for(const e of this._compilations)if(H1(e,t))return e}st.getCompilingSchema=Qw;function H1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function J1(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||_a.call(this,t,e)}function _a(t,e){const n=this.opts.uriResolver.parse(e),r=(0,Et._getFullPath)(this.opts.uriResolver,n);let o=(0,Et.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return sc.call(this,n,t);const s=(0,Et.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=_a.call(this,t,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:sc.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||Zl.call(this,i),s===(0,Et.normalizeId)(e)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Et.resolveUrl)(this.opts.uriResolver,o,u)),new Sa({schema:a,schemaId:c,root:t,baseId:o})}return sc.call(this,n,i)}}st.resolveSchema=_a;const Q1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function sc(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,Sh.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!Q1.has(a)&&u&&(e=(0,Et.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Sh.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Et.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=_a.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Sa({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}const Y1="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Z1="Meta-schema for $data reference (JSON AnySchema extension proposal)",X1="object",ej=["$data"],tj={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},nj=!1,rj={$id:Y1,description:Z1,type:X1,required:ej,properties:tj,additionalProperties:nj};var Xl={},Na={exports:{}};const oj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Yw=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),ed=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Zw=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),sj=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Xw(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}const ij=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _h(t){return t.length=0,!0}function aj(t,e,n){if(t.length){const r=Xw(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function cj(t){let e=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=aj;for(let c=0;c<t.length;c++){const u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=_h}else{o.push(u);continue}}return o.length&&(a===_h?n.zone=o.join(""):i?r.push(o.join("")):r.push(Xw(o))),n.address=r.join(""),n}function ev(t){if(uj(t,":")<2)return{host:t,isIPV6:!1};const e=cj(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function uj(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function lj(t){let e=t;const n=[];let r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}const dj={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},fj=/[@/?#:]/g,pj=/[@/?#]/g;function tv(t,e){const n=e?pj:fj;return n.lastIndex=0,t.replace(n,r=>dj[r])}function hj(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){const o=t.slice(r+1,r+3);if(ed(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Zw(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function mj(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(ed(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Zw(s)?e+=s:e+="%"+o,n+=2;continue}}sj(t[n])?e+=t[n]:e+=escape(t[n])}return e}function gj(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(ed(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function yj(t){const e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Yw(n)){const r=ev(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=tv(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}var nv={nonSimpleDomain:ij,recomposeAuthority:yj,reescapeHostDelimiters:tv,normalizePercentEncoding:hj,normalizePathEncoding:mj,escapePreservingEscapes:gj,removeDotSegments:lj,isIPv4:Yw,isUUID:oj,normalizeIPv6:ev};const{isUUID:wj}=nv,vj=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function rv(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function ov(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function sv(t){const e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function $j(t){return t.secure=rv(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function bj(t){if((t.port===(rv(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){const[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function Ej(t,e){if(!t.path)return t.error="URN can not be parsed",t;const n=t.path.match(vj);if(n){const r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];const o=`${r}:${e.nid||t.nid}`,s=td(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Sj(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=td(o);s&&(t=s.serialize(t,e));const i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function _j(t,e){const n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!wj(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Nj(t){const e=t;return e.nss=(t.uuid||"").toLowerCase(),e}const iv={scheme:"http",domainHost:!0,parse:ov,serialize:sv},Oj={scheme:"https",domainHost:iv.domainHost,parse:ov,serialize:sv},wi={scheme:"ws",domainHost:!0,parse:$j,serialize:bj},kj={scheme:"wss",domainHost:wi.domainHost,parse:wi.parse,serialize:wi.serialize},jj={scheme:"urn",parse:Ej,serialize:Sj,skipNormalize:!0},Aj={scheme:"urn:uuid",parse:_j,serialize:Nj,skipNormalize:!0},zi={http:iv,https:Oj,ws:wi,wss:kj,urn:jj,"urn:uuid":Aj};Object.setPrototypeOf(zi,null);function td(t){return t&&(zi[t]||zi[t.toLowerCase()])||void 0}var Ij={SCHEMES:zi,getSchemeHandler:td};const{normalizeIPv6:Pj,removeDotSegments:Ao,recomposeAuthority:xj,normalizePercentEncoding:Rj,normalizePathEncoding:Tj,escapePreservingEscapes:Cj,reescapeHostDelimiters:Mj,isIPv4:Lj,nonSimpleDomain:Dj}=nv,{SCHEMES:Uj,getSchemeHandler:av}=Ij;function Bj(t,e){return typeof t=="string"?t=zj(t,e):typeof t=="object"&&(t=to(gr(t,e),e)),t}function Fj(t,e,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=cv(to(t,r),to(e,r),r,!0);return r.skipEscape=!0,gr(o,r)}function cv(t,e,n,r){const o={};return r||(t=to(gr(t,n),n),e=to(gr(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ao(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ao(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ao(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Ao(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function qj(t,e,n){const r=Nh(t,n),o=Nh(e,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function gr(t,e){const n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],s=av(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Rj(n.path):(n.path=Cj(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=xj(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=Ao(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const Kj=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Vj=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function Gj(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function uv(t,e){const n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1,s=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);const i=t.match(Vj);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=t.match(Kj);if(a){r.scheme=a[1],r.userinfo=a[3],r.host=a[4],r.port=parseInt(a[5],10),r.path=a[6]||"",r.query=a[7],r.fragment=a[8],isNaN(r.port)&&(r.port=a[5]);const c=Gj(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(Lj(r.host)===!1){const l=Pj(r.host);r.host=l.host.toLowerCase(),s=l.isIPV6}else s=!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 u=av(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&Dj(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(l){r.error=r.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Mj(unescape(r.host),s))),r.path&&(r.path=Tj(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}u&&u.parse&&u.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function to(t,e){return uv(t,e).parsed}function zj(t,e){return lv(t,e).normalized}function lv(t,e){const{parsed:n,malformedAuthorityOrPort:r}=uv(t,e);return{normalized:r?t:gr(n,e),malformedAuthorityOrPort:r}}function Nh(t,e){if(typeof t=="string"){const{normalized:n,malformedAuthorityOrPort:r}=lv(t,e);return r?void 0:n}if(typeof t=="object")return gr(t,e)}const nd={SCHEMES:Uj,normalize:Bj,resolve:Fj,resolveComponent:cv,equal:qj,serialize:gr,parse:to};Na.exports=nd;Na.exports.default=nd;Na.exports.fastUri=nd;var Wj=Na.exports;Object.defineProperty(Xl,"__esModule",{value:!0});const dv=Wj;dv.code='require("ajv/dist/runtime/uri").default';Xl.default=dv;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=Nt;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var n=ae;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=_s,o=uo,s=mr,i=st,a=ae,c=Le,u=Ae,l=K,d=rj,f=Xl,g=(A,S)=>new RegExp(A,S);g.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),w={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."},h={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function b(A){var S,k,_,m,$,O,x,R,U,q,re,Qe,jn,An,In,Pn,xn,Rn,Tn,Cn,Mn,Ln,Dn,Un,Bn;const yt=A.strict,Fn=(S=A.code)===null||S===void 0?void 0:S.optimize,wo=Fn===!0||Fn===void 0?1:Fn||0,vo=(_=(k=A.code)===null||k===void 0?void 0:k.regExp)!==null&&_!==void 0?_:g,Ha=(m=A.uriResolver)!==null&&m!==void 0?m:f.default;return{strictSchema:(O=($=A.strictSchema)!==null&&$!==void 0?$:yt)!==null&&O!==void 0?O:!0,strictNumbers:(R=(x=A.strictNumbers)!==null&&x!==void 0?x:yt)!==null&&R!==void 0?R:!0,strictTypes:(q=(U=A.strictTypes)!==null&&U!==void 0?U:yt)!==null&&q!==void 0?q:"log",strictTuples:(Qe=(re=A.strictTuples)!==null&&re!==void 0?re:yt)!==null&&Qe!==void 0?Qe:"log",strictRequired:(An=(jn=A.strictRequired)!==null&&jn!==void 0?jn:yt)!==null&&An!==void 0?An:!1,code:A.code?{...A.code,optimize:wo,regExp:vo}:{optimize:wo,regExp:vo},loopRequired:(In=A.loopRequired)!==null&&In!==void 0?In:v,loopEnum:(Pn=A.loopEnum)!==null&&Pn!==void 0?Pn:v,meta:(xn=A.meta)!==null&&xn!==void 0?xn:!0,messages:(Rn=A.messages)!==null&&Rn!==void 0?Rn:!0,inlineRefs:(Tn=A.inlineRefs)!==null&&Tn!==void 0?Tn:!0,schemaId:(Cn=A.schemaId)!==null&&Cn!==void 0?Cn:"$id",addUsedSchema:(Mn=A.addUsedSchema)!==null&&Mn!==void 0?Mn:!0,validateSchema:(Ln=A.validateSchema)!==null&&Ln!==void 0?Ln:!0,validateFormats:(Dn=A.validateFormats)!==null&&Dn!==void 0?Dn:!0,unicodeRegExp:(Un=A.unicodeRegExp)!==null&&Un!==void 0?Un:!0,int32range:(Bn=A.int32range)!==null&&Bn!==void 0?Bn:!0,uriResolver:Ha}}class E{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...b(S)};const{es5:k,lines:_}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:k,lines:_}),this.logger=Z(S.logger);const m=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,w,S,"NOT SUPPORTED"),N.call(this,h,S,"DEPRECATED","warn"),this._metaOpts=G.call(this),S.formats&&M.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&C.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),T.call(this),S.validateFormats=m}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:k,schemaId:_}=this.opts;let m=d;_==="id"&&(m={...d},m.id=m.$id,delete m.$id),k&&S&&this.addMetaSchema(m,m[_],!1)}defaultMeta(){const{meta:S,schemaId:k}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[k]||S:void 0}validate(S,k){let _;if(typeof S=="string"){if(_=this.getSchema(S),!_)throw new Error(`no schema with key or ref "${S}"`)}else _=this.compile(S);const m=_(k);return"$async"in _||(this.errors=_.errors),m}compile(S,k){const _=this._addSchema(S,k);return _.validate||this._compileSchemaEnv(_)}compileAsync(S,k){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:_}=this.opts;return m.call(this,S,k);async function m(q,re){await $.call(this,q.$schema);const Qe=this._addSchema(q,re);return Qe.validate||O.call(this,Qe)}async function $(q){q&&!this.getSchema(q)&&await m.call(this,{$ref:q},!0)}async function O(q){try{return this._compileSchemaEnv(q)}catch(re){if(!(re instanceof o.default))throw re;return x.call(this,re),await R.call(this,re.missingSchema),O.call(this,q)}}function x({missingSchema:q,missingRef:re}){if(this.refs[q])throw new Error(`AnySchema ${q} is loaded but ${re} cannot be resolved`)}async function R(q){const re=await U.call(this,q);this.refs[q]||await $.call(this,re.$schema),this.refs[q]||this.addSchema(re,q,k)}async function U(q){const re=this._loading[q];if(re)return re;try{return await(this._loading[q]=_(q))}finally{delete this._loading[q]}}}addSchema(S,k,_,m=this.opts.validateSchema){if(Array.isArray(S)){for(const O of S)this.addSchema(O,void 0,_,m);return this}let $;if(typeof S=="object"){const{schemaId:O}=this.opts;if($=S[O],$!==void 0&&typeof $!="string")throw new Error(`schema ${O} must be string`)}return k=(0,c.normalizeId)(k||$),this._checkUnique(k),this.schemas[k]=this._addSchema(S,_,k,m,!0),this}addMetaSchema(S,k,_=this.opts.validateSchema){return this.addSchema(S,k,!0,_),this}validateSchema(S,k){if(typeof S=="boolean")return!0;let _;if(_=S.$schema,_!==void 0&&typeof _!="string")throw new Error("$schema must be a string");if(_=_||this.opts.defaultMeta||this.defaultMeta(),!_)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const m=this.validate(_,S);if(!m&&k){const $="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error($);else throw new Error($)}return m}getSchema(S){let k;for(;typeof(k=j.call(this,S))=="string";)S=k;if(k===void 0){const{schemaId:_}=this.opts,m=new i.SchemaEnv({schema:{},schemaId:_});if(k=i.resolveSchema.call(this,m,S),!k)return;this.refs[S]=k}return k.validate||this._compileSchemaEnv(k)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const k=j.call(this,S);return typeof k=="object"&&this._cache.delete(k.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const k=S;this._cache.delete(k);let _=S[this.opts.schemaId];return _&&(_=(0,c.normalizeId)(_),delete this.schemas[_],delete this.refs[_]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const k of S)this.addKeyword(k);return this}addKeyword(S,k){let _;if(typeof S=="string")_=S,typeof k=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),k.keyword=_);else if(typeof S=="object"&&k===void 0){if(k=S,_=k.keyword,Array.isArray(_)&&!_.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(fe.call(this,_,k),!k)return(0,l.eachItem)(_,$=>he.call(this,$)),this;Oe.call(this,k);const m={...k,type:(0,u.getJSONTypes)(k.type),schemaType:(0,u.getJSONTypes)(k.schemaType)};return(0,l.eachItem)(_,m.type.length===0?$=>he.call(this,$,m):$=>m.type.forEach(O=>he.call(this,$,m,O))),this}getKeyword(S){const k=this.RULES.all[S];return typeof k=="object"?k.definition:!!k}removeKeyword(S){const{RULES:k}=this;delete k.keywords[S],delete k.all[S];for(const _ of k.rules){const m=_.rules.findIndex($=>$.keyword===S);m>=0&&_.rules.splice(m,1)}return this}addFormat(S,k){return typeof k=="string"&&(k=new RegExp(k)),this.formats[S]=k,this}errorsText(S=this.errors,{separator:k=", ",dataVar:_="data"}={}){return!S||S.length===0?"No errors":S.map(m=>`${_}${m.instancePath} ${m.message}`).reduce((m,$)=>m+k+$)}$dataMetaSchema(S,k){const _=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const m of k){const $=m.split("/").slice(1);let O=S;for(const x of $)O=O[x];for(const x in _){const R=_[x];if(typeof R!="object")continue;const{$data:U}=R.definition,q=O[x];U&&q&&(O[x]=ut(q))}}return S}_removeAllSchemas(S,k){for(const _ in S){const m=S[_];(!k||k.test(_))&&(typeof m=="string"?delete S[_]:m&&!m.meta&&(this._cache.delete(m.schema),delete S[_]))}}_addSchema(S,k,_,m=this.opts.validateSchema,$=this.opts.addUsedSchema){let O;const{schemaId:x}=this.opts;if(typeof S=="object")O=S[x];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let R=this._cache.get(S);if(R!==void 0)return R;_=(0,c.normalizeId)(O||_);const U=c.getSchemaRefs.call(this,S,_);return R=new i.SchemaEnv({schema:S,schemaId:x,meta:k,baseId:_,localRefs:U}),this._cache.set(R.schema,R),$&&!_.startsWith("#")&&(_&&this._checkUnique(_),this.refs[_]=R),m&&this.validateSchema(S,!0),R}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):i.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const k=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=k}}}E.ValidationError=r.default,E.MissingRefError=o.default,t.default=E;function N(A,S,k,_="error"){for(const m in A){const $=m;$ in S&&this.logger[_](`${k}: option ${m}. ${A[$]}`)}}function j(A){return A=(0,c.normalizeId)(A),this.schemas[A]||this.refs[A]}function T(){const A=this.opts.schemas;if(A)if(Array.isArray(A))this.addSchema(A);else for(const S in A)this.addSchema(A[S],S)}function M(){for(const A in this.opts.formats){const S=this.opts.formats[A];S&&this.addFormat(A,S)}}function C(A){if(Array.isArray(A)){this.addVocabulary(A);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in A){const k=A[S];k.keyword||(k.keyword=S),this.addKeyword(k)}}function G(){const A={...this.opts};for(const S of p)delete A[S];return A}const H={log(){},warn(){},error(){}};function Z(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 ue=/^[a-z_$][a-z0-9_$:-]*$/i;function fe(A,S){const{RULES:k}=this;if((0,l.eachItem)(A,_=>{if(k.keywords[_])throw new Error(`Keyword ${_} is already defined`);if(!ue.test(_))throw new Error(`Keyword ${_} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function he(A,S,k){var _;const m=S==null?void 0:S.post;if(k&&m)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:$}=this;let O=m?$.post:$.rules.find(({type:R})=>R===k);if(O||(O={type:k,rules:[]},$.rules.push(O)),$.keywords[A]=!0,!S)return;const x={keyword:A,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?pe.call(this,O,x,S.before):O.rules.push(x),$.all[A]=x,(_=S.implements)===null||_===void 0||_.forEach(R=>this.addKeyword(R))}function pe(A,S,k){const _=A.rules.findIndex(m=>m.keyword===k);_>=0?A.rules.splice(_,0,S):(A.rules.push(S),this.logger.warn(`rule ${k} is not defined`))}function Oe(A){let{metaSchema:S}=A;S!==void 0&&(A.$data&&this.opts.$data&&(S=ut(S)),A.validateSchema=this.compile(S,!0))}const gt={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ut(A){return{anyOf:[A,gt]}}})(ww);var rd={},od={},sd={};Object.defineProperty(sd,"__esModule",{value:!0});const Hj={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sd.default=Hj;var yr={};Object.defineProperty(yr,"__esModule",{value:!0});yr.callRef=yr.getValidate=void 0;const Jj=uo,Oh=se,et=ae,jr=Bt,kh=st,qs=K,Qj={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();const l=kh.resolveRef.call(c,u,o,n);if(l===void 0)throw new Jj.default(r.opts.uriResolver,o,n);if(l instanceof kh.SchemaEnv)return f(l);return g(l);function d(){if(s===u)return vi(t,i,s,s.$async);const p=e.scopeValue("root",{ref:u});return vi(t,(0,et._)`${p}.validate`,u,u.$async)}function f(p){const y=fv(t,p);vi(t,y,p,p.$async)}function g(p){const y=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,et.stringify)(p)}:{ref:p}),w=e.name("valid"),h=t.subschema({schema:p,dataTypes:[],schemaPath:et.nil,topSchemaRef:y,errSchemaPath:n},w);t.mergeEvaluated(h),t.ok(w)}}};function fv(t,e){const{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,et._)`${n.scopeValue("wrapper",{ref:e})}.validate`}yr.getValidate=fv;function vi(t,e,n,r){const{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?jr.default.this:et.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const p=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,Oh.callValidateCode)(t,e,u)}`),g(e),i||o.assign(p,!0)},y=>{o.if((0,et._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),f(y),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,Oh.callValidateCode)(t,e,u),()=>g(e),()=>f(e))}function f(p){const y=(0,et._)`${p}.errors`;o.assign(jr.default.vErrors,(0,et._)`${jr.default.vErrors} === null ? ${y} : ${jr.default.vErrors}.concat(${y})`),o.assign(jr.default.errors,(0,et._)`${jr.default.vErrors}.length`)}function g(p){var y;if(!s.opts.unevaluated)return;const w=(y=n==null?void 0:n.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(s.props=qs.mergeEvaluated.props(o,w.props,s.props));else{const h=o.var("props",(0,et._)`${p}.evaluated.props`);s.props=qs.mergeEvaluated.props(o,h,s.props,et.Name)}if(s.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(s.items=qs.mergeEvaluated.items(o,w.items,s.items));else{const h=o.var("items",(0,et._)`${p}.evaluated.items`);s.items=qs.mergeEvaluated.items(o,h,s.items,et.Name)}}}yr.callRef=vi;yr.default=Qj;Object.defineProperty(od,"__esModule",{value:!0});const Yj=sd,Zj=yr,Xj=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Yj.default,Zj.default];od.default=Xj;var id={},ad={};Object.defineProperty(ad,"__esModule",{value:!0});const Wi=ae,un=Wi.operators,Hi={maximum:{okStr:"<=",ok:un.LTE,fail:un.GT},minimum:{okStr:">=",ok:un.GTE,fail:un.LT},exclusiveMaximum:{okStr:"<",ok:un.LT,fail:un.GTE},exclusiveMinimum:{okStr:">",ok:un.GT,fail:un.LTE}},eA={message:({keyword:t,schemaCode:e})=>(0,Wi.str)`must be ${Hi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Wi._)`{comparison: ${Hi[t].okStr}, limit: ${e}}`},tA={keyword:Object.keys(Hi),type:"number",schemaType:"number",$data:!0,error:eA,code(t){const{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Wi._)`${n} ${Hi[e].fail} ${r} || isNaN(${n})`)}};ad.default=tA;var cd={};Object.defineProperty(cd,"__esModule",{value:!0});const Fo=ae,nA={message:({schemaCode:t})=>(0,Fo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Fo._)`{multipleOf: ${t}}`},rA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:nA,code(t){const{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Fo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Fo._)`${i} !== parseInt(${i})`;t.fail$data((0,Fo._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};cd.default=rA;var ud={},ld={};Object.defineProperty(ld,"__esModule",{value:!0});function pv(t){const e=t.length;let n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}ld.default=pv;pv.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(ud,"__esModule",{value:!0});const Xn=ae,oA=K,sA=ld,iA={message({keyword:t,schemaCode:e}){const n=t==="maxLength"?"more":"fewer";return(0,Xn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Xn._)`{limit: ${t}}`},aA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:iA,code(t){const{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Xn.operators.GT:Xn.operators.LT,i=o.opts.unicode===!1?(0,Xn._)`${n}.length`:(0,Xn._)`${(0,oA.useFunc)(t.gen,sA.default)}(${n})`;t.fail$data((0,Xn._)`${i} ${s} ${r}`)}};ud.default=aA;var dd={};Object.defineProperty(dd,"__esModule",{value:!0});const cA=se,uA=K,Kr=ae,lA={message:({schemaCode:t})=>(0,Kr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Kr._)`{pattern: ${t}}`},dA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:lA,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Kr._)`new RegExp`:(0,uA.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Kr._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,Kr._)`!${l}`)}else{const c=(0,cA.usePattern)(t,o);t.fail$data((0,Kr._)`!${c}.test(${n})`)}}};dd.default=dA;var fd={};Object.defineProperty(fd,"__esModule",{value:!0});const qo=ae,fA={message({keyword:t,schemaCode:e}){const n=t==="maxProperties"?"more":"fewer";return(0,qo.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,qo._)`{limit: ${t}}`},pA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:fA,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?qo.operators.GT:qo.operators.LT;t.fail$data((0,qo._)`Object.keys(${n}).length ${o} ${r}`)}};fd.default=pA;var pd={};Object.defineProperty(pd,"__esModule",{value:!0});const bo=se,Ko=ae,hA=K,mA={message:({params:{missingProperty:t}})=>(0,Ko.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ko._)`{missingProperty: ${t}}`},gA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:mA,code(t){const{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const g=t.parentSchema.properties,{definedProperties:p}=t.it;for(const y of n)if((g==null?void 0:g[y])===void 0&&!p.has(y)){const w=i.schemaEnv.baseId+i.errSchemaPath,h=`required property "${y}" is not defined at "${w}" (strictRequired)`;(0,hA.checkStrictMode)(i,h,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ko.nil,d);else for(const g of n)(0,bo.checkReportMissingProp)(t,g)}function l(){const g=e.let("missing");if(c||s){const p=e.let("valid",!0);t.block$data(p,()=>f(g,p)),t.ok(p)}else e.if((0,bo.checkMissingProp)(t,n,g)),(0,bo.reportMissingProp)(t,g),e.else()}function d(){e.forOf("prop",r,g=>{t.setParams({missingProperty:g}),e.if((0,bo.noPropertyInData)(e,o,g,a.ownProperties),()=>t.error())})}function f(g,p){t.setParams({missingProperty:g}),e.forOf(g,r,()=>{e.assign(p,(0,bo.propertyInData)(e,o,g,a.ownProperties)),e.if((0,Ko.not)(p),()=>{t.error(),e.break()})},Ko.nil)}}};pd.default=gA;var hd={};Object.defineProperty(hd,"__esModule",{value:!0});const Vo=ae,yA={message({keyword:t,schemaCode:e}){const n=t==="maxItems"?"more":"fewer";return(0,Vo.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Vo._)`{limit: ${t}}`},wA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:yA,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Vo.operators.GT:Vo.operators.LT;t.fail$data((0,Vo._)`${n}.length ${o} ${r}`)}};hd.default=wA;var md={},Ns={};Object.defineProperty(Ns,"__esModule",{value:!0});const hv=Tw;hv.code='require("ajv/dist/runtime/equal").default';Ns.default=hv;Object.defineProperty(md,"__esModule",{value:!0});const ic=Ae,Ce=ae,vA=K,$A=Ns,bA={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},EA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:bA,code(t){const{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;const c=e.let("valid"),u=s.items?(0,ic.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ce._)`${i} === false`),t.ok(c);function l(){const p=e.let("i",(0,Ce._)`${n}.length`),y=e.let("j");t.setParams({i:p,j:y}),e.assign(c,!0),e.if((0,Ce._)`${p} > 1`,()=>(d()?f:g)(p,y))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,y){const w=e.name("item"),h=(0,ic.checkDataTypes)(u,w,a.opts.strictNumbers,ic.DataType.Wrong),v=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${p}--;`,()=>{e.let(w,(0,Ce._)`${n}[${p}]`),e.if(h,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${w} == "string"`,(0,Ce._)`${w} += "_"`),e.if((0,Ce._)`typeof ${v}[${w}] == "number"`,()=>{e.assign(y,(0,Ce._)`${v}[${w}]`),t.error(),e.assign(c,!1).break()}).code((0,Ce._)`${v}[${w}] = ${p}`)})}function g(p,y){const w=(0,vA.useFunc)(e,$A.default),h=e.name("outer");e.label(h).for((0,Ce._)`;${p}--;`,()=>e.for((0,Ce._)`${y} = ${p}; ${y}--;`,()=>e.if((0,Ce._)`${w}(${n}[${p}], ${n}[${y}])`,()=>{t.error(),e.assign(c,!1).break(h)})))}}};md.default=EA;var gd={};Object.defineProperty(gd,"__esModule",{value:!0});const pu=ae,SA=K,_A=Ns,NA={message:"must be equal to constant",params:({schemaCode:t})=>(0,pu._)`{allowedValue: ${t}}`},OA={keyword:"const",$data:!0,error:NA,code(t){const{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,pu._)`!${(0,SA.useFunc)(e,_A.default)}(${n}, ${o})`):t.fail((0,pu._)`${s} !== ${n}`)}};gd.default=OA;var yd={};Object.defineProperty(yd,"__esModule",{value:!0});const Io=ae,kA=K,jA=Ns,AA={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Io._)`{allowedValues: ${t}}`},IA={keyword:"enum",schemaType:"array",$data:!0,error:AA,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&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,kA.useFunc)(e,jA.default));let l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const g=e.const("vSchema",s);l=(0,Io.or)(...o.map((p,y)=>f(g,y)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,g=>e.if((0,Io._)`${u()}(${n}, ${g})`,()=>e.assign(l,!0).break()))}function f(g,p){const y=o[p];return typeof y=="object"&&y!==null?(0,Io._)`${u()}(${n}, ${g}[${p}])`:(0,Io._)`${n} === ${y}`}}};yd.default=IA;Object.defineProperty(id,"__esModule",{value:!0});const PA=ad,xA=cd,RA=ud,TA=dd,CA=fd,MA=pd,LA=hd,DA=md,UA=gd,BA=yd,FA=[PA.default,xA.default,RA.default,TA.default,CA.default,MA.default,LA.default,DA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},UA.default,BA.default];id.default=FA;var wd={},lo={};Object.defineProperty(lo,"__esModule",{value:!0});lo.validateAdditionalItems=void 0;const er=ae,hu=K,qA={message:({params:{len:t}})=>(0,er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,er._)`{limit: ${t}}`},KA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:qA,code(t){const{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,hu.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}mv(t,r)}};function mv(t,e){const{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;const a=n.const("len",(0,er._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,er._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,hu.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,er._)`${a} <= ${e.length}`);n.if((0,er.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:hu.Type.Num},u),i.allErrors||n.if((0,er.not)(u),()=>n.break())})}}lo.validateAdditionalItems=mv;lo.default=KA;var vd={},fo={};Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;const jh=ae,$i=K,VA=se,GA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:n}=t;if(Array.isArray(e))return gv(t,"additionalItems",e);n.items=!0,!(0,$i.alwaysValidSchema)(n,e)&&t.ok((0,VA.validateArray)(t))}};function gv(t,e,n=t.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=$i.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,jh._)`${s}.length`);n.forEach((d,f)=>{(0,$i.alwaysValidSchema)(a,d)||(r.if((0,jh._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){const{opts:f,errSchemaPath:g}=a,p=n.length,y=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!y){const w=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0,$i.checkStrictMode)(a,w,f.strictTuples)}}}fo.validateTuple=gv;fo.default=GA;Object.defineProperty(vd,"__esModule",{value:!0});const zA=fo,WA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,zA.validateTuple)(t,"items")};vd.default=WA;var $d={};Object.defineProperty($d,"__esModule",{value:!0});const Ah=ae,HA=K,JA=se,QA=lo,YA={message:({params:{len:t}})=>(0,Ah.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ah._)`{limit: ${t}}`},ZA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:YA,code(t){const{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,HA.alwaysValidSchema)(r,e)&&(o?(0,QA.validateAdditionalItems)(t,o):t.ok((0,JA.validateArray)(t)))}};$d.default=ZA;var bd={};Object.defineProperty(bd,"__esModule",{value:!0});const dt=ae,Ks=K,XA={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},eI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:XA,code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=e.const("len",(0,dt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ks.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ks.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ks.alwaysValidSchema)(s,n)){let y=(0,dt._)`${l} >= ${i}`;a!==void 0&&(y=(0,dt._)`${y} && ${l} <= ${a}`),t.pass(y);return}s.items=!0;const d=e.name("valid");a===void 0&&i===1?g(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dt._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){const y=e.name("_valid"),w=e.let("count",0);g(y,()=>e.if(y,()=>p(w)))}function g(y,w){e.forRange("i",0,l,h=>{t.subschema({keyword:"contains",dataProp:h,dataPropType:Ks.Type.Num,compositeRule:!0},y),w()})}function p(y){e.code((0,dt._)`${y}++`),a===void 0?e.if((0,dt._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dt._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dt._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};bd.default=eI;var yv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=ae,n=K,r=se;t.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const d=u===1?"property":"properties";return(0,e.str)`must have ${d} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:d}})=>(0,e._)`{property: ${c},
|
|
190
|
+
missingProperty: ${d},
|
|
161
191
|
depsCount: ${u},
|
|
162
|
-
deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const f in c){if(f==="__proto__")continue;const p=Array.isArray(c[f])?u:l;p[f]=c[f]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:f,it:p}=c;if(Object.keys(u).length===0)return;const h=l.let("missing");for(const d in u){const m=u[d];if(m.length===0)continue;const y=(0,r.propertyInData)(l,f,d,p.opts.ownProperties);c.setParams({property:d,depsCount:m.length,deps:m.join(", ")}),p.allErrors?l.if(y,()=>{for(const $ of m)(0,r.checkReportMissingProp)(c,$)}):(l.if((0,t._)`${y} && (${(0,r.checkMissingProp)(c,m,h)})`),(0,r.reportMissingProp)(c,h),l.else())}}e.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:f,keyword:p,it:h}=c,d=l.name("valid");for(const m in u)(0,n.alwaysValidSchema)(h,u[m])||(l.if((0,r.propertyInData)(l,f,m,h.opts.ownProperties),()=>{const y=c.subschema({keyword:p,schemaProp:m},d);c.mergeValidEvaluated(y,d)},()=>l.var(d,!0)),c.ok(d))}e.validateSchemaDeps=a,e.default=o})(Zd);var ia={};Object.defineProperty(ia,"__esModule",{value:!0});const Xd=G,AE=P,jE={message:"property name must be valid",params:({params:e})=>(0,Xd._)`{propertyName: ${e.propertyName}}`},IE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jE,code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,AE.alwaysValidSchema)(o,n))return;const s=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,Xd.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};ia.default=IE;var Jr={};Object.defineProperty(Jr,"__esModule",{value:!0});const tr=K,xe=G,xE=Fe,nr=P,PE={message:"must NOT have additional properties",params:({params:e})=>(0,xe._)`{additionalProperty: ${e.additionalProperty}}`},TE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PE,code(e){const{gen:t,schema:n,parentSchema:r,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,nr.alwaysValidSchema)(i,n))return;const u=(0,tr.allSchemaProperties)(r.properties),l=(0,tr.allSchemaProperties)(r.patternProperties);f(),e.ok((0,xe._)`${s} === ${xE.default.errors}`);function f(){t.forIn("key",o,y=>{!u.length&&!l.length?d(y):t.if(p(y),()=>d(y))})}function p(y){let $;if(u.length>8){const v=(0,nr.schemaRefOrVal)(i,r.properties,"properties");$=(0,tr.isOwnProperty)(t,v,y)}else u.length?$=(0,xe.or)(...u.map(v=>(0,xe._)`${y} === ${v}`)):$=xe.nil;return l.length&&($=(0,xe.or)($,...l.map(v=>(0,xe._)`${(0,tr.usePattern)(e,v)}.test(${y})`))),(0,xe.not)($)}function h(y){t.code((0,xe._)`delete ${o}[${y}]`)}function d(y){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(y);return}if(n===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,nr.alwaysValidSchema)(i,n)){const $=t.name("valid");c.removeAdditional==="failing"?(m(y,$,!1),t.if((0,xe.not)($),()=>{e.reset(),h(y)})):(m(y,$),a||t.if((0,xe.not)($),()=>t.break()))}}function m(y,$,v){const E={keyword:"additionalProperties",dataProp:y,dataPropType:nr.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(E,$)}}};Jr.default=TE;var aa={};Object.defineProperty(aa,"__esModule",{value:!0});const CE=Ce,fu=K,Po=P,du=Jr,RE={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&du.default.code(new CE.KeywordCxt(s,du.default,"additionalProperties"));const i=(0,fu.allSchemaProperties)(n);for(const f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Po.mergeEvaluated.props(t,(0,Po.toHash)(i),s.props));const a=i.filter(f=>!(0,Po.alwaysValidSchema)(s,n[f]));if(a.length===0)return;const c=t.name("valid");for(const f of a)u(f)?l(f):(t.if((0,fu.propertyInData)(t,o,f,s.opts.ownProperties)),l(f),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function u(f){return s.opts.useDefaults&&!s.compositeRule&&n[f].default!==void 0}function l(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};aa.default=RE;var ca={};Object.defineProperty(ca,"__esModule",{value:!0});const pu=K,rr=G,hu=P,mu=P,ME={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,pu.allSchemaProperties)(n),c=a.filter(m=>(0,hu.alwaysValidSchema)(s,n[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof rr.Name)&&(s.props=(0,mu.evaluatedPropsToName)(t,s.props));const{props:f}=s;p();function p(){for(const m of a)u&&h(m),s.allErrors?d(m):(t.var(l,!0),d(m),t.if(l))}function h(m){for(const y in u)new RegExp(m).test(y)&&(0,hu.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function d(m){t.forIn("key",r,y=>{t.if((0,rr._)`${(0,pu.usePattern)(e,m)}.test(${y})`,()=>{const $=c.includes(m);$||e.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:mu.Type.Str},l),s.opts.unevaluated&&f!==!0?t.assign((0,rr._)`${f}[${y}]`,!0):!$&&!s.allErrors&&t.if((0,rr.not)(l),()=>t.break())})})}}};ca.default=ME;var ua={};Object.defineProperty(ua,"__esModule",{value:!0});const DE=P,LE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,DE.alwaysValidSchema)(r,n)){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"}};ua.default=LE;var la={};Object.defineProperty(la,"__esModule",{value:!0});const UE=K,BE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:UE.validateUnion,error:{message:"must match a schema in anyOf"}};la.default=BE;var fa={};Object.defineProperty(fa,"__esModule",{value:!0});const yr=G,FE=P,qE={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,yr._)`{passingSchemas: ${e.passing}}`},VE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qE,code(e){const{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=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(){s.forEach((l,f)=>{let p;(0,FE.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,yr._)`${c} && ${i}`).assign(i,!1).assign(a,(0,yr._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),p&&e.mergeEvaluated(p,yr.Name)})})}}};fa.default=VE;var da={};Object.defineProperty(da,"__esModule",{value:!0});const KE=P,GE={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 o=t.name("valid");n.forEach((s,i)=>{if((0,KE.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};da.default=GE;var pa={};Object.defineProperty(pa,"__esModule",{value:!0});const _r=G,ep=P,JE={message:({params:e})=>(0,_r.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,_r._)`{failingKeyword: ${e.ifClause}}`},HE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:JE,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,ep.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=gu(r,"then"),s=gu(r,"else");if(!o&&!s)return;const i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){const l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,_r.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 p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),f?t.assign(f,(0,_r._)`${l}`):e.setParams({ifClause:l})}}}};function gu(e,t){const n=e.schema[t];return n!==void 0&&!(0,ep.alwaysValidSchema)(e,n)}pa.default=HE;var ha={};Object.defineProperty(ha,"__esModule",{value:!0});const zE=P,WE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,zE.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};ha.default=WE;Object.defineProperty(na,"__esModule",{value:!0});const YE=sn,QE=ra,ZE=an,XE=oa,eS=sa,tS=Zd,nS=ia,rS=Jr,oS=aa,sS=ca,iS=ua,aS=la,cS=fa,uS=da,lS=pa,fS=ha;function dS(e=!1){const t=[iS.default,aS.default,cS.default,uS.default,lS.default,fS.default,nS.default,rS.default,tS.default,oS.default,sS.default];return e?t.push(QE.default,XE.default):t.push(YE.default,ZE.default),t.push(eS.default),t}na.default=dS;var ma={},ga={};Object.defineProperty(ga,"__esModule",{value:!0});const ne=G,pS={message:({schemaCode:e})=>(0,ne.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ne._)`{format: ${e}}`},hS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:pS,code(e,t){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:f}=a;if(!c.validateFormats)return;o?p():h();function p(){const d=n.scopeValue("formats",{ref:f.formats,code:c.code.formats}),m=n.const("fDef",(0,ne._)`${d}[${i}]`),y=n.let("fType"),$=n.let("format");n.if((0,ne._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(y,(0,ne._)`${m}.type || "string"`).assign($,(0,ne._)`${m}.validate`),()=>n.assign(y,(0,ne._)`"string"`).assign($,m)),e.fail$data((0,ne.or)(v(),E()));function v(){return c.strictSchema===!1?ne.nil:(0,ne._)`${i} && !${$}`}function E(){const b=l.$async?(0,ne._)`(${m}.async ? await ${$}(${r}) : ${$}(${r}))`:(0,ne._)`${$}(${r})`,N=(0,ne._)`(typeof ${$} == "function" ? ${b} : ${$}.test(${r}))`;return(0,ne._)`${$} && ${$} !== true && ${y} === ${t} && !${N}`}}function h(){const d=f.formats[s];if(!d){v();return}if(d===!0)return;const[m,y,$]=E(d);m===t&&e.pass(b());function v(){if(c.strictSchema===!1){f.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function E(N){const j=N instanceof RegExp?(0,ne.regexpCode)(N):c.code.formats?(0,ne._)`${c.code.formats}${(0,ne.getProperty)(s)}`:void 0,R=n.scopeValue("formats",{key:s,ref:N,code:j});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,ne._)`${R}.validate`]:["string",N,R]}function b(){if(typeof d=="object"&&!(d instanceof RegExp)&&d.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ne._)`await ${$}(${r})`}return typeof y=="function"?(0,ne._)`${$}(${r})`:(0,ne._)`${$}.test(${r})`}}}};ga.default=hS;Object.defineProperty(ma,"__esModule",{value:!0});const mS=ga,gS=[mS.default];ma.default=gS;var tn={};Object.defineProperty(tn,"__esModule",{value:!0});tn.contentVocabulary=tn.metadataVocabulary=void 0;tn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];tn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(Fi,"__esModule",{value:!0});const yS=qi,$S=Ki,vS=na,wS=ma,yu=tn,bS=[yS.default,$S.default,(0,vS.default)(),wS.default,yu.metadataVocabulary,yu.contentVocabulary];Fi.default=bS;var ya={},Hr={};Object.defineProperty(Hr,"__esModule",{value:!0});Hr.DiscrError=void 0;var $u;(function(e){e.Tag="tag",e.Mapping="mapping"})($u||(Hr.DiscrError=$u={}));Object.defineProperty(ya,"__esModule",{value:!0});const Ft=G,Os=Hr,vu=Ee,ES=on,SS=P,NS={message:({params:{discrError:e,tagName:t}})=>e===Os.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Ft._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},OS={keyword:"discriminator",type:"object",schemaType:"object",error:NS,code(e){const{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.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,Ft._)`${n}${(0,Ft.getProperty)(a)}`);t.if((0,Ft._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Os.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){const h=p();t.if(!1);for(const d in h)t.elseIf((0,Ft._)`${u} === ${d}`),t.assign(c,f(h[d]));t.else(),e.error(!1,{discrError:Os.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(h){const d=t.name("valid"),m=e.subschema({keyword:"oneOf",schemaProp:h},d);return e.mergeEvaluated(m,Ft.Name),d}function p(){var h;const d={},m=$(o);let y=!0;for(let b=0;b<i.length;b++){let N=i[b];if(N!=null&&N.$ref&&!(0,SS.schemaHasRulesButRef)(N,s.self.RULES)){const R=N.$ref;if(N=vu.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),N instanceof vu.SchemaEnv&&(N=N.schema),N===void 0)throw new ES.default(s.opts.uriResolver,s.baseId,R)}const j=(h=N==null?void 0:N.properties)===null||h===void 0?void 0:h[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||$(N)),v(j,b)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return d;function $({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,N){if(b.const)E(b.const,N);else if(b.enum)for(const j of b.enum)E(j,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(b,N){if(typeof b!="string"||b in d)throw new Error(`discriminator: "${a}" values must be unique strings`);d[b]=N}}}};ya.default=OS;const kS="http://json-schema.org/draft-07/schema#",_S="http://json-schema.org/draft-07/schema#",AS="Core schema meta-schema",jS={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:[]}},IS=["object","boolean"],xS={$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:"#"}},PS={$schema:kS,$id:_S,title:AS,definitions:jS,type:IS,properties:xS,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=Xf,r=Fi,o=ya,s=PS,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(d=>this.addVocabulary(d)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const d=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(d,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=Ce;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=G;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=qn;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=on;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})($s,$s.exports);var TS=$s.exports;const CS=e$(TS);class tp extends Error{constructor(t){super(t.length>0?`Config validation failed: ${t.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=t,this.name="ValidationError"}}function RS(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new CS({allErrors:!0,strict:!1}).compile(n);if(!o(e))throw new tp(MS(o.errors??[]))}function MS(e){return e.map(t=>({field:DS(t),message:t.message??"is invalid",keyword:t.keyword}))}function DS(e){var t;return(e.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((t=e.params)==null?void 0:t.missingProperty)??"(root)")}function LS(e,t){return T.join(of(e,t),lv)}const US=384,BS=448;function FS(e,t,n={}){const r=n.mode??US,o=n.dirMode??BS,s=T.dirname(e);C.mkdirSync(s,{recursive:!0,mode:o}),C.chmodSync(s,o);const i=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{C.writeFileSync(i,a,{encoding:"utf8",mode:r}),C.chmodSync(i,r),C.renameSync(i,e),C.chmodSync(e,r)}catch(c){try{C.existsSync(i)&&C.unlinkSync(i)}catch{}throw c}}const qS="0.1.0";function wu(e,t){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(e)}`)}function VS(){return`${process.pid}-${Un.randomBytes(3).toString("hex")}`}function np(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");wu(e,"project");const r=t.orgNamespace??cv,o=t.envPrefixOverride??mv(e),s=t.namespaces&&t.namespaces.length>0?t.namespaces:[uv],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${e}" (declared: ${s.join(", ")})`);wu(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=Qy({scope:n.scope,cwd:n.cwd},a),l=Xy({project:e,namespace:i,orgNamespace:r,projectRoot:u,adhdRoot:n.adhdRoot});return{project:e,namespace:i,orgNamespace:r,envPrefix:o,scope:c,projectRoot:u,roots:l}}function KS(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=np(e,t,n),u=n.processEnv??process.env,l=Ov(c),f=n.instanceId??VS(),{raw:p,nested:h,typedRaw:d,provenance:m,fields:y}=Av(t.config,l,u,{prefix:s,activeScope:i}),$={};for(const N of Object.keys(y)){const j=y[N];j.live&&($[N]={env:j.env,type:j.type,fallback:j.secret===!0?void 0:j.fallbackValue})}const v=yv(t.config);RS(Zf(d),v);const E=Iv(t.dirs,{roots:c,activeScope:i,instanceId:f,projectRoot:a,namespace:r}),b=xv(t.files,E);return{version:av,libraryVersion:qS,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:f,config:h,raw:p,liveFields:$,fieldSchema:v,configHash:pv(Object.fromEntries(Object.entries(d).map(([N,j])=>[N,String(j)]))),structureHash:hv(Object.values(E).map(N=>({name:N.name,kind:N.kind,scope:N.scope}))),dirs:Object.values(E),files:Object.values(b),provenance:m}}let Tn=class extends Error{constructor(t){super(t),this.name="EnvironmentError"}};class GS extends Tn{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class JS extends Tn{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function HS(e,t){let n=e;for(const r of t.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function ks(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>ks(n));const t={};for(const[n,r]of Object.entries(e))t[n]=ks(r);return t}function zS(e,t){const n=ks(e);for(const r of Object.keys(t)){const o=t[r],s=r.split(".");let i=n;for(let c=0;c<s.length-1;c++){const u=s[c],l=i[u];(typeof l!="object"||l===null||Array.isArray(l))&&(i[u]={}),i=i[u]}const a=s[s.length-1];Object.defineProperty(i,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?ys(c,o.type):o.fallback}})}return n}function WS(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Tn(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class zr{constructor(t,n,r={}){let o,s;try{o=KS(t,n,r);const i=np(t,n,r);s=LS(i.roots,o.scope)}catch(i){throw i instanceof tp||i instanceof Tn?i:new Tn(i instanceof Error?i.message:String(i))}return bu(this,o,s)}static fromSnapshot(t){if(!C.existsSync(t))throw new GS(t);const n=JSON.parse(C.readFileSync(t,"utf8")),r=Object.create(zr.prototype);return bu(r,n,t)}get(t){const n=t.indexOf(".");if(n===-1)return;const r=t.slice(0,n),o=t.slice(n+1);switch(r){case"config":return HS(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(t){return t.startsWith(this.prefix)}resolveEnvName(t){if(this.isEnvNameAllowed(t))return process.env[t]}lock(t="singleton"){WS(t);const n=this.paths.run??this._runDirFallback();C.mkdirSync(n,{recursive:!0});const r=T.join(n,`${t}.lock`);let o;try{o=C.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new JS(t,r):i}C.writeSync(o,`${process.pid}
|
|
192
|
+
deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const d in c){if(d==="__proto__")continue;const f=Array.isArray(c[d])?u:l;f[d]=c[d]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:d,it:f}=c;if(Object.keys(u).length===0)return;const g=l.let("missing");for(const p in u){const y=u[p];if(y.length===0)continue;const w=(0,r.propertyInData)(l,d,p,f.opts.ownProperties);c.setParams({property:p,depsCount:y.length,deps:y.join(", ")}),f.allErrors?l.if(w,()=>{for(const h of y)(0,r.checkReportMissingProp)(c,h)}):(l.if((0,e._)`${w} && (${(0,r.checkMissingProp)(c,y,g)})`),(0,r.reportMissingProp)(c,g),l.else())}}t.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:d,keyword:f,it:g}=c,p=l.name("valid");for(const y in u)(0,n.alwaysValidSchema)(g,u[y])||(l.if((0,r.propertyInData)(l,d,y,g.opts.ownProperties),()=>{const w=c.subschema({keyword:f,schemaProp:y},p);c.mergeValidEvaluated(w,p)},()=>l.var(p,!0)),c.ok(p))}t.validateSchemaDeps=a,t.default=o})(yv);var Ed={};Object.defineProperty(Ed,"__esModule",{value:!0});const wv=ae,tI=K,nI={message:"property name must be valid",params:({params:t})=>(0,wv._)`{propertyName: ${t.propertyName}}`},rI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:nI,code(t){const{gen:e,schema:n,data:r,it:o}=t;if((0,tI.alwaysValidSchema)(o,n))return;const s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,wv.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ed.default=rI;var Oa={};Object.defineProperty(Oa,"__esModule",{value:!0});const Vs=se,$t=ae,oI=Bt,Gs=K,sI={message:"must NOT have additional properties",params:({params:t})=>(0,$t._)`{additionalProperty: ${t.additionalProperty}}`},iI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:sI,code(t){const{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Gs.alwaysValidSchema)(i,n))return;const u=(0,Vs.allSchemaProperties)(r.properties),l=(0,Vs.allSchemaProperties)(r.patternProperties);d(),t.ok((0,$t._)`${s} === ${oI.default.errors}`);function d(){e.forIn("key",o,w=>{!u.length&&!l.length?p(w):e.if(f(w),()=>p(w))})}function f(w){let h;if(u.length>8){const v=(0,Gs.schemaRefOrVal)(i,r.properties,"properties");h=(0,Vs.isOwnProperty)(e,v,w)}else u.length?h=(0,$t.or)(...u.map(v=>(0,$t._)`${w} === ${v}`)):h=$t.nil;return l.length&&(h=(0,$t.or)(h,...l.map(v=>(0,$t._)`${(0,Vs.usePattern)(t,v)}.test(${w})`))),(0,$t.not)(h)}function g(w){e.code((0,$t._)`delete ${o}[${w}]`)}function p(w){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){g(w);return}if(n===!1){t.setParams({additionalProperty:w}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Gs.alwaysValidSchema)(i,n)){const h=e.name("valid");c.removeAdditional==="failing"?(y(w,h,!1),e.if((0,$t.not)(h),()=>{t.reset(),g(w)})):(y(w,h),a||e.if((0,$t.not)(h),()=>e.break()))}}function y(w,h,v){const b={keyword:"additionalProperties",dataProp:w,dataPropType:Gs.Type.Str};v===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,h)}}};Oa.default=iI;var Sd={};Object.defineProperty(Sd,"__esModule",{value:!0});const aI=Nt,Ih=se,ac=K,Ph=Oa,cI={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Ph.default.code(new aI.KeywordCxt(s,Ph.default,"additionalProperties"));const i=(0,Ih.allSchemaProperties)(n);for(const d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=ac.mergeEvaluated.props(e,(0,ac.toHash)(i),s.props));const a=i.filter(d=>!(0,ac.alwaysValidSchema)(s,n[d]));if(a.length===0)return;const c=e.name("valid");for(const d of a)u(d)?l(d):(e.if((0,Ih.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Sd.default=cI;var _d={};Object.defineProperty(_d,"__esModule",{value:!0});const xh=se,zs=ae,Rh=K,Th=K,uI={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,xh.allSchemaProperties)(n),c=a.filter(y=>(0,Rh.alwaysValidSchema)(s,n[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof zs.Name)&&(s.props=(0,Th.evaluatedPropsToName)(e,s.props));const{props:d}=s;f();function f(){for(const y of a)u&&g(y),s.allErrors?p(y):(e.var(l,!0),p(y),e.if(l))}function g(y){for(const w in u)new RegExp(y).test(w)&&(0,Rh.checkStrictMode)(s,`property ${w} matches pattern ${y} (use allowMatchingProperties)`)}function p(y){e.forIn("key",r,w=>{e.if((0,zs._)`${(0,xh.usePattern)(t,y)}.test(${w})`,()=>{const h=c.includes(y);h||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:w,dataPropType:Th.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,zs._)`${d}[${w}]`,!0):!h&&!s.allErrors&&e.if((0,zs.not)(l),()=>e.break())})})}}};_d.default=uI;var Nd={};Object.defineProperty(Nd,"__esModule",{value:!0});const lI=K,dI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:n,it:r}=t;if((0,lI.alwaysValidSchema)(r,n)){t.fail();return}const o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Nd.default=dI;var Od={};Object.defineProperty(Od,"__esModule",{value:!0});const fI=se,pI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fI.validateUnion,error:{message:"must match a schema in anyOf"}};Od.default=pI;var kd={};Object.defineProperty(kd,"__esModule",{value:!0});const bi=ae,hI=K,mI={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,bi._)`{passingSchemas: ${t.passing}}`},gI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:mI,code(t){const{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let f;(0,hI.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,bi._)`${c} && ${i}`).assign(i,!1).assign(a,(0,bi._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,bi.Name)})})}}};kd.default=gI;var jd={};Object.defineProperty(jd,"__esModule",{value:!0});const yI=K,wI={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=e.name("valid");n.forEach((s,i)=>{if((0,yI.alwaysValidSchema)(r,s))return;const a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};jd.default=wI;var Ad={};Object.defineProperty(Ad,"__esModule",{value:!0});const Ji=ae,vv=K,vI={message:({params:t})=>(0,Ji.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ji._)`{failingKeyword: ${t.ifClause}}`},$I={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vI,code(t){const{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,vv.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=Ch(r,"then"),s=Ch(r,"else");if(!o&&!s)return;const i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){const l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ji.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){const l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{const f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,Ji._)`${l}`):t.setParams({ifClause:l})}}}};function Ch(t,e){const n=t.schema[e];return n!==void 0&&!(0,vv.alwaysValidSchema)(t,n)}Ad.default=$I;var Id={};Object.defineProperty(Id,"__esModule",{value:!0});const bI=K,EI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,bI.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Id.default=EI;Object.defineProperty(wd,"__esModule",{value:!0});const SI=lo,_I=vd,NI=fo,OI=$d,kI=bd,jI=yv,AI=Ed,II=Oa,PI=Sd,xI=_d,RI=Nd,TI=Od,CI=kd,MI=jd,LI=Ad,DI=Id;function UI(t=!1){const e=[RI.default,TI.default,CI.default,MI.default,LI.default,DI.default,AI.default,II.default,jI.default,PI.default,xI.default];return t?e.push(_I.default,OI.default):e.push(SI.default,NI.default),e.push(kI.default),e}wd.default=UI;var Pd={},xd={};Object.defineProperty(xd,"__esModule",{value:!0});const Se=ae,BI={message:({schemaCode:t})=>(0,Se.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Se._)`{format: ${t}}`},FI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:BI,code(t,e){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?f():g();function f(){const p=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=n.const("fDef",(0,Se._)`${p}[${i}]`),w=n.let("fType"),h=n.let("format");n.if((0,Se._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>n.assign(w,(0,Se._)`${y}.type || "string"`).assign(h,(0,Se._)`${y}.validate`),()=>n.assign(w,(0,Se._)`"string"`).assign(h,y)),t.fail$data((0,Se.or)(v(),b()));function v(){return c.strictSchema===!1?Se.nil:(0,Se._)`${i} && !${h}`}function b(){const E=l.$async?(0,Se._)`(${y}.async ? await ${h}(${r}) : ${h}(${r}))`:(0,Se._)`${h}(${r})`,N=(0,Se._)`(typeof ${h} == "function" ? ${E} : ${h}.test(${r}))`;return(0,Se._)`${h} && ${h} !== true && ${w} === ${e} && !${N}`}}function g(){const p=d.formats[s];if(!p){v();return}if(p===!0)return;const[y,w,h]=b(p);y===e&&t.pass(E());function v(){if(c.strictSchema===!1){d.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(N){const j=N instanceof RegExp?(0,Se.regexpCode)(N):c.code.formats?(0,Se._)`${c.code.formats}${(0,Se.getProperty)(s)}`:void 0,T=n.scopeValue("formats",{key:s,ref:N,code:j});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,Se._)`${T}.validate`]:["string",N,T]}function E(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Se._)`await ${h}(${r})`}return typeof w=="function"?(0,Se._)`${h}(${r})`:(0,Se._)`${h}.test(${r})`}}}};xd.default=FI;Object.defineProperty(Pd,"__esModule",{value:!0});const qI=xd,KI=[qI.default];Pd.default=KI;var no={};Object.defineProperty(no,"__esModule",{value:!0});no.contentVocabulary=no.metadataVocabulary=void 0;no.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];no.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(rd,"__esModule",{value:!0});const VI=od,GI=id,zI=wd,WI=Pd,Mh=no,HI=[VI.default,GI.default,(0,zI.default)(),WI.default,Mh.metadataVocabulary,Mh.contentVocabulary];rd.default=HI;var Rd={},ka={};Object.defineProperty(ka,"__esModule",{value:!0});ka.DiscrError=void 0;var Lh;(function(t){t.Tag="tag",t.Mapping="mapping"})(Lh||(ka.DiscrError=Lh={}));Object.defineProperty(Rd,"__esModule",{value:!0});const Mr=ae,mu=ka,Dh=st,JI=uo,QI=K,YI={message:({params:{discrError:t,tagName:e}})=>t===mu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Mr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},ZI={keyword:"discriminator",type:"object",schemaType:"object",error:YI,code(t){const{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.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=e.let("valid",!1),u=e.const("tag",(0,Mr._)`${n}${(0,Mr.getProperty)(a)}`);e.if((0,Mr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:mu.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){const g=f();e.if(!1);for(const p in g)e.elseIf((0,Mr._)`${u} === ${p}`),e.assign(c,d(g[p]));e.else(),t.error(!1,{discrError:mu.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(g){const p=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:g},p);return t.mergeEvaluated(y,Mr.Name),p}function f(){var g;const p={},y=h(o);let w=!0;for(let E=0;E<i.length;E++){let N=i[E];if(N!=null&&N.$ref&&!(0,QI.schemaHasRulesButRef)(N,s.self.RULES)){const T=N.$ref;if(N=Dh.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,T),N instanceof Dh.SchemaEnv&&(N=N.schema),N===void 0)throw new JI.default(s.opts.uriResolver,s.baseId,T)}const j=(g=N==null?void 0:N.properties)===null||g===void 0?void 0:g[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(y||h(N)),v(j,E)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return p;function h({required:E}){return Array.isArray(E)&&E.includes(a)}function v(E,N){if(E.const)b(E.const,N);else if(E.enum)for(const j of E.enum)b(j,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,N){if(typeof E!="string"||E in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[E]=N}}}};Rd.default=ZI;const XI="http://json-schema.org/draft-07/schema#",eP="http://json-schema.org/draft-07/schema#",tP="Core schema meta-schema",nP={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:[]}},rP=["object","boolean"],oP={$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:"#"}},sP={$schema:XI,$id:eP,title:tP,definitions:nP,type:rP,properties:oP,default:!0};(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const n=ww,r=rd,o=Rd,s=sP,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(p=>this.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(p,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=Nt;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=ae;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=_s;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=uo;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})(cu,cu.exports);var iP=cu.exports;const aP=_N(iP);let $v=class extends Error{constructor(e){super(e.length>0?`Config validation failed: ${e.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=e,this.name="ValidationError"}};function cP(t,e){if(!e)return;const n=e,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new aP({allErrors:!0,strict:!1}).compile(n);if(!o(t))throw new $v(uP(o.errors??[]))}function uP(t){return t.map(e=>({field:lP(e),message:e.message??"is invalid",keyword:e.keyword}))}function lP(t){var e;return(t.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((e=t.params)==null?void 0:e.missingProperty)??"(root)")}function dP(t,e){return L.join(Ey(t,e),LO)}const fP=384,pP=448;function hP(t,e,n={}){const r=n.mode??fP,o=n.dirMode??pP,s=L.dirname(t);J.mkdirSync(s,{recursive:!0,mode:o}),J.chmodSync(s,o);const i=`${t}.tmp`,a=typeof e=="string"?e:JSON.stringify(e,null,2);try{J.writeFileSync(i,a,{encoding:"utf8",mode:r}),J.chmodSync(i,r),J.renameSync(i,t),J.chmodSync(t,r)}catch(c){try{J.existsSync(i)&&J.unlinkSync(i)}catch{}throw c}}const mP="0.1.0";function Uh(t,e){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(t)}`)}function gP(){return`${process.pid}-${kn.randomBytes(3).toString("hex")}`}function bv(t,e,n={}){if(!t)throw new Error("Environment requires a non-empty 'project' name");Uh(t,"project");const r=e.orgNamespace??CO,o=e.envPrefixOverride??qO(t),s=e.namespaces&&e.namespaces.length>0?e.namespaces:[MO],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${t}" (declared: ${s.join(", ")})`);Uh(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=bN({scope:n.scope,cwd:n.cwd},a),l=SN({project:t,namespace:i,orgNamespace:r,projectRoot:u,adhdRoot:n.adhdRoot});return{project:t,namespace:i,orgNamespace:r,envPrefix:o,scope:c,projectRoot:u,roots:l}}function yP(t,e,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=bv(t,e,n),u=n.processEnv??process.env,l=ZO(c),d=n.instanceId??gP(),{raw:f,nested:g,typedRaw:p,provenance:y,fields:w}=tk(e.config,l,u,{prefix:s,activeScope:i}),h={};for(const N of Object.keys(w)){const j=w[N];j.live&&(h[N]={env:j.env,type:j.type,fallback:j.secret===!0?void 0:j.fallbackValue})}const v=VO(e.config);cP(yw(p),v);const b=rk(e.dirs,{roots:c,activeScope:i,instanceId:d,projectRoot:a,namespace:r}),E=ok(e.files,b);return{version:TO,libraryVersion:mP,generatedAt:new Date().toISOString(),project:t,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:d,config:g,raw:f,liveFields:h,fieldSchema:v,configHash:BO(Object.fromEntries(Object.entries(p).map(([N,j])=>[N,String(j)]))),structureHash:FO(Object.values(b).map(N=>({name:N.name,kind:N.kind,scope:N.scope}))),dirs:Object.values(b),files:Object.values(E),provenance:y}}let us=class extends Error{constructor(e){super(e),this.name="EnvironmentError"}},wP=class extends us{constructor(e){super(`adhd-environment snapshot not found: ${e}`),this.snapshotPath=e,this.name="SnapshotNotFoundError"}},vP=class extends us{constructor(e,n){super(`lock "${e}" is already held (${n})`),this.lockName=e,this.lockPath=n,this.name="LockHeldError"}};function $P(t,e){let n=t;for(const r of e.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function gu(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>gu(n));const e={};for(const[n,r]of Object.entries(t))e[n]=gu(r);return e}function bP(t,e){const n=gu(t);for(const r of Object.keys(e)){const o=e[r],s=r.split(".");let i=n;for(let c=0;c<s.length-1;c++){const u=s[c],l=i[u];(typeof l!="object"||l===null||Array.isArray(l))&&(i[u]={}),i=i[u]}const a=s[s.length-1];Object.defineProperty(i,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?au(c,o.type):o.fallback}})}return n}function EP(t){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new us(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(t)}`)}let Ev=class Sv{constructor(e,n,r={}){let o,s;try{o=yP(e,n,r);const i=bv(e,n,r);s=dP(i.roots,o.scope)}catch(i){throw i instanceof $v||i instanceof us?i:new us(i instanceof Error?i.message:String(i))}return Bh(this,o,s)}static fromSnapshot(e){if(!J.existsSync(e))throw new wP(e);const n=JSON.parse(J.readFileSync(e,"utf8")),r=Object.create(Sv.prototype);return Bh(r,n,e)}get(e){const n=e.indexOf(".");if(n===-1)return;const r=e.slice(0,n),o=e.slice(n+1);switch(r){case"config":return $P(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(e){return e.startsWith(this.prefix)}resolveEnvName(e){if(this.isEnvNameAllowed(e))return process.env[e]}lock(e="singleton"){EP(e);const n=this.paths.run??this._runDirFallback();J.mkdirSync(n,{recursive:!0});const r=L.join(n,`${e}.lock`);let o;try{o=J.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new vP(e,r):i}J.writeSync(o,`${process.pid}
|
|
163
193
|
${this.instanceId}
|
|
164
|
-
`),C.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{C.unlinkSync(r)}catch{}}}}_runDirFallback(){return T.join(T.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))C.mkdirSync(t,{recursive:!0})}write(){return FS(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function bu(e,t,n){const r={};for(const i of t.dirs)r[i.name]=i.path;const o={};for(const i of t.files)o[i.name]=i.path;const s=zS(t.config,t.liveFields??{});return Object.defineProperties(e,{project:{value:t.project,enumerable:!0},namespace:{value:t.namespace,enumerable:!0},orgNamespace:{value:t.orgNamespace,enumerable:!0},scope:{value:t.scope,enumerable:!0},prefix:{value:t.envPrefix,enumerable:!0},instanceId:{value:t.instanceId,enumerable:!0},hash:{value:t.configHash,enumerable:!0},version:{value:{configHash:t.configHash,structureHash:t.structureHash,generatedAt:t.generatedAt,libraryVersion:t.libraryVersion},enumerable:!0},provenance:{value:t.provenance,enumerable:!0},dirs:{value:t.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:s,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(i,a,c){return typeof a=="string"&&!(a in i)?i.get(a):Reflect.get(i,a,c)}})}const $a={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production"],dirs:{data:{kind:"data"},cache:{kind:"cache"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"SQLite backlog-graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"SQLite `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"migration.phase":{type:"string",env:"ADHD_BACKLOG_MIGRATION_PHASE",default:"not-started",enum:["not-started","phase-1","phase-2","phase-3","phase-4","phase-5","complete"],description:"MIGRATION.md §4.4 — a queried signal (never hardcoded prose) for whether BACKLOG.md or the tool is authoritative right now. Read via `migrationStatus(ctx)`/`backlog migration-status`. NOT yet per-repo-keyed (MIGRATION.md §9 open decision 6) — one global value."}}};function rp(e){if(e)return e;const t=process.env.ADHD_BACKLOG_SCOPE;if(t)return t;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function va(e={}){const t={namespace:"production",scope:rp(e.scope)};return e.adhdRoot!==void 0&&(t.adhdRoot=e.adhdRoot),e.cwd!==void 0&&(t.cwd=e.cwd),e.instanceId!==void 0&&(t.instanceId=e.instanceId),new zr("backlog",$a,t)}function wa(e){return e.config.db.path??e.files.db}function YS(e,t){return`${e}:${t}`}function QS(e={}){const t=process.env.APIGEN_IR_CACHE_FILE;if(t)return t;const n={namespace:"production",scope:"global"};e.adhdRoot!==void 0&&(n.adhdRoot=e.adhdRoot),e.instanceId!==void 0&&(n.instanceId=e.instanceId);const r=new zr("backlog",$a,n);return T.join(r.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}const op=Symbol.for("adhd.apigen.extraction-session");function sp(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}sp(r,t)}}}function ip(e){try{const t=C.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const $r=new Map,Eu=new Map;function ZS(e,t,n){const r=t??"",o=$r.get(r);let s=n;if(o&&o.fileVersions.size>0){const c=[n],u=[...o.fileVersions.entries()].sort(([l],[f])=>l.localeCompare(f));for(const[l,f]of u)l!==e&&c.push(`${l}:${f}`);s=c.join("|")}const i=`${e}\0${t??""}`;let a=Eu.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},Eu.set(i,a)),a.schemas}function XS(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[op]:!0,stats:e,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(r){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const o=r??"",s=r?this.statVersion(r):"";let i=$r.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:r?new kn.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new kn.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},$r.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=$r.get(o??""),a=this.statVersion(r);let c=s.getSourceFile(r);if(c===void 0?c=s.addSourceFileAtPath(r):i&&i.fileVersions.get(r)!==a&&c.refreshFromFileSystemSync(),i==null||i.fileVersions.set(r,a),i){const u=new Set([r]);sp(c,u);for(const l of u)l!==r&&i.fileVersions.set(l,this.statVersion(l))}return c},statVersion(r){let o=t.get(r);return o===void 0&&(o=ip(r),t.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function eN(e){const t=e;if(t[op]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const Ar="x-apigen-logical";function Su(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const s=o.$ref;if(typeof s=="string"){if(t){const f=t[s];if(!f){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${p}`)}r.push(f)}continue}const i=o.oneOf;if(Array.isArray(i))for(const f of i)typeof f=="object"&&f!==null&&r.push(f);const a=o.properties;if(a)for(const f of Object.values(a))r.push(f);const c=o.items;if(Array.isArray(c))for(const f of c)typeof f=="object"&&f!==null&&r.push(f);else typeof c=="object"&&c!==null&&r.push(c);const u=o.additionalProperties;typeof u=="object"&&u!==null&&r.push(u);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}const Nu=new Set(["string","number","boolean","integer"]);function tN(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:n}=t;return typeof n=="string"?Nu.has(n):Array.isArray(n)?n.every(r=>Nu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function nN(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(tN)}function rN(e){const t={},n=r=>{for(const o of["definitions","$defs"]){const s=r[o];if(s)for(const[i,a]of Object.entries(s)){const c=i.startsWith("#/")?i:`#/${o}/${i}`;t[c]=a}}};for(const r of Object.values(e.schemas))n(r.input),n(r.output);if(Object.keys(t).length!==0)for(const[r,o]of Object.entries(e.schemas))try{Su(o.input,t),Su(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function oN(e,t){const n=['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&&n.push(`Field(s) ${e.map(r=>`"${r}"`).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-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function sN(e,t,n){rN(e);const r={};for(const[o,s]of Object.entries(e.schemas)){const i={},a=s.input.properties??{},c=s.input.required??[],u={},l=[],f={};for(const y of t)if(y.envelope&&i[y.id]!==!1)for(const[$,v]of Object.entries(y.envelope))u[$]=v,f[$]=y.id,l.includes($)||l.push($);const p={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},h=s.safe===!0||nN(s.input),d=s.input.definitions,m=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:p},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:oN(Object.keys(u),Object.keys(a).length>0),...d?{definitions:d}:{},...m?{$defs:m}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":h,...Object.keys(f).length>0?{"x-apigen-envelope":f}:{}}}return r}const iN=8;function aN(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let cN=0;async function uN(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${cN++}`;let s;try{s=t.addTypeAlias({name:o,type:n});const i=s.getType();return await r(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function ap(e,t,n){if(n>iN)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 r=e.getUnionTypes();if(r.every(i=>i.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(i=>i.getLiteralValue())};if(r.every(i=>i.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(i=>i.getLiteralValue())};const o=await Promise.all(r.map(i=>ap(i,t,n+1))),s=ba(o);return{oneOf:o,...s?{discriminator:s}:{},[Ar]:"union"}}if(e.isArray()){const r=e.getArrayElementType();return{type:"array",items:r?await t(r.getText()):{}}}if(e.isTuple()){const r=e.getTupleElements(),o=await Promise.all(r.map(s=>t(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),s=r??o,i=e.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await t(s.getText())};const a={},c=[];for(const u of i){const l=u.getName(),f=u.getDeclarations()[0];let p;if(f)try{p=u.getTypeAtLocation(f)}catch{p=void 0}if(p!==void 0&&p.getCallSignatures().length>0)continue;const h=p!==void 0?aN(p,f):void 0;a[l]=h!==void 0?await t(h):{},u.isOptional()||c.push(l)}return Object.keys(a).length>0?{type:"object",properties:a,...c.length>0?{required:c}:{}}:{}}return{}}function ba(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of t){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}function vr(e,t,n){if(t>6)return{};const r=e.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=_s[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=_s[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:vr(r.slice(0,-2),t+1,n)};if(r.includes("|")){const s=r.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=>vr(c,t+1,n)),a=ba(i);return{oneOf:i,...a?{discriminator:a}:{},[Ar]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1).trim(),i={};for(const a of s.split(";").filter(Boolean)){const[c,u]=a.split(":").map(l=>l.trim());c&&u&&(i[c.replace("?","")]=vr(u,t+1,n))}return{type:"object",properties:i}}return{}}function cp(e){const t=[];let n=0,r=0;for(let s=0;s<e.length;s++){const i=e[s];i==="<"||i==="["||i==="{"||i==="("?n++:i===">"||i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,s).trim()),r=s+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function lN(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function fN(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function dN(e){let t=e.trim();if(t.startsWith("readonly ")&&(t=t.slice(9).trim()),!t.startsWith("[")||!t.endsWith("]"))return;const n=t.slice(1,-1).trim();if(n.length!==0)return cp(n)}async function pN(e,t){const n=e.trim(),r=lN(n);if(r!==void 0){const i=cp(r);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=fN(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=dN(n);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 up={"decimal.js":"Decimal"},_s={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"}},Ou={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function ku(e){var t;const n=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=up[o];if(!s)continue;const i=r.getDefaultImport();if(i){const a=i.getText();a!==s&&n.set(a,s)}for(const a of r.getNamedImports()){const c=((t=a.getAliasNode())==null?void 0:t.getText())??a.getName();c!==s&&n.set(c,s)}}return n}function hN(e,t){return n=>{n.addNodeParser({supportsNode(r){var o,s,i;if(r.kind!==t)return!1;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return a!==void 0&&Object.prototype.hasOwnProperty.call(Ou,a)},createType(r){var o,s,i;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return new bt.AnnotatedType(new bt.StringType,{format:Ou[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){return new bt.AnnotatedType(new bt.StringType,{format:"int64"},!1)}})}}let dn;function mN(){if(dn)return dn;try{const e=T.dirname(require.resolve("ts-json-schema-generator/package.json"));dn=require(require.resolve("typescript",{paths:[e]}))}catch{dn=require("typescript")}return dn}const nt=new Map;function gN(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function yN(e){const t=nt.get(e);return t&&(nt.delete(e),nt.set(e,t)),t}function $N(e,t){const n=gN();if(n!==0)for(nt.delete(e),nt.set(e,t);nt.size>n;){const r=nt.keys().next().value;nt.delete(r)}}function vN(e,t){return`${e}\0${t??""}`}const wN=new Set(["zod",/^zod\/./]);function bN(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of wN)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function EN(e){for(const t of["$defs","definitions"]){const n=e[t];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(s=>/zod/i.test(s)));for(const[s,i]of Object.entries(n)){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 n[s]}As(e)}function As(e,t){if(!e||typeof e!="object")return;const n=t??new WeakSet;if(!n.has(e)){n.add(e);for(const r of Object.keys(e))if(r==="$ref"&&typeof e[r]=="string"){const o=e[r];/zod/i.test(o)&&delete e[r]}for(const[,r]of Object.entries(e))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&As(o,n);else As(r,n)}}function SN(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const s of Object.keys(o))t.add(s)}const n=js(e,t);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.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 js(e,t){if(!e||typeof e!="object")return[];const n=[];for(const[r,o]of Object.entries(e))if(r==="$ref"&&typeof o=="string"){const s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!t.has(s[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const s of o)typeof s=="object"&&s!==null&&n.push(...js(s,t));else n.push(...js(o,t));return n}function NN(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=ba(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Ar]:o[Ar]??"union"}}function ON(e,t,n){const{DEFAULT_CONFIG:r}=require("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},s=o.path,i=vN(s,o.tsconfig);let a;a=n?n.statVersion(s):ip(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??yN(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=require("ts-json-schema-generator/dist/factory/program.js"),f=mN(),p=hN(f.SyntaxKind.BigIntKeyword,f.SyntaxKind.TypeReference),h=l(o),d=bt.createParser(h,o,p),m=bt.createFormatter(o);if(c=new bt.SchemaGenerator(h,d,m,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const y={version:a,gen:c};$N(i,y),n==null||n.generatorCache.set(i,y)}}const u=c.createSchema(o.type);return EN(u),SN(u),u}function kN(e,t){let n=e.trim();if(n=fp(n),t!=null&&t.size){const o=t.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function lp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const _N=Object.entries(up).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${lp(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function fp(e){let t=e;for(const{pattern:n,key:r}of _N)t=t.replace(n,r);return t}function AN(e,t){let n=fp(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${lp(r)}\\b`,"g"),o);return n}async function Cn(e,t,n,r,o,s){const i=t.getFilePath(),a=`${i}\0${r??""}\0${n}`,c=s??new Set;if(c.has(a))return{};if(!o){const d=new Set(c);return d.add(a),_u(e,t,n,r,void 0,d)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=ZS(i,r,o.statVersion(i)),f=l.get(n);if(f!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(f)),f;o.stats.schemaCacheMisses++;const p=new Set(c);p.add(a);const h=_u(e,t,n,r,o,p).then(d=>(l.set(n,d),d)).catch(d=>{throw o.schemaCache.delete(a),d});return o.schemaCache.set(a,h),h}async function _u(e,t,n,r,o,s){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let i;if(o){const p=o.aliasCache.get(t);i=p??ku(t),p||o.aliasCache.set(t,i)}else i=ku(t);const a=kN(n,i),c=_s[a];if(c!==void 0)return c;const u=await pN(a,p=>Cn(e,t,p,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(t))??bN(t);if(o&&o.zodImportCache.set(t,l),!l)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},h=ON(p,!0,o);return NN(h)}catch{}try{const p=await uN(e,t,a,h=>ap(h,d=>Cn(e,t,d,r,o,s),0));if(p!==void 0)return p}catch{}const f=AN(a,i);return vr(f,0,i)}function Ea(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return jN(n,t)}function jN(e,t){var n;const r=e,o=((n=r==null?void 0:r.getJsDocs)==null?void 0:n.call(r))??[],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 IN(e){const t=e.trim(),n=t.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[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 xN(e,t){const n=IN(t);if(n===void 0)return;e.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof e.description=="string"?e.description:void 0;e.description=o?`${o} (default: ${r})`:`(default: ${r})`}function Wr(e){try{if(!e||e.getKind()!==kn.SyntaxKind.TypeReference)return;const t=e;if(t.getTypeArguments().length>0)return;const n=t.getTypeName();if(n.getKind()!==kn.SyntaxKind.Identifier)return;const r=n.getSymbol();if(!r)return;const o=r.getDeclarations().find(c=>c.getKindName()==="TypeAliasDeclaration");if(!o)return;const s=o,i=s.getType();if(!(i.isString()||i.isNumber()||i.isBoolean()))return;const a=s.getJsDocs();for(const c of a)for(const u of c.getTags())if(u.getTagName()==="format"){const l=u.getCommentText();if(l!==void 0)return l.trim()}return}catch{return}}async function PN(e){const t=e.session===void 0,n=eN(e.session??XS());try{return await TN(e,n)}finally{t&&n.dispose()}}async function TN(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:s}=e,i=t.projectFor(s),a=t.sourceFileFor(n,s),c=T.basename(n),u=Ge(DN(c)),l=o?null:u,f=Ge(r),p=[];for(const[m,y]of a.getExportedDeclarations()){if(m==="default"||sr(m))continue;const $=UN(y);if($){const N=$.getSignature(),j=ju(N,$),R=N.getReturnType().getText(),J=pt(N);p.push(await or(i,a,f,l,m,j,R,$.isAsync(),s,t,J));continue}const v=y.find(N=>N.getKindName()==="VariableDeclaration");if(!v)continue;const E=v.getInitializer(),b=E==null?void 0:E.getKindName();if(E&&["ArrowFunction","FunctionExpression"].includes(b??"")){const N=v.getType().getCallSignatures();if(N.length===0)continue;const j=N[0],R=Iu(j,v,v.getVariableStatement()),J=j.getReturnType().getText(),U=pt(j),q=E.isAsync();p.push(await or(i,a,f,l,m,R,J,q,s,t,U))}else if(b==="ObjectLiteralExpression"){const N=v.getType();for(const j of N.getProperties()){const R=j.getName();if(sr(R))continue;const J=j.getTypeAtLocation(v).getCallSignatures();if(J.length===0)continue;const U=J[0],q=Iu(U,v,v.getVariableStatement()),Q=U.getReturnType().getText(),Z=pt(U),ye=[...l?[l]:[],Ge(m),Ge(R)];p.push(await wr(i,a,f,ye,R,q,Q,!1,s,t,Z))}}else{const N=v.getType(),j=N.getText();if(yt(N,v)){const R=await Cn(i,a,j,s,t);p.push(RN(f,l,m,R))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${m}`)}}const h=a.getDefaultExportSymbol();if(h){const m=a.getExportAssignment(y=>!y.isExportEquals());if(m){const y=m.getExpression(),$=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes($)){const v=y.getType().getCallSignatures();if(v.length>0){const E=v[0],b=To(E,m),N=E.getReturnType().getText(),j=pt(E),R=y.isAsync();p.push(await or(i,a,f,l,"default",b,N,R,s,t,j))}}else{const v=y.getType();for(const E of v.getProperties()){const b=E.getName();if(sr(b))continue;const N=E.getTypeAtLocation(m).getCallSignatures();if(N.length===0)continue;const j=N[0],R=To(j,m),J=j.getReturnType().getText(),U=pt(j),q=[...l?[l]:[],Ge("default"),Ge(b)];p.push(await wr(i,a,f,q,b,R,J,!1,s,t,U))}}}else{const y=h.getDeclarations();for(const $ of y){if($.getKindName()!=="FunctionDeclaration")continue;const v=$,E=v.getName(),b=E&&E.length>0?E:"default",N=v.getSignature(),j=ju(N,v),R=N.getReturnType().getText(),J=pt(N);p.push(await or(i,a,f,l,b,j,R,v.isAsync(),s,t,J))}}}const d=LN(a);if(d.length>0)for(const{name:m,sig:y}of d){if(sr(m))continue;const $=To(y),v=y.getReturnType().getText(),E=pt(y),b=[...l?[l]:[],Ge(m)];p.push(await wr(i,a,f,b,m,$,v,!1,s,t,E))}return p}function CN(e,t,n,r){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,l]of Object.entries(a)){if(u==="definitions"||u==="$defs"){const f=u,p=t[f];for(const[h,d]of Object.entries(l)){const m=s(d),y=p[h];if(y!==void 0&&JSON.stringify(y)!==JSON.stringify(m))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${f}.${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]=m}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(e)}function Au(e,t){if(!t||e.format!==void 0||"$ref"in e||"properties"in e||"items"in e)return;const n=e.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(e.format=t)}function pt(e){var t;try{return Wr((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function or(e,t,n,r,o,s,i,a,c,u,l){const f=Ge(o);return wr(e,t,n,r?[r,f]:[f],o,s,i,a,c,u,l)}async function wr(e,t,n,r,o,s,i,a,c,u,l){const f=s.length>0&&s[0].name==="ctx",p=s.filter(b=>b.name!=="ctx"),h=p.filter(b=>!b.optional).map(b=>b.name),d={},m={definitions:{},$defs:{}};for(const b of p){const N=await Cn(e,t,b.type,c,u),j=CN(N,m,o,b.name);b.defaultValue!==void 0&&xN(j,b.defaultValue),Au(j,b.format),d[b.name]=j}const y=i.replace(/^Promise<(.+)>$/,"$1").trim(),$=await Cn(e,t,y,c,u),v=l?{...$}:$;Au(v,l);const E={type:"object",properties:d,required:h,...Object.keys(m.definitions).length>0?{definitions:m.definitions}:{},...Object.keys(m.$defs).length>0?{$defs:m.$defs}:{}};return{id:dp(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:E,output:v,envelope:{},typeText:{lang:"ts",input:BN(s),output:y},...f?{hasCtx:!0}:{}}}function RN(e,t,n,r){const o=Ge(n),s=t?[t,o]:[o];return{id:dp(e,s),host:"ts",namespace:e,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function dp(e,t){return(e.raw?[e,...t]:t).map(n=>n.words.join("-")).join("/")}function MN(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 Ge(e){return{raw:e,words:MN(e)}}function DN(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function LN(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;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 UN(e){let t;for(const n of e){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(t||(t=r),r.getBody())return r}return t}function ju(e,t){return e.getParameters().map(n=>{var r;const o=n.getDeclarations(),s=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=n.isOptional()||((s==null?void 0:s.hasInitializer())??!1)||(((r=s==null?void 0:s.hasQuestionToken)==null?void 0:r.call(s))??!1);return{name:n.getName(),type:n.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:Ea(s,n.getName(),t),format:Wr(s==null?void 0:s.getTypeNode())}})}function Iu(e,t,n){return e.getParameters().map(r=>{var o;const s=r.getDeclarations(),i=s.length>0&&s[0].getKindName()==="Parameter"?s[0]:null,a=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((o=i==null?void 0:i.hasQuestionToken)==null?void 0:o.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(t).getText(),optional:a,defaultValue:Ea(i,r.getName(),n??t),format:Wr(i==null?void 0:i.getTypeNode())}})}function To(e,t){return e.getParameters().map(n=>{var r,o,s;const i=n.getDeclarations(),a=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,c=n.isOptional()||((a==null?void 0:a.hasInitializer())??!1)||(((r=a==null?void 0:a.hasQuestionToken)==null?void 0:r.call(a))??!1);return{name:n.getName(),type:a?a.getType().getText():((s=(o=n.getValueDeclaration())==null?void 0:o.getType())==null?void 0:s.getText())??"unknown",optional:c,defaultValue:Ea(a,n.getName(),t),format:Wr(a==null?void 0:a.getTypeNode())}})}function BN(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function sr(e){return!!(e==="__samples__"||e.startsWith("__"))}function yt(e,t,n=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 r=e.getArrayElementType();return r?yt(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>yt(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>yt(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>yt(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),s=e.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||yt(a,t,n));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return yt(c,t,n)})}return!1}function FN(e,t){return async n=>{let r=()=>t(n);for(let o=e.length-1;o>=0;o--){const s=e[o],i=r;r=()=>s(n,i)}return r()}}function qN(e,t){return FN(e,t)}function VN(e,t,n={}){const r=e.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return qN(r,t)}function pp(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}pp(r,t)}}}let Co;function KN(){return Co||(Co=new kn.Project({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})),Co}function hp(e){const t=KN(),n=t.getSourceFile(e),r=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([e]);return pp(r,o),[...o].sort()}const GN={"decimal.js":"Decimal"};function JN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(GN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${JN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));async function HN(e,t){await Et.mkdir(T.dirname(e),{recursive:!0});const n=`${e}.${process.pid}.${Un.randomUUID()}.tmp`;try{await Et.writeFile(n,JSON.stringify(t),"utf8"),await Et.rename(n,e)}catch(r){throw await Et.unlink(n).catch(()=>{}),r}}function zN(e){return{async get(){try{const t=await Et.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await HN(e,n)}}}const Is=1;function WN(e){return Un.createHash("sha256").update(e).digest("hex")}async function xu(e){return WN(await Et.readFile(e,"utf8"))}async function jr(e){try{return(await Et.stat(e)).mtimeMs}catch{return}}async function Pu(e,t){const n=await xu(e.source),r=Un.createHash("sha256");r.update(`formatVersion:${Is}
|
|
165
|
-
`),r.update(`extractorVersion:${
|
|
166
|
-
`),r.update(`host:${
|
|
167
|
-
`),r.update(`namespace:${
|
|
194
|
+
`),J.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{J.unlinkSync(r)}catch{}}}}_runDirFallback(){return L.join(L.dirname(this.snapshotPath),"run")}ensureDirs(){for(const e of Object.values(this.paths))J.mkdirSync(e,{recursive:!0})}write(){return hP(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}};function Bh(t,e,n){const r={};for(const i of e.dirs)r[i.name]=i.path;const o={};for(const i of e.files)o[i.name]=i.path;const s=bP(e.config,e.liveFields??{});return Object.defineProperties(t,{project:{value:e.project,enumerable:!0},namespace:{value:e.namespace,enumerable:!0},orgNamespace:{value:e.orgNamespace,enumerable:!0},scope:{value:e.scope,enumerable:!0},prefix:{value:e.envPrefix,enumerable:!0},instanceId:{value:e.instanceId,enumerable:!0},hash:{value:e.configHash,enumerable:!0},version:{value:{configHash:e.configHash,structureHash:e.structureHash,generatedAt:e.generatedAt,libraryVersion:e.libraryVersion},enumerable:!0},provenance:{value:e.provenance,enumerable:!0},dirs:{value:e.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:s,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:e,enumerable:!1}}),new Proxy(t,{get(i,a,c){return typeof a=="string"&&!(a in i)?i.get(a):Reflect.get(i,a,c)}})}const ls={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production","test","sandbox"],dirs:{data:{kind:"data"},cache:{kind:"cache"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"Backlog graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"The store adapter's `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"embedding.enabled":{type:"boolean",env:"ADHD_BACKLOG_EMBEDDING_ENABLED",default:!1,description:'RAG-SPEC.md §1.6 — opt IN to the semantic/RAG stack. Default FALSE: semantic inputs (filter.semantic, filter.anchor, view:"similar", sort:"relevance", fields:["_vector"]) answer RagNotConfiguredError (§5a) until this is set. Requires the optionalDependencies @adhd/sox-embedding-provider + @adhd/sox-vector-store to be installed, and a store whose adapter reports capabilities.nativeVectors (turso). Enabling it with any of those missing logs a typed reason and leaves RAG unconfigured — it never crashes startup.'},"embedding.provider":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_PROVIDER",default:"fastembed",description:"Embedding provider type, forwarded verbatim to @adhd/sox-embedding-provider's createEmbeddingProvider ('fastembed' | 'remote')."},"embedding.model":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_MODEL",default:"bge-base-en-v1.5",description:"Embedding model id (768-dim bge-base-en-v1.5 by default). RAG-SPEC.md §2.5: the dimensional contract is STRUCTURAL — changing this after items are embedded orphans existing vectors under the old model id rather than silently truncating; re-embed via admin(embedding_backfill)."}}};function _v(t){if(t)return t;const e=process.env.ADHD_BACKLOG_SCOPE;if(e)return e;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function Go(t={}){const e={namespace:t.namespace??"production",scope:_v(t.scope)};return t.adhdRoot!==void 0&&(e.adhdRoot=t.adhdRoot),t.cwd!==void 0&&(e.cwd=t.cwd),t.instanceId!==void 0&&(e.instanceId=t.instanceId),new Ev("backlog",ls,e)}function zo(t){return t.config.db.path??t.files.db}function SP(t,e){return`${t}:${e}`}function _P(t={}){const e=process.env.APIGEN_IR_CACHE_FILE;if(e)return e;const n={namespace:"production",scope:"global"};t.adhdRoot!==void 0&&(n.adhdRoot=t.adhdRoot),t.instanceId!==void 0&&(n.instanceId=t.instanceId);const r=new Ev("backlog",ls,n);return L.join(r.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}const zt=Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);let cc;function NP(){return cc||(cc=zt("ts-morph").Project,cc)}const Nv=Symbol.for("adhd.apigen.extraction-session");function Ov(t,e){const n=[...t.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...t.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!e.has(o)){e.add(o);try{r.refreshFromFileSystemSync()}catch{}Ov(r,e)}}}function kv(t){try{const e=J.statSync(t);return`${e.mtimeMs}:${e.size}`}catch{return"nostat"}}const Ei=new Map,Fh=new Map;function OP(t,e,n){const r=e??"",o=Ei.get(r);let s=n;if(o&&o.fileVersions.size>0){const c=[n],u=[...o.fileVersions.entries()].sort(([l],[d])=>l.localeCompare(d));for(const[l,d]of u)l!==t&&c.push(`${l}:${d}`);s=c.join("|")}const i=`${t}\0${e??""}`;let a=Fh.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},Fh.set(i,a)),a.schemas}function kP(){const t={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},e=new Map;let n=!1;return{[Nv]:!0,stats:t,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(r){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const o=r??"",s=r?this.statVersion(r):"";let i=Ei.get(o);if(i&&i.tsconfigVersion!==s&&(i=void 0),!i){const a=NP();i={project:r?new a({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new a({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},Ei.set(o,i),t.projectsBuilt++}return i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=Ei.get(o??""),a=this.statVersion(r);let c=s.getSourceFile(r);if(c===void 0?c=s.addSourceFileAtPath(r):i&&i.fileVersions.get(r)!==a&&c.refreshFromFileSystemSync(),i==null||i.fileVersions.set(r,a),i){const u=new Set([r]);Ov(c,u);for(const l of u)l!==r&&i.fileVersions.set(l,this.statVersion(l))}return c},statVersion(r){let o=e.get(r);return o===void 0&&(o=kv(r),e.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),e.clear()}}}function jP(t){const e=t;if(e[Nv]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return e}const Qi="x-apigen-logical";function qh(t,e){const n=new Set,r=[t];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const s=o.$ref;if(typeof s=="string"){if(e){const d=e[s];if(!d){const f=Object.keys(e).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${f}`)}r.push(d)}continue}const i=o.oneOf;if(Array.isArray(i))for(const d of i)typeof d=="object"&&d!==null&&r.push(d);const a=o.properties;if(a)for(const d of Object.values(a))r.push(d);const c=o.items;if(Array.isArray(c))for(const d of c)typeof d=="object"&&d!==null&&r.push(d);else typeof c=="object"&&c!==null&&r.push(c);const u=o.additionalProperties;typeof u=="object"&&u!==null&&r.push(u);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}const Kh=new Set(["string","number","boolean","integer"]);function AP(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Kh.has(n):Array.isArray(n)?n.every(r=>Kh.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function IP(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(AP)}function PP(t){const e={},n=r=>{for(const o of["definitions","$defs"]){const s=r[o];if(s)for(const[i,a]of Object.entries(s)){const c=i.startsWith("#/")?i:`#/${o}/${i}`;e[c]=a}}};for(const r of Object.values(t.schemas))n(r.input),n(r.output);if(Object.keys(e).length!==0)for(const[r,o]of Object.entries(t.schemas))try{qh(o.input,e),qh(o.output,e)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function xP(t,e){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(e?".":" (an empty object for this zero-parameter tool).")];return t.length>0&&n.push(`Field(s) ${t.map(r=>`"${r}"`).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-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function RP(t,e,n){PP(t);const r={};for(const[o,s]of Object.entries(t.schemas)){const i={},a=s.input.properties??{},c=s.input.required??[],u={},l=[],d={};for(const w of e)if(w.envelope&&i[w.id]!==!1)for(const[h,v]of Object.entries(w.envelope))u[h]=v,d[h]=w.id,l.includes(h)||l.push(h);const f={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},g=s.safe===!0||IP(s.input),p=s.input.definitions,y=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:xP(Object.keys(u),Object.keys(a).length>0),...p?{definitions:p}:{},...y?{$defs:y}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":g,...Object.keys(d).length>0?{"x-apigen-envelope":d}:{}}}return r}const TP=8;function CP(t,e){try{return e?t.getText(e):t.getText()}catch{try{return t.getText()}catch{return}}}let MP=0;async function LP(t,e,n,r){const o=`__ApigenProbe_${process.pid}_${MP++}`;let s;try{s=e.addTypeAlias({name:o,type:n});const i=s.getType();return await r(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function jv(t,e,n){if(n>TP)return{};if(t.isString()||t.isStringLiteral())return t.isStringLiteral()?{type:"string",enum:[t.getLiteralValue()]}:{type:"string"};if(t.isNumber()||t.isNumberLiteral())return t.isNumberLiteral()?{type:"number",enum:[t.getLiteralValue()]}:{type:"number"};if(t.isBoolean())return{type:"boolean"};if(t.isBooleanLiteral())return{type:"boolean"};if(t.isNull()||t.isUndefined()||t.isVoid())return{type:"null"};if(t.isUnion()){const r=t.getUnionTypes();if(r.every(i=>i.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(i=>i.getLiteralValue())};if(r.every(i=>i.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(i=>i.getLiteralValue())};const o=await Promise.all(r.map(i=>jv(i,e,n+1))),s=Td(o);return{oneOf:o,...s?{discriminator:s}:{},[Qi]:"union"}}if(t.isArray()){const r=t.getArrayElementType();return{type:"array",items:r?await e(r.getText()):{}}}if(t.isTuple()){const r=t.getTupleElements(),o=await Promise.all(r.map(s=>e(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(t.isObject()){const r=t.getStringIndexType(),o=t.getNumberIndexType(),s=r??o,i=t.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await e(s.getText())};const a={},c=[];for(const u of i){const l=u.getName(),d=u.getDeclarations()[0];let f;if(d)try{f=u.getTypeAtLocation(d)}catch{f=void 0}if(f!==void 0&&f.getCallSignatures().length>0)continue;const g=f!==void 0?CP(f,d):void 0;a[l]=g!==void 0?await e(g):{},u.isOptional()||c.push(l)}if(Object.keys(a).length>0){const u=s?await e(s.getText()):!1;return{type:"object",properties:a,...c.length>0?{required:c}:{},additionalProperties:u}}return{}}return{}}function Td(t){if(t.length<2)return;const e=[];for(const r of t){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;e.push(o)}const n=Object.keys(e[0]).filter(r=>e.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of e){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}function Si(t,e,n){if(e>6)return{};const r=t.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=yu[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=yu[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:Si(r.slice(0,-2),e+1,n)};if(r.includes("|")){const s=r.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=>Si(c,e+1,n)),a=Td(i);return{oneOf:i,...a?{discriminator:a}:{},[Qi]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1).trim(),i={};for(const a of s.split(";").filter(Boolean)){const[c,u]=a.split(":").map(l=>l.trim());c&&u&&(i[c.replace("?","")]=Si(u,e+1,n))}return{type:"object",properties:i}}return{}}function Av(t){const e=[];let n=0,r=0;for(let s=0;s<t.length;s++){const i=t[s];i==="<"||i==="["||i==="{"||i==="("?n++:i===">"||i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(e.push(t.slice(r,s).trim()),r=s+1)}const o=t.slice(r).trim();return o.length>0&&e.push(o),e}function DP(t){const e=/^(?:Readonly)?Map<(.+)>$/.exec(t);return e?e[1]:void 0}function UP(t){const e=/^(?:Readonly)?Set<(.+)>$/.exec(t);return e?e[1]:void 0}function BP(t){let e=t.trim();if(e.startsWith("readonly ")&&(e=e.slice(9).trim()),!e.startsWith("[")||!e.endsWith("]"))return;const n=e.slice(1,-1).trim();if(n.length!==0)return Av(n)}async function FP(t,e){const n=t.trim(),r=DP(n);if(r!==void 0){const i=Av(r);if(i.length===2){const[a,c]=await Promise.all([e(i[0]),e(i[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=UP(n);if(o!==void 0)return{type:"array",items:await e(o),uniqueItems:!0};const s=BP(n);if(s!==void 0){const i=await Promise.all(s.map(a=>e(a)));return{type:"array",items:i,minItems:i.length,maxItems:i.length}}}const Iv={"decimal.js":"Decimal"},yu={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"}},Vh={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Gh(t){var e;const n=new Map;for(const r of t.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=Iv[o];if(!s)continue;const i=r.getDefaultImport();if(i){const a=i.getText();a!==s&&n.set(a,s)}for(const a of r.getNamedImports()){const c=((e=a.getAliasNode())==null?void 0:e.getText())??a.getName();c!==s&&n.set(c,s)}}return n}function qP(t,e){return n=>{n.addNodeParser({supportsNode(r){var o,s,i;if(r.kind!==e)return!1;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return a!==void 0&&Object.prototype.hasOwnProperty.call(Vh,a)},createType(r){var o,s,i;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText),{AnnotatedType:c,StringType:u}=wu();return new c(new u,{format:Vh[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===t},createType(){const{AnnotatedType:r,StringType:o}=wu();return new r(new o,{format:"int64"},!1)}})}}let uc;function wu(){return uc||(uc=zt("ts-json-schema-generator"),uc)}let Eo;function KP(){if(Eo)return Eo;try{const t=L.dirname(zt.resolve("ts-json-schema-generator/package.json"));Eo=zt(zt.resolve("typescript",{paths:[t]}))}catch{Eo=zt("typescript")}return Eo}const hn=new Map;function VP(){const t=process.env.APIGEN_PROGRAM_CACHE,e=t===void 0?NaN:Number(t);return Number.isFinite(e)&&e>=0?e:8}function GP(t){const e=hn.get(t);return e&&(hn.delete(t),hn.set(t,e)),e}function zP(t,e){const n=VP();if(n!==0)for(hn.delete(t),hn.set(t,e);hn.size>n;){const r=hn.keys().next().value;hn.delete(r)}}function WP(t,e){return`${t}\0${e??""}`}const HP=new Set(["zod",/^zod\/./]);function JP(t){for(const e of t.getImportDeclarations()){const n=e.getModuleSpecifierValue();for(const r of HP)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function QP(t){for(const e of["$defs","definitions"]){const n=t[e];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(s=>/zod/i.test(s)));for(const[s,i]of Object.entries(n)){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 n[s]}vu(t)}function vu(t,e){if(!t||typeof t!="object")return;const n=e??new WeakSet;if(!n.has(t)){n.add(t);for(const r of Object.keys(t))if(r==="$ref"&&typeof t[r]=="string"){const o=t[r];/zod/i.test(o)&&delete t[r]}for(const[,r]of Object.entries(t))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&vu(o,n);else vu(r,n)}}function YP(t){const e=new Set;for(const r of["$defs","definitions"]){const o=t[r];if(o&&typeof o=="object")for(const s of Object.keys(o))e.add(s)}const n=$u(t,e);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.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 $u(t,e){if(!t||typeof t!="object")return[];const n=[];for(const[r,o]of Object.entries(t))if(r==="$ref"&&typeof o=="string"){const s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!e.has(s[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const s of o)typeof s=="object"&&s!==null&&n.push(...$u(s,e));else n.push(...$u(o,e));return n}function ZP(t){const e=t.anyOf;if(!Array.isArray(e)||e.length<2)return t;const n=e,r=Td(n),o={...t};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Qi]:o[Qi]??"union"}}function XP(t,e,n){const{DEFAULT_CONFIG:r}=zt("ts-json-schema-generator/dist/src/Config.js"),o={...r,...t},s=o.path,i=WP(s,o.tsconfig);let a;a=n?n.statVersion(s):kv(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??GP(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=zt("ts-json-schema-generator/dist/factory/program.js"),{createParser:d,createFormatter:f,SchemaGenerator:g}=wu(),p=KP(),y=qP(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),w=l(o),h=d(w,o,y),v=f(o);if(c=new g(w,h,v,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const b={version:a,gen:c};zP(i,b),n==null||n.generatorCache.set(i,b)}}const u=c.createSchema(o.type);return QP(u),YP(u),u}function ex(t,e){let n=t.trim();if(n=xv(n),e!=null&&e.size){const o=e.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function Pv(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const tx=Object.entries(Iv).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${Pv(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function xv(t){let e=t;for(const{pattern:n,key:r}of tx)e=e.replace(n,r);return e}function nx(t,e){let n=xv(t);for(const[r,o]of e)n=n.replace(new RegExp(`\\b${Pv(r)}\\b`,"g"),o);return n}async function ds(t,e,n,r,o,s){const i=e.getFilePath(),a=`${i}\0${r??""}\0${n}`,c=s??new Set;if(c.has(a))return{};if(!o){const p=new Set(c);return p.add(a),zh(t,e,n,r,void 0,p)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=OP(i,r,o.statVersion(i)),d=l.get(n);if(d!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(d)),d;o.stats.schemaCacheMisses++;const f=new Set(c);f.add(a);const g=zh(t,e,n,r,o,f).then(p=>(l.set(n,p),p)).catch(p=>{throw o.schemaCache.delete(a),p});return o.schemaCache.set(a,g),g}async function zh(t,e,n,r,o,s){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let i;if(o){const f=o.aliasCache.get(e);i=f??Gh(e),f||o.aliasCache.set(e,i)}else i=Gh(e);const a=ex(n,i),c=yu[a];if(c!==void 0)return c;const u=await FP(a,f=>ds(t,e,f,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(e))??JP(e);if(o&&o.zodImportCache.set(e,l),!l)try{const f={path:e.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},g=XP(f,!0,o);return ZP(g)}catch{}try{const f=await LP(t,e,a,g=>jv(g,p=>ds(t,e,p,r,o,s),0));if(f!==void 0)return f}catch{}const d=nx(a,i);return Si(d,0,i)}function Cd(t,e,n){if(t!=null&&t.hasInitializer()){const r=t.getInitializer();if(r)return r.getText()}return rx(n,e)}function rx(t,e){var n;const r=t,o=((n=r==null?void 0:r.getJsDocs)==null?void 0:n.call(r))??[],s=e.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 ox(t){const e=t.trim(),n=e.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(e))return Number(e);try{return JSON.parse(e)}catch{return e}}}function sx(t,e){const n=ox(e);if(n===void 0)return;t.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof t.description=="string"?t.description:void 0;t.description=o?`${o} (default: ${r})`:`(default: ${r})`}let lc;function ix(){return lc||(lc=zt("ts-morph").SyntaxKind,lc)}function ja(t){try{if(!t)return;const e=ix();if(t.getKind()!==e.TypeReference)return;const n=t;if(n.getTypeArguments().length>0)return;const r=n.getTypeName();if(r.getKind()!==e.Identifier)return;const o=r.getSymbol();if(!o)return;const s=o.getDeclarations().find(u=>u.getKindName()==="TypeAliasDeclaration");if(!s)return;const i=s,a=i.getType();if(!(a.isString()||a.isNumber()||a.isBoolean()))return;const c=i.getJsDocs();for(const u of c)for(const l of u.getTags())if(l.getTagName()==="format"){const d=l.getCommentText();if(d!==void 0)return d.trim()}return}catch{return}}const ax=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function cx(t){const e=[];let n=0,r="";for(const o of t)o==="<"||o==="("||o==="["||o==="{"?n++:(o===">"||o===")"||o==="]"||o==="}")&&n--,o===","&&n===0?(e.push(r.trim()),r=""):r+=o;return r.trim().length>0&&e.push(r.trim()),e}function ux(t){const e=t.trim(),n=e.indexOf("<");if(n===-1||!e.endsWith(">"))return null;const r=e.slice(0,n),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;if(!ax.has(o))return null;let s=0;for(let c=n;c<e.length;c++){const u=e[c];if(u==="<")s++;else if(u===">"&&(s--,s===0&&c!==e.length-1))return null}if(s!==0)return null;const i=e.slice(n+1,-1),a=cx(i);return a.length>0?a[0]:null}async function lx(t){const e=t.session===void 0,n=jP(t.session??kP());try{return await dx(t,n)}finally{e&&n.dispose()}}async function dx(t,e){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:s}=t,i=e.projectFor(s),a=e.sourceFileFor(n,s),c=L.basename(n),u=Gt(hx(c)),l=o?null:u,d=Gt(r),f=[];for(const[y,w]of a.getExportedDeclarations()){if(y==="default"||Hs(y))continue;const h=gx(w);if(h){const N=h.getSignature(),j=Jh(N,h),T=N.getReturnType().getText(),M=Gn(N);f.push(await Ws(i,a,d,l,y,j,T,h.isAsync(),s,e,M));continue}const v=w.find(N=>N.getKindName()==="VariableDeclaration");if(!v)continue;const b=v.getInitializer(),E=b==null?void 0:b.getKindName();if(b&&["ArrowFunction","FunctionExpression"].includes(E??"")){const N=v.getType().getCallSignatures();if(N.length===0)continue;const j=N[0],T=Qh(j,v,v.getVariableStatement()),M=j.getReturnType().getText(),C=Gn(j),G=b.isAsync();f.push(await Ws(i,a,d,l,y,T,M,G,s,e,C))}else if(E==="ObjectLiteralExpression"){const N=v.getType();for(const j of N.getProperties()){const T=j.getName();if(Hs(T))continue;const M=j.getTypeAtLocation(v).getCallSignatures();if(M.length===0)continue;const C=M[0],G=Qh(C,v,v.getVariableStatement()),H=C.getReturnType().getText(),Z=Gn(C),ue=[...l?[l]:[],Gt(y),Gt(T)];f.push(await _i(i,a,d,ue,T,G,H,!1,s,e,Z))}}else{const N=v.getType(),j=N.getText();if(Qn(N,v)){const T=await ds(i,a,j,s,e);f.push(fx(d,l,y,T))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${y}`)}}const g=a.getDefaultExportSymbol();if(g){const y=a.getExportAssignment(w=>!w.isExportEquals());if(y){const w=y.getExpression(),h=w.getKindName();if(["ArrowFunction","FunctionExpression"].includes(h)){const v=w.getType().getCallSignatures();if(v.length>0){const b=v[0],E=dc(b,y),N=b.getReturnType().getText(),j=Gn(b),T=w.isAsync();f.push(await Ws(i,a,d,l,"default",E,N,T,s,e,j))}}else{const v=w.getType();for(const b of v.getProperties()){const E=b.getName();if(Hs(E))continue;const N=b.getTypeAtLocation(y).getCallSignatures();if(N.length===0)continue;const j=N[0],T=dc(j,y),M=j.getReturnType().getText(),C=Gn(j),G=[...l?[l]:[],Gt("default"),Gt(E)];f.push(await _i(i,a,d,G,E,T,M,!1,s,e,C))}}}else{const w=g.getDeclarations();for(const h of w){if(h.getKindName()!=="FunctionDeclaration")continue;const v=h,b=v.getName(),E=b&&b.length>0?b:"default",N=v.getSignature(),j=Jh(N,v),T=N.getReturnType().getText(),M=Gn(N);f.push(await Ws(i,a,d,l,E,j,T,v.isAsync(),s,e,M))}}}const p=mx(a);if(p.length>0)for(const{name:y,sig:w}of p){if(Hs(y))continue;const h=dc(w),v=w.getReturnType().getText(),b=Gn(w),E=[...l?[l]:[],Gt(y)];f.push(await _i(i,a,d,E,y,h,v,!1,s,e,b))}return f}function Wh(t,e,n,r){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,l]of Object.entries(a)){if(u==="definitions"||u==="$defs"){const d=u,f=e[d];for(const[g,p]of Object.entries(l)){const y=s(p),w=f[g];if(w!==void 0&&JSON.stringify(w)!==JSON.stringify(y))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${d}.${g}" 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.`);f[g]=y}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(t)}function Hh(t,e){if(!e||t.format!==void 0||"$ref"in t||"properties"in t||"items"in t)return;const n=t.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(t.format=e)}function Gn(t){var e;try{return ja((e=t.getDeclaration())==null?void 0:e.getReturnTypeNode())}catch{return}}async function Ws(t,e,n,r,o,s,i,a,c,u,l){const d=Gt(o);return _i(t,e,n,r?[r,d]:[d],o,s,i,a,c,u,l)}async function _i(t,e,n,r,o,s,i,a,c,u,l){const d=s.length>0&&s[0].name==="ctx",f=s.filter(C=>C.name!=="ctx"),g=f.filter(C=>!C.optional).map(C=>C.name),p={},y={definitions:{},$defs:{}};for(const C of f){const G=await ds(t,e,C.type,c,u),H=Wh(G,y,o,C.name);C.defaultValue!==void 0&&sx(H,C.defaultValue),Hh(H,C.format),p[C.name]=H}const w=i.replace(/^Promise<(.+)>$/,"$1").trim(),h=ux(w),v=h!==null,b=v?h:w,E=await ds(t,e,b,c,u),N={definitions:{},$defs:{}},j=Wh(E,N,o,"<return>"),T=l?{...j}:j;Hh(T,l),Object.keys(N.definitions).length>0&&(T.definitions={...T.definitions,...N.definitions}),Object.keys(N.$defs).length>0&&(T.$defs={...T.$defs,...N.$defs});const M={type:"object",properties:p,required:g,...Object.keys(y.definitions).length>0?{definitions:y.definitions}:{},...Object.keys(y.$defs).length>0?{$defs:y.$defs}:{}};return{id:Rv(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:v,safe:!1,input:M,output:T,envelope:{},typeText:{lang:"ts",input:yx(s),output:b},...d?{hasCtx:!0}:{}}}function fx(t,e,n,r){const o=Gt(n),s=e?[e,o]:[o];return{id:Rv(t,s),host:"ts",namespace:t,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function Rv(t,e){return(t.raw?[t,...e]:e).map(n=>n.words.join("-")).join("/")}function px(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}function Gt(t){return{raw:t,words:px(t)}}function hx(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function mx(t){const e=[];for(const n of t.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;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&&e.push({name:a.getName(),sig:c[0]})}}return e}function gx(t){let e;for(const n of t){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(e||(e=r),r.getBody())return r}return e}function Jh(t,e){return t.getParameters().map(n=>{var r;const o=n.getDeclarations(),s=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=n.isOptional()||((s==null?void 0:s.hasInitializer())??!1)||(((r=s==null?void 0:s.hasQuestionToken)==null?void 0:r.call(s))??!1);return{name:n.getName(),type:n.getTypeAtLocation(t.getDeclaration()).getText(),optional:i,defaultValue:Cd(s,n.getName(),e),format:ja(s==null?void 0:s.getTypeNode())}})}function Qh(t,e,n){return t.getParameters().map(r=>{var o;const s=r.getDeclarations(),i=s.length>0&&s[0].getKindName()==="Parameter"?s[0]:null,a=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((o=i==null?void 0:i.hasQuestionToken)==null?void 0:o.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(e).getText(),optional:a,defaultValue:Cd(i,r.getName(),n??e),format:ja(i==null?void 0:i.getTypeNode())}})}function dc(t,e){return t.getParameters().map(n=>{var r,o,s;const i=n.getDeclarations(),a=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,c=n.isOptional()||((a==null?void 0:a.hasInitializer())??!1)||(((r=a==null?void 0:a.hasQuestionToken)==null?void 0:r.call(a))??!1);return{name:n.getName(),type:a?a.getType().getText():((s=(o=n.getValueDeclaration())==null?void 0:o.getType())==null?void 0:s.getText())??"unknown",optional:c,defaultValue:Cd(a,n.getName(),e),format:ja(a==null?void 0:a.getTypeNode())}})}function yx(t){const e=t.filter(n=>n.name!=="ctx");return e.length===0?"()":"("+e.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Hs(t){return!!(t==="__samples__"||t.startsWith("__"))}function Qn(t,e,n=new Set){if(t.getCallSignatures().length>0||t.getConstructSignatures().length>0)return!1;if(t.isString()||t.isNumber()||t.isBoolean()||t.isNull()||t.isUndefined()||t.isStringLiteral()||t.isNumberLiteral()||t.isBooleanLiteral()||t.isEnumLiteral())return!0;if(t.isArray()||t.isReadonlyArray()){const r=t.getArrayElementType();return r?Qn(r,e,n):!1}if(t.isTuple())return t.getTupleElements().every(r=>Qn(r,e,n));if(t.isUnion())return t.getUnionTypes().every(r=>Qn(r,e,n));if(t.isIntersection())return t.getIntersectionTypes().every(r=>Qn(r,e,n));if(t.isObject()){const r=t.getText(e);if(n.has(r))return!0;n.add(r);const o=t.getStringIndexType(),s=t.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||Qn(a,e,n));const i=t.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(e);return Qn(c,e,n)})}return!1}function wx(t,e){return async n=>{let r=()=>e(n);for(let o=t.length-1;o>=0;o--){const s=t[o],i=r;r=()=>s(n,i)}return r()}}function vx(t,e){return wx(t,e)}function $x(t,e,n={}){const r=t.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return vx(r,e)}const bx=Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);let fc;function Ex(){return fc||(fc=bx("ts-morph").Project,fc)}function Tv(t,e){const n=[...t.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...t.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!e.has(o)){e.add(o);try{r.refreshFromFileSystemSync()}catch{}Tv(r,e)}}}let pc;function Sx(){if(!pc){const t=Ex();pc=new t({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return pc}function Cv(t){const e=Sx(),n=e.getSourceFile(t),r=n??e.addSourceFileAtPath(t);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([t]);return Tv(r,o),[...o].sort()}const _x={"decimal.js":"Decimal"};function Nx(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(_x).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${Nx(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));async function Ox(t,e){await or.mkdir(L.dirname(t),{recursive:!0});const n=`${t}.${process.pid}.${kn.randomUUID()}.tmp`;try{await or.writeFile(n,JSON.stringify(e),"utf8"),await or.rename(n,t)}catch(r){throw await or.unlink(n).catch(()=>{}),r}}function kx(t){return{async get(){try{const e=await or.readFile(t,"utf8");return JSON.parse(e)}catch{return}},async put(e,n){await Ox(t,n)}}}const bu=1;function jx(t){return kn.createHash("sha256").update(t).digest("hex")}async function Yh(t){return jx(await or.readFile(t,"utf8"))}async function Yi(t){try{return(await or.stat(t)).mtimeMs}catch{return}}async function Zh(t,e){const n=await Yh(t.source),r=kn.createHash("sha256");r.update(`formatVersion:${bu}
|
|
195
|
+
`),r.update(`extractorVersion:${e}
|
|
196
|
+
`),r.update(`host:${t.host}
|
|
197
|
+
`),r.update(`namespace:${t.namespace??""}
|
|
168
198
|
`),r.update(`source:${n}
|
|
169
|
-
`);for(const o of
|
|
170
|
-
`);return r.digest("hex")}async function Tu(e,t){const n=await jr(e.source)??0,r=[];for(const o of hp(e.source)){if(o===e.source)continue;const s=await jr(o);s!==void 0&&r.push({path:o,mtimeMs:s})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:r}}async function YN(e,t){if(t.source.path!==e.source)return!1;const n=await jr(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const r of t.deps){const o=await jr(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function QN(e){if(e.cache==="artifact")throw new Error("apigen-plugin-ir-cache: createIrCacheLayer() (the RUNTIME CACHE 'extractLayer' capability) received cache: 'artifact'. That value selects the ARTIFACT-mode 'target' capability instead (--type ir-cache --opt cache=artifact) — a file path is required here. See docs/apigen/design-notes/extract-stage-onion-and-ir-cache.md Revision 2 (R2.2).");const t=zN(e.cache),n=e.extractorVersion;async function r(o,s,i){const a=i??await Pu(o,n),c=await Tu(o,a);await t.put(e.cache,{formatVersion:Is,operations:s,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,s)=>{const i=await t.get(e.cache);if(!i||i.formatVersion!==Is||i.extractorVersion!==n||!i.staleness){const u=await s();return r(o,u).catch(()=>{}),u}if(await YN(o,i.staleness))return i.operations;const a=await Pu(o,n);if(a===i.staleness.contentKey)return Tu(o,a).then(u=>t.put(e.cache,{...i,staleness:u})).catch(()=>{}),i.operations;const c=await s();return r(o,c,a).catch(()=>{}),c}}Pl.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href);const ZN={"decimal.js":"Decimal"};function XN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ZN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${XN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const eO=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],tO={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let nO=class 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}};function Sa(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&eO.includes(e.code)&&typeof e.toJSON=="function"}const xs="$apigen";let Cu=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function rO(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Cu(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Cu("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Na="x-apigen-logical",Oa="x-apigen-codec",Ps="x-apigen-ctor",Ts="x-apigen-tojson",oO="0.1.0";function Ru(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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 qt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return qt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=mp(e,s,t);return qt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Ro(e,t,n);const a=t.items;if(!a)return e.map(u=>kt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?kt(u):qt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>qt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Ro(e,t,n);const a=t.properties;if(!a)return kt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=qt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Ro(e,t,n):kt(e)}function Vt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Vt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=mp(e,s,t);return Vt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Vt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Vt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Vt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?sO(e,n):e}function mp(e,t,n,r){const o=n.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 Ro(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[xs]:r,v:s}}catch{}}return kt(e)}function sO(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&xs in e){const n=e,r=n[xs],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function kt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(kt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=kt(r));return t}return null}function iO(e){return{encode(t,n,r){const o=Ru(e,r);return qt(t,n,o)},decode(t,n,r){const o=Ru(e,r);return Vt(t,n,o)}}}const ka={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},_a={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},Aa={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},ja={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},aO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ia={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!aO.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Cs="NaN",Rs="Infinity",Ms="-Infinity",cO=new Set([Cs,Rs,Ms]),xa={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Cs:e===1/0?Rs:e===-1/0?Ms:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Cs)return NaN;if(e===Rs)return 1/0;if(e===Ms)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...cO].join(", ")}.`);return NaN}},uO=[ka,_a,Aa,ja,Ia,xa];function lO(e,t={}){for(const n of uO)e.register(n,{override:t.override??!1})}const fO=12;function dO(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Mu(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function pO(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function hO(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function Du(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Rn(a,t,n+1):`<${i}>`}return s}function mO(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Rn(r,t,n+1)]:[]}function Rn(e,t=e??{},n=0){if(!e||n>fO)return null;if(typeof e.$ref=="string"){const o=dO(e.$ref,t);return o!==void 0?Rn(o,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return Du({...e,properties:o,required:s},t,n)}const r=Mu(e.oneOf)??Mu(e.anyOf);if(r)return Rn(r,t,n+1);switch(pO(e)){case"object":return Du(e,t,n);case"array":return mO(e,t,n);case"string":return hO(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function gO(e){if(!e)return;const t=Rn(e);return`Example: ${JSON.stringify(t)}`}ka.id,_a.id,Aa.id,ja.id,Ia.id,xa.id;const gp=rO();lO(gp);const yp=iO(gp.freeze());function yO(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function $O(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function vO(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function wO(e,t){return t===void 0||e===void 0?e:yp.decode(e,t)}function Mo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:yp.encode(e,n)}async function bO(e,t,n,r,o,s){const i=$O(n).map(c=>wO(s[c],vO(n,c)));if(yO(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Mo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Mo(u,n)}const a=await e[r](...i);return Mo(a,n)}let $p=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function EO(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>bO(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const SO={"decimal.js":"Decimal"};function NO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(SO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${NO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function OO(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},je(s);const i=n?je.destination({dest:e.destination,mkdir:!0,sync:!0}):je.destination(2);return je(s,i)}function vp(e){return e?e.type==="array"?`${vp(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function wp(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:vp(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function kO(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function _O(e,t){var n,r;const o=((r=(n=((t==null?void 0:t.input)??{}).properties)==null?void 0:n.data)==null?void 0:r.properties)??{},s={...e};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=kO(a==null?void 0:a.type);if(u==="number"||u==="integer"){const l=Number(c);!Number.isNaN(l)&&c.trim()!==""&&(s[i]=l)}else u==="boolean"&&(c==="true"?s[i]=!0:c==="false"&&(s[i]=!1))}return s}let AO=class 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}};const Yr=new Pr({allErrors:!0});Tr(Yr);for(const e of[Na,Oa,Ps,Ts,"discriminator"])Yr.addKeyword({keyword:e,valid:!0});Yr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function jO(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function IO(e,t){const n=gO(t),r=[`Validation failed: ${jO(e)}`];return n&&r.push(n),r.join(" — ")}function xO(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Yr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new AO("invalid_argument",IO(a,o.input),a)}return n()}}function PO(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class ht extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Do(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function bp(e,t){const n=e[Oa];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function TO(e,t,n){const r=bp(t,n);return r?r.encode(e,t,n):e}function CO(e,t,n){const r=bp(t,n);return r?r.decode(e,t,n):e}function RO(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Na]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Do(r)!==void 0},encode(r,o,s){const i=Do(o);if(!i)throw new ht("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=r[a];if(u==null)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return TO(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ht("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Do(o);if(!a)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return CO(r,h,{...s,path:`${s.path}[${f}]`})}}}const MO="x-apigen-instances";let ir=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Lu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function DO(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Uu(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function LO(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function UO(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Na]==="nominal"?!0:o[Oa]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new ir("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=Lu(s),c=typeof s[Ts]=="string"?s[Ts]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=Uu($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=Uu(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new ir("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of DO(s))if(!(l in a))throw new ir("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[MO]===!1)throw new ir("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=Lu(s),u={};for(const[l,f]of Object.entries(a))u[l]=LO(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Ps]=="string"?s[Ps]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const BO=[ka,_a,Aa,ja,Ia,xa],FO={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Bu=UO({id:"ts.NominalSentinel",schema:FO}),qO={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Fu=RO({id:"ts.UnionSentinel",schema:qO});function VO(){const e=[...BO.map(t=>[t.id,t]),[Bu.id,Bu],[Fu.id,Fu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:oO,codecs:VO()});const qu=new Set(["string","number","boolean","integer"]);function KO(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:n}=t;return typeof n=="string"?qu.has(n):Array.isArray(n)?n.every(r=>qu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function GO(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(KO)}const JO={"decimal.js":"Decimal"};function HO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(JO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${HO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Vu(e){return e.words.join("-")}function Ku(e){return e.words.map(ZO).join("")}function Gu(e){return e.words.join("_")}function zO(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||GO(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Vu(h)).join("/"),c=o.map(h=>Gu(h)).join("_"),u=o.map(h=>Gu(h)).slice(0,-1).join("."),l=Ku(o[o.length-2]??o[0]),f=Ku(o[o.length-1]),p=o.map(h=>Vu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function WO(e,t){return`x-${e}-${t}`}function YO(e,t){return`--${e}-${t}`}function QO(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function ZO(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Pa(e){return e.anyOf??e.oneOf}function XO(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Pa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function ek(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Pa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function tk(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Pa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function nk(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function rk(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Ju(e){return typeof e.handler=="function"}function ok(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=WO(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:YO(i,s),envVar:QO(i,s)})}return o}function sk(e,t){const n=new Map,{props:r}=rk(e);for(const[o,s]of Object.entries(r)){let i="string";ek(s)?i="boolean":(XO(s)||tk(s))&&(i="json"),n.set(nk(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Hu(e){const{op:t,schema:n,transport:r,projection:o}=e,s=zO(t,o),i=n?ok(n):[],a=n?sk(n,i):new Map,c=n?wp(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:Ju(t)};if(Ju(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function ik(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function ak(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function ck(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Lo(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(ck(s))}return r.push(xO(e)),EO(r)}function uk(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const lk={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function zu(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new $p};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:uk(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:lk}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const fk={"decimal.js":"Decimal"};function dk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(fk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${dk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ds(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 Wu(e){return{raw:e,words:Ds(e)}}function pk(e,t,n,r){for(const o of r??[]){const s=o.path[o.path.length-1];if(o.namespace.raw===e&&(s==null?void 0:s.raw)===t)return o}return{id:`${Ds(e).join("-")}/${Ds(t).join("-")}`,host:"ts",namespace:Wu(e),path:[Wu(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function hk(e){return`data: ${e}
|
|
199
|
+
`);for(const o of Cv(t.source))o!==t.source&&r.update(`dep:${o}:${await Yh(o)}
|
|
200
|
+
`);return r.digest("hex")}async function Xh(t,e){const n=await Yi(t.source)??0,r=[];for(const o of Cv(t.source)){if(o===t.source)continue;const s=await Yi(o);s!==void 0&&r.push({path:o,mtimeMs:s})}return{contentKey:e,source:{path:t.source,mtimeMs:n},deps:r}}async function Ax(t,e){if(e.source.path!==t.source)return!1;const n=await Yi(e.source.path);if(n===void 0||n!==e.source.mtimeMs)return!1;for(const r of e.deps){const o=await Yi(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function Ix(t){if(t.cache==="artifact")throw new Error("apigen-plugin-ir-cache: createIrCacheLayer() (the RUNTIME CACHE 'extractLayer' capability) received cache: 'artifact'. That value selects the ARTIFACT-mode 'target' capability instead (--type ir-cache --opt cache=artifact) — a file path is required here. See docs/apigen/design-notes/extract-stage-onion-and-ir-cache.md Revision 2 (R2.2).");const e=kx(t.cache),n=t.extractorVersion;async function r(o,s,i){const a=i??await Zh(o,n),c=await Xh(o,a);await e.put(t.cache,{formatVersion:bu,operations:s,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,s)=>{const i=await e.get(t.cache);if(!i||i.formatVersion!==bu||i.extractorVersion!==n||!i.staleness){const u=await s();return r(o,u).catch(()=>{}),u}if(await Ax(o,i.staleness))return i.operations;const a=await Zh(o,n);if(a===i.staleness.contentKey)return Xh(o,a).then(u=>e.put(t.cache,{...i,staleness:u})).catch(()=>{}),i.operations;const c=await s();return r(o,c,a).catch(()=>{}),c}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);function Px(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return t[r]}})}),n}const je={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},P={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},Ni="tag:yaml.org,2002:",wn={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function em(t){const e=[0];let n=t.indexOf(`
|
|
201
|
+
`);for(;n!==-1;)n+=1,e.push(n),n=t.indexOf(`
|
|
202
|
+
`,n);return e}function Mv(t){let e,n;return typeof t=="string"?(e=em(t),n=t):(Array.isArray(t)&&(t=t[0]),t&&t.context&&(t.lineStarts||(t.lineStarts=em(t.context.src)),e=t.lineStarts,n=t.context.src)),{lineStarts:e,src:n}}function Eu(t,e){if(typeof t!="number"||t<0)return null;const{lineStarts:n,src:r}=Mv(e);if(!n||!r||t>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(t<i)return{line:s,col:t-n[s-1]+1};if(t===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:t-n[o-1]+1}}function xx(t,e){const{lineStarts:n,src:r}=Mv(e);if(!n||!(t>=1)||t>n.length)return null;const o=n[t-1];let s=n[t];for(;s&&s>o&&r[s-1]===`
|
|
203
|
+
`;)--s;return r.slice(o,s)}function Rx({start:t,end:e},n,r=80){let o=xx(t.line,n);if(!o)return null;let{col:s}=t;if(o.length>r)if(s<=r-10)o=o.substr(0,r-1)+"…";else{const l=Math.round(r/2);o.length>s+l&&(o=o.substr(0,s+l-1)+"…"),s-=o.length-r,o="…"+o.substr(1-r)}let i=1,a="";e&&(e.line===t.line&&s+(e.col-t.col)<=r+1?i=e.col-t.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
|
|
204
|
+
${c}${u}${a}`}let Ee=class Lv{static copy(e){return new Lv(e.start,e.end)}constructor(e,n){this.start=e,this.end=n||e}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(e,n){const{start:r,end:o}=this;if(e.length===0||o<=e[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<e.length&&!(e[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<e.length&&!(e[s]>=o);)++s;return this.origEnd=o+s,i}},F=class Vt{static addStringTerminator(e,n,r){if(r[r.length-1]===`
|
|
205
|
+
`)return r;const o=Vt.endOfWhiteSpace(e,n);return o>=e.length||e[o]===`
|
|
206
|
+
`?r+`
|
|
207
|
+
`:r}static atDocumentBoundary(e,n,r){const o=e[n];if(!o)return!0;const s=e[n-1];if(s&&s!==`
|
|
208
|
+
`)return!1;if(r){if(o!==r)return!1}else if(o!==je.DIRECTIVES_END&&o!==je.DOCUMENT_END)return!1;const i=e[n+1],a=e[n+2];if(i!==o||a!==o)return!1;const c=e[n+3];return!c||c===`
|
|
209
|
+
`||c===" "||c===" "}static endOfIdentifier(e,n){let r=e[n];const o=r==="<",s=o?[`
|
|
210
|
+
`," "," ",">"]:[`
|
|
211
|
+
`," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=e[n+=1];return o&&r===">"&&(n+=1),n}static endOfIndent(e,n){let r=e[n];for(;r===" ";)r=e[n+=1];return n}static endOfLine(e,n){let r=e[n];for(;r&&r!==`
|
|
212
|
+
`;)r=e[n+=1];return n}static endOfWhiteSpace(e,n){let r=e[n];for(;r===" "||r===" ";)r=e[n+=1];return n}static startOfLine(e,n){let r=e[n-1];if(r===`
|
|
213
|
+
`)return n;for(;r&&r!==`
|
|
214
|
+
`;)r=e[n-=1];return n+1}static endOfBlockIndent(e,n,r){const o=Vt.endOfIndent(e,r);if(o>r+n)return o;{const s=Vt.endOfWhiteSpace(e,o),i=e[s];if(!i||i===`
|
|
215
|
+
`)return s}return null}static atBlank(e,n,r){const o=e[n];return o===`
|
|
216
|
+
`||o===" "||o===" "||r&&!o}static nextNodeIsIndented(e,n,r){return!e||n<0?!1:n>0?!0:r&&e==="-"}static normalizeOffset(e,n){const r=e[n];return r?r!==`
|
|
217
|
+
`&&e[n-1]===`
|
|
218
|
+
`?n-1:Vt.endOfWhiteSpace(e,n):n}static foldNewline(e,n,r){let o=0,s=!1,i="",a=e[n+1];for(;a===" "||a===" "||a===`
|
|
219
|
+
`;){switch(a){case`
|
|
220
|
+
`:o=0,n+=1,i+=`
|
|
221
|
+
`;break;case" ":o<=r&&(s=!0),n=Vt.endOfWhiteSpace(e,n+2)-1;break;case" ":o+=1,n+=1;break}a=e[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(e,n,r){Object.defineProperty(this,"context",{value:r||null,writable:!0}),this.error=null,this.range=null,this.valueRange=null,this.props=n||[],this.type=e,this.value=null}getPropValue(e,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[e];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,je.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const e=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,je.COMMENT,!0);r!=null&&e.push(r)}return e.length>0?e.join(`
|
|
222
|
+
`):null}commentHasRequiredWhitespace(e){const{src:n}=this.context;if(this.header&&e===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return e!==r||Vt.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]===je.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]!==je.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[P.FLOW_MAP,P.FLOW_SEQ,P.QUOTE_DOUBLE,P.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const e=Eu(this.range.start,this.context.root);if(!e)return;const n=Eu(this.range.end,this.context.root);return{start:e,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:e,end:n}=this.valueRange;return this.context.src.slice(e,n)}get tag(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,je.TAG,!1);if(n!=null){if(n[1]==="<")return{verbatim:n.slice(2,-1)};{const[r,o,s]=n.match(/^(.*!)([^!]*)$/);return{handle:o,suffix:s}}}}return null}get valueRangeContainsNewline(){if(!this.valueRange||!this.context)return!1;const{start:e,end:n}=this.valueRange,{src:r}=this.context;for(let o=e;o<n;++o)if(r[o]===`
|
|
223
|
+
`)return!0;return!1}parseComment(e){const{src:n}=this.context;if(n[e]===je.COMMENT){const r=Vt.endOfLine(n,e+1),o=new Ee(e,r);return this.props.push(o),r}return e}setOrigRanges(e,n){return this.range&&(n=this.range.setOrigRange(e,n)),this.valueRange&&this.valueRange.setOrigRange(e,n),this.props.forEach(r=>r.setOrigRange(e,n)),n}toString(){const{context:{src:e},range:n,value:r}=this;if(r!=null)return r;const o=e.slice(n.start,n.end);return Vt.addStringTerminator(e,n.end,o)}},wr=class extends Error{constructor(e,n,r){if(!r||!(n instanceof F))throw new Error(`Invalid arguments for new ${e}`);super(),this.name=e,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const e=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new Ee(this.offset,this.offset+1);const n=e&&Eu(this.offset,e);if(n){const r={line:n.line,col:n.col+1};this.linePos={start:n,end:r}}delete this.offset}else this.range=this.source.range,this.linePos=this.source.rangeAsLinePos;if(this.linePos){const{line:n,col:r}=this.linePos.start;this.message+=` at line ${n}, column ${r}`;const o=e&&Rx(this.linePos,e);o&&(this.message+=`:
|
|
171
224
|
|
|
172
|
-
|
|
173
|
-
|
|
225
|
+
${o}
|
|
226
|
+
`)}delete this.source}};class fs extends wr{constructor(e,n){super("YAMLReferenceError",e,n)}}let ee=class extends wr{constructor(e,n){super("YAMLSemanticError",e,n)}},qe=class extends wr{constructor(e,n){super("YAMLSyntaxError",e,n)}},po=class extends wr{constructor(e,n){super("YAMLWarning",e,n)}};function We(t,e,n){return(e=Cx(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Tx(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Cx(t){var e=Tx(t,"string");return typeof e=="symbol"?e:e+""}let Dv=class Su extends F{static endOfLine(e,n,r){let o=e[n],s=n;for(;o&&o!==`
|
|
227
|
+
`&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=e[s+1];if(o===":"&&(!i||i===`
|
|
228
|
+
`||i===" "||i===" "||r&&i===",")||(o===" "||o===" ")&&i==="#")break;s+=1,o=i}return s}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;e<n&&(o===`
|
|
229
|
+
`||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=e;a<n;++a){const c=r[a];if(c===`
|
|
230
|
+
`){const{fold:u,offset:l}=F.foldNewline(r,a,-1);s+=u,a=l}else if(c===" "||c===" "){const u=a;let l=r[a+1];for(;a<n&&(l===" "||l===" ");)a+=1,l=r[a+1];l!==`
|
|
231
|
+
`&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[e];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new ee(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new ee(this,a)],str:s}}default:return s}}parseBlockValue(e){const{indent:n,inFlow:r,src:o}=this.context;let s=e,i=e;for(let a=o[s];a===`
|
|
232
|
+
`&&!F.atDocumentBoundary(o,s+1);a=o[s]){const c=F.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
|
|
233
|
+
`?s=c:(i=Su.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=e),this.valueRange.end=i,i}parse(e,n){this.context=e;const{inFlow:r,src:o}=e;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
|
|
234
|
+
`&&(s=Su.endOfLine(o,n,r)),this.valueRange=new Ee(n,s),s=F.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}};class ps extends F{constructor(){super(P.BLANK_LINE)}get includesTrailingLines(){return!0}parse(e,n){return this.context=e,this.range=new Ee(n,n+1),n+1}}let Md=class extends F{constructor(e,n){super(e,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{atLineStart:s,lineStart:i}=e;!s&&this.type===P.SEQ_ITEM&&(this.error=new ee(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:e.indent;let c=F.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",d=[];let f=null;for(;u===`
|
|
235
|
+
`||u==="#";){if(u==="#"){const p=F.endOfLine(o,c+1);d.push(new Ee(c,p)),c=p}else{s=!0,i=c+1;const p=F.endOfWhiteSpace(o,i);o[p]===`
|
|
236
|
+
`&&d.length===0&&(f=new ps,i=f.parse({src:o},i)),c=F.endOfIndent(o,i)}u=o[c]}if(F.nextNodeIsIndented(u,c-(i+a),this.type!==P.SEQ_ITEM)?this.node=r({atLineStart:s,inCollection:!1,indent:a,lineStart:i,parent:this},c):u&&i>n+1&&(c=i-1),this.node){if(f){const p=e.parent.items||e.parent.contents;p&&p.push(f)}d.length&&Array.prototype.push.apply(this.props,d),c=this.node.range.end}else if(l){const p=d[0];this.props.push(p),c=p.end}else c=F.endOfLine(o,n+1);const g=this.node?this.node.valueRange.end:c;return this.valueRange=new Ee(n,g),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.node?this.node.setOrigRanges(e,n):n}toString(){const{context:{src:e},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?e.slice(r.start,n.range.start)+String(n):e.slice(r.start,r.end);return F.addStringTerminator(e,r.end,s)}},Wo=class extends F{constructor(){super(P.COMMENT)}parse(e,n){this.context=e;const r=this.parseComment(n);return this.range=new Ee(n,r),r}};function _u(t){let e=t;for(;e instanceof Md;)e=e.node;if(!(e instanceof Uv))return null;const n=e.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=e.items[i];if(a.type===P.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===P.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=e.items.splice(r,n-r),s=o[0].range.start;for(;e.range.end=s,e.valueRange&&e.valueRange.end>s&&(e.valueRange.end=s),e!==t;)e=e.context.parent;return o}let Uv=class Nu extends F{static nextContentHasIndent(e,n,r){const o=F.endOfLine(e,n)+1;n=F.endOfWhiteSpace(e,o);const s=e[n];return s?n>=o+r?!0:s!=="#"&&s!==`
|
|
237
|
+
`?!1:Nu.nextContentHasIndent(e,n,r):!1}constructor(e){super(e.type===P.SEQ_ITEM?P.SEQ:P.MAP);for(let r=e.props.length-1;r>=0;--r)if(e.props[r].start<e.context.lineStart){this.props=e.props.slice(0,r+1),e.props=e.props.slice(r+1);const o=e.props[0]||e.valueRange;e.range.start=o.start;break}this.items=[e];const n=_u(e);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let s=F.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=Ee.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=F.normalizeOffset(o,c);let u=o[c],l=F.endOfWhiteSpace(o,s)===c,d=!1;for(;u;){for(;u===`
|
|
238
|
+
`||u==="#";){if(l&&u===`
|
|
239
|
+
`&&!d){const p=new ps;if(c=p.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(p),c-=1}else if(u==="#"){if(c<s+a&&!Nu.nextContentHasIndent(o,c,a))return c;const p=new Wo;if(c=p.parse({indent:a,lineStart:s,src:o},c),this.items.push(p),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=F.endOfIndent(o,s),F.atBlank(o,c)){const p=F.endOfWhiteSpace(o,c),y=o[p];(!y||y===`
|
|
240
|
+
`||y==="#")&&(c=p)}u=o[c],l=!0}if(!u)break;if(c!==s+a&&(l||u!==":")){if(c<s+a){s>n&&(c=s);break}else if(!this.error){const p="All collection items must start at the same column";this.error=new qe(this,p)}}if(i.type===P.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const p=o[c+1];if(!p||p===`
|
|
241
|
+
`||p===" "||p===" "){const y="A collection cannot be both a mapping and a sequence";this.error=new qe(this,y)}}const f=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!f)return c;if(this.items.push(f),this.valueRange.end=f.valueRange.end,c=F.normalizeOffset(o,f.range.end),u=o[c],l=!1,d=f.includesTrailingLines,u){let p=c-1,y=o[p];for(;y===" "||y===" ";)y=o[--p];y===`
|
|
242
|
+
`&&(s=p+1,l=!0)}const g=_u(f);g&&Array.prototype.push.apply(this.items,g)}return c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{n=r.setOrigRanges(e,n)}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;let s=e.slice(r.start,n[0].range.start)+String(n[0]);for(let i=1;i<n.length;++i){const a=n[i],{atLineStart:c,indent:u}=a.context;if(c)for(let l=0;l<u;++l)s+=" ";s+=String(a)}return F.addStringTerminator(e,r.end,s)}};class Mx extends F{constructor(){super(P.DIRECTIVE),this.name=null}get parameters(){const e=this.rawValue;return e?e.trim().split(/[ \t]+/):[]}parseName(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
|
|
243
|
+
`&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(e,r),r}parseParameters(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
|
|
244
|
+
`&&o!=="#";)o=n[r+=1];return this.valueRange=new Ee(e,r),r}parse(e,n){this.context=e;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new Ee(n,r),r}}let Lx=class Ou extends F{static startCommentOrEndBlankLine(e,n){const r=F.endOfWhiteSpace(e,n),o=e[r];return o==="#"||o===`
|
|
245
|
+
`?r:n}constructor(){super(P.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(e){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=e;for(;!F.atDocumentBoundary(n,s,je.DIRECTIVES_END);)switch(s=Ou.startCommentOrEndBlankLine(n,s),n[s]){case`
|
|
246
|
+
`:if(r){const i=new ps;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new Wo;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new Mx;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new ee(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new Ee(s,s+3),s+3):(o?this.error=new ee(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(e){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=e;for(;r[o-1]==="-";)o-=1;let s=F.endOfWhiteSpace(r,e),i=o===e;for(this.valueRange=new Ee(s);!F.atDocumentBoundary(r,s,je.DOCUMENT_END);){switch(r[s]){case`
|
|
247
|
+
`:if(i){const a=new ps;s=a.parse({src:r},s),s<r.length&&this.contents.push(a)}else s+=1,i=!0;o=s;break;case"#":{const a=new Wo;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=F.endOfIndent(r,s),c=n({atLineStart:i,indent:-1,inFlow:!1,inCollection:!1,lineStart:o,parent:this},a);if(!c)return this.valueRange.end=a;this.contents.push(c),s=c.range.end,i=!1;const u=_u(c);u&&Array.prototype.push.apply(this.contents,u)}}s=Ou.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new Ee(s,s+3),s+=3,r[s])){if(s=F.endOfWhiteSpace(r,s),r[s]==="#"){const a=new Wo;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
|
|
248
|
+
`:s+=1;break;case void 0:break;default:this.error=new qe(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(e,n){e.root=this,this.context=e;const{src:r}=e;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.directives.forEach(r=>{n=r.setOrigRanges(e,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(e,n)),this.contents.forEach(r=>{n=r.setOrigRanges(e,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(e,n)),n}toString(){const{contents:e,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return e.length>0&&((n.length>0||e[0].type===P.COMMENT)&&(o+=`---
|
|
249
|
+
`),o+=e.join("")),o[o.length-1]!==`
|
|
250
|
+
`&&(o+=`
|
|
251
|
+
`),o}},Dx=class extends F{parse(t,e){this.context=t;const{src:n}=t;let r=F.endOfIdentifier(n,e+1);return this.valueRange=new Ee(e+1,r),r=F.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const ln={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class Ux extends F{constructor(e,n){super(e,n),this.blockIndent=null,this.chomping=ln.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===ln.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{indent:r,src:o}=this.context;if(this.valueRange.isEmpty())return"";let s=null,i=o[n-1];for(;i===`
|
|
252
|
+
`||i===" "||i===" ";){if(n-=1,n<=e){if(this.chomping===ln.KEEP)break;return""}i===`
|
|
253
|
+
`&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===ln.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===P.BLOCK_FOLDED;let l=!0,d="",f="",g=!1;for(let p=e;p<n;++p){for(let w=0;w<c&&o[p]===" ";++w)p+=1;const y=o[p];if(y===`
|
|
254
|
+
`)f===`
|
|
255
|
+
`?d+=`
|
|
256
|
+
`:f=`
|
|
257
|
+
`;else{const w=F.endOfLine(o,p),h=o.slice(p,w);p=w,u&&(y===" "||y===" ")&&p<a?(f===" "?f=`
|
|
258
|
+
`:!g&&!l&&f===`
|
|
259
|
+
`&&(f=`
|
|
174
260
|
|
|
175
|
-
`}async function gk(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let s=!1;try{for await(const i of e){if(r.signal.aborted)break;s||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),s=!0),o.write(hk(JSON.stringify(i)))}s||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(i){const a=Sa(i)?i:new nO("internal",i instanceof Error?i.message:String(i));if(s)o.write(mk(JSON.stringify(a.toJSON()))),o.end();else{const c=$k(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const yk={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function $k(e){return yk[e]??500}function Ep(e){return Sa(e)?tO[e.code]??500:500}function Sp(e){return Sa(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function vk(e,t){if(e)for(const n of t){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),e.info(n,o)}}let wk=class{constructor(t,n,r){this.app=t,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}routeFor(t){return t.isMount?`${this.routePrefix}/${t.op.id}`:this.routePrefix+t.http.route}registerRoute(t,n){const r=this.routeFor(t),o=async(s,i)=>{const a={req:s,reply:i};try{const c=await this.readCall(a,t),u=await n(c);await this.writeResult(a,u,t)}catch(c){await this.writeError(a,c,t)}};t.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(t,n){const{req:r}=t,o=r.headers,s={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(s[a.field]=c)}let i={};if(n.isMount)i=n.http.verb==="GET"?r.query??{}:r.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};i=a?_O(c,a):c}else{const{data:c={}}=r.body??{};i=c}}return{envelope:s,domainArgs:i,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:s}=t;if(PO(n)){await gk(n,o,s);return}s.type("application/json"),s.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(Ep(n)).send(Sp(n))}};function bk(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("http")||i.push(f)}return i}async function Ek(e){var t,n;const r=e.options.port??3e3,o=e.options.host??"127.0.0.1",s=e.options.routePrefix??"",i=e.options.projection??{},a=ik(e.options),c=ak(e.options),u=e.logger??OO(),l=ym({logger:u});l.setErrorHandler((E,b,N)=>{N.status(Ep(E)).send(Sp(E))});const f=new wk(l,s,e.signal),p=[],h={},d={};for(const E of e.packages){if(!E.fns)throw new Error(`Package "${E.id}" is missing fns`);const b=E.fns,N=Object.entries(E.schemas).map(([q,Q])=>({fnName:q,fnSchema:Q,op:pk(E.id,q,Q,e.operations)})),j={},R={};for(const{fnName:q,fnSchema:Q,op:Z}of N)j[Z.id]=Q,R[Z.id]=b[q],h[Z.id]=Q,d[Z.id]=b[q];const J=Lo(j,a),U={fns:R,createClient:E.createClient,schemas:j};for(const{fnSchema:q,op:Q}of N){const Z=Hu({op:Q,schema:q,transport:"http",projection:i});f.bindSchema(Q.id,q),f.registerRoute(Z,Ve=>zu(Z,J,Ve,U));const{params:ye,text:_e}=wp(q);p.push({method:Z.http.verb,route:s+Z.http.route,text:_e,params:ye})}}const m=((t=e.packages[0])==null?void 0:t.id)??"ts",y=Lo(h,a),$={invoke:(E,b,N)=>y(E,{operation:{id:E},ctx:new $p,domainArgs:b.domainArgs,envelope:b.envelope,signal:b.signal},N),invokeOptions:{fns:d,schemas:h,createClient:(n=e.packages[0])==null?void 0:n.createClient}},v=bk(a,c,m,e.operations??[],$);if(v.length>0){const E=Lo({},a),b={fns:{},schemas:{}};for(const N of v){const j=Hu({op:N,transport:"http",projection:i});f.registerRoute(j,R=>zu(j,E,R,b)),p.push({method:j.http.verb,route:`${s}/${N.id}`,text:"",params:[]})}}return await l.listen({port:r,host:o}),u.info({host:o,port:r},`listening on http://${o}:${r}`),vk(u,p),new Promise(E=>{e.signal&&e.signal.addEventListener("abort",async()=>{await l.close(),E()})})}const Sk={id:"api-fastify",run(e){return Ek(e)}};function Yu(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Nk(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Yu(i),path:s.map(Yu),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}const Ok={"decimal.js":"Decimal"};function kk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ok).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${kk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const Qu=new Set(["string","number","boolean","integer"]);function _k(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:n}=t;return typeof n=="string"?Qu.has(n):Array.isArray(n)?n.every(r=>Qu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Ak(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(_k)}const jk={"decimal.js":"Decimal"};function Ik(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(jk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ik(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Zu(e){return e.words.join("-")}function Xu(e){return e.words.map(Pk).join("")}function el(e){return e.words.join("_")}function xk(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Ak(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Zu(h)).join("/"),c=o.map(h=>el(h)).join("_"),u=o.map(h=>el(h)).slice(0,-1).join("."),l=Xu(o[o.length-2]??o[0]),f=Xu(o[o.length-1]),p=o.map(h=>Zu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Pk(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Tk(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const s of e){const i=xk(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:Ck(s.output)}};if(a==="GET")l.parameters=Rk(s.input);else{const f=s.input;typeof f=="object"&&f!==null&&Object.keys(f).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:f}}})}o[c]===void 0&&(o[c]={}),o[c][u]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function Ck(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function Rk(e){if(typeof e!="object"||e===null||typeof e.properties!="object"||e.properties===null)return[];const t=Array.isArray(e.required)?e.required:[],n=e.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:t.includes(r),schema:o}))}function Mk(e,t={}){return[{...Nk("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>Tk(e.operations,{title:t.title,version:t.version})}]}const Dk={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 Mk(e,t)}}}},Ls="$apigen";class tl extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Lk(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new tl(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new tl("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Ta="x-apigen-logical",Ca="x-apigen-codec",Us="x-apigen-ctor",Bs="x-apigen-tojson",Uk="0.1.0";function nl(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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 Kt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Kt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Np(e,s,t);return Kt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Uo(e,t,n);const a=t.items;if(!a)return e.map(u=>_t(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?_t(u):Kt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Kt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Uo(e,t,n);const a=t.properties;if(!a)return _t(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Kt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Uo(e,t,n):_t(e)}function Gt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Gt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Np(e,s,t);return Gt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Gt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Gt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Gt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Bk(e,n):e}function Np(e,t,n,r){const o=n.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 Uo(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Ls]:r,v:s}}catch{}}return _t(e)}function Bk(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Ls in e){const n=e,r=n[Ls],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function _t(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(_t);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=_t(r));return t}return null}function Fk(e){return{encode(t,n,r){const o=nl(e,r);return Kt(t,n,o)},decode(t,n,r){const o=nl(e,r);return Gt(t,n,o)}}}const Ra={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},Ma={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},Da={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},La={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},qk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ua={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!qk.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Fs="NaN",qs="Infinity",Vs="-Infinity",Vk=new Set([Fs,qs,Vs]),Ba={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Fs:e===1/0?qs:e===-1/0?Vs:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Fs)return NaN;if(e===qs)return 1/0;if(e===Vs)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Vk].join(", ")}.`);return NaN}},Kk=[Ra,Ma,Da,La,Ua,Ba];function Gk(e,t={}){for(const n of Kk)e.register(n,{override:t.override??!1})}const Jk=12;function Hk(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function rl(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function zk(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function Wk(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function ol(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Mn(a,t,n+1):`<${i}>`}return s}function Yk(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Mn(r,t,n+1)]:[]}function Mn(e,t=e??{},n=0){if(!e||n>Jk)return null;if(typeof e.$ref=="string"){const o=Hk(e.$ref,t);return o!==void 0?Mn(o,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return ol({...e,properties:o,required:s},t,n)}const r=rl(e.oneOf)??rl(e.anyOf);if(r)return Mn(r,t,n+1);switch(zk(e)){case"object":return ol(e,t,n);case"array":return Yk(e,t,n);case"string":return Wk(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function Op(e){if(!e)return;const t=Mn(e);return`Example: ${JSON.stringify(t)}`}Ra.id,Ma.id,Da.id,La.id,Ua.id,Ba.id;const kp=Lk();Gk(kp);const _p=Fk(kp.freeze());function Qk(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Zk(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Xk(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function e_(e,t){return t===void 0||e===void 0?e:_p.decode(e,t)}function Bo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:_p.encode(e,n)}async function t_(e,t,n,r,o,s){const i=Zk(n).map(c=>e_(s[c],Xk(n,c)));if(Qk(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Bo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Bo(u,n)}const a=await e[r](...i);return Bo(a,n)}let Ap=class{constructor(){this._map=new Map}set(e,t){this._map.set(e,t)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function n_(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>t_(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const r_={"decimal.js":"Decimal"};function o_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(r_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${o_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function s_(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},je(s);const i=n?je.destination({dest:e.destination,mkdir:!0,sync:!0}):je.destination(2);return je(s,i)}function jp(e){return e?e.type==="array"?`${jp(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function i_(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:jp(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const a_=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class Ip 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}}function c_(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&a_.includes(e.code)&&typeof e.toJSON=="function"}function sl(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Qr=new Pr({allErrors:!0});Tr(Qr);for(const e of[Ta,Ca,Us,Bs,"discriminator"])Qr.addKeyword({keyword:e,valid:!0});Qr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function u_(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function l_(e,t){const n=Op(t),r=[`Validation failed: ${u_(e)}`];return n&&r.push(n),r.join(" — ")}function f_(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Qr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Ip("invalid_argument",l_(a,o.input),a)}return n()}}async function d_(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=c_(n)?n:new Ip("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:sl("before-first-chunk",r)}:{ok:!1,carrier:sl("after-first-chunk",r,t.length)}}}function p_(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class mt extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Fo(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function xp(e,t){const n=e[Ca];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function h_(e,t,n){const r=xp(t,n);return r?r.encode(e,t,n):e}function m_(e,t,n){const r=xp(t,n);return r?r.decode(e,t,n):e}function g_(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Ta]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Fo(r)!==void 0},encode(r,o,s){const i=Fo(o);if(!i)throw new mt("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=r[a];if(u==null)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new mt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return h_(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new mt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Fo(o);if(!a)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new mt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return m_(r,h,{...s,path:`${s.path}[${f}]`})}}}const y_="x-apigen-instances";class ar extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function il(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function $_(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function al(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function v_(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function w_(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Ta]==="nominal"?!0:o[Ca]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new ar("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=il(s),c=typeof s[Bs]=="string"?s[Bs]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=al($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=al(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new ar("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of $_(s))if(!(l in a))throw new ar("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[y_]===!1)throw new ar("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=il(s),u={};for(const[l,f]of Object.entries(a))u[l]=v_(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Us]=="string"?s[Us]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const b_=[Ra,Ma,Da,La,Ua,Ba],E_={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},cl=w_({id:"ts.NominalSentinel",schema:E_}),S_={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ul=g_({id:"ts.UnionSentinel",schema:S_});function N_(){const e=[...b_.map(t=>[t.id,t]),[cl.id,cl],[ul.id,ul]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Uk,codecs:N_()});function ll(e,t,n){var r;const o=typeof((r=t==null?void 0:t.input)==null?void 0:r.description)=="string"?t.input.description:void 0,s=Op(t==null?void 0:t.input),i=[n,o,s].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function Pp(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 O_(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const fl=new Set(["string","number","boolean","integer"]);function k_(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:n}=t;return typeof n=="string"?fl.has(n):Array.isArray(n)?n.every(r=>fl.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function __(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(k_)}const A_={"decimal.js":"Decimal"};function j_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(A_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${j_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function dl(e){return e.words.join("-")}function pl(e){return e.words.map(C_).join("")}function hl(e){return e.words.join("_")}function I_(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||__(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>dl(h)).join("/"),c=o.map(h=>hl(h)).join("_"),u=o.map(h=>hl(h)).slice(0,-1).join("."),l=pl(o[o.length-2]??o[0]),f=pl(o[o.length-1]),p=o.map(h=>dl(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function x_(e,t){return`x-${e}-${t}`}function P_(e,t){return`--${e}-${t}`}function T_(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function C_(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Fa(e){return e.anyOf??e.oneOf}function R_(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Fa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function M_(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Fa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function D_(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Fa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function L_(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function U_(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function ml(e){return typeof e.handler=="function"}function B_(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=x_(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:P_(i,s),envVar:T_(i,s)})}return o}function F_(e,t){const n=new Map,{props:r}=U_(e);for(const[o,s]of Object.entries(r)){let i="string";M_(s)?i="boolean":(R_(s)||D_(s))&&(i="json"),n.set(L_(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function gl(e){const{op:t,schema:n,transport:r,projection:o}=e,s=I_(t,o),i=n?B_(n):[],a=n?F_(n,i):new Map,c=n?i_(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:ml(t)};if(ml(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function q_(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function V_(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function K_(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function qo(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(K_(s))}return r.push(f_(e)),n_(r)}function G_(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const J_={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function yl(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Ap};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:G_(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:J_}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const H_={"decimal.js":"Decimal"};function z_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(H_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${z_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function W_(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)}const Y_={"decimal.js":"Decimal"};function Q_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Y_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Q_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Z_(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Ks(e){return{raw:e,words:W_(e)}}function X_(e){return Ks(Z_(Go.basename(e)))}function eA(e,t,n){if(n){const o=n.find(s=>{var i;return s.kind==="action"&&s.namespace.raw===e.id&&((i=s.path[s.path.length-1])==null?void 0:i.raw)===t});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${e.id}" fn "${t}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const r=Ks(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Ks(e.id),path:e.dropFileSegment?[r]:[X_(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}const tA=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function nA(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&tA.includes(e.code)&&typeof e.toJSON=="function"}async function rA(e){const t=await d_(e);if(t.ok){const o=t.chunks.map(s=>({type:"text",text:JSON.stringify(s)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=t;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}class oA{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}bindToolMeta(t,n){this.toolMeta.set(t,n)}registerRoute(t,n){this.plans.set(t.mcp.name,t),this.dispatchers.set(t.mcp.name,n)}getPlan(t){return this.plans.get(t)}getDispatch(t){return this.dispatchers.get(t)}listTools(){return[...this.plans.keys()].map(t=>{const n=this.toolMeta.get(t);return{name:t,description:(n==null?void 0:n.description)??t,inputSchema:(n==null?void 0:n.inputSchema)??{type:"object",properties:{}},...n!=null&&n.outputSchema?{outputSchema:n.outputSchema}:{}}})}readCall(t,n){const r={};for(const s of n.envelope){const i=t.meta[s.mcpMetaKey];i!==void 0&&(r[s.field]=i)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(p_(n)){t.output=await rA(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=Pp(o==null?void 0:o.output),i=O_(s,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(t,n,r){throw nA(n)&&n.code,n}}function sA(e){if(e&&typeof e=="object"&&e.type==="object")return e;const t=e==null?void 0:e.oneOf;if(Array.isArray(t)&&t.length>0){const n={};let r=null;for(const o of t){if(!o||typeof o!="object")continue;const s=o,i=s.properties;if(i&&typeof i=="object")for(const[c,u]of Object.entries(i))c in n||(n[c]=u);const a=Array.isArray(s.required)?s.required:[];r=r===null?[...a]:r.filter(c=>a.includes(c))}return{...e,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function iA(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("mcp")||i.push(f)}return i}function aA(e,t){var n,r;const o=e.options.projection??{},s=e.options.toolDescriptions??{},i=q_(e.options),a=V_(e.options),c={},u={};for(const d of e.packages){if(!d.fns)throw new Error(`Package "${d.id}" is missing fns`);const m=d.fns,y=Object.entries(d.schemas).map(([N,j])=>({fnName:N,fnSchema:j,op:eA({id:d.id,importPath:d.importPath},N,e.operations)})),$={},v={};for(const{fnName:N,fnSchema:j,op:R}of y)$[R.id]=j,v[R.id]=m[N],c[R.id]=j,u[R.id]=m[N];const E=qo($,i),b={fns:v,createClient:d.createClient,schemas:$};for(const{fnName:N,fnSchema:j,op:R}of y){const J=gl({op:R,schema:j,transport:"mcp",projection:o});t.bindSchema(R.id,j);const{outputSchema:U}=Pp(j.output),q=ll(J.mcp.name,j,s[J.mcp.name]??s[N]);t.bindToolMeta(J.mcp.name,{description:q,inputSchema:j.input,outputSchema:U}),t.registerRoute(J,Q=>yl(J,E,Q,b))}}const l=((n=e.packages[0])==null?void 0:n.id)??"ts",f=qo(c,i),p={invoke:(d,m,y)=>f(d,{operation:{id:d},ctx:new Ap,domainArgs:m.domainArgs,envelope:m.envelope,signal:m.signal},y),invokeOptions:{fns:u,schemas:c,createClient:(r=e.packages[0])==null?void 0:r.createClient}},h=iA(i,a,l,e.operations??[],p);if(h.length>0){const d=qo({},i),m={fns:{},schemas:{}};for(const y of h){const $=gl({op:y,transport:"mcp",projection:o}),v=sA(y.input),E=ll($.mcp.name,{input:v},s[$.mcp.name]);t.bindToolMeta($.mcp.name,{description:E,inputSchema:v}),t.registerRoute($,b=>yl($,d,b,m))}}}function Vo(e,t){const n=new $m.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(rc.ListToolsRequestSchema,async()=>({tools:e.listTools()})),n.setRequestHandler(rc.CallToolRequestSchema,async r=>{const{name:o,arguments:s={}}=r.params,i=e.getPlan(o),a=e.getDispatch(o);if(!i||!a)throw new Error(`Unknown tool: ${o}`);const c=s,u=c._meta??{},l={args:c,meta:u},f=Date.now();try{const p=await e.readCall(l,i),h=await a(p);return await e.writeResult(l,h,i),t.info({tool:o,ms:Date.now()-f},`→ ${o}`),l.output}catch(p){throw t.error({tool:o,ms:Date.now()-f,err:p},`✗ ${o}`),e.writeError(l,p,i),p}}),n}function $l(e,t){return async(n,r)=>{try{await t(n,r)}catch(o){e.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}async function cA(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??s_();o.info(`mcp server starting (${t})`);const s=new oA;aA(e,s);const i=s.listTools().map(c=>c.name);o.info({tools:i},`${i.length} tools available`);for(const c of i){const u=s.getPlan(c),l=(u==null?void 0:u.params)??[],f=l.map(p=>`${p.name}${p.required?"":"?"}: ${p.type}`).join(", ");o.info({tool:c,args:{data:l}},`tool: ${c} args { data: {${f?` ${f} `:""}} }`)}if(t==="stdio"){const c=Vo(s,o),u=new vm.StdioServerTransport;return await c.connect(u),o.info("stdio transport ready"),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),l()})})}if(t==="sse"){const c=new Map,u=nc.createServer($l(o,async(l,f)=>{const p=l.url??"";if(l.method==="GET"&&p==="/sse"){const h=Vo(s,o),d=new wm.SSEServerTransport("/messages",f);c.set(d.sessionId,d),d.onclose=()=>c.delete(d.sessionId),await h.connect(d)}else if(l.method==="POST"&&p.startsWith("/messages")){const h=new URLSearchParams(p.split("?")[1]??"").get("sessionId"),d=h?c.get(h):void 0;if(!d){f.writeHead(404),f.end("Session not found");return}await d.handlePostMessage(l,f)}else f.writeHead(404),f.end("Not found")}));return u.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),u.close(()=>l())})})}const a=nc.createServer($l(o,async(c,u)=>{const l=Vo(s,o),f=new bm.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await l.connect(f),await f.handleRequest(c,u)}));return a.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(c=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),a.close(()=>c())})})}const uA={id:"mcp",run(e){return cA(e)}},Tp=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED"]),Cp=new Set(["MITIGATED"]),Rp=new Set(["SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]),qa=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Be(e){return qa.has(e)}function Ir(e){return Tp.has(e)||Cp.has(e)}function xr(e){return Rp.has(e)}class Mp extends Error{constructor(t,n,r=[]){const o=r.length>0?` - did you mean repo ${r.map(s=>`'${s}'`).join(" or ")}?`:"";super(`backlog item not found: ${t}::${n}${o}`),this.foundInRepos=r,this.name="BacklogItemNotFoundError"}}class Dp extends Error{constructor(t){super(`transition to terminal status "${t}" requires at least one citation (either already attached via addCitation or passed inline to transitionStatus/resolveItem) — per the global CLAUDE.md rule "No citation, no claim."`),this.name="CitationRequiredError"}}class Lp extends Error{constructor(t){super(`transition to terminal-dismissed status "${t}" requires a reason string`),this.name="ReasonRequiredError"}}class Up extends Error{constructor(t,n){super(`item is claimed by "${t}" since ${n} (not stale) — cannot start work`),this.heldBy=t,this.heldSince=n,this.name="ClaimHeldError"}}class lA extends Error{constructor(t){super(`dependency cycle detected: ${t.join(" -> ")}`),this.cycle=t,this.name="DependencyCycleError"}}class ae extends Error{constructor(t,n){super(n),this.argument=t,this.name="InvalidArgumentError"}}class Va extends Error{constructor(t,n,r){super(`backlog: ambiguous lookup — ${r.length} live items share the same (repo, humanId) key "${t}"::"${n}" (nodeIds: ${r.join(", ")}). Refusing to silently pick one — this is a data-integrity defect (see BUG-BACKLOG-HUMANID-COLLISION-001); repair the collision (e.g. rename one of these nodeIds to a distinct humanId) before retrying this operation.`),this.nodeIds=r,this.name="AmbiguousHumanIdError"}}function fA(e,t){const n=t??T.join(Ue.homedir(),`.${e.orgNamespace}`);return T.join(n,e.project,e.namespace,"config.yaml")}function dA(e,t,n){const r=fA(e,n);let o={};if(C.existsSync(r))try{const a=oc.parse(C.readFileSync(r,"utf8"));a!==null&&typeof a=="object"&&!Array.isArray(a)&&(o=a)}catch{o={}}const s=o.migration&&typeof o.migration=="object"&&!Array.isArray(o.migration)?o.migration:{},i={...o,migration:{...s,phase:t}};return C.mkdirSync(T.dirname(r),{recursive:!0}),C.writeFileSync(r,oc.stringify(i),"utf8"),r}const ge="backlog-item",vl="backlog-plan",wl="backlog-assignee",pA="adhd-backlog:";function Bp(e){return Un.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Ka(e){return e.replace(/[^\p{L}\p{N}_\s]/gu," ").trim().replace(/\s+/g," ")}function nn(e){return e.split("-")[0]??e}function ct(e){return e.replace(/-\d+$/,"")}function Zr(e,t,n,r){return`${n}
|
|
261
|
+
`),d+=f+h,f=w<n&&o[w]||"",g=!0):(d+=f+h,f=u&&p<a?" ":`
|
|
262
|
+
`,g=!1),l&&h!==""&&(l=!1)}}return this.chomping===ln.STRIP?d:d+`
|
|
263
|
+
`}parseBlockHeader(e){const{src:n}=this.context;let r=e+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=ln.STRIP;break;case"+":this.chomping=ln.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o+=s;break;default:return this.blockIndent=Number(o)||null,this.header=new Ee(e,r),r}r+=1}}parseBlockValue(e){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=e,i=e,a=1;for(let c=r[s];c===`
|
|
264
|
+
`&&(s+=1,!F.atDocumentBoundary(r,s));c=r[s]){const u=F.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],d=u-(s+n);if(this.blockIndent){if(l&&l!==`
|
|
265
|
+
`&&d<this.blockIndent){if(r[u]==="#")break;if(!this.error){const f=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new ee(this,f)}}}else if(r[u]!==`
|
|
266
|
+
`){if(d<a){const f="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new ee(this,f)}this.blockIndent=d}else d>a&&(a=d);r[u]===`
|
|
267
|
+
`?s=u:s=i=F.endOfLine(r,u)}return this.chomping!==ln.KEEP&&(s=r[i]?i+1:i),this.valueRange=new Ee(e+1,s),s}parse(e,n){this.context=e;const{src:r}=e;let o=this.parseBlockHeader(n);return o=F.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.header?this.header.setOrigRange(e,n):n}}class Bx extends F{constructor(e,n){super(e,n),this.items=null}prevNodeIsJsonLike(e=this.items.length){const n=this.items[e-1];return!!n&&(n.jsonLike||n.type===P.COMMENT&&this.prevNodeIsJsonLike(e-1))}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{indent:s,lineStart:i}=e,a=o[n];this.items=[{char:a,offset:n}];let c=F.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
|
|
268
|
+
`:{i=c+1;const u=F.endOfWhiteSpace(o,i);if(o[u]===`
|
|
269
|
+
`){const l=new ps;i=l.parse({src:o},i),this.items.push(l)}if(c=F.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new ee(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new Wo;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
|
|
270
|
+
`||u===" "||u===" "||u===","||a===":"&&this.prevNodeIsJsonLike()){this.items.push({char:a,offset:c}),c+=1;break}}default:{const u=r({atLineStart:!1,inCollection:!1,inFlow:!0,indent:-1,lineStart:i,parent:this},c);if(!u)return this.valueRange=new Ee(n,c),c;this.items.push(u),c=F.normalizeOffset(o,u.range.end)}}c=F.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new Ee(n,c+1),a&&(this.items.push({char:a,offset:c}),c=F.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{if(r instanceof F)n=r.setOrigRanges(e,n);else if(e.length===0)r.origOffset=r.offset;else{let o=n;for(;o<e.length&&!(e[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof F);let i="",a=r.start;return s.forEach(c=>{const u=e.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
|
|
271
|
+
`&&e[a-1]!==`
|
|
272
|
+
`&&e[a]===`
|
|
273
|
+
`&&(a+=1)}),i+=e.slice(a,r.end),F.addStringTerminator(e,r.end,i)}}let Fx=class Bv extends F{static endOfQuote(e,n){let r=e[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=e[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&e.push(new qe(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
|
|
274
|
+
`){F.atDocumentBoundary(s,a+1)&&e.push(new ee(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=F.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new ee(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(c==="\\")switch(a+=1,s[a]){case"0":i+="\0";break;case"a":i+="\x07";break;case"b":i+="\b";break;case"e":i+="\x1B";break;case"f":i+="\f";break;case"n":i+=`
|
|
275
|
+
`;break;case"r":i+="\r";break;case"t":i+=" ";break;case"v":i+="\v";break;case"N":i+="
";break;case"_":i+=" ";break;case"L":i+="\u2028";break;case"P":i+="\u2029";break;case" ":i+=" ";break;case'"':i+='"';break;case"/":i+="/";break;case"\\":i+="\\";break;case" ":i+=" ";break;case"x":i+=this.parseCharCode(a+1,2,e),a+=2;break;case"u":i+=this.parseCharCode(a+1,4,e),a+=4;break;case"U":i+=this.parseCharCode(a+1,8,e),a+=8;break;case`
|
|
276
|
+
`:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:e.push(new qe(this,`Invalid escape sequence ${s.substr(a-1,2)}`)),i+="\\"+s[a]}else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
|
|
277
|
+
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parseCharCode(e,n,r){const{src:o}=this.context,s=o.substr(e,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new qe(this,`Invalid escape sequence ${o.substr(e-2,n+2)}`)),o.substr(e-2,n+2)):String.fromCodePoint(i)}parse(e,n){this.context=e;const{src:r}=e;let o=Bv.endOfQuote(r,n+1);return this.valueRange=new Ee(n,o),o=F.endOfWhiteSpace(r,o),o=this.parseComment(o),o}};class Ld extends F{static endOfQuote(e,n){let r=e[n];for(;r;)if(r==="'"){if(e[n+1]!=="'")break;r=e[n+=2]}else r=e[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&e.push(new qe(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
|
|
278
|
+
`){F.atDocumentBoundary(s,a+1)&&e.push(new ee(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=F.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new ee(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&e.push(new qe(this,"Unescaped single quote? This should not happen."));else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
|
|
279
|
+
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parse(e,n){this.context=e;const{src:r}=e;let o=Ld.endOfQuote(r,n+1);return this.valueRange=new Ee(n,o),o=F.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function qx(t,e){switch(t){case P.ALIAS:return new Dx(t,e);case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:return new Ux(t,e);case P.FLOW_MAP:case P.FLOW_SEQ:return new Bx(t,e);case P.MAP_KEY:case P.MAP_VALUE:case P.SEQ_ITEM:return new Md(t,e);case P.COMMENT:case P.PLAIN:return new Dv(t,e);case P.QUOTE_DOUBLE:return new Fx(t,e);case P.QUOTE_SINGLE:return new Ld(t,e);default:return null}}let Kx=class Oi{static parseType(e,n,r){switch(e[n]){case"*":return P.ALIAS;case">":return P.BLOCK_FOLDED;case"|":return P.BLOCK_LITERAL;case"{":return P.FLOW_MAP;case"[":return P.FLOW_SEQ;case"?":return!r&&F.atBlank(e,n+1,!0)?P.MAP_KEY:P.PLAIN;case":":return!r&&F.atBlank(e,n+1,!0)?P.MAP_VALUE:P.PLAIN;case"-":return!r&&F.atBlank(e,n+1,!0)?P.SEQ_ITEM:P.PLAIN;case'"':return P.QUOTE_DOUBLE;case"'":return P.QUOTE_SINGLE;default:return P.PLAIN}}constructor(e={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){We(this,"parseNode",(c,u)=>{if(F.atDocumentBoundary(this.src,u))return null;const l=new Oi(this,c),{props:d,type:f,valueStart:g}=l.parseProps(u),p=qx(f,d);let y=u;try{y=p.parse(l,g)}catch(w){const h=w instanceof Error?w.message:String(w);p.error||(p.error=new qe(p,h))}if(p.range=new Ee(u,y),y<=u&&(p.error||(p.error=new Error("Node#parse consumed no characters")),p.error.parseEnd=y,p.error.source=p,p.range.end=u+1),l.nodeStartsCollection(p)){!p.error&&!l.atLineStart&&l.parent.type===P.DOCUMENT&&(p.error=new qe(p,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const w=new Uv(p);return y=w.parse(new Oi(l),y),w.range=new Ee(u,y),w}return p}),this.atLineStart=n??(e.atLineStart||!1),this.inCollection=r??(e.inCollection||!1),this.inFlow=o??(e.inFlow||!1),this.indent=s??e.indent,this.lineStart=i??e.lineStart,this.parent=a??(e.parent||{}),this.root=e.root,this.src=e.src}nodeStartsCollection(e){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(e instanceof Md)return!0;let s=e.range.end;return o[s]===`
|
|
280
|
+
`||o[s-1]===`
|
|
281
|
+
`?!1:(s=F.endOfWhiteSpace(o,s),o[s]===":")}parseProps(e){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;e=this.atLineStart?F.endOfIndent(o,e):F.endOfWhiteSpace(o,e);let a=o[e];for(;a===je.ANCHOR||a===je.COMMENT||a===je.TAG||a===`
|
|
282
|
+
`;){if(a===`
|
|
283
|
+
`){let u=e,l;do l=u+1,u=F.endOfIndent(o,l);while(o[u]===`
|
|
284
|
+
`);const d=u-(l+this.indent),f=r.type===P.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!F.nextNodeIsIndented(o[u],d,!f))break;this.atLineStart=!0,this.lineStart=l,i=!1,e=u}else if(a===je.COMMENT){const u=F.endOfLine(o,e+1);s.push(new Ee(e,u)),e=u}else{let u=F.endOfIdentifier(o,e+1);a===je.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(e+1,u+13))&&(u=F.endOfIdentifier(o,u+5)),s.push(new Ee(e,u)),i=!0,e=F.endOfWhiteSpace(o,u)}a=o[e]}i&&a===":"&&F.atBlank(o,e+1,!0)&&(e-=1);const c=Oi.parseType(o,e,n);return{props:s,type:c,valueStart:e}}};function Dd(t){const e=[];t.indexOf("\r")!==-1&&(t=t.replace(/\r\n?/g,(o,s)=>(o.length>1&&e.push(s),`
|
|
285
|
+
`)));const n=[];let r=0;do{const o=new Lx,s=new Kx({src:t});r=o.parse(s,r),n.push(o)}while(r<t.length);return n.setOrigRanges=()=>{if(e.length===0)return!1;for(let s=1;s<e.length;++s)e[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(e,o);return e.splice(0,e.length),!0},n.toString=()=>n.join(`...
|
|
286
|
+
`),n}function Vx(t,e,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${e}#`)}
|
|
287
|
+
${e}${t}`:t}function Vr(t,e,n){return n?n.indexOf(`
|
|
288
|
+
`)===-1?`${t} #${n}`:`${t}
|
|
289
|
+
`+n.replace(/^/gm,`${e||""}#`):t}let rt=class{};function Ot(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Ot(r,String(o),n));if(t&&typeof t.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(t);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=t.toJSON(e,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof t=="bigint"?Number(t):t}let ge=class extends rt{constructor(e){super(),this.value=e}toJSON(e,n){return n&&n.keep?this.value:Ot(this.value,e,n)}toString(){return String(this.value)}};function tm(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){const s=e[o];if(Number.isInteger(s)&&s>=0){const i=[];i[s]=r,r=i}else{const i={};Object.defineProperty(i,s,{value:r,writable:!0,enumerable:!0,configurable:!0}),r=i}}return t.createNode(r,!1)}const Po=t=>t==null||typeof t=="object"&&t[Symbol.iterator]().next().done;let Be=class Yn extends rt{constructor(e){super(),We(this,"items",[]),this.schema=e}addIn(e,n){if(Po(e))this.add(n);else{const[r,...o]=e,s=this.get(r,!0);if(s instanceof Yn)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,tm(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([e,...n]){if(n.length===0)return this.delete(e);const r=this.get(e,!0);if(r instanceof Yn)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}getIn([e,...n],r){const o=this.get(e,!0);return n.length===0?!r&&o instanceof ge?o.value:o:o instanceof Yn?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(e=>{if(!e||e.type!=="PAIR")return!1;const n=e.value;return n==null||n instanceof ge&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([e,...n]){if(n.length===0)return this.has(e);const r=this.get(e,!0);return r instanceof Yn?r.hasIn(n):!1}setIn([e,...n],r){if(n.length===0)this.set(e,r);else{const o=this.get(e,!0);if(o instanceof Yn)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(e,tm(this.schema,n,r));else throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}}toJSON(){return null}toString(e,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=e,d=this.type===P.FLOW_MAP||this.type===P.FLOW_SEQ||e.inFlow;d&&(s+=u);const f=o&&this.hasAllNullValues();e=Object.assign({},e,{allNullValues:f,indent:s,inFlow:d,type:null});let g=!1,p=!1;const y=this.items.reduce((h,v,b)=>{let E;v&&(!g&&v.spaceBefore&&h.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(j=>{h.push({type:"comment",str:`#${j}`})}),v.comment&&(E=v.comment),d&&(!g&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(p=!0)),g=!1;let N=l(v,e,()=>E=null,()=>g=!0);return d&&!p&&N.includes(`
|
|
290
|
+
`)&&(p=!0),d&&b<this.items.length-1&&(N+=","),N=Vr(N,s,E),g&&(E||d)&&(g=!1),h.push({type:"item",str:N}),h},[]);let w;if(y.length===0)w=r.start+r.end;else if(d){const{start:h,end:v}=r,b=y.map(E=>E.str);if(p||b.reduce((E,N)=>E+N.length+2,2)>Yn.maxFlowStringSingleLineLength){w=h;for(const E of b)w+=E?`
|
|
291
|
+
${u}${c}${E}`:`
|
|
292
|
+
`;w+=`
|
|
293
|
+
${c}${v}`}else w=`${h} ${b.join(" ")} ${v}`}else{const h=y.map(n);w=h.shift();for(const v of h)w+=v?`
|
|
294
|
+
${c}${v}`:`
|
|
295
|
+
`}return this.comment?(w+=`
|
|
296
|
+
`+this.comment.replace(/^/gm,`${c}#`),i&&i()):g&&a&&a(),w}};We(Be,"maxFlowStringSingleLineLength",60);function Js(t){let e=t instanceof ge?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),Number.isInteger(e)&&e>=0?e:null}let Ut=class extends Be{add(e){this.items.push(e)}delete(e){const n=Js(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){const r=Js(e);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof ge?o.value:o}has(e){const n=Js(e);return typeof n=="number"&&n<this.items.length}set(e,n){const r=Js(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);this.items[r]=n}toJSON(e,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(Ot(s,String(o++),n));return r}toString(e,n,r){return e?super.toString(e,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(e.indent||"")+" "},n,r):JSON.stringify(this)}};const Gx=(t,e,n)=>e===null?"":typeof e!="object"?String(e):t instanceof rt&&n&&n.doc?t.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(e);let de=class Fv extends rt{constructor(e,n=null){super(),this.key=e,this.value=n,this.type=Fv.Type.PAIR}get commentBefore(){return this.key instanceof rt?this.key.commentBefore:void 0}set commentBefore(e){if(this.key==null&&(this.key=new ge(null)),this.key instanceof rt)this.key.commentBefore=e;else{const n="Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.";throw new Error(n)}}addToJSMap(e,n){const r=Ot(this.key,"",e);if(n instanceof Map){const o=Ot(this.value,r,e);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=Gx(this.key,r,e),s=Ot(this.value,o,e);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(e,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(e,n,r){if(!e||!e.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=e.doc.options;let{key:a,value:c}=this,u=a instanceof rt&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof Be){const N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let l=!i&&(!a||u||(a instanceof rt?a instanceof Be||a.type===P.BLOCK_FOLDED||a.type===P.BLOCK_LITERAL:typeof a=="object"));const{doc:d,indent:f,indentStep:g,stringify:p}=e;e=Object.assign({},e,{implicitKey:!l,indent:f+g});let y=!1,w=p(a,e,()=>u=null,()=>y=!0);if(w=Vr(w,e.indent,u),!l&&w.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(e.allNullValues&&!i)return this.comment?(w=Vr(w,e.indent,this.comment),n&&n()):y&&!u&&r&&r(),e.inFlow&&!l?w:`? ${w}`;w=l?`? ${w}
|
|
297
|
+
${f}:`:`${w}:`,this.comment&&(w=Vr(w,e.indent,this.comment),n&&n());let h="",v=null;if(c instanceof rt){if(c.spaceBefore&&(h=`
|
|
298
|
+
`),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${e.indent}#`);h+=`
|
|
299
|
+
${N}`}v=c.comment}else c&&typeof c=="object"&&(c=d.schema.createNode(c,!0));e.implicitKey=!1,!l&&!this.comment&&c instanceof ge&&(e.indentAtStart=w.length+1),y=!1,!s&&o>=2&&!e.inFlow&&!l&&c instanceof Ut&&c.type!==P.FLOW_SEQ&&!c.tag&&!d.anchors.getName(c)&&(e.indent=e.indent.substr(2));const b=p(c,e,()=>v=null,()=>y=!0);let E=" ";return h||this.comment?E=`${h}
|
|
300
|
+
${e.indent}`:!l&&c instanceof Be?(!(b[0]==="["||b[0]==="{")||b.includes(`
|
|
301
|
+
`))&&(E=`
|
|
302
|
+
${e.indent}`):b[0]===`
|
|
303
|
+
`&&(E=""),y&&!v&&r&&r(),Vr(w+E+b,e.indent,v)}};We(de,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const ki=(t,e)=>{if(t instanceof rn){const n=e.get(t.source);return n.count*n.aliasCount}else if(t instanceof Be){let n=0;for(const r of t.items){const o=ki(r,e);o>n&&(n=o)}return n}else if(t instanceof de){const n=ki(t.key,e),r=ki(t.value,e);return Math.max(n,r)}return 1};let rn=class qv extends rt{static stringify({range:e,source:n},{anchors:r,doc:o,implicitKey:s,inStringifyKey:i}){let a=Object.keys(r).find(u=>r[u]===n);if(!a&&i&&(a=o.anchors.getName(n)||o.anchors.newName()),a)return`*${a}${s?" ":""}`;const c=o.anchors.getName(n)?"Alias node must be after source node":"Source node not found for alias node";throw new Error(`${c} [${e}]`)}constructor(e){super(),this.source=e,this.type=P.ALIAS}set tag(e){throw new Error("Alias nodes cannot have tags")}toJSON(e,n){if(!n)return Ot(this.source,e,n);const{anchors:r,maxAliasCount:o}=n,s=r.get(this.source);if(!s||s.res===void 0){const i="This should not happen: Alias anchor was not resolved?";throw this.cstNode?new fs(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ki(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new fs(this.cstNode,i):new ReferenceError(i)}return s.res}toString(e){return qv.stringify(this,e)}};We(rn,"default",!0);function cr(t,e){const n=e instanceof ge?e.value:e;for(const r of t)if(r instanceof de&&(r.key===e||r.key===n||r.key&&r.key.value===n))return r}let it=class extends Be{add(e,n){e?e instanceof de||(e=new de(e.key||e,e.value)):e=new de(e);const r=cr(this.items,e.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=e.value;else throw new Error(`Key ${e.key} already set`);else if(o){const s=this.items.findIndex(i=>o(e,i)<0);s===-1?this.items.push(e):this.items.splice(s,0,e)}else this.items.push(e)}delete(e){const n=cr(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){const r=cr(this.items,e),o=r&&r.value;return!n&&o instanceof ge?o.value:o}has(e){return!!cr(this.items,e)}set(e,n){this.add(new de(e,n),!0)}toJSON(e,n,r){const o=r?new r:n&&n.mapAsMap?new Map:{};n&&n.onCreate&&n.onCreate(o);for(const s of this.items)s.addToJSMap(n,o);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof de))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(e,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:e.indent||""},n,r)}};const Kv="<<";class Vv extends de{constructor(e){if(e instanceof de){let n=e.value;n instanceof Ut||(n=new Ut,n.items.push(e.value),n.range=e.value.range),super(e.key,n),this.range=e.range}else super(new ge(Kv),new Ut);this.type=de.Type.MERGE_PAIR}addToJSMap(e,n){for(const{source:r}of this.value.items){if(!(r instanceof it))throw new Error("Merge sources must be maps");const o=r.toJSON(null,e,Map);for(const[s,i]of o)n instanceof Map?n.has(s)||n.set(s,i):n instanceof Set?n.add(s):Object.prototype.hasOwnProperty.call(n,s)||Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return n}toString(e,n){const r=this.value;if(r.items.length>1)return super.toString(e,n);this.value=r.items[0];const o=super.toString(e,n);return this.value=r,o}}const Ho={defaultType:P.BLOCK_LITERAL,lineWidth:76},Yt={trueStr:"true",falseStr:"false"},On={asBigInt:!1},ro={nullStr:"null"},on={defaultType:P.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function Ud(t,e,n){for(const{format:r,test:o,resolve:s}of e)if(o){const i=t.match(o);if(i){let a=s.apply(null,i);return a instanceof ge||(a=new ge(a)),r&&(a.format=r),a}}return n&&(t=n(t)),new ge(t)}const Gv="flow",ku="block",ji="quoted",nm=(t,e)=>{let n=t[e+1];for(;n===" "||n===" ";){do n=t[e+=1];while(n&&n!==`
|
|
304
|
+
`);n=t[e+1]}return e};function Aa(t,e,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return t;const c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;const u=[],l={};let d=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):d=o-r);let f,g,p=!1,y=-1,w=-1,h=-1;n===ku&&(y=nm(t,y),y!==-1&&(d=y+c));for(let b;b=t[y+=1];){if(n===ji&&b==="\\"){switch(w=y,t[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}h=y}if(b===`
|
|
305
|
+
`)n===ku&&(y=nm(t,y)),d=y+c,f=void 0;else{if(b===" "&&g&&g!==" "&&g!==`
|
|
306
|
+
`&&g!==" "){const E=t[y+1];E&&E!==" "&&E!==`
|
|
307
|
+
`&&E!==" "&&(f=y)}if(y>=d)if(f)u.push(f),d=f+c,f=void 0;else if(n===ji){for(;g===" "||g===" ";)g=b,b=t[y+=1],p=!0;const E=y>h+1?y-2:w-1;if(l[E])return t;u.push(E),l[E]=!0,d=E+c,f=void 0}else p=!0}g=b}if(p&&a&&a(),u.length===0)return t;i&&i();let v=t.slice(0,u[0]);for(let b=0;b<u.length;++b){const E=u[b],N=u[b+1]||t.length;E===0?v=`
|
|
308
|
+
${e}${t.slice(0,N)}`:(n===ji&&l[E]&&(v+=`${t[E]}\\`),v+=`
|
|
309
|
+
${e}${t.slice(E+1,N)}`)}return v}const Bd=({indentAtStart:t})=>t?Object.assign({indentAtStart:t},on.fold):on.fold,Ia=t=>/^(%|---|\.\.\.)/m.test(t);function zx(t,e,n){if(!e||e<0)return!1;const r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`
|
|
310
|
+
`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function fr(t,e){const{implicitKey:n}=e,{jsonEncoding:r,minMultiLineLength:o}=on.doubleQuoted,s=JSON.stringify(t);if(r)return s;const i=e.indent||(Ia(t)?" ":"");let a="",c=0;for(let u=0,l=s[u];l;l=s[++u])if(l===" "&&s[u+1]==="\\"&&s[u+2]==="n"&&(a+=s.slice(c,u)+"\\ ",u+=1,c=u,l="\\"),l==="\\")switch(s[u+1]){case"u":{a+=s.slice(c,u);const d=s.substr(u+2,4);switch(d){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:d.substr(0,2)==="00"?a+="\\x"+d.substr(2):a+=s.substr(u,6)}u+=5,c=u+1}break;case"n":if(n||s[u+2]==='"'||s.length<o)u+=1;else{for(a+=s.slice(c,u)+`
|
|
176
311
|
|
|
177
|
-
|
|
312
|
+
`;s[u+2]==="\\"&&s[u+3]==="n"&&s[u+4]!=='"';)a+=`
|
|
313
|
+
`,u+=2;a+=i,s[u+2]===" "&&(a+="\\"),u+=1,c=u+1}break;default:u+=1}return a=c?a+s.slice(c):s,n?a:Aa(a,i,ji,Bd(e))}function zv(t,e){if(e.implicitKey){if(/\n/.test(t))return fr(t,e)}else if(/[ \t]\n|\n[ \t]/.test(t))return fr(t,e);const n=e.indent||(Ia(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
314
|
+
${n}`)+"'";return e.implicitKey?r:Aa(r,n,Gv,Bd(e))}function Ai({comment:t,type:e,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return fr(n,r);const i=r.indent||(r.forceBlockIndent||Ia(n)?" ":""),a=i?"2":"1",c=e===P.BLOCK_FOLDED?!1:e===P.BLOCK_LITERAL?!0:!zx(n,on.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
|
|
315
|
+
`;let l="",d="";if(n=n.replace(/[\n\t ]*$/,g=>{const p=g.indexOf(`
|
|
316
|
+
`);return p===-1?u+="-":(n===g||p!==g.length-1)&&(u+="+",s&&s()),d=g.replace(/\n$/,""),""}).replace(/^[\n ]*/,g=>{g.indexOf(" ")!==-1&&(u+=a);const p=g.match(/ +$/);return p?(l=g.slice(0,-p[0].length),p[0]):(l=g,"")}),d&&(d=d.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),t&&(u+=" #"+t.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
|
|
317
|
+
${i}${d}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
|
|
318
|
+
${i}${l}${n}${d}`;n=n.replace(/\n+/g,`
|
|
319
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const f=Aa(`${l}${n}${d}`,i,ku,on.fold);return`${u}
|
|
320
|
+
${i}${f}`}function Wx(t,e,n,r){const{comment:o,type:s,value:i}=t,{actualString:a,implicitKey:c,indent:u,inFlow:l}=e;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return fr(i,e);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
|
|
321
|
+
`)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?zv(i,e):fr(i,e):Ai(t,e,n,r);if(!c&&!l&&s!==P.PLAIN&&i.indexOf(`
|
|
322
|
+
`)!==-1)return Ai(t,e,n,r);if(u===""&&Ia(i))return e.forceBlockIndent=!0,Ai(t,e,n,r);const d=i.replace(/\n+/g,`$&
|
|
323
|
+
${u}`);if(a){const{tags:g}=e.doc.schema;if(typeof Ud(d,g,g.scalarFallback).value!="string")return fr(i,e)}const f=c?d:Aa(d,u,Gv,Bd(e));return o&&!l&&(f.indexOf(`
|
|
324
|
+
`)!==-1||o.indexOf(`
|
|
325
|
+
`)!==-1)?(n&&n(),Vx(f,u,o)):f}function Fd(t,e,n,r){const{defaultType:o}=on,{implicitKey:s,inFlow:i}=e;let{type:a,value:c}=t;typeof c!="string"&&(c=String(c),t=Object.assign({},t,{value:c}));const u=d=>{switch(d){case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:return Ai(t,e,n,r);case P.QUOTE_DOUBLE:return fr(c,e);case P.QUOTE_SINGLE:return zv(c,e);case P.PLAIN:return Wx(t,e,n,r);default:return null}};(a!==P.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===P.BLOCK_FOLDED||a===P.BLOCK_LITERAL))&&(a=P.QUOTE_DOUBLE);let l=u(a);if(l===null&&(l=u(o),l===null))throw new Error(`Unsupported default string type ${o}`);return l}function Zt({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=e-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function Wv(t,e){let n,r;switch(e.type){case P.FLOW_MAP:n="}",r="flow map";break;case P.FLOW_SEQ:n="]",r="flow sequence";break;default:t.push(new ee(e,"Not a flow collection!?"));return}let o;for(let s=e.items.length-1;s>=0;--s){const i=e.items[s];if(!i||i.type!==P.COMMENT){o=i;break}}if(o&&o.char!==n){const s=`Expected ${r} to end with ${n}`;let i;typeof o.offset=="number"?(i=new ee(e,s),i.offset=o.offset+1):(i=new ee(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),t.push(i)}}function Hv(t,e){const n=e.context.src[e.range.start-1];if(n!==`
|
|
326
|
+
`&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";t.push(new ee(e,r))}}function Jv(t,e){const n=String(e),r=n.substr(0,8)+"..."+n.substr(-8);return new ee(t,`The "${r}" key is too long`)}function Qv(t,e){for(const{afterKey:n,before:r,comment:o}of e){let s=t.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
|
|
327
|
+
`+o:s.commentBefore=o):o!==void 0&&(t.comment?t.comment+=`
|
|
328
|
+
`+o:t.comment=o)}}function Os(t,e){const n=e.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=e),t.errors.push(r)}),n.str):""}function Hx(t,e){const{handle:n,suffix:r}=e.tag;let o=t.tagPrefixes.find(s=>s.handle===n);if(!o){const s=t.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new ee(e,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new ee(e,`The ${n} tag has no suffix.`);if(n==="!"&&(t.version||t.options.version)==="1.0"){if(r[0]==="^")return t.warnings.push(new po(e,"YAML 1.0 ^ tag expansion is not supported")),r;if(/[:/]/.test(r)){const s=r.match(/^([a-z0-9-]+)\/(.*)/i);return s?`tag:${s[1]}.yaml.org,2002:${s[2]}`:`tag:${r}`}}return o.prefix+decodeURIComponent(r)}function Jx(t,e){const{tag:n,type:r}=e;let o=!1;if(n){const{handle:s,suffix:i,verbatim:a}=n;if(a){if(a!=="!"&&a!=="!!")return a;const c=`Verbatim tags aren't resolved, so ${a} is invalid.`;t.errors.push(new ee(e,c))}else if(s==="!"&&!i)o=!0;else try{return Hx(t,e)}catch(c){t.errors.push(c)}}switch(r){case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:case P.QUOTE_DOUBLE:case P.QUOTE_SINGLE:return wn.STR;case P.FLOW_MAP:case P.MAP:return wn.MAP;case P.FLOW_SEQ:case P.SEQ:return wn.SEQ;case P.PLAIN:return o?wn.STR:null;default:return null}}function rm(t,e,n){const{tags:r}=t.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(t,e);return a instanceof Be?a:new ge(a)}const s=Os(t,e);return typeof s=="string"&&o.length>0?Ud(s,o,r.scalarFallback):null}function Qx({type:t}){switch(t){case P.FLOW_MAP:case P.MAP:return wn.MAP;case P.FLOW_SEQ:case P.SEQ:return wn.SEQ;default:return wn.STR}}function Yx(t,e,n){try{const r=rm(t,e,n);if(r)return n&&e.tag&&(r.tag=n),r}catch(r){if(r instanceof wr)r.source||(r.source=e),t.errors.push(r);else{const o=r instanceof Error?r.message:String(r);t.errors.push(new ee(e,o))}return null}try{const r=Qx(e);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;t.warnings.push(new po(e,o));const s=rm(t,e,r);return s.tag=n,s}catch(r){const o=new fs(e,r.message);return o.stack=r.stack,t.errors.push(o),null}}const Zx=t=>{if(!t)return!1;const{type:e}=t;return e===P.MAP_KEY||e===P.MAP_VALUE||e===P.SEQ_ITEM};function Xx(t,e){const n={before:[],after:[]};let r=!1,o=!1;const s=Zx(e.context.parent)?e.context.parent.props.concat(e.props):e.props;for(const{start:i,end:a}of s)switch(e.context.src[i]){case je.COMMENT:{if(!e.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";t.push(new ee(e,l))}const{header:c,valueRange:u}=e;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(e.context.src.slice(i+1,a));break}case je.ANCHOR:if(r){const c="A node can have at most one anchor";t.push(new ee(e,c))}r=!0;break;case je.TAG:if(o){const c="A node can have at most one tag";t.push(new ee(e,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function eR(t,e){const{anchors:n,errors:r,schema:o}=t;if(e.type===P.ALIAS){const i=e.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new fs(e,u)),null}const c=new rn(a);return n._cstAliases.push(c),c}const s=Jx(t,e);if(s)return Yx(t,e,s);if(e.type!==P.PLAIN){const i=`Failed to resolve ${e.type} node here`;return r.push(new qe(e,i)),null}try{const i=Os(t,e);return Ud(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=e),r.push(i),null}}function En(t,e){if(!e)return null;e.error&&t.errors.push(e.error);const{comments:n,hasAnchor:r,hasTag:o}=Xx(t.errors,e);if(r){const{anchors:i}=t,a=e.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=e}if(e.type===P.ALIAS&&(r||o)){const i="An alias node must not specify any properties";t.errors.push(new ee(e,i))}const s=eR(t,e);if(s){s.range=[e.range.start,e.range.end],t.options.keepCstNodes&&(s.cstNode=e),t.options.keepNodeTypes&&(s.type=e.type);const i=n.before.join(`
|
|
329
|
+
`);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
|
|
330
|
+
${i}`:i);const a=n.after.join(`
|
|
331
|
+
`);a&&(s.comment=s.comment?`${s.comment}
|
|
332
|
+
${a}`:a)}return e.resolved=s}function Yv(t,e){if(e.type!==P.MAP&&e.type!==P.FLOW_MAP){const i=`A ${e.type} node cannot be resolved as a mapping`;return t.errors.push(new qe(e,i)),null}const{comments:n,items:r}=e.type===P.FLOW_MAP?oR(t,e):rR(t,e),o=new it;o.items=r,Qv(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof Be&&(s=!0),t.schema.merge&&a&&a.value===Kv){r[i]=new Vv(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof rn){const{type:d}=l.source;return d===P.MAP||d===P.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&t.errors.push(new ee(e,u))}else for(let c=i+1;c<r.length;++c){const{key:u}=r[c];if(a===u||a&&u&&Object.prototype.hasOwnProperty.call(a,"value")&&a.value===u.value){const l=`Map keys must be unique; "${a}" is repeated`;t.errors.push(new ee(e,l));break}}}if(s&&!t.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new po(e,i))}return e.resolved=o,o}const tR=({context:{lineStart:t,node:e,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(e&&o>e.valueRange.start||n[o]!==je.COMMENT)return!1;for(let s=t;s<o;++s)if(n[s]===`
|
|
333
|
+
`)return!1;return!0};function nR(t,e){if(!tR(t))return;const n=t.getPropValue(0,je.COMMENT,!0);let r=!1;const o=e.value.commentBefore;if(o&&o.startsWith(n))e.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=e.value.comment;!t.node&&s&&s.startsWith(n)&&(e.value.comment=s.substr(n.length+1),r=!0)}r&&(e.comment=n)}function rR(t,e){const n=[],r=[];let o,s=null;for(let i=0;i<e.items.length;++i){const a=e.items[i];switch(a.type){case P.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case P.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case P.MAP_KEY:o!==void 0&&r.push(new de(o)),a.error&&t.errors.push(a.error),o=En(t,a.node),s=null;break;case P.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&t.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===P.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";t.errors.push(new ee(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new Dv(P.PLAIN,[]),c.context={parent:a,src:a.context.src};const l=a.range.start+1;if(c.range={start:l,end:l},c.valueRange={start:l,end:l},typeof a.range.origStart=="number"){const d=a.range.origStart+1;c.range.origStart=c.range.origEnd=d,c.valueRange.origStart=c.valueRange.origEnd=d}}const u=new de(o,En(t,c));nR(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&t.errors.push(Jv(e,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new de(o)),o=En(t,a),s=a.range.start,a.error&&t.errors.push(a.error);e:for(let c=i+1;;++c){const u=e.items[c];switch(u&&u.type){case P.BLANK_LINE:case P.COMMENT:continue e;case P.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";t.errors.push(new ee(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";t.errors.push(new ee(a,c))}}}return o!==void 0&&r.push(new de(o)),{comments:n,items:r}}function oR(t,e){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<e.items.length;++a){const c=e.items[a];if(typeof c.char=="string"){const{char:u,offset:l}=c;if(u==="?"&&o===void 0&&!s){s=!0,i=":";continue}if(u===":"){if(o===void 0&&(o=null),i===":"){i=",";continue}}else if(s&&(o===void 0&&u!==","&&(o=null),s=!1),o!==void 0&&(r.push(new de(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===e.items.length-1)continue}else if(u===i){i=":";continue}const d=`Flow map contains an unexpected ${u}`,f=new qe(e,d);f.offset=l,t.errors.push(f)}else c.type===P.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===P.COMMENT?(Hv(t.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&t.errors.push(new ee(c,"Separator , missing in flow map")),o=En(t,c)):(i!==","&&t.errors.push(new ee(c,"Indicator : missing in flow map entry")),r.push(new de(o,En(t,c))),o=void 0,s=!1)}return Wv(t.errors,e),o!==void 0&&r.push(new de(o)),{comments:n,items:r}}function Zv(t,e){if(e.type!==P.SEQ&&e.type!==P.FLOW_SEQ){const s=`A ${e.type} node cannot be resolved as a sequence`;return t.errors.push(new qe(e,s)),null}const{comments:n,items:r}=e.type===P.FLOW_SEQ?iR(t,e):sR(t,e),o=new Ut;if(o.items=r,Qv(o,n),!t.options.mapAsMap&&r.some(s=>s instanceof de&&s.key instanceof Be)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new po(e,s))}return e.resolved=o,o}function sR(t,e){const n=[],r=[];for(let o=0;o<e.items.length;++o){const s=e.items[o];switch(s.type){case P.BLANK_LINE:n.push({before:r.length});break;case P.COMMENT:n.push({comment:s.comment,before:r.length});break;case P.SEQ_ITEM:if(s.error&&t.errors.push(s.error),r.push(En(t,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";t.errors.push(new ee(s,i))}break;default:s.error&&t.errors.push(s.error),t.errors.push(new qe(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function iR(t,e){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<e.items.length;++u){const l=e.items[u];if(typeof l.char=="string"){const{char:d,offset:f}=l;if(d!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new de(s)),o=!1,s=void 0,i=null),d===a)a=null;else if(!a&&d==="?")o=!0;else if(a!=="["&&d===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof de){const g="Chaining flow sequence pairs is invalid",p=new ee(e,g);p.offset=f,t.errors.push(p)}if(!o&&typeof i=="number"){const g=l.range?l.range.start:l.offset;g>i+1024&&t.errors.push(Jv(e,s));const{src:p}=c.context;for(let y=i;y<g;++y)if(p[y]===`
|
|
334
|
+
`){const w="Implicit keys of flow sequence pairs need to be on a single line";t.errors.push(new ee(c,w));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||d!=="]"||u<e.items.length-1){const g=`Flow sequence contains an unexpected ${d}`,p=new qe(e,g);p.offset=f,t.errors.push(p)}}else if(l.type===P.BLANK_LINE)n.push({before:r.length});else if(l.type===P.COMMENT)Hv(t.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const f=`Expected a ${a} in flow sequence`;t.errors.push(new ee(l,f))}const d=En(t,l);s===void 0?(r.push(d),c=l):(r.push(new de(s,d)),s=void 0),i=l.range.start,a=","}}return Wv(t.errors,e),s!==void 0&&r.push(new de(s)),{comments:n,items:r}}const Xv={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(t,e)=>{const n=Os(t,e);if(typeof Buffer=="function")return Buffer.from(n,"base64");if(typeof atob=="function"){const r=atob(n.replace(/[\n\r]/g,"")),o=new Uint8Array(r.length);for(let s=0;s<r.length;++s)o[s]=r.charCodeAt(s);return o}else{const r="This environment does not support reading binary tags; either Buffer or atob is required";return t.errors.push(new fs(e,r)),null}},options:Ho,stringify:({comment:t,type:e,value:n},r,o,s)=>{let i;if(typeof Buffer=="function")i=n instanceof Buffer?n.toString("base64"):Buffer.from(n.buffer).toString("base64");else if(typeof btoa=="function"){let a="";for(let c=0;c<n.length;++c)a+=String.fromCharCode(n[c]);i=btoa(a)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e||(e=Ho.defaultType),e===P.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=Ho,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,d=0;l<c;++l,d+=a)u[l]=i.substr(d,a);n=u.join(e===P.BLOCK_LITERAL?`
|
|
335
|
+
`:" ")}return Fd({comment:t,type:e,value:n},r,o,s)}};function e$(t,e){const n=Zv(t,e);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof de)){if(o instanceof it){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new ee(e,i)}const s=o.items[0]||new de;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
|
|
336
|
+
${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
|
|
337
|
+
${s.comment}`:o.comment),o=s}n.items[r]=o instanceof de?o:new de(o)}}return n}function t$(t,e,n){const r=new Ut(t);r.tag="tag:yaml.org,2002:pairs";for(const o of e){let s,i;if(Array.isArray(o))if(o.length===2)s=o[0],i=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const c=Object.keys(o);if(c.length===1)s=c[0],i=o[s];else throw new TypeError(`Expected { key: value } tuple: ${o}`)}else s=o;const a=t.createPair(s,i,n);r.items.push(a)}return r}const n$={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:e$,createNode:t$};let Pa=class r$ extends Ut{constructor(){super(),We(this,"add",it.prototype.add.bind(this)),We(this,"delete",it.prototype.delete.bind(this)),We(this,"get",it.prototype.get.bind(this)),We(this,"has",it.prototype.has.bind(this)),We(this,"set",it.prototype.set.bind(this)),this.tag=r$.tag}toJSON(e,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof de?(s=Ot(o.key,"",n),i=Ot(o.value,s,n)):s=Ot(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};We(Pa,"tag","tag:yaml.org,2002:omap");function aR(t,e){const n=e$(t,e),r=[];for(const{key:o}of n.items)if(o instanceof ge)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new ee(e,s)}else r.push(o.value);return Object.assign(new Pa,n)}function cR(t,e,n){const r=t$(t,e,n),o=new Pa;return o.items=r.items,o}const o$={identify:t=>t instanceof Map,nodeClass:Pa,default:!1,tag:"tag:yaml.org,2002:omap",resolve:aR,createNode:cR};let xa=class s$ extends it{constructor(){super(),this.tag=s$.tag}add(e){const n=e instanceof de?e:new de(e);cr(this.items,n.key)||this.items.push(n)}get(e,n){const r=cr(this.items,e);return!n&&r instanceof de?r.key instanceof ge?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=cr(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new de(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(e,n,r);throw new Error("Set items must all have null values")}};We(xa,"tag","tag:yaml.org,2002:set");function uR(t,e){const n=Yv(t,e);if(!n.hasAllNullValues())throw new ee(e,"Set items must all have null values");return Object.assign(new xa,n)}function lR(t,e,n){const r=new xa;for(const o of e)r.items.push(t.createPair(o,null,n));return r}const i$={identify:t=>t instanceof Set,nodeClass:xa,default:!1,tag:"tag:yaml.org,2002:set",resolve:uR,createNode:lR},qd=(t,e)=>{const n=e.split(":").reduce((r,o)=>r*60+Number(o),0);return t==="-"?-n:n},a$=({value:t})=>{if(isNaN(t)||!isFinite(t))return Zt(t);let e="";t<0&&(e="-",t=Math.abs(t));const n=[t%60];return t<60?n.unshift(0):(t=Math.round((t-n[0])/60),n.unshift(t%60),t>=60&&(t=Math.round((t-n[0])/60),n.unshift(t))),e+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},c$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(t,e,n)=>qd(e,n.replace(/_/g,"")),stringify:a$},u$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(t,e,n)=>qd(e,n.replace(/_/g,"")),stringify:a$},l$={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?)$"),resolve:(t,e,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(e,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=qd(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function d$(t){const e=typeof process<"u"&&process.env||{};return t?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!e.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!e.YAML_SILENCE_WARNINGS}function f$(t,e){if(d$(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(t,e):console.warn(e?`${e}: ${t}`:t)}}const om={};function dR(t,e){if(!om[t]&&d$(!0)){om[t]=!0;let n=`The option '${t}' will be removed in a future release`;n+=`, use '${e}' instead.`,f$(n,"DeprecationWarning")}}function fR(t,e,n){const r=new it(t);if(e instanceof Map)for(const[o,s]of e)r.items.push(t.createPair(o,s,n));else if(e&&typeof e=="object")for(const o of Object.keys(e))r.items.push(t.createPair(o,e[o],n));return typeof t.sortMapEntries=="function"&&r.items.sort(t.sortMapEntries),r}const hs={createNode:fR,default:!0,nodeClass:it,tag:"tag:yaml.org,2002:map",resolve:Yv};function pR(t,e,n){const r=new Ut(t);if(e&&e[Symbol.iterator])for(const o of e){const s=t.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const Ra={createNode:pR,default:!0,nodeClass:Ut,tag:"tag:yaml.org,2002:seq",resolve:Zv},hR={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Os,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),Fd(t,e,n,r)},options:on},Kd=[hs,Ra,hR],Ta=t=>typeof t=="bigint"||Number.isInteger(t),Vd=(t,e,n)=>On.asBigInt?BigInt(t):parseInt(e,n);function p$(t,e,n){const{value:r}=t;return Ta(r)&&r>=0?n+r.toString(e):Zt(t)}const h$={identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new ge(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:ro,stringify:()=>ro.nullStr},m$={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>t[0]==="t"||t[0]==="T",options:Yt,stringify:({value:t})=>t?Yt.trueStr:Yt.falseStr},g$={identify:t=>Ta(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(t,e)=>Vd(t,e,8),options:On,stringify:t=>p$(t,8,"0o")},y$={identify:Ta,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:t=>Vd(t,t,10),options:On,stringify:Zt},w$={identify:t=>Ta(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(t,e)=>Vd(t,e,16),options:On,stringify:t=>p$(t,16,"0x")},v$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Zt},$$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify:({value:t})=>Number(t).toExponential()},b$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(t,e,n){const r=e||n,o=new ge(parseFloat(t));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Zt},mR=Kd.concat([h$,m$,g$,y$,w$,v$,$$,b$]),sm=t=>typeof t=="bigint"||Number.isInteger(t),Qs=({value:t})=>JSON.stringify(t),E$=[hs,Ra,{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Os,stringify:Qs},{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new ge(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Qs},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:t=>t==="true",stringify:Qs},{identify:sm,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:t=>On.asBigInt?BigInt(t):parseInt(t,10),stringify:({value:t})=>sm(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Qs}];E$.scalarFallback=t=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(t)}`)};const im=({value:t})=>t?Yt.trueStr:Yt.falseStr,xo=t=>typeof t=="bigint"||Number.isInteger(t);function Ys(t,e,n){let r=e.replace(/_/g,"");if(On.asBigInt){switch(n){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}const s=BigInt(r);return t==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return t==="-"?-1*o:o}function hc(t,e,n){const{value:r}=t;if(xo(r)){const o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return Zt(t)}const gR=Kd.concat([{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new ge(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:ro,stringify:()=>ro.nullStr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Yt,stringify:im},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>!1,options:Yt,stringify:im},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(t,e,n)=>Ys(e,n,2),stringify:t=>hc(t,2,"0b")},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(t,e,n)=>Ys(e,n,8),stringify:t=>hc(t,8,"0")},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(t,e,n)=>Ys(e,n,10),stringify:Zt},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(t,e,n)=>Ys(e,n,16),stringify:t=>hc(t,16,"0x")},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Zt},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify:({value:t})=>Number(t).toExponential()},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(t,e){const n=new ge(parseFloat(t.replace(/_/g,"")));if(e){const r=e.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Zt}],Xv,o$,n$,i$,c$,u$,l$),yR={core:mR,failsafe:Kd,json:E$,yaml11:gR},wR={binary:Xv,bool:m$,float:b$,floatExp:$$,floatNaN:v$,floatTime:u$,int:y$,intHex:w$,intOct:g$,intTime:c$,map:hs,null:h$,omap:o$,pairs:n$,seq:Ra,set:i$,timestamp:l$};function vR(t,e,n){if(e){const r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>(r.identify&&r.identify(t)||r.class&&t instanceof r.class)&&!r.format)}function $R(t,e,n){if(t instanceof rt)return t;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;e&&e.startsWith("!!")&&(e=r+e.slice(2));let c=vR(t,e,i.tags);if(!c){if(typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object")return a?new ge(t):t;c=t instanceof Map?hs:t[Symbol.iterator]?Ra:hs}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(t&&typeof t=="object"&&s){const l=s.get(t);if(l){const d=new rn(l);return n.aliasNodes.push(d),d}u.value=t,s.set(t,u)}return u.node=c.createNode?c.createNode(n.schema,t,n):a?new ge(t):t,e&&u.node instanceof rt&&(u.node.tag=e),u.node}function bR(t,e,n,r){let o=t[r.replace(/\W/g,"")];if(!o){const s=Object.keys(t).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${r}"; use one of ${s}`)}if(Array.isArray(n))for(const s of n)o=o.concat(s);else typeof n=="function"&&(o=n(o.slice()));for(let s=0;s<o.length;++s){const i=o[s];if(typeof i=="string"){const a=e[i];if(!a){const c=Object.keys(e).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const ER=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0;let ms=class S${constructor({customTags:e,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?ER:o||null,!e&&s&&dR("tags","customTags"),this.tags=bR(yR,wR,e||s,r)}createNode(e,n,r,o){const s={defaultPrefix:S$.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return $R(e,r,i)}createPair(e,n,r){r||(r={wrapScalars:!0});const o=this.createNode(e,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new de(o,s)}};We(ms,"defaultPrefix",Ni);We(ms,"defaultTags",wn);const Zi={anchorPrefix:"a",customTags:null,indent:2,indentSeq:!0,keepCstNodes:!1,keepNodeTypes:!0,keepBlobsInJSON:!0,mapAsMap:!1,maxAliasCount:100,prettyErrors:!1,simpleKeys:!1,version:"1.2"},SR={get binary(){return Ho},set binary(t){Object.assign(Ho,t)},get bool(){return Yt},set bool(t){Object.assign(Yt,t)},get int(){return On},set int(t){Object.assign(On,t)},get null(){return ro},set null(t){Object.assign(ro,t)},get str(){return on},set str(t){Object.assign(on,t)}},_$={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:Ni},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Ni}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Ni}]}};function am(t,e){if((t.version||t.options.version)==="1.0"){const o=e.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=e.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${e.replace(/^tag:/,"")}`}let n=t.tagPrefixes.find(o=>e.indexOf(o.prefix)===0);if(!n){const o=t.getDefaults().tagPrefixes;n=o&&o.find(s=>e.indexOf(s.prefix)===0)}if(!n)return e[0]==="!"?e:`!<${e}>`;const r=e.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function _R(t,e){if(e instanceof rn)return rn;if(e.tag){const o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)||o[0]}let n,r;if(e instanceof ge){r=e.value;const o=t.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===e.format)||o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){const o=r&&r.constructor?r.constructor.name:typeof r;throw new Error(`Tag not resolved for ${o} value`)}return n}function NR(t,e,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(t);return s&&(n[s]=t,o.push(`&${s}`)),t.tag?o.push(am(r,t.tag)):e.default||o.push(am(r,e.tag)),o.join(" ")}function Zs(t,e,n,r){const{anchors:o,schema:s}=e.doc;let i;if(!(t instanceof rt)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};t=s.createNode(t,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let d=o.getName(l.source);d||(d=o.newName(),o.map[d]=l.source)}}if(t instanceof de)return t.toString(e,n,r);i||(i=_R(s.tags,t));const a=NR(t,i,e);a.length>0&&(e.indentAtStart=(e.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(t,e,n,r):t instanceof ge?Fd(t,e,n,r):t.toString(e,n,r);return a?t instanceof ge||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
|
|
338
|
+
${e.indent}${c}`:c}class Gd{static validAnchorNode(e){return e instanceof ge||e instanceof Ut||e instanceof it}constructor(e){We(this,"map",Object.create(null)),this.prefix=e}createAlias(e,n){return this.setAnchor(e,n),new rn(e)}createMergePair(...e){const n=new Vv;return n.value.items=e.map(r=>{if(r instanceof rn){if(r.source instanceof it)return r}else if(r instanceof it)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(e){const{map:n}=this;return Object.keys(n).find(r=>n[r]===e)}getNames(){return Object.keys(this.map)}getNode(e){return this.map[e]}newName(e){e||(e=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${e}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:e,_cstAliases:n}=this;Object.keys(e).forEach(r=>{e[r]=e[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(e,n){if(e!=null&&!Gd.validAnchorNode(e))throw new Error("Anchors may only be set for Scalar, Seq and Map nodes");if(n&&/[\x00-\x19\s,[\]{}]/.test(n))throw new Error("Anchor names must not contain whitespace or control characters");const{map:r}=this,o=e&&Object.keys(r).find(s=>r[s]===e);if(o)if(n)o!==n&&(delete r[o],r[n]=e);else return o;else{if(!n){if(!e)return null;n=this.newName()}r[n]=e}return n}}const Ii=(t,e)=>{if(t&&typeof t=="object"){const{tag:n}=t;t instanceof Be?(n&&(e[n]=!0),t.items.forEach(r=>Ii(r,e))):t instanceof de?(Ii(t.key,e),Ii(t.value,e)):t instanceof ge&&n&&(e[n]=!0)}return e},OR=t=>Object.keys(Ii(t,{}));function kR(t,e){const n={before:[],after:[]};let r,o=!1;for(const s of e)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";t.errors.push(new qe(s,a));break}const i=En(t,s);o&&(i.spaceBefore=!0,o=!1),r=i}else s.comment!==null?(r===void 0?n.before:n.after).push(s.comment):s.type===P.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!t.commentBefore&&(t.commentBefore=n.before.join(`
|
|
339
|
+
`),n.before=[]));if(t.contents=r||null,!r)t.comment=n.before.concat(n.after).join(`
|
|
340
|
+
`)||null;else{const s=n.before.join(`
|
|
341
|
+
`);if(s){const i=r instanceof Be&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
|
|
342
|
+
${i.commentBefore}`:s}t.comment=n.after.join(`
|
|
343
|
+
`)||null}}function jR({tagPrefixes:t},e){const[n,r]=e.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new ee(e,o)}if(t.some(o=>o.handle===n)){const o="The %TAG directive must only be given at most once per handle in the same document.";throw new ee(e,o)}return{handle:n,prefix:r}}function AR(t,e){let[n]=e.parameters;if(e.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new ee(e,r)}if(!_$[n]){const r=`Document will be parsed as YAML ${t.version||t.options.version} rather than YAML ${n}`;t.warnings.push(new po(e,r))}return n}function IR(t,e,n){const r=[];let o=!1;for(const s of e){const{comment:i,name:a}=s;switch(a){case"TAG":try{t.tagPrefixes.push(jR(t,s))}catch(c){t.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(t.version){const c="The %YAML directive must only be given at most once per document.";t.errors.push(new ee(s,c))}try{t.version=AR(t,s)}catch(c){t.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;t.warnings.push(new po(s,c))}}i&&r.push(i)}if(n&&!o&&(t.version||n.version||t.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});t.tagPrefixes=n.tagPrefixes.map(s),t.version=n.version}t.commentBefore=r.join(`
|
|
344
|
+
`)||null}function Ar(t){if(t instanceof Be)return!0;throw new Error("Expected a YAML collection as document contents")}let zd=class ju{constructor(e){this.anchors=new Gd(e.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=e,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(e){return Ar(this.contents),this.contents.add(e)}addIn(e,n){Ar(this.contents),this.contents.addIn(e,n)}delete(e){return Ar(this.contents),this.contents.delete(e)}deleteIn(e){return Po(e)?this.contents==null?!1:(this.contents=null,!0):(Ar(this.contents),this.contents.deleteIn(e))}getDefaults(){return ju.defaults[this.version]||ju.defaults[this.options.version]||{}}get(e,n){return this.contents instanceof Be?this.contents.get(e,n):void 0}getIn(e,n){return Po(e)?!n&&this.contents instanceof ge?this.contents.value:this.contents:this.contents instanceof Be?this.contents.getIn(e,n):void 0}has(e){return this.contents instanceof Be?this.contents.has(e):!1}hasIn(e){return Po(e)?this.contents!==void 0:this.contents instanceof Be?this.contents.hasIn(e):!1}set(e,n){Ar(this.contents),this.contents.set(e,n)}setIn(e,n){Po(e)?this.contents=n:(Ar(this.contents),this.contents.setIn(e,n))}setSchema(e,n){if(!e&&!n&&this.schema)return;typeof e=="number"&&(e=e.toFixed(1)),e==="1.0"||e==="1.1"||e==="1.2"?(this.version?this.version=e:this.options.version=e,delete this.options.schema):e&&typeof e=="string"&&(this.options.schema=e),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new ms(r)}parse(e,n){this.options.keepCstNodes&&(this.cstNode=e),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=e;if(i&&(i.source||(i.source=this),this.errors.push(i)),IR(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],kR(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof wr&&c.makePretty();for(const c of this.warnings)c instanceof wr&&c.makePretty()}return this}listNonDefaultTags(){return OR(this.contents).filter(e=>e.indexOf(ms.defaultPrefix)!==0)}setTagPrefix(e,n){if(e[0]!=="!"||e[e.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===e);r?r.prefix=n:this.tagPrefixes.push({handle:e,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==e)}toJSON(e,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof e!="string"||!(this.contents instanceof ge)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Zs},c=Object.keys(this.anchors.map);c.length>0&&(a.anchors=new Map(c.map(l=>[this.anchors.map[l],{alias:[],aliasCount:0,count:1}])));const u=Ot(this.contents,e,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:d}of a.anchors.values())n(d,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const e=this.options.indent;if(!Number.isInteger(e)||e<=0){const c=JSON.stringify(e);throw new Error(`"indent" option must be a positive integer, not ${c}`)}this.setSchema();const n=[];let r=!1;if(this.version){let c="%YAML 1.2";this.schema.name==="yaml-1.1"&&(this.version==="1.0"?c="%YAML:1.0":this.version==="1.1"&&(c="%YAML 1.1")),n.push(c),r=!0}const o=this.listNonDefaultTags();this.tagPrefixes.forEach(({handle:c,prefix:u})=>{o.some(l=>l.indexOf(u)===0)&&(n.push(`%TAG ${c} ${u}`),r=!0)}),(r||this.directivesEndMarker)&&n.push("---"),this.commentBefore&&((r||!this.directivesEndMarker)&&n.unshift(""),n.unshift(this.commentBefore.replace(/^/gm,"#")));const s={anchors:Object.create(null),doc:this,indent:"",indentStep:" ".repeat(e),stringify:Zs};let i=!1,a=null;if(this.contents){this.contents instanceof rt&&(this.contents.spaceBefore&&(r||this.directivesEndMarker)&&n.push(""),this.contents.commentBefore&&n.push(this.contents.commentBefore.replace(/^/gm,"#")),s.forceBlockIndent=!!this.comment,a=this.contents.comment);const c=a?null:()=>i=!0,u=Zs(this.contents,s,()=>a=null,c);n.push(Vr(u,"",a))}else this.contents!==void 0&&n.push(Zs(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
|
|
345
|
+
`)+`
|
|
346
|
+
`}};We(zd,"defaults",_$);function PR(t,e=!0,n){n===void 0&&typeof e=="string"&&(n=e,e=!0);const r=Object.assign({},zd.defaults[Zi.version],Zi);return new ms(r).createNode(t,e,n)}class Ca extends zd{constructor(e){super(Object.assign({},Zi,e))}}function xR(t,e){const n=[];let r;for(const o of Dd(t)){const s=new Ca(e);s.parse(o,r),n.push(s),r=s}return n}function N$(t,e){const n=Dd(t),r=new Ca(e).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new ee(n[1],o))}return r}function RR(t,e){const n=N$(t,e);if(n.warnings.forEach(r=>f$(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function TR(t,e){const n=new Ca(e);return n.contents=t,String(n)}const CR={createNode:PR,defaultOptions:Zi,Document:Ca,parse:RR,parseAllDocuments:xR,parseCST:Dd,parseDocument:N$,scalarOptions:SR,stringify:TR},MR=Object.freeze(Object.defineProperty({__proto__:null,YAML:CR},Symbol.toStringTag,{value:"Module"})),LR=Px(MR);LR.YAML;var cm={exports:{}},O$={},kt={},oo={},ks={},ce={},gs={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class r extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((b,E)=>`${b}${E}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((b,E)=>(E instanceof n&&(b[E.str]=(b[E.str]||0)+1),b),{})}}t._Code=r,t.nil=new r("");function o(h,...v){const b=[h[0]];let E=0;for(;E<v.length;)a(b,v[E]),b.push(h[++E]);return new r(b)}t._=o;const s=new r("+");function i(h,...v){const b=[g(h[0])];let E=0;for(;E<v.length;)b.push(s),a(b,v[E]),b.push(s,g(h[++E]));return c(b),new r(b)}t.str=i;function a(h,v){v instanceof r?h.push(...v._items):v instanceof n?h.push(v):h.push(d(v))}t.addCodeArg=a;function c(h){let v=1;for(;v<h.length-1;){if(h[v]===s){const b=u(h[v-1],h[v+1]);if(b!==void 0){h.splice(v-1,3,b);continue}h[v++]="+"}v++}}function u(h,v){if(v==='""')return h;if(h==='""')return v;if(typeof h=="string")return v instanceof n||h[h.length-1]!=='"'?void 0:typeof v!="string"?`${h.slice(0,-1)}${v}"`:v[0]==='"'?h.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(h instanceof n))return`"${h}${v.slice(1)}`}function l(h,v){return v.emptyStr()?h:h.emptyStr()?v:i`${h}${v}`}t.strConcat=l;function d(h){return typeof h=="number"||typeof h=="boolean"||h===null?h:g(Array.isArray(h)?h.join(","):h)}function f(h){return new r(g(h))}t.stringify=f;function g(h){return JSON.stringify(h).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=g;function p(h){return typeof h=="string"&&t.IDENTIFIER.test(h)?new r(`.${h}`):o`[${h}]`}t.getProperty=p;function y(h){if(typeof h=="string"&&t.IDENTIFIER.test(h))return new r(`${h}`);throw new Error(`CodeGen: invalid export name: ${h}, use explicit $id name mapping`)}t.getEsmExportName=y;function w(h){return new r(h.toString())}t.regexpCode=w})(gs);var Au={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=gs;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||(t.UsedValueState=r={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.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}}}t.Scope=o;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;const i=(0,e._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const f=this.toName(u),{prefix:g}=f,p=(d=l.key)!==null&&d!==void 0?d:l.ref;let y=this._values[g];if(y){const v=y.get(p);if(v)return v}else y=this._values[g]=new Map;y.set(p,f);const w=this._scope[g]||(this._scope[g]=[]),h=w.length;return w[h]=l.ref,f.setValue(l,{property:g,itemIndex:h}),f}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},l,d)}_reduceValues(u,l,d={},f){let g=e.nil;for(const p in u){const y=u[p];if(!y)continue;const w=d[p]=d[p]||new Map;y.forEach(h=>{if(w.has(h))return;w.set(h,r.Started);let v=l(h);if(v){const b=this.opts.es5?t.varKinds.var:t.varKinds.const;g=(0,e._)`${g}${b} ${h} = ${v};${this.opts._n}`}else if(v=f==null?void 0:f(h))g=(0,e._)`${g}${v}${this.opts._n}`;else throw new n(h);w.set(h,r.Completed)})}return g}}t.ValueScope=a})(Au);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=gs,n=Au;var r=gs;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}});var o=Au;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(m,$){return this}}class i extends s{constructor(m,$,O){super(),this.varKind=m,this.name=$,this.rhs=O}render({es5:m,_n:$}){const O=m?n.varKinds.var:this.varKind,x=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${x};`+$}optimizeNames(m,$){if(m[this.name.str])return this.rhs&&(this.rhs=fe(this.rhs,m,$)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(m,$,O){super(),this.lhs=m,this.rhs=$,this.sideEffects=O}render({_n:m}){return`${this.lhs} = ${this.rhs};`+m}optimizeNames(m,$){if(!(this.lhs instanceof e.Name&&!m[this.lhs.str]&&!this.sideEffects))return this.rhs=fe(this.rhs,m,$),this}get names(){const m=this.lhs instanceof e.Name?{}:{...this.lhs.names};return ue(m,this.rhs)}}class c extends a{constructor(m,$,O,x){super(m,O,x),this.op=$}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 l extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`break${this.label?` ${this.label}`:""};`+m}}class d extends s{constructor(m){super(),this.error=m}render({_n:m}){return`throw ${this.error};`+m}get names(){return this.error.names}}class f extends s{constructor(m){super(),this.code=m}render({_n:m}){return`${this.code};`+m}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(m,$){return this.code=fe(this.code,m,$),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class g extends s{constructor(m=[]){super(),this.nodes=m}render(m){return this.nodes.reduce(($,O)=>$+O.render(m),"")}optimizeNodes(){const{nodes:m}=this;let $=m.length;for(;$--;){const O=m[$].optimizeNodes();Array.isArray(O)?m.splice($,1,...O):O?m[$]=O:m.splice($,1)}return m.length>0?this:void 0}optimizeNames(m,$){const{nodes:O}=this;let x=O.length;for(;x--;){const R=O[x];R.optimizeNames(m,$)||(he(m,R.names),O.splice(x,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((m,$)=>Z(m,$.names),{})}}class p extends g{render(m){return"{"+m._n+super.render(m)+"}"+m._n}}class y extends g{}class w extends p{}w.kind="else";class h extends p{constructor(m,$){super($),this.condition=m}render(m){let $=`if(${this.condition})`+super.render(m);return this.else&&($+="else "+this.else.render(m)),$}optimizeNodes(){super.optimizeNodes();const m=this.condition;if(m===!0)return this.nodes;let $=this.else;if($){const O=$.optimizeNodes();$=this.else=Array.isArray(O)?new w(O):O}if($)return m===!1?$ instanceof h?$:$.nodes:this.nodes.length?this:new h(pe(m),$ instanceof h?[$]:$.nodes);if(!(m===!1||!this.nodes.length))return this}optimizeNames(m,$){var O;if(this.else=(O=this.else)===null||O===void 0?void 0:O.optimizeNames(m,$),!!(super.optimizeNames(m,$)||this.else))return this.condition=fe(this.condition,m,$),this}get names(){const m=super.names;return ue(m,this.condition),this.else&&Z(m,this.else.names),m}}h.kind="if";class v extends p{}v.kind="for";class b extends v{constructor(m){super(),this.iteration=m}render(m){return`for(${this.iteration})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iteration=fe(this.iteration,m,$),this}get names(){return Z(super.names,this.iteration.names)}}class E extends v{constructor(m,$,O,x){super(),this.varKind=m,this.name=$,this.from=O,this.to=x}render(m){const $=m.es5?n.varKinds.var:this.varKind,{name:O,from:x,to:R}=this;return`for(${$} ${O}=${x}; ${O}<${R}; ${O}++)`+super.render(m)}get names(){const m=ue(super.names,this.from);return ue(m,this.to)}}class N extends v{constructor(m,$,O,x){super(),this.loop=m,this.varKind=$,this.name=O,this.iterable=x}render(m){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iterable=fe(this.iterable,m,$),this}get names(){return Z(super.names,this.iterable.names)}}class j extends p{constructor(m,$,O){super(),this.name=m,this.args=$,this.async=O}render(m){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(m)}}j.kind="func";class T extends g{render(m){return"return "+super.render(m)}}T.kind="return";class M extends p{render(m){let $="try"+super.render(m);return this.catch&&($+=this.catch.render(m)),this.finally&&($+=this.finally.render(m)),$}optimizeNodes(){var m,$;return super.optimizeNodes(),(m=this.catch)===null||m===void 0||m.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(m,$){var O,x;return super.optimizeNames(m,$),(O=this.catch)===null||O===void 0||O.optimizeNames(m,$),(x=this.finally)===null||x===void 0||x.optimizeNames(m,$),this}get names(){const m=super.names;return this.catch&&Z(m,this.catch.names),this.finally&&Z(m,this.finally.names),m}}class C extends p{constructor(m){super(),this.error=m}render(m){return`catch(${this.error})`+super.render(m)}}C.kind="catch";class G extends p{render(m){return"finally"+super.render(m)}}G.kind="finally";class H{constructor(m,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
347
|
+
`:""},this._extScope=m,this._scope=new n.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,$){const O=this._extScope.value(m,$);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(m,$){return this._extScope.getValue(m,$)}scopeRefs(m){return this._extScope.scopeRefs(m,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(m,$,O,x){const R=this._scope.toName($);return O!==void 0&&x&&(this._constants[R.str]=O),this._leafNode(new i(m,R,O)),R}const(m,$,O){return this._def(n.varKinds.const,m,$,O)}let(m,$,O){return this._def(n.varKinds.let,m,$,O)}var(m,$,O){return this._def(n.varKinds.var,m,$,O)}assign(m,$,O){return this._leafNode(new a(m,$,O))}add(m,$){return this._leafNode(new c(m,t.operators.ADD,$))}code(m){return typeof m=="function"?m():m!==e.nil&&this._leafNode(new f(m)),this}object(...m){const $=["{"];for(const[O,x]of m)$.length>1&&$.push(","),$.push(O),(O!==x||this.opts.es5)&&($.push(":"),(0,e.addCodeArg)($,x));return $.push("}"),new e._Code($)}if(m,$,O){if(this._blockNode(new h(m)),$&&O)this.code($).else().code(O).endIf();else if($)this.code($).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(m){return this._elseNode(new h(m))}else(){return this._elseNode(new w)}endIf(){return this._endBlockNode(h,w)}_for(m,$){return this._blockNode(m),$&&this.code($).endFor(),this}for(m,$){return this._for(new b(m),$)}forRange(m,$,O,x,R=this.opts.es5?n.varKinds.var:n.varKinds.let){const U=this._scope.toName(m);return this._for(new E(R,U,$,O),()=>x(U))}forOf(m,$,O,x=n.varKinds.const){const R=this._scope.toName(m);if(this.opts.es5){const U=$ instanceof e.Name?$:this.var("_arr",$);return this.forRange("_i",0,(0,e._)`${U}.length`,q=>{this.var(R,(0,e._)`${U}[${q}]`),O(R)})}return this._for(new N("of",x,R,$),()=>O(R))}forIn(m,$,O,x=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(m,(0,e._)`Object.keys(${$})`,O);const R=this._scope.toName(m);return this._for(new N("in",x,R,$),()=>O(R))}endFor(){return this._endBlockNode(v)}label(m){return this._leafNode(new u(m))}break(m){return this._leafNode(new l(m))}return(m){const $=new T;if(this._blockNode($),this.code(m),$.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(m,$,O){if(!$&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');const x=new M;if(this._blockNode(x),this.code(m),$){const R=this.name("e");this._currNode=x.catch=new C(R),$(R)}return O&&(this._currNode=x.finally=new G,this.code(O)),this._endBlockNode(C,G)}throw(m){return this._leafNode(new d(m))}block(m,$){return this._blockStarts.push(this._nodes.length),m&&this.code(m).endBlock($),this}endBlock(m){const $=this._blockStarts.pop();if($===void 0)throw new Error("CodeGen: not in self-balancing block");const O=this._nodes.length-$;if(O<0||m!==void 0&&O!==m)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${m} expected`);return this._nodes.length=$,this}func(m,$=e.nil,O,x){return this._blockNode(new j(m,$,O)),x&&this.code(x).endFunc(),this}endFunc(){return this._endBlockNode(j)}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,$){const O=this._currNode;if(O instanceof m||$&&O instanceof $)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${$?`${m.kind}/${$.kind}`:m.kind}"`)}_elseNode(m){const $=this._currNode;if(!($ instanceof h))throw new Error('CodeGen: "else" without "if"');return this._currNode=$.else=m,this}get _root(){return this._nodes[0]}get _currNode(){const m=this._nodes;return m[m.length-1]}set _currNode(m){const $=this._nodes;$[$.length-1]=m}}t.CodeGen=H;function Z(_,m){for(const $ in m)_[$]=(_[$]||0)+(m[$]||0);return _}function ue(_,m){return m instanceof e._CodeOrName?Z(_,m.names):_}function fe(_,m,$){if(_ instanceof e.Name)return O(_);if(!x(_))return _;return new e._Code(_._items.reduce((R,U)=>(U instanceof e.Name&&(U=O(U)),U instanceof e._Code?R.push(...U._items):R.push(U),R),[]));function O(R){const U=$[R.str];return U===void 0||m[R.str]!==1?R:(delete m[R.str],U)}function x(R){return R instanceof e._Code&&R._items.some(U=>U instanceof e.Name&&m[U.str]===1&&$[U.str]!==void 0)}}function he(_,m){for(const $ in m)_[$]=(_[$]||0)-(m[$]||0)}function pe(_){return typeof _=="boolean"||typeof _=="number"||_===null?!_:(0,e._)`!${k(_)}`}t.not=pe;const Oe=S(t.operators.AND);function gt(..._){return _.reduce(Oe)}t.and=gt;const ut=S(t.operators.OR);function A(..._){return _.reduce(ut)}t.or=A;function S(_){return(m,$)=>m===e.nil?$:$===e.nil?m:(0,e._)`${k(m)} ${_} ${k($)}`}function k(_){return _ instanceof e.Name?_:(0,e._)`(${_})`}})(ce);var V={};Object.defineProperty(V,"__esModule",{value:!0});V.checkStrictMode=V.getErrorPath=V.Type=V.useFunc=V.setEvaluated=V.evaluatedPropsToName=V.mergeEvaluated=V.eachItem=V.unescapeJsonPointer=V.escapeJsonPointer=V.escapeFragment=V.unescapeFragment=V.schemaRefOrVal=V.schemaHasRulesButRef=V.schemaHasRules=V.checkUnknownRules=V.alwaysValidSchema=V.toHash=void 0;const we=ce,DR=gs;function UR(t){const e={};for(const n of t)e[n]=!0;return e}V.toHash=UR;function BR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(k$(t,e),!j$(e,t.self.RULES.all))}V.alwaysValidSchema=BR;function k$(t,e=t.schema){const{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;const o=r.RULES.keywords;for(const s in e)o[s]||P$(t,`unknown keyword: "${s}"`)}V.checkUnknownRules=k$;function j$(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(e[n])return!0;return!1}V.schemaHasRules=j$;function FR(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}V.schemaHasRulesButRef=FR;function qR({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,we._)`${n}`}return(0,we._)`${t}${e}${(0,we.getProperty)(r)}`}V.schemaRefOrVal=qR;function KR(t){return A$(decodeURIComponent(t))}V.unescapeFragment=KR;function VR(t){return encodeURIComponent(Wd(t))}V.escapeFragment=VR;function Wd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}V.escapeJsonPointer=Wd;function A$(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}V.unescapeJsonPointer=A$;function GR(t,e){if(Array.isArray(t))for(const n of t)e(n);else e(t)}V.eachItem=GR;function um({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):n(s,i);return a===we.Name&&!(c instanceof we.Name)?r(o,c):c}}V.mergeEvaluated={props:um({mergeNames:(t,e,n)=>t.if((0,we._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,we._)`${n} || {}`).code((0,we._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,we._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,we._)`${n} || {}`),Hd(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:I$}),items:um({mergeNames:(t,e,n)=>t.if((0,we._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,we._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,we._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,we._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function I$(t,e){if(e===!0)return t.var("props",!0);const n=t.var("props",(0,we._)`{}`);return e!==void 0&&Hd(t,n,e),n}V.evaluatedPropsToName=I$;function Hd(t,e,n){Object.keys(n).forEach(r=>t.assign((0,we._)`${e}${(0,we.getProperty)(r)}`,!0))}V.setEvaluated=Hd;const lm={};function zR(t,e){return t.scopeValue("func",{ref:e,code:lm[e.code]||(lm[e.code]=new DR._Code(e.code))})}V.useFunc=zR;var Iu;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Iu||(V.Type=Iu={}));function WR(t,e,n){if(t instanceof we.Name){const r=e===Iu.Num;return n?r?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:r?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,we.getProperty)(t).toString():"/"+Wd(t)}V.getErrorPath=WR;function P$(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}V.checkStrictMode=P$;var Ft={};Object.defineProperty(Ft,"__esModule",{value:!0});const Ge=ce,HR={data:new Ge.Name("data"),valCxt:new Ge.Name("valCxt"),instancePath:new Ge.Name("instancePath"),parentData:new Ge.Name("parentData"),parentDataProperty:new Ge.Name("parentDataProperty"),rootData:new Ge.Name("rootData"),dynamicAnchors:new Ge.Name("dynamicAnchors"),vErrors:new Ge.Name("vErrors"),errors:new Ge.Name("errors"),this:new Ge.Name("this"),self:new Ge.Name("self"),scope:new Ge.Name("scope"),json:new Ge.Name("json"),jsonPos:new Ge.Name("jsonPos"),jsonLen:new Ge.Name("jsonLen"),jsonPart:new Ge.Name("jsonPart")};Ft.default=HR;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=ce,n=V,r=Ft;t.keywordError={message:({keyword:w})=>(0,e.str)`must pass "${w}" keyword validation`},t.keyword$DataError={message:({keyword:w,schemaType:h})=>h?(0,e.str)`"${w}" keyword must be ${h} ($data)`:(0,e.str)`"${w}" keyword is invalid ($data)`};function o(w,h=t.keywordError,v,b){const{it:E}=w,{gen:N,compositeRule:j,allErrors:T}=E,M=d(w,h,v);b??(j||T)?c(N,M):u(E,(0,e._)`[${M}]`)}t.reportError=o;function s(w,h=t.keywordError,v){const{it:b}=w,{gen:E,compositeRule:N,allErrors:j}=b,T=d(w,h,v);c(E,T),N||j||u(b,r.default.vErrors)}t.reportExtraError=s;function i(w,h){w.assign(r.default.errors,h),w.if((0,e._)`${r.default.vErrors} !== null`,()=>w.if(h,()=>w.assign((0,e._)`${r.default.vErrors}.length`,h),()=>w.assign(r.default.vErrors,null)))}t.resetErrorsCount=i;function a({gen:w,keyword:h,schemaValue:v,data:b,errsCount:E,it:N}){if(E===void 0)throw new Error("ajv implementation error");const j=w.name("err");w.forRange("i",E,r.default.errors,T=>{w.const(j,(0,e._)`${r.default.vErrors}[${T}]`),w.if((0,e._)`${j}.instancePath === undefined`,()=>w.assign((0,e._)`${j}.instancePath`,(0,e.strConcat)(r.default.instancePath,N.errorPath))),w.assign((0,e._)`${j}.schemaPath`,(0,e.str)`${N.errSchemaPath}/${h}`),N.opts.verbose&&(w.assign((0,e._)`${j}.schema`,v),w.assign((0,e._)`${j}.data`,b))})}t.extendErrors=a;function c(w,h){const v=w.const("err",h);w.if((0,e._)`${r.default.vErrors} === null`,()=>w.assign(r.default.vErrors,(0,e._)`[${v}]`),(0,e._)`${r.default.vErrors}.push(${v})`),w.code((0,e._)`${r.default.errors}++`)}function u(w,h){const{gen:v,validateName:b,schemaEnv:E}=w;E.$async?v.throw((0,e._)`new ${w.ValidationError}(${h})`):(v.assign((0,e._)`${b}.errors`,h),v.return(!1))}const l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(w,h,v){const{createErrors:b}=w.it;return b===!1?(0,e._)`{}`:f(w,h,v)}function f(w,h,v={}){const{gen:b,it:E}=w,N=[g(E,v),p(w,v)];return y(w,h,N),b.object(...N)}function g({errorPath:w},{instancePath:h}){const v=h?(0,e.str)`${w}${(0,n.getErrorPath)(h,n.Type.Str)}`:w;return[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,v)]}function p({keyword:w,it:{errSchemaPath:h}},{schemaPath:v,parentSchema:b}){let E=b?h:(0,e.str)`${h}/${w}`;return v&&(E=(0,e.str)`${E}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,E]}function y(w,{params:h,message:v},b){const{keyword:E,data:N,schemaValue:j,it:T}=w,{opts:M,propertyName:C,topSchemaRef:G,schemaPath:H}=T;b.push([l.keyword,E],[l.params,typeof h=="function"?h(w):h||(0,e._)`{}`]),M.messages&&b.push([l.message,typeof v=="function"?v(w):v]),M.verbose&&b.push([l.schema,j],[l.parentSchema,(0,e._)`${G}${H}`],[r.default.data,N]),C&&b.push([l.propertyName,C])}})(ks);Object.defineProperty(oo,"__esModule",{value:!0});oo.boolOrEmptySchema=oo.topBoolOrEmptySchema=void 0;const JR=ks,QR=ce,YR=Ft,ZR={message:"boolean schema is false"};function XR(t){const{gen:e,schema:n,validateName:r}=t;n===!1?x$(t,!1):typeof n=="object"&&n.$async===!0?e.return(YR.default.data):(e.assign((0,QR._)`${r}.errors`,null),e.return(!0))}oo.topBoolOrEmptySchema=XR;function eT(t,e){const{gen:n,schema:r}=t;r===!1?(n.var(e,!1),x$(t)):n.var(e,!0)}oo.boolOrEmptySchema=eT;function x$(t,e){const{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,JR.reportError)(o,ZR,void 0,e)}var Ie={},vr={};Object.defineProperty(vr,"__esModule",{value:!0});vr.getRules=vr.isJSONType=void 0;const tT=["string","number","integer","boolean","null","object","array"],nT=new Set(tT);function rT(t){return typeof t=="string"&&nT.has(t)}vr.isJSONType=rT;function oT(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}vr.getRules=oT;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.shouldUseRule=Xt.shouldUseGroup=Xt.schemaHasRulesForType=void 0;function sT({schema:t,self:e},n){const r=e.RULES.types[n];return r&&r!==!0&&R$(t,r)}Xt.schemaHasRulesForType=sT;function R$(t,e){return e.rules.some(n=>T$(t,n))}Xt.shouldUseGroup=R$;function T$(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Xt.shouldUseRule=T$;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;const iT=vr,aT=Xt,cT=ks,ne=ce,C$=V;var Hr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Hr||(Ie.DataType=Hr={}));function uT(t){const e=M$(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ie.getSchemaTypes=uT;function M$(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(iT.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ie.getJSONTypes=M$;function lT(t,e){const{gen:n,data:r,opts:o}=t,s=dT(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,aT.schemaHasRulesForType)(t,e[0]));if(i){const a=Jd(e,r,o.strictNumbers,Hr.Wrong);n.if(a,()=>{s.length?fT(t,e,s):Qd(t)})}return i}Ie.coerceAndCheckDataType=lT;const L$=new Set(["string","number","integer","boolean","null"]);function dT(t,e){return e?t.filter(n=>L$.has(n)||e==="array"&&n==="array"):[]}function fT(t,e,n){const{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(Jd(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(const u of n)(L$.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Qd(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),pT(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null
|
|
348
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ne._)`+${o}`);return;case"integer":r.elseIf((0,ne._)`${i} === "boolean" || ${o} === null
|
|
349
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ne._)`+${o}`);return;case"boolean":r.elseIf((0,ne._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ne._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ne._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ne._)`${i} === "string" || ${i} === "number"
|
|
350
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function pT({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function Pu(t,e,n,r=Hr.Correct){const o=r===Hr.Correct?ne.operators.EQ:ne.operators.NEQ;let s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===Hr.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}Ie.checkDataType=Pu;function Jd(t,e,n,r){if(t.length===1)return Pu(t[0],e,n,r);let o;const s=(0,C$.toHash)(t);if(s.array&&s.object){const i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(const i in s)o=(0,ne.and)(o,Pu(i,e,n,r));return o}Ie.checkDataTypes=Jd;const hT={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function Qd(t){const e=mT(t);(0,cT.reportError)(e,hT)}Ie.reportTypeError=Qd;function mT(t){const{gen:e,data:n,schema:r}=t,o=(0,C$.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0});Ma.assignDefaults=void 0;const Ir=ce,gT=V;function yT(t,e){const{properties:n,items:r}=t.schema;if(e==="object"&&n)for(const o in n)dm(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>dm(t,s,o.default))}Ma.assignDefaults=yT;function dm(t,e,n){const{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;const a=(0,Ir._)`${s}${(0,Ir.getProperty)(e)}`;if(o){(0,gT.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ir._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ir._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Ir._)`${a} = ${(0,Ir.stringify)(n)}`)}var Ct={},ie={};Object.defineProperty(ie,"__esModule",{value:!0});ie.validateUnion=ie.validateArray=ie.usePattern=ie.callValidateCode=ie.schemaProperties=ie.allSchemaProperties=ie.noPropertyInData=ie.propertyInData=ie.isOwnProperty=ie.hasPropFunc=ie.reportMissingProp=ie.checkMissingProp=ie.checkReportMissingProp=void 0;const $e=ce,Yd=V,dn=Ft,wT=V;function vT(t,e){const{gen:n,data:r,it:o}=t;n.if(Xd(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,$e._)`${e}`},!0),t.error()})}ie.checkReportMissingProp=vT;function $T({gen:t,data:e,it:{opts:n}},r,o){return(0,$e.or)(...r.map(s=>(0,$e.and)(Xd(t,e,s,n.ownProperties),(0,$e._)`${o} = ${s}`)))}ie.checkMissingProp=$T;function bT(t,e){t.setParams({missingProperty:e},!0),t.error()}ie.reportMissingProp=bT;function D$(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,$e._)`Object.prototype.hasOwnProperty`})}ie.hasPropFunc=D$;function Zd(t,e,n){return(0,$e._)`${D$(t)}.call(${e}, ${n})`}ie.isOwnProperty=Zd;function ET(t,e,n,r){const o=(0,$e._)`${e}${(0,$e.getProperty)(n)} !== undefined`;return r?(0,$e._)`${o} && ${Zd(t,e,n)}`:o}ie.propertyInData=ET;function Xd(t,e,n,r){const o=(0,$e._)`${e}${(0,$e.getProperty)(n)} === undefined`;return r?(0,$e.or)(o,(0,$e.not)(Zd(t,e,n))):o}ie.noPropertyInData=Xd;function U$(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ie.allSchemaProperties=U$;function ST(t,e){return U$(e).filter(n=>!(0,Yd.alwaysValidSchema)(t,e[n]))}ie.schemaProperties=ST;function _T({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,$e._)`${t}, ${e}, ${r}${o}`:e,d=[[dn.default.instancePath,(0,$e.strConcat)(dn.default.instancePath,s)],[dn.default.parentData,i.parentData],[dn.default.parentDataProperty,i.parentDataProperty],[dn.default.rootData,dn.default.rootData]];i.opts.dynamicRef&&d.push([dn.default.dynamicAnchors,dn.default.dynamicAnchors]);const f=(0,$e._)`${l}, ${n.object(...d)}`;return c!==$e.nil?(0,$e._)`${a}.call(${c}, ${f})`:(0,$e._)`${a}(${f})`}ie.callValidateCode=_T;const NT=(0,$e._)`new RegExp`;function OT({gen:t,it:{opts:e}},n){const r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,$e._)`${o.code==="new RegExp"?NT:(0,wT.useFunc)(t,o)}(${n}, ${r})`})}ie.usePattern=OT;function kT(t){const{gen:e,data:n,keyword:r,it:o}=t,s=e.name("valid");if(o.allErrors){const a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){const c=e.const("len",(0,$e._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Yd.Type.Num},s),e.if((0,$e.not)(s),a)})}}ie.validateArray=kT;function jT(t){const{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,Yd.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=e.let("valid",!1),i=e.name("_valid");e.block(()=>n.forEach((a,c)=>{const u=t.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);e.assign(s,(0,$e._)`${s} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,$e.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}ie.validateUnion=jT;Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;const Ze=ce,tr=Ft,AT=ie,IT=ks;function PT(t,e){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=B$(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");t.subschema({schema:a,schemaPath:Ze.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ct.macroKeywordCode=PT;function xT(t,e){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;TT(c,e);const u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=B$(r,o,u),d=r.let("valid");t.block$data(d,f),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function f(){if(e.errors===!1)y(),e.modifying&&fm(t),w(()=>t.error());else{const h=e.async?g():p();e.modifying&&fm(t),w(()=>RT(t,h))}}function g(){const h=r.let("ruleErrs",null);return r.try(()=>y((0,Ze._)`await `),v=>r.assign(d,!1).if((0,Ze._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(h,(0,Ze._)`${v}.errors`),()=>r.throw(v))),h}function p(){const h=(0,Ze._)`${l}.errors`;return r.assign(h,null),y(Ze.nil),h}function y(h=e.async?(0,Ze._)`await `:Ze.nil){const v=c.opts.passContext?tr.default.this:tr.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,Ze._)`${h}${(0,AT.callValidateCode)(t,l,v,b)}`,e.modifying)}function w(h){var v;r.if((0,Ze.not)((v=e.valid)!==null&&v!==void 0?v:d),h)}}Ct.funcKeywordCode=xT;function fm(t){const{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Ze._)`${r.parentData}[${r.parentDataProperty}]`))}function RT(t,e){const{gen:n}=t;n.if((0,Ze._)`Array.isArray(${e})`,()=>{n.assign(tr.default.vErrors,(0,Ze._)`${tr.default.vErrors} === null ? ${e} : ${tr.default.vErrors}.concat(${e})`).assign(tr.default.errors,(0,Ze._)`${tr.default.vErrors}.length`),(0,IT.extendErrors)(t)},()=>t.error())}function TT({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function B$(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Ze.stringify)(n)})}function CT(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ct.validSchemaType=CT;function MT({schema:t,opts:e,self:n,errSchemaPath:r},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(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){const a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}Ct.validateKeywordUsage=MT;var Sn={};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.extendSubschemaMode=Sn.extendSubschemaData=Sn.getSubschema=void 0;const Rt=ce,F$=V;function LT(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Rt._)`${t.schemaPath}${(0,Rt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Rt._)`${t.schemaPath}${(0,Rt.getProperty)(e)}${(0,Rt.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,F$.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Sn.getSubschema=LT;function DT(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,Rt._)`${e.data}${(0,Rt.getProperty)(n)}`,!0);c(f),t.errorPath=(0,Rt.str)`${u}${(0,F$.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Rt._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){const u=o instanceof Rt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Sn.extendSubschemaData=DT;function UT(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Sn.extendSubschemaMode=UT;var De={},q$=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n},K$={exports:{}},vn=K$.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Pi(e,r,o,t,"",t)};vn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};vn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};vn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};vn.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 Pi(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in vn.arrayKeywords)for(var f=0;f<d.length;f++)Pi(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in vn.propsKeywords){if(d&&typeof d=="object")for(var g in d)Pi(t,e,n,d[g],o+"/"+l+"/"+BT(g),s,o,l,r,g)}else(l in vn.keywords||t.allKeys&&!(l in vn.skipKeywords))&&Pi(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function BT(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var FT=K$.exports;Object.defineProperty(De,"__esModule",{value:!0});De.getSchemaRefs=De.resolveUrl=De.normalizeId=De._getFullPath=De.getFullPath=De.inlineRef=void 0;const qT=V,KT=q$,VT=FT,GT=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function zT(t,e=!0){return typeof t=="boolean"?!0:e===!0?!xu(t):e?V$(t)<=e:!1}De.inlineRef=zT;const WT=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function xu(t){for(const e in t){if(WT.has(e))return!0;const n=t[e];if(Array.isArray(n)&&n.some(xu)||typeof n=="object"&&xu(n))return!0}return!1}function V$(t){let e=0;for(const n in t)if(n==="$ref"||(e++,!GT.has(n)&&(typeof t[n]=="object"&&(0,qT.eachItem)(t[n],r=>e+=V$(r)),e===1/0)))return 1/0;return e}function G$(t,e="",n){n!==!1&&(e=Jr(e));const r=t.parse(e);return z$(t,r)}De.getFullPath=G$;function z$(t,e){return t.serialize(e).split("#")[0]+"#"}De._getFullPath=z$;const HT=/#\/?$/;function Jr(t){return t?t.replace(HT,""):""}De.normalizeId=Jr;function JT(t,e,n){return n=Jr(n),t.resolve(e,n)}De.resolveUrl=JT;const QT=/^[a-z_][-a-z0-9._]*$/i;function YT(t,e){if(typeof t=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Jr(t[n]||e),s={"":o},i=G$(r,o,!1),a={},c=new Set;return VT(t,{allKeys:!0},(d,f,g,p)=>{if(p===void 0)return;const y=i+f;let w=s[p];typeof d[n]=="string"&&(w=h.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=w;function h(b){const E=this.opts.uriResolver.resolve;if(b=Jr(w?E(w,b):b),c.has(b))throw l(b);c.add(b);let N=this.refs[b];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(d,N.schema,b):b!==Jr(y)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=y),b}function v(b){if(typeof b=="string"){if(!QT.test(b))throw new Error(`invalid anchor "${b}"`);h.call(this,`#${b}`)}}}),a;function u(d,f,g){if(f!==void 0&&!KT(d,f))throw l(g)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}De.getSchemaRefs=YT;Object.defineProperty(kt,"__esModule",{value:!0});kt.getData=kt.KeywordCxt=kt.validateFunctionCode=void 0;const W$=oo,pm=Ie,ef=Xt,Xi=Ie,ZT=Ma,Jo=Ct,mc=Sn,W=ce,Y=Ft,XT=De,en=V,So=ks;function eC(t){if(Q$(t)&&(Y$(t),J$(t))){rC(t);return}H$(t,()=>(0,W$.topBoolOrEmptySchema)(t))}kt.validateFunctionCode=eC;function H$({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,W._)`${Y.default.data}, ${Y.default.valCxt}`,r.$async,()=>{t.code((0,W._)`"use strict"; ${hm(n,o)}`),nC(t,o),t.code(s)}):t.func(e,(0,W._)`${Y.default.data}, ${tC(o)}`,r.$async,()=>t.code(hm(n,o)).code(s))}function tC(t){return(0,W._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,W._)`, ${Y.default.dynamicAnchors}={}`:W.nil}}={}`}function nC(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,W._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,W._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,W._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,W._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,W._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,W._)`""`),t.var(Y.default.parentData,(0,W._)`undefined`),t.var(Y.default.parentDataProperty,(0,W._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,W._)`{}`)})}function rC(t){const{schema:e,opts:n,gen:r}=t;H$(t,()=>{n.$comment&&e.$comment&&X$(t),cC(t),r.let(Y.default.vErrors,null),r.let(Y.default.errors,0),n.unevaluated&&oC(t),Z$(t),dC(t)})}function oC(t){const{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,W._)`${n}.evaluated`),e.if((0,W._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,W._)`${t.evaluated}.props`,(0,W._)`undefined`)),e.if((0,W._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,W._)`${t.evaluated}.items`,(0,W._)`undefined`))}function hm(t,e){const n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,W._)`/*# sourceURL=${n} */`:W.nil}function sC(t,e){if(Q$(t)&&(Y$(t),J$(t))){iC(t,e);return}(0,W$.boolOrEmptySchema)(t,e)}function J$({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const n in t)if(e.RULES.all[n])return!0;return!1}function Q$(t){return typeof t.schema!="boolean"}function iC(t,e){const{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&X$(t),uC(t),lC(t);const s=r.const("_errs",Y.default.errors);Z$(t,s),r.var(e,(0,W._)`${s} === ${Y.default.errors}`)}function Y$(t){(0,en.checkUnknownRules)(t),aC(t)}function Z$(t,e){if(t.opts.jtd)return mm(t,[],!1,e);const n=(0,pm.getSchemaTypes)(t.schema),r=(0,pm.coerceAndCheckDataType)(t,n);mm(t,n,!r,e)}function aC(t){const{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,en.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function cC(t){const{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,en.checkStrictMode)(t,"default is ignored in the schema root")}function uC(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,XT.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function lC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function X$({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)t.code((0,W._)`${Y.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,W.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,W._)`${Y.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function dC(t){const{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,W._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,W._)`new ${o}(${Y.default.vErrors})`)):(e.assign((0,W._)`${r}.errors`,Y.default.vErrors),s.unevaluated&&fC(t),e.return((0,W._)`${Y.default.errors} === 0`))}function fC({gen:t,evaluated:e,props:n,items:r}){n instanceof W.Name&&t.assign((0,W._)`${e}.props`,n),r instanceof W.Name&&t.assign((0,W._)`${e}.items`,r)}function mm(t,e,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,en.schemaHasRulesButRef)(s,l))){o.block(()=>n0(t,"$ref",l.all.$ref.definition));return}c.jtd||pC(t,e),o.block(()=>{for(const f of l.rules)d(f);d(l.post)});function d(f){(0,ef.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Xi.checkDataType)(f.type,i,c.strictNumbers)),gm(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,Xi.reportTypeError)(t)),o.endIf()):gm(t,f),a||o.if((0,W._)`${Y.default.errors} === ${r||0}`))}}function gm(t,e){const{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,ZT.assignDefaults)(t,e.type),n.block(()=>{for(const s of e.rules)(0,ef.shouldUseRule)(r,s)&&n0(t,s.keyword,s.definition,e.type)})}function pC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(hC(t,e),t.opts.allowUnionTypes||mC(t,e),gC(t,t.dataTypes))}function hC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{e0(t.dataTypes,n)||tf(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),wC(t,e)}}function mC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&tf(t,"use allowUnionTypes to allow union type keyword")}function gC(t,e){const n=t.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,ef.shouldUseRule)(t.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>yC(e,i))&&tf(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function yC(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function e0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function wC(t,e){const n=[];for(const r of t.dataTypes)e0(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function tf(t,e){const n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,en.checkStrictMode)(t,e,t.opts.strictTypes)}class t0{constructor(e,n,r){if((0,Jo.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,en.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",r0(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Jo.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Y.default.errors))}result(e,n,r){this.failResult((0,W.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,W.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:n}=this;this.fail((0,W._)`${n} !== undefined && (${(0,W.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?So.reportExtraError:So.reportError)(this,this.def.error,n)}$dataError(){(0,So.reportError)(this,this.def.$dataError||So.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,So.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=W.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=W.nil,n=W.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,W.or)((0,W._)`${o} === undefined`,n)),e!==W.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==W.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,W.or)(i(),a());function i(){if(r.length){if(!(n instanceof W.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,W._)`${(0,Xi.checkDataTypes)(c,n,s.opts.strictNumbers,Xi.DataType.Wrong)}`}return W.nil}function a(){if(o.validateSchema){const c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,W._)`!${c}(${n})`}return W.nil}}subschema(e,n){const r=(0,mc.getSubschema)(this.it,e);(0,mc.extendSubschemaData)(r,this.it,e),(0,mc.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return sC(o,n),o}mergeEvaluated(e,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=en.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=en.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,W.Name)),!0}}kt.KeywordCxt=t0;function n0(t,e,n,r){const o=new t0(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Jo.funcKeywordCode)(o,n):"macro"in n?(0,Jo.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Jo.funcKeywordCode)(o,n)}const vC=/^\/(?:[^~]|~0|~1)*$/,$C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function r0(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!vC.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=Y.default.rootData}else{const u=$C.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,W._)`${s}${(0,W.getProperty)((0,en.unescapeJsonPointer)(u))}`,i=(0,W._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}kt.getData=r0;var js={};Object.defineProperty(js,"__esModule",{value:!0});let bC=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};js.default=bC;var ho={};Object.defineProperty(ho,"__esModule",{value:!0});const gc=De;class EC extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,gc.resolveUrl)(e,n,r),this.missingSchema=(0,gc.normalizeId)((0,gc.getFullPath)(e,this.missingRef))}}ho.default=EC;var at={};Object.defineProperty(at,"__esModule",{value:!0});at.resolveSchema=at.getCompilingSchema=at.resolveRef=at.compileSchema=at.SchemaEnv=void 0;const vt=ce,SC=js,zn=Ft,St=De,ym=V,_C=kt;class La{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,St.normalizeId)(r==null?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}at.SchemaEnv=La;function nf(t){const e=o0.call(this,t);if(e)return e;const n=(0,St.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;t.$async&&(a=i.scopeValue("Error",{ref:SC.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");t.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:zn.default.data,parentData:zn.default.parentData,parentDataProperty:zn.default.parentDataProperty,dataNames:[zn.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(t),(0,_C.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const d=i.toString();l=`${i.scopeRefs(zn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));const f=new Function(`${zn.default.self}`,`${zn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){const{props:g,items:p}=u;f.evaluated={props:g instanceof vt.Name?void 0:g,items:p instanceof vt.Name?void 0:p,dynamicProps:g instanceof vt.Name,dynamicItems:p instanceof vt.Name},f.source&&(f.source.evaluated=(0,vt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}at.compileSchema=nf;function NC(t,e,n){var r;n=(0,St.resolveUrl)(this.opts.uriResolver,e,n);const o=t.refs[n];if(o)return o;let s=jC.call(this,t,n);if(s===void 0){const i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new La({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=OC.call(this,s)}at.resolveRef=NC;function OC(t){return(0,St.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:nf.call(this,t)}function o0(t){for(const e of this._compilations)if(kC(e,t))return e}at.getCompilingSchema=o0;function kC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function jC(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Da.call(this,t,e)}function Da(t,e){const n=this.opts.uriResolver.parse(e),r=(0,St._getFullPath)(this.opts.uriResolver,n);let o=(0,St.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return yc.call(this,n,t);const s=(0,St.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Da.call(this,t,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:yc.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||nf.call(this,i),s===(0,St.normalizeId)(e)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,St.resolveUrl)(this.opts.uriResolver,o,u)),new La({schema:a,schemaId:c,root:t,baseId:o})}return yc.call(this,n,i)}}at.resolveSchema=Da;const AC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function yc(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,ym.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!AC.has(a)&&u&&(e=(0,St.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,ym.schemaHasRulesButRef)(n,this.RULES)){const a=(0,St.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=Da.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new La({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}const IC="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",PC="Meta-schema for $data reference (JSON AnySchema extension proposal)",xC="object",RC=["$data"],TC={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},CC=!1,MC={$id:IC,description:PC,type:xC,required:RC,properties:TC,additionalProperties:CC};var rf={},Ua={exports:{}};const LC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),s0=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),of=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),i0=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),DC=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function a0(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}const UC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wm(t){return t.length=0,!0}function BC(t,e,n){if(t.length){const r=a0(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function FC(t){let e=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=BC;for(let c=0;c<t.length;c++){const u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=wm}else{o.push(u);continue}}return o.length&&(a===wm?n.zone=o.join(""):i?r.push(o.join("")):r.push(a0(o))),n.address=r.join(""),n}function c0(t){if(qC(t,":")<2)return{host:t,isIPV6:!1};const e=FC(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function qC(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function KC(t){let e=t;const n=[];let r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}const VC={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},GC=/[@/?#:]/g,zC=/[@/?#]/g;function u0(t,e){const n=e?zC:GC;return n.lastIndex=0,t.replace(n,r=>VC[r])}function WC(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){const o=t.slice(r+1,r+3);if(of(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&i0(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function HC(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(of(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&i0(s)?e+=s:e+="%"+o,n+=2;continue}}DC(t[n])?e+=t[n]:e+=escape(t[n])}return e}function JC(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(of(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function QC(t){const e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!s0(n)){const r=c0(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=u0(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}var l0={nonSimpleDomain:UC,recomposeAuthority:QC,reescapeHostDelimiters:u0,normalizePercentEncoding:WC,normalizePathEncoding:HC,escapePreservingEscapes:JC,removeDotSegments:KC,isIPv4:s0,isUUID:LC,normalizeIPv6:c0};const{isUUID:YC}=l0,ZC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function d0(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function f0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function p0(t){const e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function XC(t){return t.secure=d0(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function eM(t){if((t.port===(d0(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){const[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function tM(t,e){if(!t.path)return t.error="URN can not be parsed",t;const n=t.path.match(ZC);if(n){const r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];const o=`${r}:${e.nid||t.nid}`,s=sf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function nM(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=sf(o);s&&(t=s.serialize(t,e));const i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function rM(t,e){const n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!YC(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function oM(t){const e=t;return e.nss=(t.uuid||"").toLowerCase(),e}const h0={scheme:"http",domainHost:!0,parse:f0,serialize:p0},sM={scheme:"https",domainHost:h0.domainHost,parse:f0,serialize:p0},xi={scheme:"ws",domainHost:!0,parse:XC,serialize:eM},iM={scheme:"wss",domainHost:xi.domainHost,parse:xi.parse,serialize:xi.serialize},aM={scheme:"urn",parse:tM,serialize:nM,skipNormalize:!0},cM={scheme:"urn:uuid",parse:rM,serialize:oM,skipNormalize:!0},ea={http:h0,https:sM,ws:xi,wss:iM,urn:aM,"urn:uuid":cM};Object.setPrototypeOf(ea,null);function sf(t){return t&&(ea[t]||ea[t.toLowerCase()])||void 0}var uM={SCHEMES:ea,getSchemeHandler:sf};const{normalizeIPv6:lM,removeDotSegments:Ro,recomposeAuthority:dM,normalizePercentEncoding:fM,normalizePathEncoding:pM,escapePreservingEscapes:hM,reescapeHostDelimiters:mM,isIPv4:gM,nonSimpleDomain:yM}=l0,{SCHEMES:wM,getSchemeHandler:m0}=uM;function vM(t,e){return typeof t=="string"?t=NM(t,e):typeof t=="object"&&(t=so($r(t,e),e)),t}function $M(t,e,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=g0(so(t,r),so(e,r),r,!0);return r.skipEscape=!0,$r(o,r)}function g0(t,e,n,r){const o={};return r||(t=so($r(t,n),n),e=so($r(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ro(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ro(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ro(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Ro(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function bM(t,e,n){const r=vm(t,n),o=vm(e,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function $r(t,e){const n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],s=m0(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=fM(n.path):(n.path=hM(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=dM(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=Ro(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const EM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,SM=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function _M(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function y0(t,e){const n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1,s=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);const i=t.match(SM);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=t.match(EM);if(a){r.scheme=a[1],r.userinfo=a[3],r.host=a[4],r.port=parseInt(a[5],10),r.path=a[6]||"",r.query=a[7],r.fragment=a[8],isNaN(r.port)&&(r.port=a[5]);const c=_M(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(gM(r.host)===!1){const l=lM(r.host);r.host=l.host.toLowerCase(),s=l.isIPV6}else s=!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 u=m0(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&yM(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(l){r.error=r.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=mM(unescape(r.host),s))),r.path&&(r.path=pM(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}u&&u.parse&&u.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function so(t,e){return y0(t,e).parsed}function NM(t,e){return w0(t,e).normalized}function w0(t,e){const{parsed:n,malformedAuthorityOrPort:r}=y0(t,e);return{normalized:r?t:$r(n,e),malformedAuthorityOrPort:r}}function vm(t,e){if(typeof t=="string"){const{normalized:n,malformedAuthorityOrPort:r}=w0(t,e);return r?void 0:n}if(typeof t=="object")return $r(t,e)}const af={SCHEMES:wM,normalize:vM,resolve:$M,resolveComponent:g0,equal:bM,serialize:$r,parse:so};Ua.exports=af;Ua.exports.default=af;Ua.exports.fastUri=af;var OM=Ua.exports;Object.defineProperty(rf,"__esModule",{value:!0});const v0=OM;v0.code='require("ajv/dist/runtime/uri").default';rf.default=v0;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=kt;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var n=ce;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=js,o=ho,s=vr,i=at,a=ce,c=De,u=Ie,l=V,d=MC,f=rf,g=(A,S)=>new RegExp(A,S);g.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),w={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."},h={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function b(A){var S,k,_,m,$,O,x,R,U,q,re,Qe,jn,An,In,Pn,xn,Rn,Tn,Cn,Mn,Ln,Dn,Un,Bn;const yt=A.strict,Fn=(S=A.code)===null||S===void 0?void 0:S.optimize,wo=Fn===!0||Fn===void 0?1:Fn||0,vo=(_=(k=A.code)===null||k===void 0?void 0:k.regExp)!==null&&_!==void 0?_:g,Ha=(m=A.uriResolver)!==null&&m!==void 0?m:f.default;return{strictSchema:(O=($=A.strictSchema)!==null&&$!==void 0?$:yt)!==null&&O!==void 0?O:!0,strictNumbers:(R=(x=A.strictNumbers)!==null&&x!==void 0?x:yt)!==null&&R!==void 0?R:!0,strictTypes:(q=(U=A.strictTypes)!==null&&U!==void 0?U:yt)!==null&&q!==void 0?q:"log",strictTuples:(Qe=(re=A.strictTuples)!==null&&re!==void 0?re:yt)!==null&&Qe!==void 0?Qe:"log",strictRequired:(An=(jn=A.strictRequired)!==null&&jn!==void 0?jn:yt)!==null&&An!==void 0?An:!1,code:A.code?{...A.code,optimize:wo,regExp:vo}:{optimize:wo,regExp:vo},loopRequired:(In=A.loopRequired)!==null&&In!==void 0?In:v,loopEnum:(Pn=A.loopEnum)!==null&&Pn!==void 0?Pn:v,meta:(xn=A.meta)!==null&&xn!==void 0?xn:!0,messages:(Rn=A.messages)!==null&&Rn!==void 0?Rn:!0,inlineRefs:(Tn=A.inlineRefs)!==null&&Tn!==void 0?Tn:!0,schemaId:(Cn=A.schemaId)!==null&&Cn!==void 0?Cn:"$id",addUsedSchema:(Mn=A.addUsedSchema)!==null&&Mn!==void 0?Mn:!0,validateSchema:(Ln=A.validateSchema)!==null&&Ln!==void 0?Ln:!0,validateFormats:(Dn=A.validateFormats)!==null&&Dn!==void 0?Dn:!0,unicodeRegExp:(Un=A.unicodeRegExp)!==null&&Un!==void 0?Un:!0,int32range:(Bn=A.int32range)!==null&&Bn!==void 0?Bn:!0,uriResolver:Ha}}class E{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...b(S)};const{es5:k,lines:_}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:k,lines:_}),this.logger=Z(S.logger);const m=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,w,S,"NOT SUPPORTED"),N.call(this,h,S,"DEPRECATED","warn"),this._metaOpts=G.call(this),S.formats&&M.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&C.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),T.call(this),S.validateFormats=m}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:k,schemaId:_}=this.opts;let m=d;_==="id"&&(m={...d},m.id=m.$id,delete m.$id),k&&S&&this.addMetaSchema(m,m[_],!1)}defaultMeta(){const{meta:S,schemaId:k}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[k]||S:void 0}validate(S,k){let _;if(typeof S=="string"){if(_=this.getSchema(S),!_)throw new Error(`no schema with key or ref "${S}"`)}else _=this.compile(S);const m=_(k);return"$async"in _||(this.errors=_.errors),m}compile(S,k){const _=this._addSchema(S,k);return _.validate||this._compileSchemaEnv(_)}compileAsync(S,k){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:_}=this.opts;return m.call(this,S,k);async function m(q,re){await $.call(this,q.$schema);const Qe=this._addSchema(q,re);return Qe.validate||O.call(this,Qe)}async function $(q){q&&!this.getSchema(q)&&await m.call(this,{$ref:q},!0)}async function O(q){try{return this._compileSchemaEnv(q)}catch(re){if(!(re instanceof o.default))throw re;return x.call(this,re),await R.call(this,re.missingSchema),O.call(this,q)}}function x({missingSchema:q,missingRef:re}){if(this.refs[q])throw new Error(`AnySchema ${q} is loaded but ${re} cannot be resolved`)}async function R(q){const re=await U.call(this,q);this.refs[q]||await $.call(this,re.$schema),this.refs[q]||this.addSchema(re,q,k)}async function U(q){const re=this._loading[q];if(re)return re;try{return await(this._loading[q]=_(q))}finally{delete this._loading[q]}}}addSchema(S,k,_,m=this.opts.validateSchema){if(Array.isArray(S)){for(const O of S)this.addSchema(O,void 0,_,m);return this}let $;if(typeof S=="object"){const{schemaId:O}=this.opts;if($=S[O],$!==void 0&&typeof $!="string")throw new Error(`schema ${O} must be string`)}return k=(0,c.normalizeId)(k||$),this._checkUnique(k),this.schemas[k]=this._addSchema(S,_,k,m,!0),this}addMetaSchema(S,k,_=this.opts.validateSchema){return this.addSchema(S,k,!0,_),this}validateSchema(S,k){if(typeof S=="boolean")return!0;let _;if(_=S.$schema,_!==void 0&&typeof _!="string")throw new Error("$schema must be a string");if(_=_||this.opts.defaultMeta||this.defaultMeta(),!_)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const m=this.validate(_,S);if(!m&&k){const $="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error($);else throw new Error($)}return m}getSchema(S){let k;for(;typeof(k=j.call(this,S))=="string";)S=k;if(k===void 0){const{schemaId:_}=this.opts,m=new i.SchemaEnv({schema:{},schemaId:_});if(k=i.resolveSchema.call(this,m,S),!k)return;this.refs[S]=k}return k.validate||this._compileSchemaEnv(k)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const k=j.call(this,S);return typeof k=="object"&&this._cache.delete(k.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const k=S;this._cache.delete(k);let _=S[this.opts.schemaId];return _&&(_=(0,c.normalizeId)(_),delete this.schemas[_],delete this.refs[_]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const k of S)this.addKeyword(k);return this}addKeyword(S,k){let _;if(typeof S=="string")_=S,typeof k=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),k.keyword=_);else if(typeof S=="object"&&k===void 0){if(k=S,_=k.keyword,Array.isArray(_)&&!_.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(fe.call(this,_,k),!k)return(0,l.eachItem)(_,$=>he.call(this,$)),this;Oe.call(this,k);const m={...k,type:(0,u.getJSONTypes)(k.type),schemaType:(0,u.getJSONTypes)(k.schemaType)};return(0,l.eachItem)(_,m.type.length===0?$=>he.call(this,$,m):$=>m.type.forEach(O=>he.call(this,$,m,O))),this}getKeyword(S){const k=this.RULES.all[S];return typeof k=="object"?k.definition:!!k}removeKeyword(S){const{RULES:k}=this;delete k.keywords[S],delete k.all[S];for(const _ of k.rules){const m=_.rules.findIndex($=>$.keyword===S);m>=0&&_.rules.splice(m,1)}return this}addFormat(S,k){return typeof k=="string"&&(k=new RegExp(k)),this.formats[S]=k,this}errorsText(S=this.errors,{separator:k=", ",dataVar:_="data"}={}){return!S||S.length===0?"No errors":S.map(m=>`${_}${m.instancePath} ${m.message}`).reduce((m,$)=>m+k+$)}$dataMetaSchema(S,k){const _=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const m of k){const $=m.split("/").slice(1);let O=S;for(const x of $)O=O[x];for(const x in _){const R=_[x];if(typeof R!="object")continue;const{$data:U}=R.definition,q=O[x];U&&q&&(O[x]=ut(q))}}return S}_removeAllSchemas(S,k){for(const _ in S){const m=S[_];(!k||k.test(_))&&(typeof m=="string"?delete S[_]:m&&!m.meta&&(this._cache.delete(m.schema),delete S[_]))}}_addSchema(S,k,_,m=this.opts.validateSchema,$=this.opts.addUsedSchema){let O;const{schemaId:x}=this.opts;if(typeof S=="object")O=S[x];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let R=this._cache.get(S);if(R!==void 0)return R;_=(0,c.normalizeId)(O||_);const U=c.getSchemaRefs.call(this,S,_);return R=new i.SchemaEnv({schema:S,schemaId:x,meta:k,baseId:_,localRefs:U}),this._cache.set(R.schema,R),$&&!_.startsWith("#")&&(_&&this._checkUnique(_),this.refs[_]=R),m&&this.validateSchema(S,!0),R}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):i.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const k=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=k}}}E.ValidationError=r.default,E.MissingRefError=o.default,t.default=E;function N(A,S,k,_="error"){for(const m in A){const $=m;$ in S&&this.logger[_](`${k}: option ${m}. ${A[$]}`)}}function j(A){return A=(0,c.normalizeId)(A),this.schemas[A]||this.refs[A]}function T(){const A=this.opts.schemas;if(A)if(Array.isArray(A))this.addSchema(A);else for(const S in A)this.addSchema(A[S],S)}function M(){for(const A in this.opts.formats){const S=this.opts.formats[A];S&&this.addFormat(A,S)}}function C(A){if(Array.isArray(A)){this.addVocabulary(A);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in A){const k=A[S];k.keyword||(k.keyword=S),this.addKeyword(k)}}function G(){const A={...this.opts};for(const S of p)delete A[S];return A}const H={log(){},warn(){},error(){}};function Z(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 ue=/^[a-z_$][a-z0-9_$:-]*$/i;function fe(A,S){const{RULES:k}=this;if((0,l.eachItem)(A,_=>{if(k.keywords[_])throw new Error(`Keyword ${_} is already defined`);if(!ue.test(_))throw new Error(`Keyword ${_} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function he(A,S,k){var _;const m=S==null?void 0:S.post;if(k&&m)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:$}=this;let O=m?$.post:$.rules.find(({type:R})=>R===k);if(O||(O={type:k,rules:[]},$.rules.push(O)),$.keywords[A]=!0,!S)return;const x={keyword:A,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?pe.call(this,O,x,S.before):O.rules.push(x),$.all[A]=x,(_=S.implements)===null||_===void 0||_.forEach(R=>this.addKeyword(R))}function pe(A,S,k){const _=A.rules.findIndex(m=>m.keyword===k);_>=0?A.rules.splice(_,0,S):(A.rules.push(S),this.logger.warn(`rule ${k} is not defined`))}function Oe(A){let{metaSchema:S}=A;S!==void 0&&(A.$data&&this.opts.$data&&(S=ut(S)),A.validateSchema=this.compile(S,!0))}const gt={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ut(A){return{anyOf:[A,gt]}}})(O$);var cf={},uf={},lf={};Object.defineProperty(lf,"__esModule",{value:!0});const kM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};lf.default=kM;var br={};Object.defineProperty(br,"__esModule",{value:!0});br.callRef=br.getValidate=void 0;const jM=ho,$m=ie,tt=ce,Pr=Ft,bm=at,Xs=V,AM={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();const l=bm.resolveRef.call(c,u,o,n);if(l===void 0)throw new jM.default(r.opts.uriResolver,o,n);if(l instanceof bm.SchemaEnv)return f(l);return g(l);function d(){if(s===u)return Ri(t,i,s,s.$async);const p=e.scopeValue("root",{ref:u});return Ri(t,(0,tt._)`${p}.validate`,u,u.$async)}function f(p){const y=$0(t,p);Ri(t,y,p,p.$async)}function g(p){const y=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,tt.stringify)(p)}:{ref:p}),w=e.name("valid"),h=t.subschema({schema:p,dataTypes:[],schemaPath:tt.nil,topSchemaRef:y,errSchemaPath:n},w);t.mergeEvaluated(h),t.ok(w)}}};function $0(t,e){const{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,tt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}br.getValidate=$0;function Ri(t,e,n,r){const{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Pr.default.this:tt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const p=o.let("valid");o.try(()=>{o.code((0,tt._)`await ${(0,$m.callValidateCode)(t,e,u)}`),g(e),i||o.assign(p,!0)},y=>{o.if((0,tt._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),f(y),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,$m.callValidateCode)(t,e,u),()=>g(e),()=>f(e))}function f(p){const y=(0,tt._)`${p}.errors`;o.assign(Pr.default.vErrors,(0,tt._)`${Pr.default.vErrors} === null ? ${y} : ${Pr.default.vErrors}.concat(${y})`),o.assign(Pr.default.errors,(0,tt._)`${Pr.default.vErrors}.length`)}function g(p){var y;if(!s.opts.unevaluated)return;const w=(y=n==null?void 0:n.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(s.props=Xs.mergeEvaluated.props(o,w.props,s.props));else{const h=o.var("props",(0,tt._)`${p}.evaluated.props`);s.props=Xs.mergeEvaluated.props(o,h,s.props,tt.Name)}if(s.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(s.items=Xs.mergeEvaluated.items(o,w.items,s.items));else{const h=o.var("items",(0,tt._)`${p}.evaluated.items`);s.items=Xs.mergeEvaluated.items(o,h,s.items,tt.Name)}}}br.callRef=Ri;br.default=AM;Object.defineProperty(uf,"__esModule",{value:!0});const IM=lf,PM=br,xM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",IM.default,PM.default];uf.default=xM;var df={},ff={};Object.defineProperty(ff,"__esModule",{value:!0});const ta=ce,fn=ta.operators,na={maximum:{okStr:"<=",ok:fn.LTE,fail:fn.GT},minimum:{okStr:">=",ok:fn.GTE,fail:fn.LT},exclusiveMaximum:{okStr:"<",ok:fn.LT,fail:fn.GTE},exclusiveMinimum:{okStr:">",ok:fn.GT,fail:fn.LTE}},RM={message:({keyword:t,schemaCode:e})=>(0,ta.str)`must be ${na[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ta._)`{comparison: ${na[t].okStr}, limit: ${e}}`},TM={keyword:Object.keys(na),type:"number",schemaType:"number",$data:!0,error:RM,code(t){const{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,ta._)`${n} ${na[e].fail} ${r} || isNaN(${n})`)}};ff.default=TM;var pf={};Object.defineProperty(pf,"__esModule",{value:!0});const Qo=ce,CM={message:({schemaCode:t})=>(0,Qo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Qo._)`{multipleOf: ${t}}`},MM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:CM,code(t){const{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Qo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Qo._)`${i} !== parseInt(${i})`;t.fail$data((0,Qo._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};pf.default=MM;var hf={},mf={};Object.defineProperty(mf,"__esModule",{value:!0});function b0(t){const e=t.length;let n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}mf.default=b0;b0.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(hf,"__esModule",{value:!0});const nr=ce,LM=V,DM=mf,UM={message({keyword:t,schemaCode:e}){const n=t==="maxLength"?"more":"fewer";return(0,nr.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,nr._)`{limit: ${t}}`},BM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:UM,code(t){const{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?nr.operators.GT:nr.operators.LT,i=o.opts.unicode===!1?(0,nr._)`${n}.length`:(0,nr._)`${(0,LM.useFunc)(t.gen,DM.default)}(${n})`;t.fail$data((0,nr._)`${i} ${s} ${r}`)}};hf.default=BM;var gf={};Object.defineProperty(gf,"__esModule",{value:!0});const FM=ie,qM=V,Gr=ce,KM={message:({schemaCode:t})=>(0,Gr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Gr._)`{pattern: ${t}}`},VM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KM,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Gr._)`new RegExp`:(0,qM.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Gr._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,Gr._)`!${l}`)}else{const c=(0,FM.usePattern)(t,o);t.fail$data((0,Gr._)`!${c}.test(${n})`)}}};gf.default=VM;var yf={};Object.defineProperty(yf,"__esModule",{value:!0});const Yo=ce,GM={message({keyword:t,schemaCode:e}){const n=t==="maxProperties"?"more":"fewer";return(0,Yo.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Yo._)`{limit: ${t}}`},zM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:GM,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Yo.operators.GT:Yo.operators.LT;t.fail$data((0,Yo._)`Object.keys(${n}).length ${o} ${r}`)}};yf.default=zM;var wf={};Object.defineProperty(wf,"__esModule",{value:!0});const _o=ie,Zo=ce,WM=V,HM={message:({params:{missingProperty:t}})=>(0,Zo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Zo._)`{missingProperty: ${t}}`},JM={keyword:"required",type:"object",schemaType:"array",$data:!0,error:HM,code(t){const{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const g=t.parentSchema.properties,{definedProperties:p}=t.it;for(const y of n)if((g==null?void 0:g[y])===void 0&&!p.has(y)){const w=i.schemaEnv.baseId+i.errSchemaPath,h=`required property "${y}" is not defined at "${w}" (strictRequired)`;(0,WM.checkStrictMode)(i,h,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Zo.nil,d);else for(const g of n)(0,_o.checkReportMissingProp)(t,g)}function l(){const g=e.let("missing");if(c||s){const p=e.let("valid",!0);t.block$data(p,()=>f(g,p)),t.ok(p)}else e.if((0,_o.checkMissingProp)(t,n,g)),(0,_o.reportMissingProp)(t,g),e.else()}function d(){e.forOf("prop",r,g=>{t.setParams({missingProperty:g}),e.if((0,_o.noPropertyInData)(e,o,g,a.ownProperties),()=>t.error())})}function f(g,p){t.setParams({missingProperty:g}),e.forOf(g,r,()=>{e.assign(p,(0,_o.propertyInData)(e,o,g,a.ownProperties)),e.if((0,Zo.not)(p),()=>{t.error(),e.break()})},Zo.nil)}}};wf.default=JM;var vf={};Object.defineProperty(vf,"__esModule",{value:!0});const Xo=ce,QM={message({keyword:t,schemaCode:e}){const n=t==="maxItems"?"more":"fewer";return(0,Xo.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Xo._)`{limit: ${t}}`},YM={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:QM,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Xo.operators.GT:Xo.operators.LT;t.fail$data((0,Xo._)`${n}.length ${o} ${r}`)}};vf.default=YM;var $f={},As={};Object.defineProperty(As,"__esModule",{value:!0});const E0=q$;E0.code='require("ajv/dist/runtime/equal").default';As.default=E0;Object.defineProperty($f,"__esModule",{value:!0});const wc=Ie,Me=ce,ZM=V,XM=As,eL={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},tL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:eL,code(t){const{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;const c=e.let("valid"),u=s.items?(0,wc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Me._)`${i} === false`),t.ok(c);function l(){const p=e.let("i",(0,Me._)`${n}.length`),y=e.let("j");t.setParams({i:p,j:y}),e.assign(c,!0),e.if((0,Me._)`${p} > 1`,()=>(d()?f:g)(p,y))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,y){const w=e.name("item"),h=(0,wc.checkDataTypes)(u,w,a.opts.strictNumbers,wc.DataType.Wrong),v=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${p}--;`,()=>{e.let(w,(0,Me._)`${n}[${p}]`),e.if(h,(0,Me._)`continue`),u.length>1&&e.if((0,Me._)`typeof ${w} == "string"`,(0,Me._)`${w} += "_"`),e.if((0,Me._)`typeof ${v}[${w}] == "number"`,()=>{e.assign(y,(0,Me._)`${v}[${w}]`),t.error(),e.assign(c,!1).break()}).code((0,Me._)`${v}[${w}] = ${p}`)})}function g(p,y){const w=(0,ZM.useFunc)(e,XM.default),h=e.name("outer");e.label(h).for((0,Me._)`;${p}--;`,()=>e.for((0,Me._)`${y} = ${p}; ${y}--;`,()=>e.if((0,Me._)`${w}(${n}[${p}], ${n}[${y}])`,()=>{t.error(),e.assign(c,!1).break(h)})))}}};$f.default=tL;var bf={};Object.defineProperty(bf,"__esModule",{value:!0});const Ru=ce,nL=V,rL=As,oL={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ru._)`{allowedValue: ${t}}`},sL={keyword:"const",$data:!0,error:oL,code(t){const{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,Ru._)`!${(0,nL.useFunc)(e,rL.default)}(${n}, ${o})`):t.fail((0,Ru._)`${s} !== ${n}`)}};bf.default=sL;var Ef={};Object.defineProperty(Ef,"__esModule",{value:!0});const To=ce,iL=V,aL=As,cL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,To._)`{allowedValues: ${t}}`},uL={keyword:"enum",schemaType:"array",$data:!0,error:cL,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&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,iL.useFunc)(e,aL.default));let l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const g=e.const("vSchema",s);l=(0,To.or)(...o.map((p,y)=>f(g,y)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,g=>e.if((0,To._)`${u()}(${n}, ${g})`,()=>e.assign(l,!0).break()))}function f(g,p){const y=o[p];return typeof y=="object"&&y!==null?(0,To._)`${u()}(${n}, ${g}[${p}])`:(0,To._)`${n} === ${y}`}}};Ef.default=uL;Object.defineProperty(df,"__esModule",{value:!0});const lL=ff,dL=pf,fL=hf,pL=gf,hL=yf,mL=wf,gL=vf,yL=$f,wL=bf,vL=Ef,$L=[lL.default,dL.default,fL.default,pL.default,hL.default,mL.default,gL.default,yL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wL.default,vL.default];df.default=$L;var Sf={},mo={};Object.defineProperty(mo,"__esModule",{value:!0});mo.validateAdditionalItems=void 0;const rr=ce,Tu=V,bL={message:({params:{len:t}})=>(0,rr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,rr._)`{limit: ${t}}`},EL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:bL,code(t){const{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Tu.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}S0(t,r)}};function S0(t,e){const{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;const a=n.const("len",(0,rr._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,rr._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Tu.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,rr._)`${a} <= ${e.length}`);n.if((0,rr.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Tu.Type.Num},u),i.allErrors||n.if((0,rr.not)(u),()=>n.break())})}}mo.validateAdditionalItems=S0;mo.default=EL;var _f={},go={};Object.defineProperty(go,"__esModule",{value:!0});go.validateTuple=void 0;const Em=ce,Ti=V,SL=ie,_L={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:n}=t;if(Array.isArray(e))return _0(t,"additionalItems",e);n.items=!0,!(0,Ti.alwaysValidSchema)(n,e)&&t.ok((0,SL.validateArray)(t))}};function _0(t,e,n=t.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Ti.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,Em._)`${s}.length`);n.forEach((d,f)=>{(0,Ti.alwaysValidSchema)(a,d)||(r.if((0,Em._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){const{opts:f,errSchemaPath:g}=a,p=n.length,y=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!y){const w=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0,Ti.checkStrictMode)(a,w,f.strictTuples)}}}go.validateTuple=_0;go.default=_L;Object.defineProperty(_f,"__esModule",{value:!0});const NL=go,OL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,NL.validateTuple)(t,"items")};_f.default=OL;var Nf={};Object.defineProperty(Nf,"__esModule",{value:!0});const Sm=ce,kL=V,jL=ie,AL=mo,IL={message:({params:{len:t}})=>(0,Sm.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Sm._)`{limit: ${t}}`},PL={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:IL,code(t){const{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,kL.alwaysValidSchema)(r,e)&&(o?(0,AL.validateAdditionalItems)(t,o):t.ok((0,jL.validateArray)(t)))}};Nf.default=PL;var Of={};Object.defineProperty(Of,"__esModule",{value:!0});const ft=ce,ei=V,xL={message:({params:{min:t,max:e}})=>e===void 0?(0,ft.str)`must contain at least ${t} valid item(s)`:(0,ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ft._)`{minContains: ${t}}`:(0,ft._)`{minContains: ${t}, maxContains: ${e}}`},RL={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:xL,code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=e.const("len",(0,ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ei.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ei.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ei.alwaysValidSchema)(s,n)){let y=(0,ft._)`${l} >= ${i}`;a!==void 0&&(y=(0,ft._)`${y} && ${l} <= ${a}`),t.pass(y);return}s.items=!0;const d=e.name("valid");a===void 0&&i===1?g(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ft._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){const y=e.name("_valid"),w=e.let("count",0);g(y,()=>e.if(y,()=>p(w)))}function g(y,w){e.forRange("i",0,l,h=>{t.subschema({keyword:"contains",dataProp:h,dataPropType:ei.Type.Num,compositeRule:!0},y),w()})}function p(y){e.code((0,ft._)`${y}++`),a===void 0?e.if((0,ft._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ft._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ft._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};Of.default=RL;var N0={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=ce,n=V,r=ie;t.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const d=u===1?"property":"properties";return(0,e.str)`must have ${d} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:d}})=>(0,e._)`{property: ${c},
|
|
351
|
+
missingProperty: ${d},
|
|
352
|
+
depsCount: ${u},
|
|
353
|
+
deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const d in c){if(d==="__proto__")continue;const f=Array.isArray(c[d])?u:l;f[d]=c[d]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:d,it:f}=c;if(Object.keys(u).length===0)return;const g=l.let("missing");for(const p in u){const y=u[p];if(y.length===0)continue;const w=(0,r.propertyInData)(l,d,p,f.opts.ownProperties);c.setParams({property:p,depsCount:y.length,deps:y.join(", ")}),f.allErrors?l.if(w,()=>{for(const h of y)(0,r.checkReportMissingProp)(c,h)}):(l.if((0,e._)`${w} && (${(0,r.checkMissingProp)(c,y,g)})`),(0,r.reportMissingProp)(c,g),l.else())}}t.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:d,keyword:f,it:g}=c,p=l.name("valid");for(const y in u)(0,n.alwaysValidSchema)(g,u[y])||(l.if((0,r.propertyInData)(l,d,y,g.opts.ownProperties),()=>{const w=c.subschema({keyword:f,schemaProp:y},p);c.mergeValidEvaluated(w,p)},()=>l.var(p,!0)),c.ok(p))}t.validateSchemaDeps=a,t.default=o})(N0);var kf={};Object.defineProperty(kf,"__esModule",{value:!0});const O0=ce,TL=V,CL={message:"property name must be valid",params:({params:t})=>(0,O0._)`{propertyName: ${t.propertyName}}`},ML={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:CL,code(t){const{gen:e,schema:n,data:r,it:o}=t;if((0,TL.alwaysValidSchema)(o,n))return;const s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,O0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};kf.default=ML;var Ba={};Object.defineProperty(Ba,"__esModule",{value:!0});const ti=ie,bt=ce,LL=Ft,ni=V,DL={message:"must NOT have additional properties",params:({params:t})=>(0,bt._)`{additionalProperty: ${t.additionalProperty}}`},UL={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:DL,code(t){const{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,ni.alwaysValidSchema)(i,n))return;const u=(0,ti.allSchemaProperties)(r.properties),l=(0,ti.allSchemaProperties)(r.patternProperties);d(),t.ok((0,bt._)`${s} === ${LL.default.errors}`);function d(){e.forIn("key",o,w=>{!u.length&&!l.length?p(w):e.if(f(w),()=>p(w))})}function f(w){let h;if(u.length>8){const v=(0,ni.schemaRefOrVal)(i,r.properties,"properties");h=(0,ti.isOwnProperty)(e,v,w)}else u.length?h=(0,bt.or)(...u.map(v=>(0,bt._)`${w} === ${v}`)):h=bt.nil;return l.length&&(h=(0,bt.or)(h,...l.map(v=>(0,bt._)`${(0,ti.usePattern)(t,v)}.test(${w})`))),(0,bt.not)(h)}function g(w){e.code((0,bt._)`delete ${o}[${w}]`)}function p(w){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){g(w);return}if(n===!1){t.setParams({additionalProperty:w}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,ni.alwaysValidSchema)(i,n)){const h=e.name("valid");c.removeAdditional==="failing"?(y(w,h,!1),e.if((0,bt.not)(h),()=>{t.reset(),g(w)})):(y(w,h),a||e.if((0,bt.not)(h),()=>e.break()))}}function y(w,h,v){const b={keyword:"additionalProperties",dataProp:w,dataPropType:ni.Type.Str};v===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,h)}}};Ba.default=UL;var jf={};Object.defineProperty(jf,"__esModule",{value:!0});const BL=kt,_m=ie,vc=V,Nm=Ba,FL={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Nm.default.code(new BL.KeywordCxt(s,Nm.default,"additionalProperties"));const i=(0,_m.allSchemaProperties)(n);for(const d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=vc.mergeEvaluated.props(e,(0,vc.toHash)(i),s.props));const a=i.filter(d=>!(0,vc.alwaysValidSchema)(s,n[d]));if(a.length===0)return;const c=e.name("valid");for(const d of a)u(d)?l(d):(e.if((0,_m.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};jf.default=FL;var Af={};Object.defineProperty(Af,"__esModule",{value:!0});const Om=ie,ri=ce,km=V,jm=V,qL={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Om.allSchemaProperties)(n),c=a.filter(y=>(0,km.alwaysValidSchema)(s,n[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ri.Name)&&(s.props=(0,jm.evaluatedPropsToName)(e,s.props));const{props:d}=s;f();function f(){for(const y of a)u&&g(y),s.allErrors?p(y):(e.var(l,!0),p(y),e.if(l))}function g(y){for(const w in u)new RegExp(y).test(w)&&(0,km.checkStrictMode)(s,`property ${w} matches pattern ${y} (use allowMatchingProperties)`)}function p(y){e.forIn("key",r,w=>{e.if((0,ri._)`${(0,Om.usePattern)(t,y)}.test(${w})`,()=>{const h=c.includes(y);h||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:w,dataPropType:jm.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ri._)`${d}[${w}]`,!0):!h&&!s.allErrors&&e.if((0,ri.not)(l),()=>e.break())})})}}};Af.default=qL;var If={};Object.defineProperty(If,"__esModule",{value:!0});const KL=V,VL={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:n,it:r}=t;if((0,KL.alwaysValidSchema)(r,n)){t.fail();return}const o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};If.default=VL;var Pf={};Object.defineProperty(Pf,"__esModule",{value:!0});const GL=ie,zL={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:GL.validateUnion,error:{message:"must match a schema in anyOf"}};Pf.default=zL;var xf={};Object.defineProperty(xf,"__esModule",{value:!0});const Ci=ce,WL=V,HL={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ci._)`{passingSchemas: ${t.passing}}`},JL={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:HL,code(t){const{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let f;(0,WL.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ci._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ci._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Ci.Name)})})}}};xf.default=JL;var Rf={};Object.defineProperty(Rf,"__esModule",{value:!0});const QL=V,YL={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=e.name("valid");n.forEach((s,i)=>{if((0,QL.alwaysValidSchema)(r,s))return;const a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Rf.default=YL;var Tf={};Object.defineProperty(Tf,"__esModule",{value:!0});const ra=ce,k0=V,ZL={message:({params:t})=>(0,ra.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ra._)`{failingKeyword: ${t.ifClause}}`},XL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ZL,code(t){const{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,k0.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=Am(r,"then"),s=Am(r,"else");if(!o&&!s)return;const i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){const l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,ra.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){const l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{const f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,ra._)`${l}`):t.setParams({ifClause:l})}}}};function Am(t,e){const n=t.schema[e];return n!==void 0&&!(0,k0.alwaysValidSchema)(t,n)}Tf.default=XL;var Cf={};Object.defineProperty(Cf,"__esModule",{value:!0});const eD=V,tD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,eD.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Cf.default=tD;Object.defineProperty(Sf,"__esModule",{value:!0});const nD=mo,rD=_f,oD=go,sD=Nf,iD=Of,aD=N0,cD=kf,uD=Ba,lD=jf,dD=Af,fD=If,pD=Pf,hD=xf,mD=Rf,gD=Tf,yD=Cf;function wD(t=!1){const e=[fD.default,pD.default,hD.default,mD.default,gD.default,yD.default,cD.default,uD.default,aD.default,lD.default,dD.default];return t?e.push(rD.default,sD.default):e.push(nD.default,oD.default),e.push(iD.default),e}Sf.default=wD;var Mf={},Lf={};Object.defineProperty(Lf,"__esModule",{value:!0});const _e=ce,vD={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},$D={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:vD,code(t,e){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?f():g();function f(){const p=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=n.const("fDef",(0,_e._)`${p}[${i}]`),w=n.let("fType"),h=n.let("format");n.if((0,_e._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>n.assign(w,(0,_e._)`${y}.type || "string"`).assign(h,(0,_e._)`${y}.validate`),()=>n.assign(w,(0,_e._)`"string"`).assign(h,y)),t.fail$data((0,_e.or)(v(),b()));function v(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${h}`}function b(){const E=l.$async?(0,_e._)`(${y}.async ? await ${h}(${r}) : ${h}(${r}))`:(0,_e._)`${h}(${r})`,N=(0,_e._)`(typeof ${h} == "function" ? ${E} : ${h}.test(${r}))`;return(0,_e._)`${h} && ${h} !== true && ${w} === ${e} && !${N}`}}function g(){const p=d.formats[s];if(!p){v();return}if(p===!0)return;const[y,w,h]=b(p);y===e&&t.pass(E());function v(){if(c.strictSchema===!1){d.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(N){const j=N instanceof RegExp?(0,_e.regexpCode)(N):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,T=n.scopeValue("formats",{key:s,ref:N,code:j});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,_e._)`${T}.validate`]:["string",N,T]}function E(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${h}(${r})`}return typeof w=="function"?(0,_e._)`${h}(${r})`:(0,_e._)`${h}.test(${r})`}}}};Lf.default=$D;Object.defineProperty(Mf,"__esModule",{value:!0});const bD=Lf,ED=[bD.default];Mf.default=ED;var io={};Object.defineProperty(io,"__esModule",{value:!0});io.contentVocabulary=io.metadataVocabulary=void 0;io.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];io.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(cf,"__esModule",{value:!0});const SD=uf,_D=df,ND=Sf,OD=Mf,Im=io,kD=[SD.default,_D.default,(0,ND.default)(),OD.default,Im.metadataVocabulary,Im.contentVocabulary];cf.default=kD;var Df={},Fa={};Object.defineProperty(Fa,"__esModule",{value:!0});Fa.DiscrError=void 0;var Pm;(function(t){t.Tag="tag",t.Mapping="mapping"})(Pm||(Fa.DiscrError=Pm={}));Object.defineProperty(Df,"__esModule",{value:!0});const Lr=ce,Cu=Fa,xm=at,jD=ho,AD=V,ID={message:({params:{discrError:t,tagName:e}})=>t===Cu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Lr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},PD={keyword:"discriminator",type:"object",schemaType:"object",error:ID,code(t){const{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.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=e.let("valid",!1),u=e.const("tag",(0,Lr._)`${n}${(0,Lr.getProperty)(a)}`);e.if((0,Lr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Cu.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){const g=f();e.if(!1);for(const p in g)e.elseIf((0,Lr._)`${u} === ${p}`),e.assign(c,d(g[p]));e.else(),t.error(!1,{discrError:Cu.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(g){const p=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:g},p);return t.mergeEvaluated(y,Lr.Name),p}function f(){var g;const p={},y=h(o);let w=!0;for(let E=0;E<i.length;E++){let N=i[E];if(N!=null&&N.$ref&&!(0,AD.schemaHasRulesButRef)(N,s.self.RULES)){const T=N.$ref;if(N=xm.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,T),N instanceof xm.SchemaEnv&&(N=N.schema),N===void 0)throw new jD.default(s.opts.uriResolver,s.baseId,T)}const j=(g=N==null?void 0:N.properties)===null||g===void 0?void 0:g[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(y||h(N)),v(j,E)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return p;function h({required:E}){return Array.isArray(E)&&E.includes(a)}function v(E,N){if(E.const)b(E.const,N);else if(E.enum)for(const j of E.enum)b(j,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,N){if(typeof E!="string"||E in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[E]=N}}}};Df.default=PD;const xD="http://json-schema.org/draft-07/schema#",RD="http://json-schema.org/draft-07/schema#",TD="Core schema meta-schema",CD={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:[]}},MD=["object","boolean"],LD={$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:"#"}},DD={$schema:xD,$id:RD,title:TD,definitions:CD,type:MD,properties:LD,default:!0};(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const n=O$,r=cf,o=Df,s=DD,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(p=>this.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(p,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=kt;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=ce;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=js;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=ho;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})(cm,cm.exports);Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const UD={"decimal.js":"Decimal"};function BD(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(UD).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${BD(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function FD(t,e){return`x-${t}-${e}`}function Rm(t){let e=t.replace(/[^a-zA-Z0-9_$]/g,"_");return(e===""||/^[0-9]/.test(e))&&(e=`_${e}`),e}const qD=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],KD={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let VD=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function Uf(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&qD.includes(t.code)&&typeof t.toJSON=="function"}const Mu="$apigen";let Tm=class extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function GD(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new Tm(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new Tm("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Bf="x-apigen-logical",Ff="x-apigen-codec",Lu="x-apigen-ctor",Du="x-apigen-tojson",zD="0.1.0";function Cm(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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",...e}}function Dr(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Dr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=j0(t,s,e,n);return Dr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return es(t,e,n);const a=e.items;if(!a)return t.map(u=>ur(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?ur(u):Dr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Dr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return es(t,e,n);const a=e.properties;if(!a)return ur(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Dr(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?es(t,e,n):ur(t)}function Ur(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ur(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=j0(t,s,e,n);return Ur(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Ur(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Ur(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Ur(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Uu(t,n):t}function j0(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=oa(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=WD(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=oa(u,r),d=A0(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function oa(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function Mm(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function WD(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>oa(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))Mm(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?Mm(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function HD(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function A0(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=A0(t,oa(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=HD(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function es(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[Mu]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>es(o,{},n));if(I0(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=es(i,{},n));return o}return ur(t)}function I0(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Uu(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&Mu in t){const n=t,r=n[Mu],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Uu(n,e));if(I0(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Uu(o,e);return n}return t}function ur(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(ur);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=ur(r));return e}return null}function JD(t){return{encode(e,n,r){const o=Cm(t,r);return Dr(e,n,o)},decode(e,n,r){const o=Cm(t,r);return Ur(e,n,o)}}}const qf={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},Kf={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},Vf={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},Gf={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},QD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,zf={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!QD.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},Bu="NaN",Fu="Infinity",qu="-Infinity",YD=new Set([Bu,Fu,qu]),Wf={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?Bu:t===1/0?Fu:t===-1/0?qu:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===Bu)return NaN;if(t===Fu)return 1/0;if(t===qu)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...YD].join(", ")}.`);return NaN}},ZD=[qf,Kf,Vf,Gf,zf,Wf];function XD(t,e={}){for(const n of ZD)t.register(n,{override:e.override??!1})}const eU=12;function tU(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,r,o]=n,s=r==="$defs"?e.$defs:e.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Lm(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function nU(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function rU(t){switch(t.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function Dm(t,e,n){const r=t.properties??{},o=t.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?ys(a,e,n+1):`<${i}>`}return s}function oU(t,e,n){const r=Array.isArray(t.items)?t.items[0]:t.items;return r?[ys(r,e,n+1)]:[]}function ys(t,e=t??{},n=0){if(!t||n>eU)return null;if(typeof t.$ref=="string"){const o=tU(t.$ref,e);return o!==void 0?ys(o,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const o={},s=[];for(const i of t.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return Dm({...t,properties:o,required:s},e,n)}const r=Lm(t.oneOf)??Lm(t.anyOf);if(r)return ys(r,e,n+1);switch(nU(t)){case"object":return Dm(t,e,n);case"array":return oU(t,e,n);case"string":return rU(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function sU(t){if(!t)return;const e=ys(t);return`Example: ${JSON.stringify(e)}`}qf.id,Kf.id,Vf.id,Gf.id,zf.id,Wf.id;const P0=GD();XD(P0);const x0=JD(P0.freeze());function iU(t,e){var n;const r=((n=t.input)==null?void 0:n.properties)??{};return e in r}function aU(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function cU(t,e){var n,r,o;const s=(o=(r=(n=t.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[e];return i!==void 0?i:void 0}function uU(t,e){return e===void 0||t===void 0?t:x0.decode(t,e)}function $c(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:x0.encode(t,n)}async function lU(t,e,n,r,o,s){const i=aU(n).map(c=>uU(s[c],cU(n,c)));if(iU(n,"session")&&e){const c=await e({session:o.session}),u=await t[r](c,...i);return $c(u,n)}if(n.hasCtx){const c=e?await e(o):void 0,u=await t[r](c,...i);return $c(u,n)}const a=await t[r](...i);return $c(a,n)}let R0=class{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function dU(t=[]){return async function(e,n,r){const o=r.schemas[e];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${e}"`);const s=()=>lU(r.fns,r.createClient,o,e,n.envelope,n.domainArgs);return t.reduceRight((i,a)=>()=>a(n,i),s)()}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const fU={"decimal.js":"Decimal"};function pU(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(fU).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${pU(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function hU(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,r=!n&&!!process.stderr.isTTY,o=t.format??(r?"pretty":"json"),s={level:e};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},pt(s);const i=n?pt.destination({dest:t.destination,mkdir:!0,sync:!0}):pt.destination(2);return pt(s,i)}function mU(t){if(!t||t.type!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([r,o])=>`${r}${n.has(r)?"":"?"}: ${qa(o)}`).join(", ")} }`}function gU(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function yU(t){const e=t.enum??[];return e.length===0?"unknown":e.map(gU).join("|")}function wU(t,e){return t.map(n=>qa(n,e)).join(" | ")}function qa(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${qa(t.items,0)}[]`;if(t.enum)return yU(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?wU(n,e-1):"union":e>=1&&t.type==="object"?mU(t)??"object":t.type??"object"}function T0(t){var e;const n=(e=((t==null?void 0:t.input)??{}).properties)==null?void 0:e.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:qa(c,2),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function vU(t){let e;return Array.isArray(t)?e=t:t?e=[t]:e=[],e.find(n=>n==="number"||n==="integer"||n==="boolean")}function $U(t,e){var n,r;const o=((r=(n=((e==null?void 0:e.input)??{}).properties)==null?void 0:n.data)==null?void 0:r.properties)??{},s={...t};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=vU(a==null?void 0:a.type);if(u==="number"||u==="integer"){const l=Number(c);!Number.isNaN(l)&&c.trim()!==""&&(s[i]=l)}else u==="boolean"&&(c==="true"?s[i]=!0:c==="false"&&(s[i]=!1))}return s}let bU=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};const Ka=new ia({allErrors:!0});aa(Ka);for(const t of[Bf,Ff,Lu,Du,"discriminator"])Ka.addKeyword({keyword:t,valid:!0});Ka.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function EU(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function SU(t,e){const n=sU(e),r=[`Validation failed: ${EU(t)}`];return n&&r.push(n),r.join(" — ")}function _U(t){return async function(e,n){const r=e.operation.id,o=t[r];if(o===void 0)return n();const s={data:e.domainArgs,...e.envelope},i=Ka.compile(o.input);if(!i(s)){const a=i.errors??[];throw new bU("invalid_argument",SU(a,o.input),a)}return n()}}function NU(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}class Wn extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}}function bc(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function C0(t,e){const n=t[Ff];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function OU(t,e,n){const r=C0(e,n);return r?r.encode(t,e,n):t}function kU(t,e,n){const r=C0(e,n);return r?r.decode(t,e,n):t}function jU(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[Bf]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:bc(r)!==void 0},encode(r,o,s){const i=bc(o);if(!i)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new Wn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return OU(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new Wn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=bc(o);if(!a)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new Wn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return kU(r,g,{...s,path:`${s.path}[${d}]`})}}}const AU="x-apigen-instances";let oi=class extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}};function Um(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function IU(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Bm(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function PU(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function xU(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[Bf]==="nominal"?!0:o[Ff]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new oi("E_NOMINAL_CYCLE",`[${e}] 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=Um(s),c=typeof s[Du]=="string"?s[Du]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=Bm(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=Bm(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new oi("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of IU(s))if(!(l in a))throw new oi("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[AU]===!1)throw new oi("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Um(s),u={};for(const[l,d]of Object.entries(a))u[l]=PU(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Lu]=="string"?s[Lu]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const RU=[qf,Kf,Vf,Gf,zf,Wf],TU={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Fm=xU({id:"ts.NominalSentinel",schema:TU}),CU={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},qm=jU({id:"ts.UnionSentinel",schema:CU});function MU(){const t=[...RU.map(e=>[e.id,e]),[Fm.id,Fm],[qm.id,qm]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:zD,codecs:MU()});Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Km=new Set(["string","number","boolean","integer"]);function LU(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Km.has(n):Array.isArray(n)?n.every(r=>Km.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function DU(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(LU)}const UU={"decimal.js":"Decimal"};function BU(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(UU).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${BU(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Vm(t){return t.words.join("-")}function Gm(t){return t.words.map(GU).join("")}function zm(t){return t.words.join("_")}function FU(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||DU(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>Vm(g)).join("/"),c=o.map(g=>zm(g)).join("_"),u=o.map(g=>zm(g)).slice(0,-1).join("."),l=Gm(o[o.length-2]??o[0]),d=Gm(o[o.length-1]),f=o.map(g=>Vm(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function qU(t,e){return`x-${t}-${e}`}function KU(t,e){return`--${t}-${e}`}function VU(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function GU(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function Hf(t){return t.anyOf??t.oneOf}function zU(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=Hf(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function WU(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=Hf(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function HU(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=Hf(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function JU(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function QU(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Wm(t){return typeof t.handler=="function"}function YU(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=qU(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:KU(i,s),envVar:VU(i,s)})}return o}function ZU(t,e,n,r){e===n||t.has(e)||t.set(e,{...r,aliasOf:n})}function XU(t,e){const n=new Map,{props:r}=QU(t);for(const[o,s]of Object.entries(r)){let i="string";WU(s)?i="boolean":(zU(s)||HU(s))&&(i="json");const a=JU(o),c={camelKey:o,kind:"domain",valueKind:i};n.set(a,c),ZU(n,o,a,c)}for(const o of e){const s=o.cliFlag.replace(/^--/,""),i={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(s,i)}return n}function Ku(t){const{op:e,schema:n,transport:r,projection:o}=t,s=FU(e,o),i=n?YU(n):[],a=n?XU(n,i):new Map,c=n?T0(n).params:void 0,u={op:e,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:e.streaming,isMount:Wm(e)};if(Wm(e)){const l=e.handler;u.mountHandler=async d=>l(d)}return u}function e2(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function t2(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function n2(t){return async function(e,n){const r=Object.assign(e,{data:e.domainArgs});return await t.layer(r,n)}}function Ec(t,e){var n;const r=[];for(const o of e){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(n2(s))}return r.push(_U(t)),dU(r)}function r2(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const o2={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Hm(t,e,n,r){const o={...n,operation:{id:t.op.id},ctx:new R0};if(t.isMount){const s=t.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const i={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:r2(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[t.op.id]:()=>s(i)},schemas:{[t.op.id]:o2}};return e(t.op.id,o,a)}return e(t.op.id,o,r)}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const s2={"decimal.js":"Decimal"};function i2(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(s2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${i2(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Vu(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}function Jm(t){return{raw:t,words:Vu(t)}}function M0(t,e,n,r){for(const o of r??[]){const s=o.path[o.path.length-1];if(o.namespace.raw===t&&(s==null?void 0:s.raw)===e)return o}return{id:`${Vu(t).join("-")}/${Vu(e).join("-")}`,host:"ts",namespace:Jm(t),path:[Jm(e)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function a2(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o={};for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd";o[s]=FD(i,s)}return o}function c2(t){const e=t.options.port??3e3,n=t.options.routePrefix??"",r=t.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 t.packages){const i=Rm(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(t.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 t.packages){const i=Rm(s.id);for(const[a,c]of Object.entries(s.schemas)){const u=M0(s.id,a,c,t.operations),l=Ku({op:u,schema:c,transport:"http",projection:r}),d=n+l.http.route,f=l.http.verb,g=a2(c),p=Object.entries(g);if(f==="GET"){if(o.push(`app.get('${d}', async (req) => {`),o.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas['${s.id}:${a}']['schema'] as any)`),p.length>0){const y=p.map(([w,h])=>`'${w}': (req.headers as Record<string, unknown>)['${h}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${y} }`)}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('${d}', async (req) => {`),o.push(" const { data = {} } = req.body as Record<string, unknown>"),p.length>0){const y=p.map(([w,h])=>`'${w}': (req.headers as Record<string, unknown>)['${h}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${y} }`)}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: ${e} })`),{files:[{path:"routes.ts",content:o.join(`
|
|
354
|
+
`)}]}}function u2(t){return`data: ${t}
|
|
178
355
|
|
|
179
|
-
<!-- ${pA}${e}::${t} -->`}function Xr(e,t){return`${e}::${t}`}function Ga(e){switch(e){case"CRITICAL":return 10;case"HIGH":return 8;case"MEDIUM":return 5;case"LOW":return 2;default:return 1}}function Ja(e,t,n=[]){return[...new Set([ge,e,t,...n])]}function Se(e){return e.tags.includes(ge)&&!e.isSuperseded}function se(e){const t=e.metadata??{},n=t.humanId??"",r=t.kind??nn(n),o=t.family??ct(n),s=new Set([ge,r,o]);return{nodeId:e.id,humanId:n,kind:r,family:o,title:t.title??e.summary??"",body:t.body??"",status:t.status??"UNKNOWN",priority:t.priority,repo:t.repo??e.namespace,projectPath:t.projectPath,plan:t.plan,importedFrom:t.importedFrom,assignee:t.assignee,claimedBy:t.claimedBy,claimedAt:t.claimedAt,citations:t.citations??[],notes:t.notes??[],tags:e.tags.filter(i=>!s.has(i)),createdAt:t.createdAt??e.tCreated,updatedAt:t.updatedAt??t.createdAt??e.tCreated}}const hA=5,mA=20,gA=500;function yA(e){return Ko.isBusyError(e)||Ko.isConcurrentConflict(e)}function $A(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function Ha(e,t={}){const n=t.maxAttempts??hA;for(let r=0;;r++)try{return await e()}catch(o){if(!yA(o)||r>=n-1)throw o;const s=Math.min(gA,mA*2**r);await $A(s*(.5+Math.random()*.5))}}async function vA(e,t,n){if(typeof n!="string"||n.trim().length===0)throw new ae("family",`backlog: cannot allocate a humanId for repo=${JSON.stringify(t)} — "family" is required and must be a non-empty string, received ${JSON.stringify(n)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);const r=await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{family:n}});let o=0;for(const s of r){const i=s.metadata,a=/-(\d+)$/.exec((i==null?void 0:i.humanId)??"");a&&(o=Math.max(o,Number(a[1])))}return`${n}-${String(o+1).padStart(3,"0")}`}async function wA(e,t,n){const o=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{humanId:n}})).filter(s=>{var i;return Se(s)&&((i=s.metadata)==null?void 0:i.humanId)===n});if(o.length>1)throw new Va(t,n,o.map(s=>s.id));return o[0]??null}async function Fp(e,t,n,r,o){return Ha(()=>e.adapter.transaction(async()=>{if(r){const i=await wA(e,t,r);return o(r,i)}const s=await vA(e,t,n);return o(s,null)},{mode:"immediate"}))}const qp="backlog-audit-event";async function Vp(e,t,n,r,o,s){const i=new Date().toISOString(),a={itemNodeId:t,kind:o,at:i,detail:s},c=`audit-event::${n}::${r}::${o}::${i}::${Math.random().toString(36).slice(2)}`,u=await e.graph.writeNode(c,{kind:"generic",name:`audit-event::${n}::${r}::${i}`,tags:[qp],namespace:n,metadata:a});await e.graph.writeEdge(u,t,"DERIVED_FROM")}async function bA(e,t){return(await e.graph.queryNodes({kind:"generic",tags:[qp],metadata:{itemNodeId:t}})).map(r=>r.metadata).filter(r=>r!==void 0&&r.itemNodeId===t).map(r=>({at:r.at,kind:r.kind,detail:r.detail})).sort((r,o)=>r.at.localeCompare(o.at))}const bl={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3};function El(e){const t=[ge];e.kind&&t.push(e.kind),e.tags&&t.push(...e.tags);const n={};e.family&&(n.family=e.family),e.priority&&(n.priority=e.priority),e.plan&&(n.plan=e.plan),e.importedFrom&&(n.importedFrom=e.importedFrom),e.assignee&&(n.assignee=e.assignee),e.claimedBy&&(n.claimedBy=e.claimedBy),e.status&&e.status!=="open"&&e.status!=="closed"&&(n.status=e.status);const r={kind:"generic",tags:t,tagsMatchAll:!0};return e.repo!==void 0&&(r.namespace=e.repo),e.projectPath!==void 0&&(r.projectPath=e.projectPath),Object.keys(n).length>0&&(r.metadata=n),r}function EA(e,t){return t.status==="open"?e.filter(n=>!Be(n.status)):t.status==="closed"?e.filter(n=>Be(n.status)):e}function Sl(e,t){return t.rootLevel?e.filter(n=>{const r=n.metadata;return!(r!=null&&r.projectPath)&&!(r!=null&&r.plan)}):e}function Nl(e,t){return t.excludeArchived?e.filter(n=>{var r;return!((r=n.metadata)!=null&&r.archivedAt)}):e}async function Kp(e,t={}){if(t.grep){const o=El({...t}),s=Ka(t.grep);if(!s)return[];const i=await e.graph.searchNodes(s,{limit:t.limit??1e3,filter:o});let a=Nl(Sl(i.filter(Se),t),t);return t.offset&&(a=a.slice(t.offset)),a}const n=El(t);t.limit!==void 0&&(n.limit=t.limit),t.offset!==void 0&&(n.offset=t.offset);const r=await e.graph.queryNodes(n);return Nl(Sl(r.filter(Se),t),t)}async function ut(e,t={}){const r=(await Kp(e,t)).map(se);return EA(r,t)}async function qe(e,t,n){const r=Xr(t,n),s=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{humanId:n}})).filter(Se);if(s.length>1)throw new Va(t,n,s.map(i=>i.id));return s.find(i=>i.name===r)??s[0]??null}function Gs(e){var t;return((t=e.metadata)==null?void 0:t.repo)??e.namespace??""}async function SA(e,t){return(await e.graph.queryNodes({kind:"generic",tags:[ge],metadata:{humanId:t}})).filter(Se)}async function Gp(e){const t=await e.graph.queryNodes({kind:"generic",tags:[ge]}),n=new Set;for(const r of t){if(!Se(r))continue;const o=Gs(r);o&&n.add(o)}return n}async function Oe(e,t,n){const r=(await SA(e,n)).filter(s=>Gs(s)!==t),o=[...new Set(r.map(Gs).filter(s=>s.length>0))];return new Mp(t,n,o)}function pn(e,t){const n={};for(const r of e){const o=t(r);o&&(n[o]=(n[o]??0)+1)}return n}async function NA(e,t={}){const n=await ut(e,{repo:t.repo,projectPath:t.projectPath}),r=n.filter(s=>!Be(s.status)),o=n.filter(s=>Be(s.status));return{total:n.length,open:r.length,closed:o.length,byStatus:pn(n,s=>s.status),byKind:pn(n,s=>s.kind),byFamily:pn(n,s=>s.family),byPriority:pn(n,s=>s.priority),byRepo:t.repo===void 0?pn(n,s=>s.repo):{}}}async function OA(e,t={},n=20){const o=(await ut(e,{repo:t.repo,projectPath:t.projectPath,status:"open"})).filter(s=>s.priority!==void 0);return o.sort((s,i)=>{const a=bl[s.priority??""]??4,c=bl[i.priority??""]??4;return a-c||s.humanId.localeCompare(i.humanId)}),o.slice(0,n)}async function Jp(e,t){const n=await e.graph.getEdges({src:t,rel:"DEPENDS_ON"}),r=[];for(const o of n){const s=await e.graph.getNode(o.dst);s&&r.push(s)}return r}async function kA(e,t,n){const r=await qe(e,t,n);return r?(await Jp(e,r.id)).filter(o=>!o.tInvalid).map(se).filter(o=>!Be(o.status)):[]}async function _A(e,t={}){const n=await ut(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}),r=[];for(const o of n){if(o.claimedBy)continue;const s=await qe(e,o.repo,o.humanId);if(!s)continue;(await Jp(e,s.id)).filter(a=>!a.tInvalid).every(a=>Be(se(a).status))&&r.push(o)}return r}async function Hp(e,t={}){const n=await ut(e,{repo:t.repo,projectPath:t.projectPath}),r=n.map(s=>({humanId:s.humanId,title:s.title,status:s.status})),o=[];for(const s of n){const i=await qe(e,s.repo,s.humanId);if(i)for(const a of["DEPENDS_ON","RELATES_TO","PART_OF"])for(const c of await e.graph.getEdges({src:i.id,rel:a})){const u=await e.graph.getNode(c.dst);if(!u||u.tInvalid)continue;const l=u.metadata;l!=null&&l.humanId&&o.push({from:s.humanId,to:l.humanId,rel:a})}}return{nodes:r,edges:o}}async function AA(e,t={}){var c;const n=await Hp(e,t),r=n.edges.filter(u=>u.rel==="DEPENDS_ON"),o=new Map;for(const u of n.nodes)o.set(u.humanId,new Set);for(const u of r)(c=o.get(u.from))==null||c.add(u.to);const s=new Set(n.nodes.map(u=>u.humanId)),i=[];let a=!0;for(;s.size>0&&a;){a=!1;for(const u of[...s].sort())[...o.get(u)??new Set].every(p=>!s.has(p))&&(i.push(u),s.delete(u),a=!0)}return s.size>0?{ok:!1,cycle:jA([...s],o)}:{ok:!0,order:i}}function jA(e,t){const n=new Set(e),r=new Set,o=[];function s(i){if(r.has(i)){const a=o.indexOf(i);return[...o.slice(a),i]}if(!n.has(i))return null;r.add(i),o.push(i);for(const a of t.get(i)??[]){const c=s(a);if(c)return c}return o.pop(),r.delete(i),null}for(const i of e){const a=s(i);if(a)return a}return e}async function IA(e,t,n={}){const r=await ut(e,{repo:n.repo,projectPath:n.projectPath}),o=t*6e4,s=Date.now();return r.filter(i=>!i.claimedBy||!i.claimedAt?!1:s-Date.parse(i.claimedAt)>=o)}async function xA(e,t,n){var u,l,f,p;const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);const o=se(r),s=[{at:o.createdAt,kind:"created",detail:{title:o.title,repo:o.repo}}];for(const h of o.citations)s.push({at:o.updatedAt,kind:"citation",detail:{...h}});for(const h of o.notes)s.push({at:h.at,kind:"note",detail:{by:h.by,text:h.text}});s.push(...await bA(e,r.id)),s.sort((h,d)=>h.at.localeCompare(d.at));const i=await e.graph.getSupersessionChain(r.id);let a;if(i.length>1){const h=i.findIndex(y=>y.id===r.id),d=h>0?((l=(u=i[h-1])==null?void 0:u.metadata)==null?void 0:l.humanId)??void 0:void 0,m=h>=0&&h<i.length-1?((p=(f=i[h+1])==null?void 0:f.metadata)==null?void 0:p.humanId)??void 0:void 0;a={},d&&(a.supersedes=d),m&&(a.supersededBy=m)}const c={humanId:o.humanId,history:s};return a&&(c.supersessionChain=a),c}class PA extends Error{constructor(t){super(`backlog item not found or invalidated: node ${t}`),this.nodeId=t,this.name="NotFoundError"}}async function ke(e,t,n){return Ha(()=>e.adapter.transaction(async()=>{const r=await e.graph.getNode(t);if(!r||r.tInvalid)throw new PA(t);const o=r.metadata??{},s=n(o);return await e.graph.touch(t,{metadata:s}),s},{mode:"immediate"}))}async function za(e,t,n){const r=await e.graph.getNode(t),o=r==null?void 0:r.metadata;o!=null&&o.repo&&(o!=null&&o.humanId)&&await Vp(e,t,o.repo,o.humanId,"claim",n)}const TA=30;class CA extends Error{constructor(t,n){super(`cannot release claim held by "${t}" as "${n}" without force`),this.heldBy=t,this.name="ClaimContentionError"}}async function zp(e,t,n,r={}){const o=(r.staleAfterMin??TA)*6e4;let s;return await ke(e,t,i=>{const a=Date.now(),c=new Date(a).toISOString();return!i.claimedBy||i.claimedBy===n?(s={status:i.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:c},{...i,claimedBy:n,claimedAt:c,updatedAt:c}):(i.claimedAt?a-Date.parse(i.claimedAt):Number.POSITIVE_INFINITY)<=o&&!r.force?(s={status:"held",claimedBy:n,claimedAt:c,heldBy:i.claimedBy,...i.claimedAt!==void 0?{heldSince:i.claimedAt}:{}},i):(s={status:"reclaimed-stale",claimedBy:n,claimedAt:c,previousClaimant:i.claimedBy},{...i,claimedBy:n,claimedAt:c,updatedAt:c})}),s.status!=="held"&&await za(e,t,{status:s.status,by:n}),s}async function RA(e,t,n){let r;return await ke(e,t,o=>{const s=new Date().toISOString();return r={status:o.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:s},{...o,claimedBy:n,claimedAt:s,updatedAt:s}}),await za(e,t,{status:r.status,by:n}),r}async function MA(e,t,n,r={}){let o;return await ke(e,t,s=>{if(!s.claimedBy)return o={status:"release-noop"},s;if(s.claimedBy!==n&&!r.force)throw new CA(s.claimedBy,n);o={status:"released",wasClaimedBy:s.claimedBy};const a=new Date().toISOString(),c={...s,updatedAt:a};return delete c.claimedBy,delete c.claimedAt,c}),o.status!=="release-noop"&&await za(e,t,{status:o.status,by:n,wasClaimedBy:o.wasClaimedBy}),o}async function eo(e,t,n){const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);return r}function to(e){if(typeof e.file!="string"||e.file.trim().length===0)throw new ae("citation.file",`backlog: a citation requires a non-empty "file" — received file=${JSON.stringify(e.file)}.`)}async function Dn(e,t,n,r,o){if(o.citations)for(const c of o.citations)to(c);const s=await eo(e,t,n);let i;await ke(e,s.id,c=>{i=c.status;const u=o.citations&&o.citations.length>0?[...c.citations,...o.citations]:c.citations;if(Ir(r)&&u.length===0)throw new Dp(r);if(xr(r)&&(!o.reason||o.reason.trim().length===0))throw new Lp(r);const l=new Date().toISOString(),f=[...c.notes];o.note&&f.push({by:o.by,at:l,text:o.note}),o.reason&&f.push({by:o.by,at:l,text:`[transition to ${r}] ${o.reason}`});const p={...c,status:r,citations:u,notes:f,updatedAt:l};return qa.has(r)&&(delete p.claimedBy,delete p.claimedAt),p}),await Vp(e,s.id,t,n,"transition",{from:i,to:r,by:o.by,...o.reason?{reason:o.reason}:{}});const a=await e.graph.getNode(s.id);if(!a)throw await Oe(e,t,n);return se(a)}async function DA(e,t,n,r,o){return Dn(e,t,n,r,o)}async function LA(e,t,n,r){const o=await eo(e,t,n),s=await zp(e,o.id,r);if(s.status==="held")throw new Up(s.heldBy??"unknown",s.heldSince??"unknown");return Dn(e,t,n,"IN_PROGRESS",{by:r})}async function UA(e,t,n,r){to(r);const o=await eo(e,t,n);await ke(e,o.id,i=>({...i,citations:[...i.citations,r],updatedAt:new Date().toISOString()}));const s=await e.graph.getNode(o.id);if(!s)throw await Oe(e,t,n);return se(s)}async function BA(e,t,n,r,o){const s=await eo(e,t,n);await ke(e,s.id,a=>{const c=new Date().toISOString();return{...a,notes:[...a.notes,{by:r,at:c,text:o}],updatedAt:c}});const i=await e.graph.getNode(s.id);if(!i)throw await Oe(e,t,n);return se(i)}async function FA(e,t,n={}){const r=new Set((n.exclude??[]).map(i=>i.toUpperCase())),o=await ut(e,{repo:t.repo,projectPath:t.projectPath,status:"closed"}),s=[];for(const i of o){if(r.has(i.humanId.toUpperCase())||!Be(i.status))continue;const a=new Date().toISOString();await ke(e,i.nodeId,u=>({...u,archivedAt:a,updatedAt:a}));const c=await e.graph.getNode(i.nodeId);c&&s.push(se(c))}return s}const qA=new Set(["a","an","and","are","as","at","be","been","but","by","can","do","does","for","from","had","has","have","if","in","into","is","it","its","no","not","of","on","or","our","so","such","than","that","the","their","then","there","these","this","to","was","were","will","with","would","you","your"]);function Wp(e){return Ka(e).toLowerCase().split(" ").filter(t=>t.length>0&&!qA.has(t))}function VA(e,t){if(e.length===0)return!0;const n=new Set(Wp(t));return e.every(r=>n.has(r))}async function KA(e,t,n){var i;const r=new Map,o=Ka(n.title);if(o){const a=Wp(n.title);for(const c of await e.graph.searchNodes(o,{limit:10,filter:{tags:[ge],namespace:t}})){if(!Se(c))continue;const u=((i=c.metadata)==null?void 0:i.title)??c.summary??"";VA(a,u)&&r.set(c.id,c)}}const s=n.dedupeScan;if(s!=null&&s.symbol)for(const a of await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{dedupeSymbol:s.symbol}}))Se(a)&&r.set(a.id,a);if(s!=null&&s.path)for(const a of await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{dedupePath:s.path}}))Se(a)&&r.set(a.id,a);if(s!=null&&s.errorText)for(const a of await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{dedupeErrorText:s.errorText}}))Se(a)&&r.set(a.id,a);return[...r.values()].map(se)}async function Wa(e,t){if(!t.idOverride&&(typeof t.family!="string"||t.family.trim().length===0))throw new ae("family",`backlog: createItem requires a non-empty "family" (e.g. "BUG-APIGEN") unless "idOverride" is given — received family=${JSON.stringify(t.family)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);if(typeof t.title!="string"||t.title.trim().length===0)throw new ae("title",`backlog: createItem requires a non-empty "title" — received title=${JSON.stringify(t.title)}.`);if(typeof t.body!="string"||t.body.trim().length===0)throw new ae("body",`backlog: createItem requires a non-empty "body" — received body=${JSON.stringify(t.body)}.`);if(typeof t.repo!="string"||t.repo.trim().length===0)throw new ae("repo",`backlog: createItem requires a non-empty "repo" — received repo=${JSON.stringify(t.repo)}.`);if(t.citations)for(const s of t.citations)to(s);if(t.idOverride){const s=await qe(e,t.repo,t.idOverride);if(s){const i=se(s);return{item:i,created:!1,duplicateCandidates:[i]}}}const n=t.force?[]:await KA(e,t.repo,t);if(n.length>0&&!t.force)return{item:n[0],created:!1,duplicateCandidates:n};const r=await Gp(e),o=r.size>0&&!r.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...r].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0;return Fp(e,t.repo,t.family,t.idOverride,async(s,i)=>{var h,d,m;if(i){const y=se(i);return{item:y,created:!1,duplicateCandidates:[y]}}const a=nn(s),c=ct(s),u=new Date().toISOString(),l={humanId:s,kind:a,family:c,title:t.title,body:t.body,status:"OPEN",repo:t.repo,citations:t.citations??[],notes:[],createdAt:u,updatedAt:u};t.priority!==void 0&&(l.priority=t.priority),t.projectPath!==void 0&&(l.projectPath=t.projectPath),t.plan!==void 0&&(l.plan=t.plan),t.importedFrom!==void 0&&(l.importedFrom=t.importedFrom),((h=t.dedupeScan)==null?void 0:h.symbol)!==void 0&&(l.dedupeSymbol=t.dedupeScan.symbol),((d=t.dedupeScan)==null?void 0:d.path)!==void 0&&(l.dedupePath=t.dedupeScan.path),((m=t.dedupeScan)==null?void 0:m.errorText)!==void 0&&(l.dedupeErrorText=t.dedupeScan.errorText);const f=await e.graph.writeNode(Zr(t.repo,s,t.title,t.body),{kind:"generic",name:Xr(t.repo,s),summary:t.title,tags:Ja(a,c,t.tags),namespace:t.repo,importance:Ga(t.priority),confidence:"confirmed",...t.projectPath!==void 0?{projectPath:t.projectPath}:{},metadata:l}),p=await e.graph.getNode(f);if(!p)throw new Error(`backlog: writeNode returned an id that does not resolve: ${f}`);return{item:se(p),created:!0,duplicateCandidates:[],...o!==void 0?{repoWarning:o}:{}}})}async function Yp(e,t,n){const r=await qe(e,t,n);return r?se(r):null}async function Qp(e,t,n){const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);return r}async function Zp(e,t,n,r){const o=await Qp(e,t,n);let s="",i="";if(await ke(e,o.id,c=>{const u={...c,updatedAt:new Date().toISOString()};return r.title!==void 0&&(u.title=r.title),r.body!==void 0&&(u.body=r.body),r.projectPath!==void 0&&(u.projectPath=r.projectPath),r.importedFrom!==void 0&&(u.importedFrom=r.importedFrom),s=u.title,i=u.body,u}),r.title!==void 0||r.tags!==void 0||r.projectPath!==void 0){const c={};if(r.title!==void 0&&(c.summary=r.title),r.tags!==void 0){const u=nn(n),l=ct(n);c.tags=Ja(u,l,r.tags)}r.projectPath!==void 0&&(c.projectPath=r.projectPath),await e.graph.touch(o.id,c)}if(r.title!==void 0||r.body!==void 0){const c=Zr(t,n,s,i);await e.adapter.executeRun("UPDATE node SET content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL",[c,Bp(c),o.id])}const a=await e.graph.getNode(o.id);if(!a)throw await Oe(e,t,n);return se(a)}async function GA(e,t,n,r){if(typeof r!="string"||r.trim().length===0)throw new ae("reason",`backlog: softDeleteItem requires a non-empty "reason" — received reason=${JSON.stringify(r)}.`);const o=await Qp(e,t,n);await e.graph.invalidate(o.id,r)}async function Ne(e,t,n){const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);return r}async function JA(e,t,n,r){const o=await Ne(e,t,n),s=await Ne(e,t,r);await e.graph.writeEdge(o.id,s.id,"DEPENDS_ON")}async function HA(e,t,n,r){const o=await Ne(e,t,n),s=await Ne(e,t,r);await e.adapter.executeRun("DELETE FROM edge WHERE src = ? AND dst = ? AND rel = 'DEPENDS_ON'",[o.id,s.id])}async function zA(e,t,n,r){const o=await Ne(e,t,n),s=await Ne(e,t,r);await e.graph.writeEdge(o.id,s.id,"RELATES_TO")}async function WA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new ae("reason",`backlog: supersedeItem requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);if(r.citations)for(const c of r.citations)to(c);const s=await Ne(e,t,n),i=new Date().toISOString(),a=await Fp(e,t,r.family,r.idOverride,c=>c);{const c=nn(a),u=ct(a),l={humanId:a,kind:c,family:u,title:r.title,body:r.body,status:"OPEN",repo:t,citations:r.citations??[],notes:[],createdAt:i,updatedAt:i};r.priority!==void 0&&(l.priority=r.priority),r.projectPath!==void 0&&(l.projectPath=r.projectPath),r.plan!==void 0&&(l.plan=r.plan);const f=await e.graph.supersede(s.id,Zr(t,a,r.title,r.body),{kind:"generic",name:Xr(t,a),summary:r.title,tags:["backlog-item",c,u,...r.tags??[]],namespace:t,importance:Ga(r.priority),confidence:"confirmed",...r.projectPath!==void 0?{projectPath:r.projectPath}:{},metadata:l});await ke(e,s.id,h=>{const d=[...h.notes,{by:"system",at:i,text:`[superseded by ${a}] ${o}`}],m={...h,status:"SUPERSEDED",notes:d,updatedAt:i};return delete m.claimedBy,delete m.claimedAt,m}),await e.graph.invalidate(s.id,o);const p=await e.graph.getNode(f);if(!p)throw new Error(`backlog: supersede() returned an id that does not resolve: ${f}`);return se(p)}}async function YA(e,t,n,r){const o=await Ne(e,t,n),s=[];for(const i of r){const a=await Wa(e,{...i,repo:t});await e.graph.writeEdge(a.item.nodeId,o.id,"PART_OF"),s.push(a.item)}return s}async function QA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new ae("reason",`backlog: mergeItems requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);const s=await Ne(e,t,n),i=await Ne(e,t,r);await ke(e,i.id,c=>{const u=new Date().toISOString(),l={...c,status:"DUPLICATE",notes:[...c.notes,{by:"system",at:u,text:`[merged into ${n}] ${o}`}],updatedAt:u};return delete l.claimedBy,delete l.claimedAt,l}),await e.graph.writeEdge(i.id,s.id,"SAME_AS"),await e.graph.invalidate(i.id,o);const a=await e.graph.getNode(s.id);if(!a)throw await Oe(e,t,n);return se(a)}async function Xp(e,t,n,r){const o=await Ne(e,t,n);await ke(e,o.id,i=>({...i,priority:r,updatedAt:new Date().toISOString()})),await e.graph.touch(o.id,{importance:Ga(r)});const s=await e.graph.getNode(o.id);if(!s)throw await Oe(e,t,n);return se(s)}async function ZA(e,t,n){const r=`${t}::plan:${n}`,s=(await e.graph.queryNodes({kind:"generic",tags:[vl],namespace:t,metadata:{planSlug:n}})).find(i=>i.name===r&&!i.isSuperseded);return s?s.id:e.graph.writeNode(`plan:${n}`,{kind:"generic",name:r,summary:n,tags:[vl],namespace:t,metadata:{planSlug:n}})}async function Js(e,t,n,r){const o=await Ne(e,t,n),s=await ZA(e,t,r);await ke(e,o.id,i=>({...i,plan:r,updatedAt:new Date().toISOString()})),await e.graph.writeEdge(o.id,s,"MEMBER_OF")}async function XA(e,t){const r=(await e.graph.queryNodes({kind:"entity",tags:[wl],metadata:{identity:t}})).find(o=>o.name===t&&!o.isSuperseded);return r?r.id:e.graph.writeNode(`assignee:${t}`,{kind:"entity",name:t,summary:t,tags:[wl],metadata:{identity:t}})}async function ej(e,t,n,r,o){const s=await Ne(e,t,n),i=await XA(e,r);await ke(e,s.id,c=>{const u=new Date().toISOString();return{...c,assignee:r,notes:[...c.notes,{by:o,at:u,text:`assigned to ${r}`}],updatedAt:u}}),await e.graph.writeEdge(s.id,i,"ASSIGNED_TO");const a=await e.graph.getNode(s.id);if(!a)throw await Oe(e,t,n);return se(a)}function zt(e){return e.metadata??{}}function tj(e){const t=/-(\d+)$/.exec(e);return(t==null?void 0:t[1])===void 0?void 0:Number(t[1])}async function nj(e,t,n){if(typeof t!="string"||t.trim().length===0)throw new ae("fromRepo",`backlog: planRepoMigration requires a non-empty fromRepo, received ${JSON.stringify(t)}`);if(typeof n!="string"||n.trim().length===0)throw new ae("toRepo",`backlog: planRepoMigration requires a non-empty toRepo, received ${JSON.stringify(n)}`);if(t===n)throw new ae("toRepo",`backlog: planRepoMigration requires fromRepo and toRepo to differ (both were ${JSON.stringify(t)})`);const r=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t})).filter(Se),o=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:n})).filter(Se),s=new Set,i=new Map;for(const u of o){const l=zt(u),f=l.humanId;if(!f)continue;s.add(f);const p=l.family??ct(f),h=tj(f);h!==void 0&&i.set(p,Math.max(i.get(p)??0,h))}const a=[...r].sort((u,l)=>(zt(u).humanId??"").localeCompare(zt(l).humanId??"")),c=[];for(const u of a){const l=zt(u),f=l.humanId??"",p=l.family??ct(f);let h=f,d=!1;if(s.has(f)){const m=(i.get(p)??0)+1;i.set(p,m),h=`${p}-${String(m).padStart(3,"0")}`,d=!0}s.add(h),c.push({nodeId:u.id,humanId:f,targetHumanId:h,renamed:d,title:l.title??"",status:l.status??"UNKNOWN"})}return{fromRepo:t,toRepo:n,items:c,collisionCount:c.filter(u=>u.renamed).length}}async function rj(e,t,n,r,o){const s=await e.graph.getNode(t.nodeId);if(!s||s.tInvalid||!Se(s))throw new ae("nodeId",`backlog: migration plan item nodeId=${t.nodeId} (humanId=${JSON.stringify(t.humanId)}) is no longer a live backlog item — re-run planRepoMigration and retry.`);const i=zt(s);if(i.humanId!==t.humanId||s.namespace!==n)throw new ae("nodeId",`backlog: migration plan for nodeId=${t.nodeId} is stale — expected (namespace=${JSON.stringify(n)}, humanId=${JSON.stringify(t.humanId)}), found (namespace=${JSON.stringify(s.namespace)}, humanId=${JSON.stringify(i.humanId)}). Re-run planRepoMigration and retry.`);const a=await qe(e,r,t.targetHumanId);if(a)throw new ae("targetHumanId",`backlog: migration target humanId=${JSON.stringify(t.targetHumanId)} in repo=${JSON.stringify(r)} is now claimed by nodeId=${a.id} (it was free when planRepoMigration ran) — re-run planRepoMigration and retry.`);const c=new Date().toISOString(),u=nn(t.targetHumanId),l=ct(t.targetHumanId),f=new Set([ge,i.kind??nn(t.humanId),i.family??ct(t.humanId)]),p=s.tags.filter(d=>!f.has(d));await Ha(()=>e.adapter.transaction(async()=>{const d=await e.graph.getNode(t.nodeId);if(!d||d.tInvalid)throw new ae("nodeId",`backlog: migration plan item nodeId=${t.nodeId} (humanId=${JSON.stringify(t.humanId)}) was invalidated between planning and commit — re-run planRepoMigration and retry.`);const m=zt(d),y=m.title??"",$=m.body??"",v=t.renamed?` and renamed humanId from ${JSON.stringify(t.humanId)} to ${JSON.stringify(t.targetHumanId)} (id collision with an existing item already in ${JSON.stringify(r)})`:"",E=[...m.notes??[],{by:o,at:c,text:`[repo migration] moved from repo=${JSON.stringify(n)}${v} to repo=${JSON.stringify(r)} — BUG-BACKLOG-REPO-SPLIT-001 / DEBT-BACKLOG-REPO-MOVE-001 reconciliation`}],b={...m,repo:r,humanId:t.targetHumanId,kind:u,family:l,notes:E,updatedAt:c};await e.graph.touch(t.nodeId,{metadata:b,name:Xr(r,t.targetHumanId),tags:Ja(u,l,p)});const N=Zr(r,t.targetHumanId,y,$),j=await e.adapter.executeRun("UPDATE node SET namespace = ?, content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL",[r,N,Bp(N),t.nodeId]);if(j.rowsAffected!==1)throw new ae("nodeId",`backlog: namespace UPDATE for nodeId=${t.nodeId} affected ${j.rowsAffected} row(s), expected exactly 1 — rolling back the whole move rather than leaving metadata.repo and node.namespace divergent.`)},{mode:"immediate"}));const h=await e.graph.getNode(t.nodeId);if(!h)throw new ae("nodeId",`backlog: migrateRepoItemNode nodeId=${t.nodeId} vanished mid-move — this should be unreachable.`);return se(h)}async function oj(e,t,n){const r=[];for(const o of t.items)try{await rj(e,o,t.fromRepo,t.toRepo,n),r.push({nodeId:o.nodeId,fromHumanId:o.humanId,toHumanId:o.targetHumanId,renamed:o.renamed,ok:!0})}catch(s){r.push({nodeId:o.nodeId,fromHumanId:o.humanId,toHumanId:o.targetHumanId,renamed:o.renamed,ok:!1,error:s instanceof Error?s.message:String(s)})}return r}async function sj(e,t,n,r,o=!0){const s=await nj(e,t,n);if(o)return{fromRepo:t,toRepo:n,dryRun:!0,plan:s};const i=await oj(e,s,r),a=i.filter(c=>c.ok).length;return{fromRepo:t,toRepo:n,dryRun:!1,plan:s,results:i,succeeded:a,failed:i.length-a}}const Ol=/^(#{2,3})\s+([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)/,ij=["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","CLOSED"],aj=["MITIGATED"],cj=["INVALID","SUPERSEDED","DUPLICATE","WONTFIX"],uj=new Set([...ij,...aj,...cj]),lj=new Set(["OPEN","IN_PROGRESS","PARTIAL","OUTSTANDING","DEFERRED","BLOCKED","MIXED","UNKNOWN","FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function eh(e){const t=e.toUpperCase();return t==="IN-PROGRESS"?"IN_PROGRESS":t==="CLOSED"?"RESOLVED":lj.has(t)?t:"UNKNOWN"}function th(e){var s;const t=(e??"").toLowerCase();if(!t.trim())return null;const n=i=>t.includes(i);if(n("outstanding"))return{label:"OUTSTANDING",open:!0};if(n("partially"))return{label:"PARTIAL",open:!0};if(n("in progress"))return{label:"IN-PROGRESS",open:!0};const r=n("shipped")&&"SHIPPED"||n("superseded")&&"SUPERSEDED"||n("invalid")&&"INVALID"||n("mitigated")&&"MITIGATED"||n("removed")&&!n("open")&&"REMOVED"||n("fixed")&&"FIXED"||n("resolved")&&"RESOLVED"||n("done")&&"DONE"||null,o=n("open")&&"OPEN"||(n("deferred")||n("defer"))&&"DEFERRED"||null;return r&&o?{label:"MIXED",open:!0}:r?{label:r,open:!1}:o?{label:o,open:!0}:n("downgraded")?{label:"OPEN",open:!0}:{label:((s=t.trim().split(/\s+/)[0])==null?void 0:s.toUpperCase().replace(/[^A-Z]/g,""))||"UNKNOWN",open:!0}}function nh(e,t){const n=t.match(/^\s*-?\s*\*\*Status:\*?\*?\s*([^\n]+)/im),r=n?th(n[1]):null;if(r)return r;const o=e.toUpperCase();for(const s of["RESOLVED","FIXED","MITIGATED","DONE","CLOSED"])if(o.includes(s))return{label:s,open:!1};return{label:"UNKNOWN",open:!0}}function rh(e,t){const r=`${e}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
`),a=nh(o.headerLine,i),c=rh(o.headerLine,i),{bodyLines:u,...l}=o,f=!uj.has(a.label);n.push({...l,status:a.label,open:f,terminal:!f,priority:c,body:i.trim()}),o=null};return t.forEach((i,a)=>{const c=i.match(Ol),u=/^#{2,3}\s/.test(i);if(c&&/\d/.test(c[2])){s();const l=c[2],f=i.replace(Ol,"").replace(/^\s*[—–-]\s*/,"").trim(),p=l.split("-");o={id:l,kind:p[0]??l,family:l.replace(/-\d+[a-z]?$/i,""),title:f,level:c[1].length,line:a+1,headerLine:i,bodyLines:[]}}else if(u){const l=i.replace(/^#{2,3}\s+/,"");dj(l)&&r.push({line:a+1,headerLine:i}),s(),o=null}else o&&o.bodyLines.push(i)}),s(),{items:n,malformedHeaders:r}}function pj(e){return oh(e).items}function sh(e){return oh(e)}function hj(e){return`**Citations:** [${e.map(n=>{const r=n.lines?`${n.file}:${n.lines}`:n.file;return n.context?`${r} (${n.context})`:r}).join(", ")}]`}function mj(e){return e==="IN_PROGRESS"?"IN PROGRESS":e}function ih(e){const t=[];t.push(`### ${e.humanId} — ${e.title}`),t.push(""),t.push(`**Status:** ${mj(e.status)}`),e.priority&&t.push(`**Priority:** ${e.priority}`),e.assignee&&t.push(`**Assignee:** ${e.assignee}`),e.plan&&t.push(`**Plan:** ${e.plan}`),t.push(""),e.body&&t.push(e.body,""),e.citations.length>0&&t.push(hj(e.citations));for(const n of e.notes)t.push(`- Note (${n.by}, ${n.at}): ${n.text}`);return t.join(`
|
|
183
|
-
|
|
356
|
+
`}function l2(t){return`event: error
|
|
357
|
+
data: ${t}
|
|
358
|
+
|
|
359
|
+
`}async function d2(t,e,n){const r=new AbortController;e.raw.once("close",()=>r.abort());const o=n.raw;let s=!1;try{for await(const i of t){if(r.signal.aborted)break;s||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),s=!0),o.write(u2(JSON.stringify(i)))}s||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(i){const a=Uf(i)?i:new VD("internal",i instanceof Error?i.message:String(i));if(s)o.write(l2(JSON.stringify(a.toJSON()))),o.end();else{const c=p2(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const f2={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function p2(t){return f2[t]??500}function L0(t){return Uf(t)?KD[t.code]??500:500}function D0(t){return Uf(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:"Internal error"}}function h2(t,e){if(t)for(const n of e){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),t.info(n,o)}}let m2=class{constructor(e,n,r){this.app=e,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}routeFor(e){return e.isMount?`${this.routePrefix}/${e.op.id}`:this.routePrefix+e.http.route}registerRoute(e,n){const r=this.routeFor(e),o=async(s,i)=>{const a={req:s,reply:i};try{const c=await this.readCall(a,e),u=await n(c);await this.writeResult(a,u,e)}catch(c){await this.writeError(a,c,e)}};e.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(e,n){const{req:r}=e,o=r.headers,s={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(s[a.field]=c)}let i={};if(n.isMount)i=n.http.verb==="GET"?r.query??{}:r.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};i=a?$U(c,a):c}else{const{data:c={}}=r.body??{};i=c}}return{envelope:s,domainArgs:i,signal:this.signal}}async writeResult(e,n,r){const{req:o,reply:s}=e;if(NU(n)){await d2(n,o,s);return}s.type("application/json"),s.send(JSON.stringify(n===void 0?null:n))}writeError(e,n,r){const{reply:o}=e;o.status(L0(n)).send(D0(n))}};function g2(t,e,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of t){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,e[c.id],o);for(const d of l)d.transports&&!d.transports.includes("http")||i.push(d)}return i}async function y2(t){var e,n;const r=t.options.port??3e3,o=t.options.host??"127.0.0.1",s=t.options.routePrefix??"",i=t.options.projection??{},a=e2(t.options),c=t2(t.options),u=t.logger??hU(),l=nE({logger:u});l.setErrorHandler((b,E,N)=>{N.status(L0(b)).send(D0(b))});const d=new m2(l,s,t.signal),f=[],g={},p={};for(const b of t.packages){if(!b.fns)throw new Error(`Package "${b.id}" is missing fns`);const E=b.fns,N=Object.entries(b.schemas).map(([G,H])=>({fnName:G,fnSchema:H,op:M0(b.id,G,H,t.operations)})),j={},T={};for(const{fnName:G,fnSchema:H,op:Z}of N)j[Z.id]=H,T[Z.id]=E[G],g[Z.id]=H,p[Z.id]=E[G];const M=Ec(j,a),C={fns:T,createClient:b.createClient,schemas:j};for(const{fnSchema:G,op:H}of N){const Z=Ku({op:H,schema:G,transport:"http",projection:i});d.bindSchema(H.id,G),d.registerRoute(Z,he=>Hm(Z,M,he,C));const{params:ue,text:fe}=T0(G);f.push({method:Z.http.verb,route:s+Z.http.route,text:fe,params:ue})}}const y=((e=t.packages[0])==null?void 0:e.id)??"ts",w=Ec(g,a),h={invoke:(b,E,N)=>w(b,{operation:{id:b},ctx:new R0,domainArgs:E.domainArgs,envelope:E.envelope,signal:E.signal},N),invokeOptions:{fns:p,schemas:g,createClient:(n=t.packages[0])==null?void 0:n.createClient}},v=g2(a,c,y,t.operations??[],h);if(v.length>0){const b=Ec({},a),E={fns:{},schemas:{}};for(const N of v){const j=Ku({op:N,transport:"http",projection:i});d.registerRoute(j,T=>Hm(j,b,T,E)),f.push({method:j.http.verb,route:`${s}/${N.id}`,text:"",params:[]})}}return await l.listen({port:r,host:o}),u.info({host:o,port:r},`listening on http://${o}:${r}`),h2(u,f),new Promise(b=>{t.signal&&t.signal.addEventListener("abort",async()=>{await l.close(),b()})})}const w2={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(t){return c2(t)},run(t){return y2(t)}};function Qm(t){return{raw:t,words:t.split(/(?=[A-Z])|[-_]/).map(e=>e.toLowerCase()).filter(Boolean)}}function v2(t,e,n={}){const r=t.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${t}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:t,host:e.host,namespace:Qm(i),path:s.map(Qm),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const $2={"decimal.js":"Decimal"};function b2(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries($2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${b2(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Ym=new Set(["string","number","boolean","integer"]);function E2(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Ym.has(n):Array.isArray(n)?n.every(r=>Ym.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function S2(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(E2)}const _2={"decimal.js":"Decimal"};function N2(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(_2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${N2(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Zm(t){return t.words.join("-")}function Xm(t){return t.words.map(k2).join("")}function eg(t){return t.words.join("_")}function O2(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||S2(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>Zm(g)).join("/"),c=o.map(g=>eg(g)).join("_"),u=o.map(g=>eg(g)).slice(0,-1).join("."),l=Xm(o[o.length-2]??o[0]),d=Xm(o[o.length-1]),f=o.map(g=>Zm(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function k2(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function j2(t,e={}){const n=e.title??"API",r=e.version??"0.0.0",o={};for(const s of t){const i=O2(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:A2(s.output)}};if(a==="GET")l.parameters=I2(s.input);else{const d=s.input;typeof d=="object"&&d!==null&&Object.keys(d).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:d}}})}o[c]===void 0&&(o[c]={}),o[c][u]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function A2(t){return typeof t=="object"&&t!==null&&Object.keys(t).length>0?{description:"Success",content:{"application/json":{schema:t}}}:{description:"Success"}}function I2(t){if(typeof t!="object"||t===null||typeof t.properties!="object"||t.properties===null)return[];const e=Array.isArray(t.required)?t.required:[],n=t.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:e.includes(r),schema:o}))}function P2(t,e={}){return[{...v2("_meta/openapi",t,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>j2(t.operations,{title:e.title,version:e.version})}]}const x2={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(t,e){return P2(t,e)}}}},Gu="$apigen";let tg=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function R2(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new tg(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new tg("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Jf="x-apigen-logical",Qf="x-apigen-codec",zu="x-apigen-ctor",Wu="x-apigen-tojson",T2="0.1.0";function ng(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" 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",...e}}function Br(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Br(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=U0(t,s,e,n);return Br(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return ts(t,e,n);const a=e.items;if(!a)return t.map(u=>lr(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?lr(u):Br(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Br(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return ts(t,e,n);const a=e.properties;if(!a)return lr(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Br(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?ts(t,e,n):lr(t)}function Fr(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Fr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=U0(t,s,e,n);return Fr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Fr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Fr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Fr(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Hu(t,n):t}function U0(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=sa(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=C2(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=sa(u,r),d=B0(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function sa(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function rg(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function C2(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>sa(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))rg(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?rg(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function M2(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function B0(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=B0(t,sa(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=M2(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function ts(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[Gu]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>ts(o,{},n));if(F0(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=ts(i,{},n));return o}return lr(t)}function F0(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Hu(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&Gu in t){const n=t,r=n[Gu],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Hu(n,e));if(F0(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Hu(o,e);return n}return t}function lr(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(lr);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=lr(r));return e}return null}function L2(t){return{encode(e,n,r){const o=ng(t,r);return Br(e,n,o)},decode(e,n,r){const o=ng(t,r);return Fr(e,n,o)}}}const Yf={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},Zf={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},Xf={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},ep={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},D2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,tp={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!D2.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},Ju="NaN",Qu="Infinity",Yu="-Infinity",U2=new Set([Ju,Qu,Yu]),np={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?Ju:t===1/0?Qu:t===-1/0?Yu:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===Ju)return NaN;if(t===Qu)return 1/0;if(t===Yu)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...U2].join(", ")}.`);return NaN}},B2=[Yf,Zf,Xf,ep,tp,np];function F2(t,e={}){for(const n of B2)t.register(n,{override:e.override??!1})}const q2=12;function K2(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,r,o]=n,s=r==="$defs"?e.$defs:e.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function og(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function V2(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function G2(t){switch(t.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function sg(t,e,n){const r=t.properties??{},o=t.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?ws(a,e,n+1):`<${i}>`}return s}function z2(t,e,n){const r=Array.isArray(t.items)?t.items[0]:t.items;return r?[ws(r,e,n+1)]:[]}function ws(t,e=t??{},n=0){if(!t||n>q2)return null;if(typeof t.$ref=="string"){const o=K2(t.$ref,e);return o!==void 0?ws(o,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const o={},s=[];for(const i of t.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return sg({...t,properties:o,required:s},e,n)}const r=og(t.oneOf)??og(t.anyOf);if(r)return ws(r,e,n+1);switch(V2(t)){case"object":return sg(t,e,n);case"array":return z2(t,e,n);case"string":return G2(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function q0(t){if(!t)return;const e=ws(t);return`Example: ${JSON.stringify(e)}`}Yf.id,Zf.id,Xf.id,ep.id,tp.id,np.id;const K0=R2();F2(K0);const V0=L2(K0.freeze());function W2(t,e){var n;const r=((n=t.input)==null?void 0:n.properties)??{};return e in r}function H2(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function J2(t,e){var n,r,o;const s=(o=(r=(n=t.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[e];return i!==void 0?i:void 0}function Q2(t,e){return e===void 0||t===void 0?t:V0.decode(t,e)}function Sc(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:V0.encode(t,n)}async function Y2(t,e,n,r,o,s){const i=H2(n).map(c=>Q2(s[c],J2(n,c)));if(W2(n,"session")&&e){const c=await e({session:o.session}),u=await t[r](c,...i);return Sc(u,n)}if(n.hasCtx){const c=e?await e(o):void 0,u=await t[r](c,...i);return Sc(u,n)}const a=await t[r](...i);return Sc(a,n)}class G0{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}}function Z2(t=[]){return async function(e,n,r){const o=r.schemas[e];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${e}"`);const s=()=>Y2(r.fns,r.createClient,o,e,n.envelope,n.domainArgs);return t.reduceRight((i,a)=>()=>a(n,i),s)()}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const X2={"decimal.js":"Decimal"};function eB(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(X2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${eB(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function tB(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,r=!n&&!!process.stderr.isTTY,o=t.format??(r?"pretty":"json"),s={level:e};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},pt(s);const i=n?pt.destination({dest:t.destination,mkdir:!0,sync:!0}):pt.destination(2);return pt(s,i)}function nB(t){if(!t||t.type!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([r,o])=>`${r}${n.has(r)?"":"?"}: ${Va(o)}`).join(", ")} }`}function rB(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function oB(t){const e=t.enum??[];return e.length===0?"unknown":e.map(rB).join("|")}function sB(t,e){return t.map(n=>Va(n,e)).join(" | ")}function Va(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${Va(t.items,0)}[]`;if(t.enum)return oB(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?sB(n,e-1):"union":e>=1&&t.type==="object"?nB(t)??"object":t.type??"object"}function iB(t){var e;const n=(e=((t==null?void 0:t.input)??{}).properties)==null?void 0:e.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:Va(c,2),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const aB=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class z0 extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}}function cB(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&aB.includes(t.code)&&typeof t.toJSON=="function"}function ig(t,e,n=0){return t==="before-first-chunk"?{phase:t,error:e}:{phase:t,error:e,chunksDelivered:n}}const Ga=new ia({allErrors:!0});aa(Ga);for(const t of[Jf,Qf,zu,Wu,"discriminator"])Ga.addKeyword({keyword:t,valid:!0});Ga.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function uB(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function lB(t,e){const n=q0(e),r=[`Validation failed: ${uB(t)}`];return n&&r.push(n),r.join(" — ")}function dB(t){return async function(e,n){const r=e.operation.id,o=t[r];if(o===void 0)return n();const s={data:e.domainArgs,...e.envelope},i=Ga.compile(o.input);if(!i(s)){const a=i.errors??[];throw new z0("invalid_argument",lB(a,o.input),a)}return n()}}async function fB(t){const e=[];try{for await(const n of t)e.push(n);return{ok:!0,chunks:e}}catch(n){const r=cB(n)?n:new z0("internal",n instanceof Error?n.message:String(n));return e.length===0?{ok:!1,carrier:ig("before-first-chunk",r)}:{ok:!1,carrier:ig("after-first-chunk",r,e.length)}}}function pB(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}class Hn extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}}function _c(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function W0(t,e){const n=t[Qf];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function hB(t,e,n){const r=W0(e,n);return r?r.encode(t,e,n):t}function mB(t,e,n){const r=W0(e,n);return r?r.decode(t,e,n):t}function gB(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[Jf]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:_c(r)!==void 0},encode(r,o,s){const i=_c(o);if(!i)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new Hn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return hB(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new Hn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=_c(o);if(!a)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new Hn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return mB(r,g,{...s,path:`${s.path}[${d}]`})}}}const yB="x-apigen-instances";class si extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}}function ag(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function wB(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function cg(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function vB(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function $B(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[Jf]==="nominal"?!0:o[Qf]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new si("E_NOMINAL_CYCLE",`[${e}] 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=ag(s),c=typeof s[Wu]=="string"?s[Wu]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=cg(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=cg(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new si("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of wB(s))if(!(l in a))throw new si("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[yB]===!1)throw new si("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=ag(s),u={};for(const[l,d]of Object.entries(a))u[l]=vB(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[zu]=="string"?s[zu]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const bB=[Yf,Zf,Xf,ep,tp,np],EB={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},ug=$B({id:"ts.NominalSentinel",schema:EB}),SB={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},lg=gB({id:"ts.UnionSentinel",schema:SB});function _B(){const t=[...bB.map(e=>[e.id,e]),[ug.id,ug],[lg.id,lg]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:T2,codecs:_B()});function Zu(t,e,n){var r;const o=typeof((r=e==null?void 0:e.input)==null?void 0:r.description)=="string"?e.input.description:void 0,s=q0(e==null?void 0:e.input),i=[n,o,s].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):t}function H0(t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).length===0)return{outputSchema:void 0,wrapped:!1};const e=t;return e.type==="object"?{outputSchema:e,wrapped:!1}:{outputSchema:{type:"object",properties:{result:e},required:["result"]},wrapped:!0}}function NB(t,e){return t?{result:e}:e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const dg=new Set(["string","number","boolean","integer"]);function OB(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?dg.has(n):Array.isArray(n)?n.every(r=>dg.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function kB(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(OB)}const jB={"decimal.js":"Decimal"};function AB(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(jB).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${AB(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function fg(t){return t.words.join("-")}function pg(t){return t.words.map(TB).join("")}function hg(t){return t.words.join("_")}function IB(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||kB(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>fg(g)).join("/"),c=o.map(g=>hg(g)).join("_"),u=o.map(g=>hg(g)).slice(0,-1).join("."),l=pg(o[o.length-2]??o[0]),d=pg(o[o.length-1]),f=o.map(g=>fg(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function PB(t,e){return`x-${t}-${e}`}function xB(t,e){return`--${t}-${e}`}function RB(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function TB(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function rp(t){return t.anyOf??t.oneOf}function CB(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=rp(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function MB(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=rp(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function LB(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=rp(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function DB(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function UB(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function mg(t){return typeof t.handler=="function"}function BB(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=PB(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:xB(i,s),envVar:RB(i,s)})}return o}function FB(t,e,n,r){e===n||t.has(e)||t.set(e,{...r,aliasOf:n})}function qB(t,e){const n=new Map,{props:r}=UB(t);for(const[o,s]of Object.entries(r)){let i="string";MB(s)?i="boolean":(CB(s)||LB(s))&&(i="json");const a=DB(o),c={camelKey:o,kind:"domain",valueKind:i};n.set(a,c),FB(n,o,a,c)}for(const o of e){const s=o.cliFlag.replace(/^--/,""),i={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(s,i)}return n}function Xu(t){const{op:e,schema:n,transport:r,projection:o}=t,s=IB(e,o),i=n?BB(n):[],a=n?qB(n,i):new Map,c=n?iB(n).params:void 0,u={op:e,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:e.streaming,isMount:mg(e)};if(mg(e)){const l=e.handler;u.mountHandler=async d=>l(d)}return u}function KB(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function VB(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function GB(t){return async function(e,n){const r=Object.assign(e,{data:e.domainArgs});return await t.layer(r,n)}}function Nc(t,e){var n;const r=[];for(const o of e){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(GB(s))}return r.push(dB(t)),Z2(r)}function zB(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const WB={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function gg(t,e,n,r){const o={...n,operation:{id:t.op.id},ctx:new G0};if(t.isMount){const s=t.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const i={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:zB(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[t.op.id]:()=>s(i)},schemas:{[t.op.id]:WB}};return e(t.op.id,o,a)}return e(t.op.id,o,r)}function HB(){return`// Auto-generated by @adhd/apigen-cli — do not edit
|
|
360
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
361
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
362
|
+
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
363
|
+
import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
|
|
364
|
+
import { toolMetas, groupFns, groupCreateClient } from './index.js'
|
|
365
|
+
|
|
366
|
+
// §9.1 — extract envelope from MCP _meta["x-<pluginId>-<field>"].
|
|
367
|
+
// x-apigen-envelope (field→pluginId map) is carried on each schema entry.
|
|
368
|
+
function extractEnvelope(schema: Record<string, unknown>, meta: Record<string, unknown>): Record<string, unknown> {
|
|
369
|
+
const inputProps = ((schema['input'] as any)?.['properties'] as Record<string, unknown>) ?? {}
|
|
370
|
+
const envMeta = schema['x-apigen-envelope'] as Record<string, string> | undefined
|
|
371
|
+
const envelope: Record<string, unknown> = {}
|
|
372
|
+
for (const field of Object.keys(inputProps)) {
|
|
373
|
+
if (field === 'data') continue
|
|
374
|
+
const pluginId = envMeta?.[field] ?? 'adhd'
|
|
375
|
+
const key = \`x-\${pluginId}-\${field}\`
|
|
376
|
+
if (meta[key] !== undefined) envelope[field] = meta[key]
|
|
377
|
+
}
|
|
378
|
+
return envelope
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const server = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabilities: { tools: {} } })
|
|
382
|
+
|
|
383
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
384
|
+
tools: Object.entries(toolMetas).map(([name, meta]) => {
|
|
385
|
+
// BUG-APIGEN-019: publish the function's return-type schema (oneOf+discriminator
|
|
386
|
+
// for unions) as MCP's outputSchema — wrapped under \`result\` when it isn't
|
|
387
|
+
// top-level type:"object", since the MCP protocol requires that shape.
|
|
388
|
+
const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
|
|
389
|
+
return {
|
|
390
|
+
name,
|
|
391
|
+
// BUG-APIGEN-020: description baked at generate time by generate.ts —
|
|
392
|
+
// documents the "data" envelope calling convention (+ any envelope
|
|
393
|
+
// fields) so consumers don't have to discover it by trial and error.
|
|
394
|
+
description: (meta as any).description ?? name,
|
|
395
|
+
inputSchema: (meta.schema as any).input,
|
|
396
|
+
...(outputSchema ? { outputSchema } : {}),
|
|
397
|
+
}
|
|
398
|
+
}),
|
|
399
|
+
}))
|
|
400
|
+
|
|
401
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
402
|
+
const { name, arguments: args = {} } = req.params
|
|
403
|
+
const meta = toolMetas[name]
|
|
404
|
+
if (!meta) throw new Error(\`Unknown tool: \${name}\`)
|
|
405
|
+
// §9.1: envelope from _meta, domain args from data
|
|
406
|
+
const mcpMeta = (args as any)['_meta'] as Record<string, unknown> | undefined ?? {}
|
|
407
|
+
const envelope = extractEnvelope(meta.schema as Record<string, unknown>, mcpMeta)
|
|
408
|
+
// Dispatch by the REAL exported fn name (\`meta.fnName\`, not the incoming
|
|
409
|
+
// call's canonical tool name \`name\`) — see ../tool-naming.ts module doc
|
|
410
|
+
// (BUG-APIGEN-OPENAPI-ROUTE-PATH-MISMATCH-001 / BEHAVIOR CHANGE).
|
|
411
|
+
const result = await dispatch(
|
|
412
|
+
groupFns[meta.group],
|
|
413
|
+
groupCreateClient[meta.group],
|
|
414
|
+
meta.schema as any,
|
|
415
|
+
meta.fnName,
|
|
416
|
+
envelope,
|
|
417
|
+
((args as any)['data'] ?? {}) as Record<string, unknown>,
|
|
418
|
+
)
|
|
419
|
+
// BUG-APIGEN-019: pair outputSchema with a matching structuredContent value.
|
|
420
|
+
const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
|
|
421
|
+
const structuredContent = wrapMcpStructuredContent(wrapped, result)
|
|
422
|
+
return {
|
|
423
|
+
content: [{ type: 'text', text: JSON.stringify(result) }],
|
|
424
|
+
...(structuredContent ? { structuredContent } : {}),
|
|
425
|
+
}
|
|
426
|
+
})
|
|
427
|
+
|
|
428
|
+
const transport = new StdioServerTransport()
|
|
429
|
+
server.connect(transport)
|
|
430
|
+
`}function JB(t,e){return`// Auto-generated by @adhd/apigen-cli — do not edit
|
|
431
|
+
import { createServer } from 'node:http'
|
|
432
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
433
|
+
${t==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
|
|
434
|
+
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
435
|
+
import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
|
|
436
|
+
import { toolMetas, groupFns, groupCreateClient } from './index.js'
|
|
437
|
+
|
|
438
|
+
// §9.1 — extract envelope from MCP _meta["x-<pluginId>-<field>"].
|
|
439
|
+
// x-apigen-envelope (field→pluginId map) is carried on each schema entry.
|
|
440
|
+
function extractEnvelope(schema: Record<string, unknown>, meta: Record<string, unknown>): Record<string, unknown> {
|
|
441
|
+
const inputProps = ((schema['input'] as any)?.['properties'] as Record<string, unknown>) ?? {}
|
|
442
|
+
const envMeta = schema['x-apigen-envelope'] as Record<string, string> | undefined
|
|
443
|
+
const envelope: Record<string, unknown> = {}
|
|
444
|
+
for (const field of Object.keys(inputProps)) {
|
|
445
|
+
if (field === 'data') continue
|
|
446
|
+
const pluginId = envMeta?.[field] ?? 'adhd'
|
|
447
|
+
const key = \`x-\${pluginId}-\${field}\`
|
|
448
|
+
if (meta[key] !== undefined) envelope[field] = meta[key]
|
|
449
|
+
}
|
|
450
|
+
return envelope
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const mcpServer = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabilities: { tools: {} } })
|
|
454
|
+
|
|
455
|
+
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
456
|
+
tools: Object.entries(toolMetas).map(([name, meta]) => {
|
|
457
|
+
// BUG-APIGEN-019: publish the function's return-type schema (oneOf+discriminator
|
|
458
|
+
// for unions) as MCP's outputSchema — wrapped under \`result\` when it isn't
|
|
459
|
+
// top-level type:"object", since the MCP protocol requires that shape.
|
|
460
|
+
const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
|
|
461
|
+
return {
|
|
462
|
+
name,
|
|
463
|
+
// BUG-APIGEN-020: description baked at generate time by generate.ts —
|
|
464
|
+
// documents the "data" envelope calling convention (+ any envelope
|
|
465
|
+
// fields) so consumers don't have to discover it by trial and error.
|
|
466
|
+
description: (meta as any).description ?? name,
|
|
467
|
+
inputSchema: (meta.schema as any).input,
|
|
468
|
+
...(outputSchema ? { outputSchema } : {}),
|
|
469
|
+
}
|
|
470
|
+
}),
|
|
471
|
+
}))
|
|
472
|
+
|
|
473
|
+
mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
474
|
+
const { name, arguments: args = {} } = req.params
|
|
475
|
+
const meta = toolMetas[name]
|
|
476
|
+
if (!meta) throw new Error(\`Unknown tool: \${name}\`)
|
|
477
|
+
// §9.1: envelope from _meta, domain args from data
|
|
478
|
+
const mcpMeta = (args as any)['_meta'] as Record<string, unknown> | undefined ?? {}
|
|
479
|
+
const envelope = extractEnvelope(meta.schema as Record<string, unknown>, mcpMeta)
|
|
480
|
+
// Dispatch by the REAL exported fn name (\`meta.fnName\`, not the incoming
|
|
481
|
+
// call's canonical tool name \`name\`) — see ../tool-naming.ts module doc
|
|
482
|
+
// (BUG-APIGEN-OPENAPI-ROUTE-PATH-MISMATCH-001 / BEHAVIOR CHANGE).
|
|
483
|
+
const result = await dispatch(
|
|
484
|
+
groupFns[meta.group],
|
|
485
|
+
groupCreateClient[meta.group],
|
|
486
|
+
meta.schema as any,
|
|
487
|
+
meta.fnName,
|
|
488
|
+
envelope,
|
|
489
|
+
((args as any)['data'] ?? {}) as Record<string, unknown>,
|
|
490
|
+
)
|
|
491
|
+
// BUG-APIGEN-019: pair outputSchema with a matching structuredContent value.
|
|
492
|
+
const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
|
|
493
|
+
const structuredContent = wrapMcpStructuredContent(wrapped, result)
|
|
494
|
+
return {
|
|
495
|
+
content: [{ type: 'text', text: JSON.stringify(result) }],
|
|
496
|
+
...(structuredContent ? { structuredContent } : {}),
|
|
497
|
+
}
|
|
498
|
+
})
|
|
499
|
+
|
|
500
|
+
const mcpTransport = new ${t==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
|
|
501
|
+
const httpServer = createServer((req, res) => (mcpTransport as any).handleRequest(req, res))
|
|
502
|
+
httpServer.listen(${e}, () => console.error('MCP ${t} server on port ${e}'))
|
|
503
|
+
`}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const QB={"decimal.js":"Decimal"};function YB(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(QB).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${YB(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function ZB(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const XB={"decimal.js":"Decimal"};function eF(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(XB).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${eF(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function tF(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function el(t){return{raw:t,words:ZB(t)}}function nF(t){return el(tF(Ic.basename(t)))}function J0(t,e,n){if(n){const o=n.find(s=>{var i;return s.kind==="action"&&s.namespace.raw===t.id&&((i=s.path[s.path.length-1])==null?void 0:i.raw)===e});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${t.id}" fn "${e}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const r=el(e);return{id:`${t.id}/${e}`,host:"ts",namespace:el(t.id),path:t.dropFileSegment?[r]:[nF(t.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function rF(t,e,n){const r=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const o of t)r.push(`import * as ${o.id}_ns from '${o.importPath}'`),r.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);r.push(""),r.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const o of t)for(const[s,i]of Object.entries(o.schemas)){const a=J0({id:o.id,importPath:o.importPath},s,n),c=Xu({op:a,schema:i,transport:"mcp"}).mcp.name,u=Zu(c,i,e[c]??e[s]);r.push(` ${JSON.stringify(c)}: { group: '${o.id}', fnName: ${JSON.stringify(s)}, schema: ${JSON.stringify(i)}, description: ${JSON.stringify(u)} },`)}r.push("}"),r.push(""),r.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const o of t)r.push(` '${o.id}': ${o.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 o of t)r.push(` '${o.id}': undefined, // injected at startup if createClient provided`);return r.push("}"),r.join(`
|
|
504
|
+
`)}function oF(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,r=t.options.toolDescriptions??{},o=t.operations,s=rF(t.packages,r,o),i=e==="stdio"?HB():JB(e,n);return{files:[{path:"index.ts",content:s},{path:"server.ts",content:i}]}}const sF=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function Q0(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&sF.includes(t.code)&&typeof t.toJSON=="function"}async function iF(t){const e=await fB(t);if(e.ok){const o=e.chunks.map(s=>({type:"text",text:JSON.stringify(s)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=e;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}class aF{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}bindToolMeta(e,n){this.toolMeta.set(e,n)}registerRoute(e,n){this.plans.set(e.mcp.name,e),this.dispatchers.set(e.mcp.name,n)}getPlan(e){return this.plans.get(e)}getDispatch(e){return this.dispatchers.get(e)}listTools(){return[...this.plans.keys()].map(e=>{const n=this.toolMeta.get(e);return{name:e,description:(n==null?void 0:n.description)??e,inputSchema:(n==null?void 0:n.inputSchema)??{type:"object",properties:{}},...n!=null&&n.outputSchema?{outputSchema:n.outputSchema}:{}}})}readCall(e,n){const r={};for(const s of n.envelope){const i=e.meta[s.mcpMetaKey];i!==void 0&&(r[s.field]=i)}const o=n.isMount?e.args:e.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(e,n,r){if(pB(n)){e.output=await iF(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=H0(o==null?void 0:o.output),i=NB(s,n);e.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(e,n,r){throw Q0(n)&&n.code,n}}function cF(t){if(t&&typeof t=="object"&&t.type==="object")return t;const e=t==null?void 0:t.oneOf;if(Array.isArray(e)&&e.length>0){const n={};let r=null;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=s.properties;if(i&&typeof i=="object")for(const[c,u]of Object.entries(i))c in n||(n[c]=u);const a=Array.isArray(s.required)?s.required:[];r=r===null?[...a]:r.filter(c=>a.includes(c))}return{...t,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function uF(t,e,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of t){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,e[c.id],o);for(const d of l)d.transports&&!d.transports.includes("mcp")||i.push(d)}return i}function lF(t,e){var n,r;const o=t.options.projection??{},s=t.options.toolDescriptions??{},i=KB(t.options),a=VB(t.options),c={},u={};for(const p of t.packages){if(!p.fns)throw new Error(`Package "${p.id}" is missing fns`);const y=p.fns,w=Object.entries(p.schemas).map(([N,j])=>({fnName:N,fnSchema:j,op:J0({id:p.id,importPath:p.importPath},N,t.operations)})),h={},v={};for(const{fnName:N,fnSchema:j,op:T}of w)h[T.id]=j,v[T.id]=y[N],c[T.id]=j,u[T.id]=y[N];const b=Nc(h,i),E={fns:v,createClient:p.createClient,schemas:h};for(const{fnName:N,fnSchema:j,op:T}of w){const M=Xu({op:T,schema:j,transport:"mcp",projection:o});e.bindSchema(T.id,j);const{outputSchema:C}=H0(j.output),G=Zu(M.mcp.name,j,s[M.mcp.name]??s[N]);e.bindToolMeta(M.mcp.name,{description:G,inputSchema:j.input,outputSchema:C}),e.registerRoute(M,H=>gg(M,b,H,E))}}const l=((n=t.packages[0])==null?void 0:n.id)??"ts",d=Nc(c,i),f={invoke:(p,y,w)=>d(p,{operation:{id:p},ctx:new G0,domainArgs:y.domainArgs,envelope:y.envelope,signal:y.signal},w),invokeOptions:{fns:u,schemas:c,createClient:(r=t.packages[0])==null?void 0:r.createClient}},g=uF(i,a,l,t.operations??[],f);if(g.length>0){const p=Nc({},i),y={fns:{},schemas:{}};for(const w of g){const h=Xu({op:w,transport:"mcp",projection:o}),v=cF(w.input),b=Zu(h.mcp.name,{input:v},s[h.mcp.name]);e.bindToolMeta(h.mcp.name,{description:b,inputSchema:v}),e.registerRoute(h,E=>gg(h,p,E,y))}}}function dF(t){const e=t.packages[0];return{name:(e==null?void 0:e.id)??"apigen-mcp",version:(e==null?void 0:e.version)??"1.0.0"}}function Oc(t,e,n){const r=new rE.Server(n,{capabilities:{tools:{}}});return r.setRequestHandler(gp.ListToolsRequestSchema,async()=>({tools:t.listTools()})),r.setRequestHandler(gp.CallToolRequestSchema,async o=>{const{name:s,arguments:i={}}=o.params,a=t.getPlan(s),c=t.getDispatch(s);if(!a||!c)throw new Error(`Unknown tool: ${s}`);const u=i,l=u._meta??{},d={args:u,meta:l},f=Date.now();try{const g=await t.readCall(d,a),p=await c(g);return await t.writeResult(d,p,a),e.info({tool:s,ms:Date.now()-f},`→ ${s}`),d.output}catch(g){throw Q0(g)&&g.code!=="internal"?e.error({tool:s,ms:Date.now()-f,code:g.code,message:g.message},`✗ ${s}`):e.error({tool:s,ms:Date.now()-f,err:g},`✗ ${s}`),t.writeError(d,g,a),g}}),r}function yg(t,e){return async(n,r)=>{try{await e(n,r)}catch(o){t.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}async function fF(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,r=t.options.host??"127.0.0.1",o=t.logger??tB();o.info(`mcp server starting (${e})`);const s=new aF;lF(t,s);const i=s.listTools().map(u=>u.name);o.info({tools:i},`${i.length} tools available`);for(const u of i){const l=s.getPlan(u),d=(l==null?void 0:l.params)??[],f=d.map(g=>`${g.name}${g.required?"":"?"}: ${g.type}`).join(", ");o.info({tool:u,args:{data:d}},`tool: ${u} args { data: {${f?` ${f} `:""}} }`)}const a=dF(t);if(o.info({identity:a},`mcp handshake identity: ${a.name}@${a.version}`),e==="stdio"){const u=Oc(s,o,a),l=new oE.StdioServerTransport;return await u.connect(l),o.info("stdio transport ready"),new Promise(d=>{t.signal&&t.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),d()})})}if(e==="sse"){const u=new Map,l=mp.createServer(yg(o,async(d,f)=>{const g=d.url??"";if(d.method==="GET"&&g==="/sse"){const p=Oc(s,o,a),y=new sE.SSEServerTransport("/messages",f);u.set(y.sessionId,y),y.onclose=()=>u.delete(y.sessionId),await p.connect(y)}else if(d.method==="POST"&&g.startsWith("/messages")){const p=new URLSearchParams(g.split("?")[1]??"").get("sessionId"),y=p?u.get(p):void 0;if(!y){f.writeHead(404),f.end("Session not found");return}await y.handlePostMessage(d,f)}else f.writeHead(404),f.end("Not found")}));return l.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(d=>{t.signal&&t.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),l.close(()=>d())})})}const c=mp.createServer(yg(o,async(u,l)=>{const d=Oc(s,o,a),f=new iE.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await d.connect(f),await f.handleRequest(u,l)}));return c.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(u=>{t.signal&&t.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),c.close(()=>u())})})}const pF={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(t){return oF(t)},run(t){return fF(t)}},Y0=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],Z0=["body","citations","notes","auditTrail","blockers","related","_score","_vector"],hF=new Set([...Y0,...Z0]);function mF(t){return hF.has(t)}const Is=["uid","kind","title","status","priority"],Mt=1e3,X0=50;async function op(t,e){const n=await t.getNodeByUid(e);if(!n||n.kind!=="issue"||n.tInvalid)throw new fa(e);if(n.isSuperseded)throw new da(e,await gF(t,n));return n}async function gF(t,e){const n=new Set([e.id]);let r,o=e;for(;;){const i=(await t.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!i)return r==null?void 0:r.uid;n.add(i.src);const a=(await t.getNodesByIds([i.src]))[0];if(!a||a.tInvalid)return r==null?void 0:r.uid;if(r=a,!a.isSuperseded)return a.uid;o=a}}async function xe(t,e,n){if(_r(n)){const s=await t.getNodeByUid(n);return!s||s.kind!==e||s.tInvalid?null:{id:s.id,uid:s.uid,name:s.name??n,record:s}}const o=(await t.queryNodes({kind:e,name:n,liveOnly:!0,limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}async function yo(t,e,n){var s;if(_r(n)){const i=await xe(t,"component",n);return!i||((s=i.record.metadata)==null?void 0:s.projectUid)!==e?null:i}const o=(await t.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:e}},limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}function ao(t,e){return t.getEdges({src:e})}async function eb(t,e){var c,u;const r=(c=(await t.getEdges({dst:e,rel:"owns_component"}))[0])==null?void 0:c.src;if(r===void 0)return{};const[o]=await t.getNodesByIds([r]);if(!o)return{};const i=(u=(await t.getEdges({dst:r,rel:"owns_project"}))[0])==null?void 0:u.src;if(i===void 0)return{component:o};const[a]=await t.getNodesByIds([i]);return{component:o,project:a}}async function yF(t,e){const n=e.expectedKind==="component"&&e.projectUid!==void 0?await yo(t,e.projectUid,e.ref):await xe(t,e.expectedKind,e.ref);if(!n)return;if(await wF(t,e.rel,e.expectedKind)){const o=await t.getEdges({src:n.id,rel:e.rel});return new Set(o.map(s=>s.dst))}const r=await t.getEdges({dst:n.id,rel:e.rel});return new Set(r.map(o=>o.src))}async function wF(t,e,n){var s;const o=(s=(await t.queryNodes({kind:"edge_kind",name:e,liveOnly:!0,limit:1}))[0])==null?void 0:s.metadata;return typeof(o==null?void 0:o.source_kind)=="string"&&o.source_kind===n}async function vF(t,e){return(await t.queryNodes({kind:e,liveOnly:!0})).map(r=>r.name).filter(r=>typeof r=="string")}function $F(t,e){const n=t.length+1,r=e.length+1,o=Array.from({length:n},()=>new Array(r).fill(0));for(let s=0;s<n;s+=1)o[s][0]=s;for(let s=0;s<r;s+=1)o[0][s]=s;for(let s=1;s<n;s+=1)for(let i=1;i<r;i+=1)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[t.length][e.length]}function tb(t,e,n=3){const r=Math.max(2,Math.ceil(t.length/2));return e.map(o=>({candidate:o,distance:$F(t.toLowerCase(),o.toLowerCase())})).filter(o=>o.distance<=r).sort((o,s)=>o.distance-s.distance).slice(0,n).map(o=>o.candidate)}async function Qr(t,e){const n=await vF(t,e.catalogKind),r=new Set,o=[];for(const s of e.refs){const i=await xe(t,e.catalogKind,s);if(!i){o.push(s);continue}const a=await t.getEdges({dst:i.id,rel:e.rel});for(const c of a)r.add(c.src)}if(o.length>0){const s=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",i=o.map(a=>{const c=tb(a,n);return c.length>0?`"${a}" (did you mean ${c.map(u=>`"${u}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new Er(e.field,`unknown ${e.catalogKind} value(s): ${i} — no live "${e.catalogKind}" catalog row matches (existing ${e.catalogKind} values: ${s})`)}return r}function bF(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const r=new Set;for(const o of e)n.has(o)&&r.add(o);e=r}return e}function sp(t){if(t){for(const e of t)if(!mF(e))throw new Er("fields",`unknown field "${e}" — known fields: ${[...Y0,...Z0].join(", ")}`)}}function Nr(t){var e;return((e=t==null?void 0:t.metadata)==null?void 0:e.terminal)===!0}async function EF(t,e,n){const r=n.find(l=>l.rel==="has_kind"&&l.src===e),o=n.find(l=>l.rel==="has_status"&&l.src===e),s=n.find(l=>l.rel==="has_priority"&&l.src===e),i=n.find(l=>l.rel==="authored_by"&&l.src===e),a=[r==null?void 0:r.dst,o==null?void 0:o.dst,s==null?void 0:s.dst,i==null?void 0:i.dst].filter(l=>l!==void 0);if(a.length===0)return{};const c=await t.getNodesByIds(a),u=new Map(c.map(l=>[l.id,l]));return{kind:r?u.get(r.dst):void 0,status:o?u.get(o.dst):void 0,priority:s?u.get(s.dst):void 0,author:i?u.get(i.dst):void 0}}async function SF(t,e,n){const r=n.filter(s=>s.rel==="has_citation"&&s.src===e);return r.length===0?[]:(await t.getNodesByIds(r.map(s=>s.dst))).map(s=>{var i,a,c,u,l;return{uid:s.uid,file:typeof((i=s.metadata)==null?void 0:i.target)=="string"?s.metadata.target:s.name??"",lines:typeof((a=s.metadata)==null?void 0:a.line)=="string"?s.metadata.line:void 0,context:s.content||void 0,symbol:typeof((c=s.metadata)==null?void 0:c.symbol)=="string"?s.metadata.symbol:void 0,sha:typeof((u=s.metadata)==null?void 0:u.sha)=="string"?s.metadata.sha:"unverified",at:typeof((l=s.metadata)==null?void 0:l.at)=="string"?s.metadata.at:s.tCreated}})}async function _F(t,e,n){const r=n.filter(s=>s.rel==="has_note"&&s.src===e);return r.length===0?[]:(await t.getNodesByIds(r.map(s=>s.dst))).map(s=>{var i,a,c;return{uid:s.uid,author:typeof((i=s.metadata)==null?void 0:i.author)=="string"?s.metadata.author:"",text:typeof((a=s.metadata)==null?void 0:a.text)=="string"?s.metadata.text:s.content,at:typeof((c=s.metadata)==null?void 0:c.at)=="string"?s.metadata.at:s.tCreated}})}async function NF(t,e,n){const r=(n??await ao(t,e)).filter(i=>i.rel==="audits"&&i.src===e);return r.length===0?[]:(await t.getNodesByIds(r.map(i=>i.dst))).map(i=>{var a,c,u,l,d,f,g;return{uid:i.uid,actor:typeof((a=i.metadata)==null?void 0:a.actor)=="string"?i.metadata.actor:"",action:typeof((c=i.metadata)==null?void 0:c.action)=="string"?i.metadata.action:i.name??"",from:typeof((u=i.metadata)==null?void 0:u.from)=="string"?i.metadata.from:void 0,to:typeof((l=i.metadata)==null?void 0:l.to)=="string"?i.metadata.to:void 0,note:typeof((d=i.metadata)==null?void 0:d.note)=="string"?i.metadata.note:void 0,sha:typeof((f=i.metadata)==null?void 0:f.sha)=="string"?i.metadata.sha:"",at:typeof((g=i.metadata)==null?void 0:g.at)=="string"?i.metadata.at:i.tCreated}}).sort((i,a)=>i.at.localeCompare(a.at))}async function OF(t,e){const n=await t.getEdges({dst:e,rel:"blocks"});if(n.length===0)return[];const r=n.map(i=>i.src),o=await t.getNodesByIds(r),s=await nb(t,o);return o.filter(i=>!Nr(s.get(i.id))).map(i=>{var a;return{uid:i.uid,title:i.name??"",status:((a=s.get(i.id))==null?void 0:a.name)??""}})}async function kF(t,e,n){const r=(n??await ao(t,e)).filter(c=>c.rel==="relates_to"&&c.src===e),o=await t.getEdges({dst:e,rel:"relates_to"}),s=new Set([...r.map(c=>c.dst),...o.map(c=>c.src)]);if(s.size===0)return[];const i=await t.getNodesByIds([...s]),a=await nb(t,i);return i.map(c=>{var u;return{uid:c.uid,title:c.name??"",status:((u=a.get(c.id))==null?void 0:u.name)??""}})}async function nb(t,e){if(e.length===0)return new Map;const n=new Set(e.map(u=>u.id)),r=await t.getEdges({rel:"has_status"}),o=new Map;for(const u of r)n.has(u.src)&&!o.has(u.src)&&o.set(u.src,u.dst);const s=[...new Set(o.values())];if(s.length===0)return new Map;const i=await t.getNodesByIds(s),a=new Map(i.map(u=>[u.id,u])),c=new Map;for(const[u,l]of o){const d=a.get(l);d&&c.set(u,d)}return c}async function rb(t,e,n,r={}){var p,y,w;const o={uid:e.uid},s=h=>n.includes(h),i=s("kind")||s("status")||s("priority")||s("author"),a=s("project")||s("component"),c=s("citations"),u=s("notes"),l=s("auditTrail"),d=s("blockers"),f=s("related"),g=r.outgoingEdges??(i||c||u||l||f?await ao(t,e.id):void 0);if(s("title")&&(o.title=e.name??""),s("createdAt")&&(o.createdAt=e.tCreated),s("updatedAt")&&(o.updatedAt=e.tValid),s("assignee")){const h=(p=e.metadata)==null?void 0:p.assignee;typeof h=="string"&&(o.assignee=h)}if(s("gitContext")){const h=(y=e.metadata)==null?void 0:y.gitContext;typeof h=="string"&&h.length>0&&(o.gitContext=h)}if(s("closedAt")){const h=(w=e.metadata)==null?void 0:w.closedAt;typeof h=="string"&&(o.closedAt=h)}if(s("body")&&(o.body=e.content),i&&g){const h=await EF(t,e.id,g);s("kind")&&h.kind&&(o.kind=h.kind.name??""),s("status")&&h.status&&(o.status=h.status.name??""),s("priority")&&h.priority&&(o.priority=h.priority.name??""),s("author")&&h.author&&(o.author=h.author.name??"")}if(a){const{project:h,component:v}=await eb(t,e.id);s("project")&&h&&(o.project=h.uid),s("component")&&v&&(o.component=v.uid)}return c&&g&&(o.citations=await SF(t,e.id,g)),u&&g&&(o.notes=await _F(t,e.id,g)),l&&g&&(o.auditTrail=await NF(t,e.id,g)),d&&(o.blockers=await OF(t,e.id)),f&&g&&(o.related=await kF(t,e.id,g)),s("_score")&&r.score!==void 0&&(o._score=r.score),o}async function vs(t,e,n,r){return Promise.all(e.map(o=>rb(t,o,n,{score:r==null?void 0:r.get(o.uid)})))}const jF=.0050125;function AF(t){if(t===void 0)return X0;if(!Number.isInteger(t)||t<=0||t>Mt)throw new Er("limit",`must be a positive integer ≤ ${Mt}, got ${t}`);return t}async function IF(t,e){const n=new Set;for(const r of e.refs){const o=await yF(t,{rel:e.rel,expectedKind:e.expectedKind,ref:r});if(o)for(const s of o)n.add(s)}return n}async function PF(t,e){const r=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(s=>Nr(s)===(e==="closed")),o=new Set;for(const s of r){const i=await t.getEdges({dst:s.id,rel:"has_status"});for(const a of i)o.add(a.src)}return o}async function xF(t,e){if(e.project===void 0&&e.component===void 0)return;let n,r;if(e.project!==void 0){const c=await xe(t,"project",e.project);if(!c)return new Set;n=c.uid;const u=await t.getEdges({src:c.id,rel:"owns_project"}),l=new Set;for(const d of u){const f=await t.getEdges({src:d.dst,rel:"owns_component"});for(const g of f)l.add(g.dst)}r=l}if(e.component===void 0)return r;const o=n!==void 0?await yo(t,n,e.component):await xe(t,"component",e.component);if(!o)return new Set;const s=await t.getEdges({src:o.id,rel:"owns_component"}),i=new Set(s.map(c=>c.dst));if(!r)return i;const a=new Set;for(const c of i)r.has(c)&&a.add(c);return a}function RF(t){var r,o,s,i;const e={};t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until}));const n={};return Object.keys(e).length>0&&(n.metadata=e),(r=t.createdAt)!=null&&r.since&&(n.tCreatedAfter=t.createdAt.since),(o=t.createdAt)!=null&&o.until&&(n.tCreatedBefore=t.createdAt.until),(s=t.updatedAt)!=null&&s.since&&(n.tUpdatedAfter=t.updatedAt.since),(i=t.updatedAt)!=null&&i.until&&(n.tUpdatedBefore=t.updatedAt.until),Object.keys(n).length>0?n:void 0}async function ob(t,e){if(!e)return;const n=[],r=await xF(t,e);if(r!==void 0&&n.push(r),e.kind!==void 0){const c=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await Qr(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:c}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await PF(t,e.status));else{const c=Array.isArray(e.status)?e.status:[e.status];n.push(await Qr(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:c}))}if(e.priority!==void 0){const c=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await Qr(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:c}))}e.author!==void 0&&n.push(await IF(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]}));const o=RF(e);if(n.length===0&&!o)return;let s;if(n.length>0){let[c]=n;for(const u of n.slice(1)){const l=new Set;for(const d of c)u.has(d)&&l.add(d);c=l}if(s=c,s.size===0)return new Set}const i={kind:"issue",liveOnly:!0,isSuperseded:!1,...s?{ids:[...s]}:{},...o},a=await t.queryNodes(i);return new Set(a.map(c=>c.id))}const TF=4;async function CF(t,e){if(e.length===0)return[];const n=e.map(i=>i.id),r={ids:n,isSuperseded:!1,limit:n.length},o=await t.queryNodes(r),s=new Set(o.map(i=>i.id));return e.filter(i=>s.has(i.id))}async function MF(t,e){if(!t.search)throw new oe("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");if(e.candidateIds&&e.candidateIds.size===0)return[];const n=e.candidateIds?{ids:[...e.candidateIds]}:{kind:"issue"},r={text:e.text,vec:e.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:e.decayPerHour??jF}],filters:n},o=[];let s=e.limit;for(let i=0;i<TF;i++){const a=await t.search.backend.searchRanked(r,s);if(o.length=0,o.push(...await CF(t.graph,a)),o.length>=e.limit||a.length<s)break;s*=2}return o.slice(0,e.limit)}async function LF(t,e){var w,h;const{graph:n}=t;if(!t.search)throw new oe("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");sp(e.fields);const r=e.fields??Is,o=AF(e.limit);let s,i;if(((w=e.filter)==null?void 0:w.anchor)!==void 0)i=await op(n,e.filter.anchor),s=`${i.name??""}
|
|
505
|
+
${i.content}`.trim();else if(((h=e.filter)==null?void 0:h.semantic)!==void 0)s=e.filter.semantic;else throw new oe("filter",'`view:"similar"` requires `filter.anchor` or `filter.semantic`');const a=await ob(n,e.filter);if(a&&i&&a.delete(i.id),a&&a.size===0)return[];const c=await t.search.embedQuery(s),u=i?o+1:o,l=await MF(t,{text:s,vec:c,candidateIds:a,limit:u}),d=(i?l.filter(v=>v.id!==i.id):l).slice(0,o);if(d.length===0)return[];const f=await n.getNodesByIds(d.map(v=>v.id)),g=new Map(f.map(v=>[v.id,v])),p=d.map(v=>g.get(v.id)).filter(v=>v!==void 0),y=new Map(d.map(v=>{var b;return[(b=g.get(v.id))==null?void 0:b.uid,v.score]}).filter(v=>v[0]!==void 0));return vs(n,p,r,y)}function DF(t){return t.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function UF(t){const e=typeof t.gitContext=="string"&&t.gitContext.length>0?t.gitContext:void 0,n=t.citations??[];if(e===void 0&&n.length===0)return[];const r=["",e!==void 0?`Citations: [${DF(e)}]`:"Citations:"];for(const o of n){const s=o.lines?`${o.file}:${o.lines}`:o.file;r.push(`- [${s} sha:${o.sha}]`)}return r}function BF(t){const e=[];return t.kind!==void 0&&e.push(`kind: ${t.kind}`),t.status!==void 0&&e.push(`status: ${t.status}`),t.priority!==void 0&&e.push(`priority: ${t.priority}`),t.assignee!==void 0&&e.push(`assignee: ${t.assignee}`),t.project!==void 0&&e.push(`project: ${t.project}`),t.component!==void 0&&e.push(`component: ${t.component}`),e.length>0?e.join(" · "):void 0}function FF(t){const e=[`## ${t.title??"(untitled)"}`],n=BF(t);return n!==void 0&&e.push(n),t.body!==void 0&&t.body.length>0&&e.push("",t.body),e.push(...UF(t)),e.join(`
|
|
506
|
+
`)}function qF(t){return t.length===0?`_No matching issues._
|
|
507
|
+
`:`${t.map(FF).join(`
|
|
184
508
|
|
|
185
509
|
`)}
|
|
186
|
-
`}function gj(e){return e.split(`
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
`,n
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
`,1)[0]??"",n=Number.parseInt(t,10);return Number.isInteger(n)&&n>0?n:null}catch{return null}}function Oj(e){try{return process.kill(e,0),!0}catch{return!1}}function kj(e){const t=C.openSync(e,C.constants.O_WRONLY|C.constants.O_CREAT|C.constants.O_EXCL,384);try{C.writeSync(t,`${process.pid}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
510
|
+
`}function tl(t){var e,n,r,o;return{uid:t.uid,name:t.name??"",path:typeof((e=t.metadata)==null?void 0:e.path)=="string"?t.metadata.path:void 0,repoUrl:typeof((n=t.metadata)==null?void 0:n.repoUrl)=="string"?t.metadata.repoUrl:void 0,monorepo:typeof((r=t.metadata)==null?void 0:r.monorepo)=="boolean"?t.metadata.monorepo:void 0,description:typeof((o=t.metadata)==null?void 0:o.description)=="string"?t.metadata.description:void 0}}function nl(t){var e,n,r;return{uid:t.uid,name:t.name??"",projectUid:typeof((e=t.metadata)==null?void 0:e.projectUid)=="string"?t.metadata.projectUid:"",path:typeof((n=t.metadata)==null?void 0:n.path)=="string"?t.metadata.path:void 0,description:typeof((r=t.metadata)==null?void 0:r.description)=="string"?t.metadata.description:void 0}}function rl(t){var e,n,r;return{uid:t.uid,locType:typeof((e=t.metadata)==null?void 0:e.locType)=="string"?t.metadata.locType:"path",value:typeof((n=t.metadata)==null?void 0:n.value)=="string"?t.metadata.value:t.name??"",componentUid:typeof((r=t.metadata)==null?void 0:r.componentUid)=="string"?t.metadata.componentUid:""}}async function KF(t,e){if((e==null?void 0:e.project)!==void 0){const r=await xe(t,"project",e.project);return r?[tl(r.record)]:[]}return(await t.queryNodes({kind:"project",liveOnly:!0})).map(tl)}async function VF(t,e){if((e==null?void 0:e.project)!==void 0){const r=await xe(t,"project",e.project);return r?(await t.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:r.uid}}})).map(nl):[]}return(await t.queryNodes({kind:"component",liveOnly:!0})).map(nl)}async function GF(t,e){if((e==null?void 0:e.component)!==void 0){const r=e.project!==void 0?await(async()=>{const s=await xe(t,"project",e.project);return s?yo(t,s.uid,e.component):null})():await xe(t,"component",e.component);return r?(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:r.uid}}})).map(rl):[]}return(await t.queryNodes({kind:"location",liveOnly:!0})).map(rl)}async function kc(t,e){var u,l,d,f,g,p,y,w,h;if(e.registry==="project"){const v=await xe(t,"project",e.name);if(!v)throw new Xe("project",e.name);const b=await t.getEdges({src:v.id,rel:"owns_project"}),E=b.length>0?await t.getNodesByIds(b.map(M=>M.dst),{liveOnly:!0}):[],j=(await Promise.all(E.map(M=>t.getEdges({src:M.id,rel:"has_location"})))).flatMap(M=>M.map(C=>C.dst)),T=j.length>0?await t.getNodesByIds(j,{liveOnly:!0}):[];return{...tl(v.record),components:E.map(M=>{var C;return{name:M.name??"",path:typeof((C=M.metadata)==null?void 0:C.path)=="string"?M.metadata.path:void 0}}),locations:T.map(M=>{var C,G;return{locType:typeof((C=M.metadata)==null?void 0:C.locType)=="string"?M.metadata.locType:"path",value:typeof((G=M.metadata)==null?void 0:G.value)=="string"?M.metadata.value:M.name??""}})}}if(e.registry==="component"){const v=(u=e.filter)==null?void 0:u.project,b=v!==void 0?await(async()=>{const C=await xe(t,"project",v);if(!C)throw new Xe("project",v);return yo(t,C.uid,e.name)})():await xe(t,"component",e.name);if(!b)throw new Xe("component",e.name);const E=typeof((l=b.record.metadata)==null?void 0:l.projectUid)=="string"?b.record.metadata.projectUid:void 0,N=E?await t.getNodeByUid(E):null,j=N&&!N.tInvalid?N:null,T=await t.getEdges({src:b.id,rel:"has_location"}),M=T.length>0?await t.getNodesByIds(T.map(C=>C.dst),{liveOnly:!0}):[];return{...nl(b.record),project:{name:(j==null?void 0:j.name)??"",path:typeof((d=j==null?void 0:j.metadata)==null?void 0:d.path)=="string"?j.metadata.path:void 0,repoUrl:typeof((f=j==null?void 0:j.metadata)==null?void 0:f.repoUrl)=="string"?j.metadata.repoUrl:void 0},locations:M.map(C=>{var G,H;return{locType:typeof((G=C.metadata)==null?void 0:G.locType)=="string"?C.metadata.locType:"path",value:typeof((H=C.metadata)==null?void 0:H.value)=="string"?C.metadata.value:C.name??""}})}}if(!_r(e.name))throw new oe("name","a location has no name — pass its uid");const n=await t.getNodeByUid(e.name);if(!n||n.kind!=="location"||n.tInvalid)throw new Xe("location",e.name);const r=typeof((g=n.metadata)==null?void 0:g.componentUid)=="string"?n.metadata.componentUid:void 0,o=r?await t.getNodeByUid(r):null,s=o&&!o.tInvalid?o:null,i=typeof((p=s==null?void 0:s.metadata)==null?void 0:p.projectUid)=="string"?s.metadata.projectUid:void 0,a=i?await t.getNodeByUid(i):null,c=a&&!a.tInvalid?a:null;return{...rl(n),component:{name:(s==null?void 0:s.name)??"",path:typeof((y=s==null?void 0:s.metadata)==null?void 0:y.path)=="string"?s.metadata.path:void 0},project:{name:(c==null?void 0:c.name)??"",path:typeof((w=c==null?void 0:c.metadata)==null?void 0:w.path)=="string"?c.metadata.path:void 0,repoUrl:typeof((h=c==null?void 0:c.metadata)==null?void 0:h.repoUrl)=="string"?c.metadata.repoUrl:void 0}}}function zF(t){try{return new URL(t),!0}catch{return!1}}function WF(t){return zF(t)?"url":t.includes("/")||t.includes(".")||t.startsWith("~")?"path":"tool"}async function HF(t,e){var f,g,p,y,w,h;const n=WF(e);let r=(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:e}},limit:1}))[0],o,s=!1;if(!r&&n==="path"){const v=await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit:Mt+1});s=v.length>Mt;const E=(s?v.slice(0,Mt):v).find(N=>{var T;const j=typeof((T=N.metadata)==null?void 0:T.value)=="string"?N.metadata.value:"";return j.endsWith(e)||e.endsWith(j)});E&&(r=E,o="matched by path suffix/prefix fallback, not an exact value match")}if(!r)throw new Xe("location",s?`${e} (path suffix/prefix fallback scanned only the first ${Mt} live path locations; a match may exist beyond this cap)`:e);const i=typeof((f=r.metadata)==null?void 0:f.componentUid)=="string"?r.metadata.componentUid:void 0,a=i?await t.getNodeByUid(i):null,c=a&&!a.tInvalid?a:null;if(!c)throw new Xe("component",i??"(unresolved)");const u=typeof((g=c.metadata)==null?void 0:g.projectUid)=="string"?c.metadata.projectUid:void 0,l=u?await t.getNodeByUid(u):null,d=l&&!l.tInvalid?l:null;return d?{project:{uid:d.uid,name:d.name??"",path:typeof((p=d.metadata)==null?void 0:p.path)=="string"?d.metadata.path:void 0,repoUrl:typeof((y=d.metadata)==null?void 0:y.repoUrl)=="string"?d.metadata.repoUrl:void 0},component:{uid:c.uid,name:c.name??"",path:typeof((w=c.metadata)==null?void 0:w.path)=="string"?c.metadata.path:void 0},location:{uid:r.uid,locType:n,value:typeof((h=r.metadata)==null?void 0:h.value)=="string"?r.metadata.value:e},hint:o}:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:r.uid,locType:n,value:e},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}function Ps(t){if(t===void 0)return X0;if(!Number.isInteger(t)||t<=0||t>Mt)throw new Er("limit",`must be a positive integer ≤ ${Mt}, got ${t}`);return t}function JF(t){var e,n;if(t.after!==void 0){if(t.sort!==void 0)throw new oe("sort","sort is incompatible with keyset pagination (after) — request the first page unsorted, or page by offset if a non-insertion order is required");if(((e=t.filter)==null?void 0:e.grep)!==void 0||((n=t.filter)==null?void 0:n.semantic)!==void 0)throw new oe("after","after (keyset) is incompatible with grep/semantic search — these route through the ranked search primitives, which have no rowid-ordered keyset contract; page a searched result set by sort + offset (rule 6) instead")}}async function QF(t,e){const n=new Set;for(const r of e.refs){const o=await xe(t,e.expectedKind,r);if(!o)continue;const s=await t.getEdges({dst:o.id,rel:e.rel});for(const i of s)n.add(i.src)}return n}async function sb(t,e){const r=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(s=>Nr(s)===(e==="closed")),o=new Set;for(const s of r){const i=await t.getEdges({dst:s.id,rel:"has_status"});for(const a of i)o.add(a.src)}return o}async function xs(t,e){if(!e)return;const n=[];let r;if(e.project!==void 0){const o=await xe(t,"project",e.project);if(!o)return new Set;r=o.uid;const s=await t.getEdges({src:o.id,rel:"owns_project"}),i=new Set;for(const a of s){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const u of c)i.add(u.dst)}n.push(i)}if(e.component!==void 0){const o=r!==void 0?await yo(t,r,e.component):await xe(t,"component",e.component);if(!o)return new Set;const s=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(s.map(i=>i.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await Qr(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:o}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await sb(t,e.status));else{const o=Array.isArray(e.status)?e.status:[e.status];n.push(await Qr(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:o}))}if(e.priority!==void 0){const o=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await Qr(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:o}))}if(e.author!==void 0&&n.push(await QF(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]})),e.plan!==void 0){const o=await xe(t,"issue",e.plan);if(!o)return new Set;const s=await t.getEdges({dst:o.id,rel:"part_of"});n.push(new Set(s.map(i=>i.src)))}if(e.projectPath!==void 0){const o=await t.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:e.projectPath}}});if(o.length===0)return new Set;const s=new Set;for(const i of o){const a=await t.getEdges({src:i.id,rel:"owns_component"});for(const c of a)s.add(c.dst)}n.push(s)}return bF(n)}function YF(t){if(!t)return;const e={};return t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until})),Object.keys(e).length>0?e:void 0}function ZF(t){if(t==="created")return"tCreated";if(t==="updated")return"tValid"}async function XF(t,e,n){const r=await Promise.all(e.map(u=>t.getEdges({src:u.id,rel:"has_priority"}))),o=[...new Set(r.flatMap(u=>u.map(l=>l.dst)))],s=o.length>0?await t.getNodesByIds(o):[],i=new Map(s.map(u=>{var l;return[u.id,typeof((l=u.metadata)==null?void 0:l.rank)=="number"?u.metadata.rank:Number.MAX_SAFE_INTEGER]})),a=new Map;e.forEach((u,l)=>{var f;const d=(f=r[l][0])==null?void 0:f.dst;a.set(u.id,d!==void 0?i.get(d)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)});const c=[...e].sort((u,l)=>a.get(u.id)-a.get(l.id));return n==="desc"?c.reverse():c}async function eq(t,e){var b,E,N,j,T,M,C,G,H,Z,ue,fe;const{graph:n}=t;JF(e),sp(e.fields);const r=Ps(e.limit),o=e.fields??Is;if((e.sort==="relevance"||e.sort==="textMatch")&&((b=e.filter)==null?void 0:b.grep)===void 0&&((E=e.filter)==null?void 0:E.semantic)===void 0)throw new Er("sort",`"${e.sort}" requires filter.grep or filter.semantic`);const s=await xs(n,e.filter);if(s&&s.size===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:r}};const i=YF(e.filter),a=(N=e.filter)==null?void 0:N.grep,c=(j=e.filter)==null?void 0:j.semantic,u={kind:"issue",isSuperseded:!1,...s?{ids:[...s]}:{},...i?{metadata:i}:{},...(M=(T=e.filter)==null?void 0:T.createdAt)!=null&&M.since?{tCreatedAfter:e.filter.createdAt.since}:{},...(G=(C=e.filter)==null?void 0:C.createdAt)!=null&&G.until?{tCreatedBefore:e.filter.createdAt.until}:{},...(Z=(H=e.filter)==null?void 0:H.updatedAt)!=null&&Z.since?{tUpdatedAfter:e.filter.updatedAt.since}:{},...(fe=(ue=e.filter)==null?void 0:ue.updatedAt)!=null&&fe.until?{tUpdatedBefore:e.filter.updatedAt.until}:{}};if(a!==void 0||c!==void 0){let he,pe;const Oe=e.offset??0,gt=Oe+r;if(a!==void 0){const U=await n.searchNodes(a,{limit:gt,filter:u});pe=new Set(U.map(q=>q.id))}if(c!==void 0){if(!t.search)throw new oe("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");const q={vec:await t.search.embedQuery(c),signals:[{kind:"vec"}],filters:u},re=await t.search.backend.searchRanked(q,gt);he=pe?re.filter(Qe=>pe.has(Qe.id)):re}else pe&&(he=(await n.searchNodes(a,{limit:gt,filter:u})).map(q=>({id:q.id,score:q.score,fields:{}})));const ut=(he??[]).map(U=>U.id).slice(Oe,Oe+r),A=ut.length>0?await n.getNodesByIds(ut):[],S=new Map(A.map(U=>[U.id,U])),k=ut.map(U=>S.get(U)).filter(U=>U!==void 0),_=new Map((he??[]).map(U=>{var q;return[(q=S.get(U.id))==null?void 0:q.uid,U.score]}).filter(U=>U[0]!==void 0)),m=await vs(n,k,o,_),$=a!==void 0?await n.countNodesFts(a,u):await n.countNodes(u),O=m.length,x=O<Math.min($-Oe,r),R=Oe+O<$;return{page:{items:m,hasMore:R},meta:{total:$,returned:O,limit:r,...e.offset!==void 0?{offset:e.offset}:{},...x?{truncated:!0}:{}}}}const l=ZF(e.sort),d={...u,limit:r+1,...e.after!==void 0?{after:Number(e.after)}:{},...l&&e.after===void 0?{orderBy:l,orderDir:e.direction??"desc"}:{},...e.after===void 0&&e.offset!==void 0?{offset:e.offset}:{}};let f=await n.queryNodes(d);e.sort==="priority"&&e.after===void 0&&(f=await XF(n,f,e.direction??"asc"));const g=f.length>r,p=g?f.slice(0,r):f,y=g?String(p[p.length-1].id):void 0,w=await vs(n,p,o),h=await n.countNodes(u),v=e.after===void 0?e.offset:void 0;return{page:{items:w,nextCursor:y,hasMore:g},meta:{total:h,returned:w.length,limit:r,...v!==void 0?{offset:v}:{}}}}async function tq(t,e){var v;const{graph:n}=t,r=Ps(e.limit),o=e.fields??Is,s=await sb(n,"open"),i=await xs(n,e.filter),a=i?[...s].filter(b=>i.has(b)):[...s];if(a.length===0)return[];const c=await n.getNodesByIds(a),u=await n.getEdges({rel:"blocks"}),l=new Map;for(const b of u){const E=l.get(b.dst);E?E.push(b.src):l.set(b.dst,[b.src])}const d=[...new Set(u.map(b=>b.src))],f=new Set((d.length>0?await n.getNodesByIds(d):[]).map(b=>b.id)),g=await n.getEdges({rel:"has_status"}),p=new Map;for(const b of g)p.has(b.src)||p.set(b.src,b.dst);const y=[...new Set(p.values())],w=new Map((y.length>0?await n.getNodesByIds(y):[]).map(b=>[b.id,b])),h=[];for(const b of c){if(h.length>=r)break;if(typeof((v=b.metadata)==null?void 0:v.claimedBy)=="string")continue;const E=(l.get(b.id)??[]).filter(j=>f.has(j));if(E.length===0){h.push(b);continue}E.every(j=>{const T=p.get(j);return T!==void 0&&Nr(w.get(T))})&&h.push(b)}return vs(n,h,o)}async function nq(t,e){const{graph:n}=t,r=Ps(e.limit),o=e.fields??Is,s=e.staleAfterMin??30,i=new Date(Date.now()-s*6e4).toISOString(),a=await xs(n,e.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:i}},limit:r},u=await n.queryNodes(c);return vs(n,u,o)}const rq=["blocks","relates_to","part_of"];function oq(t){return rq.includes(t)}async function sq(t,e){var d;const{graph:n}=t,r=Ps(e.limit??Mt),o=await xs(n,e.filter),s={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},i=await n.queryNodes(s),a=new Set(i.map(f=>f.id)),c=await iq(n,i),u=i.map(f=>{var g;return{uid:f.uid,title:f.name??"",status:((g=c.get(f.id))==null?void 0:g.name)??""}}),l=[];for(const f of i){const g=await ao(n,f.id);for(const p of g)if(oq(p.rel)&&a.has(p.dst)){const y=(d=(await n.getNodesByIds([p.dst]))[0])==null?void 0:d.uid;y&&l.push({from:f.uid,to:y,rel:p.rel})}}return{nodes:u,edges:l}}async function iq(t,e){const n=await Promise.all(e.map(a=>t.getEdges({src:a.id,rel:"has_status"}))),r=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=r.length>0?await t.getNodesByIds(r):[],s=new Map(o.map(a=>[a.id,a])),i=new Map;return e.forEach((a,c)=>{var l;const u=(l=n[c][0])==null?void 0:l.dst;if(u!==void 0){const d=s.get(u);d&&i.set(a.id,d)}}),i}async function aq(t,e){const{graph:n}=t,r=Ps(e.limit??Mt),o=await xs(n,e.filter),s={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},i=await n.queryNodes(s),a=new Set(i.map(p=>p.id)),c=new Map(i.map(p=>[p.id,p.uid])),u=new Map,l=new Map;for(const p of i)u.set(p.id,0),l.set(p.id,[]);for(const p of i){const y=await n.getEdges({src:p.id,rel:"blocks"});for(const w of y)a.has(w.dst)&&(l.get(p.id).push(w.dst),u.set(w.dst,(u.get(w.dst)??0)+1))}const d=i.filter(p=>(u.get(p.id)??0)===0).map(p=>p.id),f=[],g=new Map(u);for(;d.length>0;){const p=d.shift();f.push(p);for(const y of l.get(p)??[]){const w=(g.get(y)??0)-1;g.set(y,w),w===0&&d.push(y)}}return f.length!==i.length?{ok:!1,cycle:i.filter(y=>!f.includes(y.id)).map(y=>c.get(y.id))}:{ok:!0,order:f.map(p=>c.get(p))}}async function cq(t,e){var i;const{graph:n}=t,r=e.overlapAxis,o=e.overlapUids;if(!r)throw new oe("overlapAxis",'required for view:"overlap"');if(!o||o.length<2)throw new oe("overlapUids","requires at least 2 uids to detect an overlap");const s=new Map;for(const a of o){const c=await n.getNodeByUid(a);if(!c||c.kind!=="issue")continue;if(r==="file"){const g=(await ao(n,c.id)).filter(y=>y.rel==="has_citation"),p=g.length>0?await n.getNodesByIds(g.map(y=>y.dst)):[];for(const y of p){const w=typeof((i=y.metadata)==null?void 0:i.target)=="string"?y.metadata.target:void 0;w&&(s.has(w)||s.set(w,new Set),s.get(w).add(a))}continue}if(r==="author"){const g=(await ao(n,c.id)).find(y=>y.rel==="authored_by");if(!g)continue;const[p]=await n.getNodesByIds([g.dst]);if(!p)continue;s.has(p.uid)||s.set(p.uid,new Set),s.get(p.uid).add(a);continue}const{project:u,component:l}=await eb(n,c.id),d=r==="project"?u:l;d&&(s.has(d.uid)||s.set(d.uid,new Set),s.get(d.uid).add(a))}return[...s.entries()].filter(([,a])=>a.size>=2).map(([a,c])=>({axisValue:a,uids:[...c]}))}async function uq(t,e){return KF(t.graph,e.filter)}async function lq(t,e){return VF(t.graph,e.filter)}async function dq(t,e){return GF(t.graph,e.filter)}function fq(t){var e,n;return t.text!==void 0||((e=t.filter)==null?void 0:e.semantic)!==void 0||((n=t.filter)==null?void 0:n.anchor)!==void 0||t.view==="similar"||t.sort==="relevance"||(t.fields??[]).includes("_vector")}function pq(t,e){var s,i;if(e.text===void 0)return e;if(((s=e.filter)==null?void 0:s.semantic)!==void 0||((i=e.filter)==null?void 0:i.grep)!==void 0)throw new oe("text","text is mutually exclusive with filter.semantic/filter.grep — pick one: the free-text positional (text), or an explicit filter.semantic/filter.grep");if(e.text.trim().length===0)throw new oe("text","must not be blank");const n=t.search!==void 0&&t.spacePopulated===!0,{text:r,...o}=e;return{...o,sort:o.sort??(n?"relevance":"textMatch"),filter:{...o.filter,...n?{semantic:r}:{grep:r}}}}async function hq(t,e){const n=e.view??"list";switch(n){case"list":{const{page:r,meta:o}=await eq(t,e);return{result:{view:"list",...r},meta:o}}case"ready":return{result:{view:"ready",items:await tq(t,e)}};case"graph":return{result:{view:"graph",graph:await sq(t,e)}};case"order":return{result:{view:"order",order:await aq(t,e)}};case"stale":return{result:{view:"stale",items:await nq(t,e)}};case"similar":return{result:{view:"similar",items:await LF(t,e)}};case"overlap":return{result:{view:"overlap",groups:await cq(t,e)}};case"projects":return{result:{view:"projects",items:await uq(t,e)}};case"components":return{result:{view:"components",items:await lq(t,e)}};case"locations":return{result:{view:"locations",items:await dq(t,e)}};default:{const r=n;throw new Er("view",`unknown view "${r}"`)}}}const mq=["list","ready","stale","similar"];async function gq(t,e={}){var a;await((a=t.assertVocabulary)==null?void 0:a.call(t));const n=pq(t,e),r=await hq(t,n);if(n.format!=="markdown")return r;const{result:o}=r,{view:s}=o;if(s!=="list"&&s!=="ready"&&s!=="stale"&&s!=="similar")throw new oe("format",`"markdown" is only supported for view:${mq.map(c=>`"${c}"`).join("/")} — view:"${s}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const i=o.items;return{result:{view:s,format:"markdown",markdown:qF(i)},meta:r.meta}}const ib=["not_found","item_not_found","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],yq=new Set(ib);function ab(t){return typeof t=="string"&&yq.has(t)}const ip={not_found:4,item_not_found:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function wq(t){return t.ok===!0}function vq(t){return t.ok===!1&&typeof t.error=="object"&&t.error!==null&&ab(t.error.code)}function ap(t,e){const n={ok:!0,data:t};return e!=null&&e.warnings&&e.warnings.length>0&&(n.warnings=e.warnings),e!=null&&e.meta&&(n.meta=e.meta),n}function pr(t,e,n){const r={code:t,message:e},o={...n??{}};return t==="store_busy"&&o.retryable===void 0&&(o.retryable=!0),Object.keys(o).length>0&&(r.details=o),{ok:!1,error:r}}function Co(t){return t.ok?0:ip[t.error.code]}function cb(t){if(t===null||typeof t!="object")return!1;const e=t;if(typeof e.ok!="boolean")return!1;if(e.ok)return!0;const n=e.error;if(n===null||typeof n!="object")return!1;const r=n.code;return typeof r=="string"&&r in ip}class ub extends Error{constructor(e,n="not_configured"){super((n==="empty_vector_space"?`backlog: "${e}" needs an embedded vector space and this store has none — a backend is configured, but zero items have been embedded, so nearest-neighbour ranking has nothing to rank. Run an embedding backfill to populate it. `:`backlog: "${e}" needs a configured embedding backend and none is available. `)+"Keyword and dimensional queries still work."),this.reason=n,this.name="RagNotConfiguredError"}}class $q extends Error{constructor(e,n,r,o){super(`backlog embedding: ${e} produced a ${o}-dimensional vector but space "${n}" is ${r}-dimensional. The dimensional contract is structural and is never silently truncated — the configured provider does not match this vector space.`),this.operation=e,this.modelId=n,this.expected=r,this.actual=o,this.name="PermanentEmbeddingDimensionError"}}let wg=!1;async function bq(t,e){const n=t;return typeof n.hasVectors!="function"?(wg||(wg=!0,console.error(`isVectorSpacePopulated: vector backend exposes no hasVectors() probe — treating the space as EMPTY (modelId="${e}"). Bare \`text:\` queries will not route to the semantic ranker until the backend provides the probe.`)),!1):n.hasVectors(e)}async function vg(t){try{return{mod:await import(t)}}catch(e){return{err:e}}}const ii=t=>t instanceof Error?t.message:String(t),ai=new WeakMap;async function Eq(t,e,n,r=o=>console.error(o)){const o=ai.get(t);if(o)return o;const s=Sq(t,e,n,r);ai.set(t,s);try{const i=await s;return i.search===void 0&&i.embedding===void 0&&ai.delete(t),i}catch(i){throw ai.delete(t),i}}async function Sq(t,e,n,r){var g;if(!(n!=null&&n.enabled))return{};const o=(g=t.capabilities)==null?void 0:g.nativeVectors;if(o!==!0)return r(`backlog: embedding.enabled is set but this store's adapter does not report capabilities.nativeVectors (got ${JSON.stringify(o)}) — backlog's RAG layer requires a Turso-backed store. create()'s duplicate gate and query()'s/view:"similar"'s semantic filters will report as unconfigured.`),{};const[s,i]=await Promise.all([vg("@adhd/sox-vector-store"),vg("@adhd/sox-embedding-provider")]);if("err"in s||"err"in i){const p=[..."err"in s?[`@adhd/sox-vector-store (${ii(s.err)})`]:[],..."err"in i?[`@adhd/sox-embedding-provider (${ii(i.err)})`]:[]];return r(`backlog: embedding.enabled is set but optional embedding packages are unavailable: ${p.join("; ")}. Continuing WITHOUT semantic search.`),{}}let a;try{a=await i.mod.createEmbeddingProvider({type:n.provider,model:n.model})}catch(p){return r(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${ii(p)}. Continuing WITHOUT semantic search.`),{}}const c={modelId:a.metadata.modelId,dim:a.metadata.dimensions};let u;try{u=await s.mod.openTursoVectorStore(t,{dim:c.dim,modelId:c.modelId}),await u.ensureSpace(c)}catch(p){return r(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${c.dim}, modelId=${c.modelId}) failed: ${ii(p)}. Continuing WITHOUT semantic search.`),{}}const l=(p,y)=>{if(p.length!==c.dim)throw new $q(y,c.modelId,c.dim,p.length);return p},d={modelId:c.modelId,async embedDocument(p){return l(await a.embedSingle(p,"document"),"embedDocument")},async upsertVector(p,y){await u.upsert(p,l(y,"upsertVector"),c)},async deleteVector(p){await u.delete(p,c.modelId)}};return{search:{backend:new aE.StoreSearchBackend(u,e),async embedQuery(p){return l(await a.embedSingle(p,"query"),"embedQuery")},async spacePopulated(){return bq(u,c.modelId)}},embedding:d}}async function _q(t,e){sp(e.fields);const n=e.fields??Is,r=await op(t,e.uid);return rb(t,r,n)}const Nq=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function lb(t,e,n){if(t){for(const r of Nq)if(t[r]!==void 0&&!e.has(r))throw new oe(`filter.${r}`,`not supported by ${n} — this view scopes by ${[...e].join("/")} only`)}}async function db(t,e){const n=new Set;for(const r of e.refs){const o=await xe(t,e.expectedKind,r);if(!o)continue;const s=await t.getEdges({dst:o.id,rel:e.rel});for(const i of s)n.add(i.src)}return n}async function Oq(t,e){const r=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(s=>Nr(s)===(e==="closed")),o=new Set;for(const s of r){const i=await t.getEdges({dst:s.id,rel:"has_status"});for(const a of i)o.add(a.src)}return o}function fb(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const r=new Set;for(const o of e)n.has(o)&&r.add(o);e=r}return e}async function pb(t,e){if(!e)return;const n=[];let r;if(e.project!==void 0){const o=await xe(t,"project",e.project);if(!o)return new Set;r=o.uid;const s=await t.getEdges({src:o.id,rel:"owns_project"}),i=new Set;for(const a of s){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const u of c)i.add(u.dst)}n.push(i)}if(e.component!==void 0){const o=r!==void 0?await yo(t,r,e.component):await xe(t,"component",e.component);if(!o)return new Set;const s=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(s.map(i=>i.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await db(t,{rel:"has_kind",expectedKind:"kind",refs:o}))}return fb(n)}const kq=new Set(["project","component","kind","status"]);async function jq(t,e){const n=e??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await Oq(t,n),scope:n};const r=Array.isArray(n)?n:[n];return{candidates:await db(t,{rel:"has_status",expectedKind:"status",refs:r}),scope:n}}async function Aq(t,e={}){var f,g,p;const{graph:n}=t;lb(e.filter,kq,"priorityMatrix");const r=await pb(n,e.filter);if(r&&r.size===0)return{rows:[],unassigned:0,statusScope:((f=e.filter)==null?void 0:f.status)??"open"};const{candidates:o,scope:s}=await jq(n,(g=e.filter)==null?void 0:g.status),i=fb([r,o].filter(y=>y!==void 0));if(i&&i.size===0)return{rows:[],unassigned:0,statusScope:s};const a=new Set((await n.queryNodes({kind:"issue",liveOnly:!0,isSuperseded:!1,...i?{ids:[...i]}:{}})).map(y=>y.id)),c=await n.queryNodes({kind:"priority",liveOnly:!0}),u=new Set,l=[];for(const y of c){const w=await n.getEdges({dst:y.id,rel:"has_priority"});let h=0;for(const b of w)a.has(b.src)&&(h+=1,u.add(b.src));const v=typeof((p=y.metadata)==null?void 0:p.rank)=="number"?y.metadata.rank:void 0;l.push({priority:y.name??"",priorityUid:y.uid,rank:v,count:h})}l.sort((y,w)=>(y.rank??Number.MAX_SAFE_INTEGER)-(w.rank??Number.MAX_SAFE_INTEGER));let d=0;for(const y of a)u.has(y)||(d+=1);return{rows:l,unassigned:d,statusScope:s}}async function Iq(t,e){if(e.length===0)return new Map;const n=await Promise.all(e.map(c=>t.getEdges({src:c.id,rel:"has_status"}))),r=new Map;n.forEach((c,u)=>{const l=c[0];l&&r.set(e[u].id,l.dst)});const o=[...new Set(r.values())];if(o.length===0)return new Map;const s=await t.getNodesByIds(o),i=new Map(s.map(c=>[c.id,c])),a=new Map;for(const[c,u]of r){const l=i.get(u);l&&a.set(c,l)}return a}async function Pq(t,e){const{graph:n}=t,r=await op(n,e.uid),s=(await n.getSubgraph(r.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(l=>l.id!==r.id&&l.kind==="issue"&&!l.tInvalid),i=await Iq(n,s);let a=0,c=0;const u=[];for(const l of s)Nr(i.get(l.id))?c+=1:(a+=1,u.push(l.uid));return{uid:r.uid,childrenTotal:s.length,childrenOpen:a,childrenClosed:c,childrenOpenUids:u}}const xq=new Set(["project","component","kind"]);function Rq(t,e,n){var s;const r=t.filter(i=>i.to!==void 0);if(r.length===0)return n;let o;for(const i of r)if(i.at<=e)o=i;else break;return o?o.to:(s=r[0])==null?void 0:s.from}async function Tq(t){var d;const e=await t.getEdges({rel:"has_status"}),n=new Map;for(const f of e)n.has(f.src)||n.set(f.src,f.dst);const r=[...new Set(n.values())],o=new Map((r.length>0?await t.getNodesByIds(r):[]).map(f=>[f.id,f])),s=new Map;for(const[f,g]of n)s.set(f,(d=o.get(g))==null?void 0:d.name);const i=await t.getEdges({rel:"audits"}),a=new Map;for(const f of i){const g=a.get(f.src);g?g.push(f.dst):a.set(f.src,[f.dst])}const c=[...new Set(i.map(f=>f.dst))],u=new Map((c.length>0?await t.getNodesByIds(c):[]).map(f=>[f.id,f])),l=new Map;for(const[f,g]of a){const p=g.map(y=>u.get(y)).filter(y=>y!==void 0).map(y=>{var w,h,v,b,E,N,j;return{uid:y.uid,actor:typeof((w=y.metadata)==null?void 0:w.actor)=="string"?y.metadata.actor:"",action:typeof((h=y.metadata)==null?void 0:h.action)=="string"?y.metadata.action:y.name??"",from:typeof((v=y.metadata)==null?void 0:v.from)=="string"?y.metadata.from:void 0,to:typeof((b=y.metadata)==null?void 0:b.to)=="string"?y.metadata.to:void 0,note:typeof((E=y.metadata)==null?void 0:E.note)=="string"?y.metadata.note:void 0,sha:typeof((N=y.metadata)==null?void 0:N.sha)=="string"?y.metadata.sha:"",at:typeof((j=y.metadata)==null?void 0:j.at)=="string"?y.metadata.at:y.tCreated}}).sort((y,w)=>y.at.localeCompare(w.at));l.set(f,p)}return{currentStatusNameByIssue:s,auditTrailByIssue:l}}async function Cq(t,e){const{graph:n}=t;if(lb(e.filter,xq,"openCurve"),e.at.length===0)throw new oe("at","requires at least one ISO-8601 instant to sample");const r=e.at.map(d=>{const f=new Date(d);if(Number.isNaN(f.getTime()))throw new oe("at",`"${d}" is not a parsable ISO-8601 instant`);return f.toISOString()}),o=await pb(n,e.filter);if(o&&o.size===0)return{points:r.map(d=>({at:d,existed:0,open:0,closed:0}))};const s=await n.queryNodes({kind:"status",liveOnly:!0}),i=new Map(s.map(d=>[d.name??"",Nr(d)])),{currentStatusNameByIssue:a,auditTrailByIssue:c}=await Tq(n),u=new Map;for(const d of await n.getEdges({rel:"SUPERSEDES"})){const f=u.get(d.dst);(f===void 0||d.tCreated<f)&&u.set(d.dst,d.tCreated)}const l=[];for(const d of r){const f={kind:"issue",validAt:d,liveOnly:!1,...o?{ids:[...o]}:{}},g=await n.queryNodes(f);let p=0,y=0;for(const w of g){const h=u.get(w.id);if(h!==void 0&&h<=d)continue;y+=1;const v=a.get(w.id),b=c.get(w.id)??[],E=Rq(b,d,v);(E!==void 0?i.get(E)??!1:!1)||(p+=1)}l.push({at:d,existed:y,open:p,closed:y-p})}return{points:l}}const $g=["abort","force","comment"];function No(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}const bg=512;function hb(t){if(typeof t=="string"&&t.length>bg)throw new oe("gitContext",`must be at most ${bg} characters, got ${t.length}`)}async function Mq(t,e){if(!ha(t))return"unverified";const n=L.resolve(t.metadata.path),r=L.isAbsolute(e)?L.resolve(e):L.resolve(n,e),o=L.relative(n,r);if(o===".."||o.startsWith("../")||o.startsWith("..\\")||L.isAbsolute(o))return"unverified";try{const i=await sl.readFile(r);return kn.createHash("sha256").update(i).digest("hex")}catch(i){const a=i==null?void 0:i.code;if(a==="ENOENT"||a==="ENOTDIR")return"unverified";throw new kl(i)}}function Eg(t,e,n){if(t.length>0&&!t.includes(n))throw new oe(e,`"${n}" is not in this project's allowed ${e} set`)}function Lq(t,e){for(const n of t){const r=e[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new oe(n,"is required by this project's field policy")}}async function Dq(t,e,n,r,o){if(!n.dedupeScanEnabled)return[];const{search:s,graph:i}=t;if(!s||!i)return[];const a={project:e.uid},c=await ob(i,a);if(!c||c.size===0)return[];const u=xl(r,o),d=typeof s.embedQuery=="function"?await s.embedQuery(u):void 0,g={text:u,vec:d,signals:d?[{kind:"text"},{kind:"vec"}]:[{kind:"text"}],filters:{ids:[...c]}},p=5,y=p*4,w=await s.backend.search(g,y);if(w.length===0)return[];const h=await i.getNodesByIds(w.map(E=>E.id)),v=new Map(h.map(E=>[E.id,E])),b=[];for(const E of w){const N=v.get(E.id);if(!N||N.tInvalid!==void 0||N.isSuperseded)continue;const j=E.vecScore;j!==void 0&&c.has(E.id)&&j>=n.dedupeThreshold&&b.push({uid:N.uid,title:N.name??"",score:j})}return b.sort((E,N)=>N.score-E.score),b.slice(0,p)}async function Uq(t,e){No("title",e.title),No("body",e.body),No("project",e.project),No("by",e.by),jt("by",e.by),hb(e.gitContext);const n=e.citations??[];n.forEach((d,f)=>No(`citations[${f}].file`,d.file));const r=typeof e.gitContext=="string"&&e.gitContext.trim().length>0?e.gitContext:void 0,o=e.duplicateAction??"abort";if(e.duplicateAction!==void 0&&!$g.includes(e.duplicateAction))throw new oe("duplicateAction",`must be one of ${$g.map(d=>`'${d}'`).join("|")}, got "${e.duplicateAction}"`);const s=await rs(t.adapter,e.project),i=Zr(s),a=[];for(const d of n){const f=await Mq(s,d.file);if(f==="unverified"&&i.citationRequiresSha){if(ha(s))throw new jl(d.file);console.error(`createIssue: citation_requires_sha waived for path-less project uid="${s.uid}" — cannot verify citation "${d.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}a.push(f)}const c=await Dq(t,s,i,e.title,e.body);if(c.length>0&&o==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:c};let u;const l=await lt(t,async d=>{const f=He();if(c.length>0&&o==="comment"){const[ue]=c,fe=await _n(d,ue.uid),he=`${e.title}
|
|
511
|
+
|
|
512
|
+
${e.body}`,pe=await ct(d,{kind:"note",content:he,metadata:{author:e.by,text:he,at:f},at:f}),Oe=await Te(d,"has_note");return await Re(d,{at:f,srcRowid:fe.rowid,srcUid:fe.uid,srcKind:"issue",dstRowid:pe.rowid,dstUid:pe.uid,dstKind:"note",rel:"has_note",rule:Oe,typePolicy:t.typePolicy}),{created:!1,commentedOn:{uid:fe.uid,noteId:pe.uid},duplicateCandidates:c}}const g=await rs(d,e.project),p=Zr(g),y=e.component!==void 0?await Pl(d,{projectUid:g.uid,ref:e.component}):await wy(d,{projectRowid:g.rowid}),w=e.kind??p.defaultKind??"issue",h=await mn(d,{catalogKind:"kind",ref:w,at:f});Eg(p.allowedKinds,"kind",h.name);const v=e.status??p.defaultStatus??"open",b=await mn(d,{catalogKind:"status",ref:v,at:f,mintMetadata:async()=>({terminal:!1})});Eg(p.allowedStatuses,"status",b.name);let E;e.priority!==void 0&&(E=await mn(d,{catalogKind:"priority",ref:e.priority,at:f,mintMetadata:async ue=>({rank:await vy(ue)})}));const N=e.author??e.by,j=await mn(d,{catalogKind:"agent",ref:N,at:f});Lq(p.requiredFields,{...e,component:y.name,kind:h.name,status:b.name,priority:E==null?void 0:E.name});const T={};e.assignee!==void 0&&(T.assignee=e.assignee),r!==void 0&&(T.gitContext=r);const M=await ct(d,{kind:"issue",name:e.title,content:e.body,metadata:T,at:f});u={rowid:M.rowid,uid:M.uid};const C=await Te(d,"owns_component");await Re(d,{at:f,srcRowid:y.rowid,srcUid:y.uid,srcKind:"component",dstRowid:M.rowid,dstUid:M.uid,dstKind:"issue",rel:"owns_component",rule:C,typePolicy:t.typePolicy});const G=await Te(d,"has_kind");await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:h.rowid,dstUid:h.uid,dstKind:"kind",rel:"has_kind",rule:G,typePolicy:t.typePolicy});const H=await Te(d,"has_status");if(await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:b.rowid,dstUid:b.uid,dstKind:"status",rel:"has_status",rule:H,typePolicy:t.typePolicy}),E){const ue=await Te(d,"has_priority");await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:E.rowid,dstUid:E.uid,dstKind:"priority",rel:"has_priority",rule:ue,typePolicy:t.typePolicy})}const Z=await Te(d,"authored_by");if(await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:j.rowid,dstUid:j.uid,dstKind:"agent",rel:"authored_by",rule:Z,typePolicy:t.typePolicy}),n.length>0){const ue=await Te(d,"has_citation");for(let fe=0;fe<n.length;fe+=1){const he=n[fe],pe=a[fe],Oe=await ct(d,{at:f,kind:"citation",name:he.file,content:he.context??he.file,metadata:{target:he.file,target_type:"path",sha:pe,line:he.lines??null,at:f,symbol:he.symbol??null,blastRadius:he.blastRadius??null}});await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:Oe.rowid,dstUid:Oe.uid,dstKind:"citation",rel:"has_citation",rule:ue,typePolicy:t.typePolicy})}}return await Pe({tx:d,typePolicy:t.typePolicy,subjectRowid:M.rowid,subjectUid:M.uid,subjectKind:"issue",actor:e.by,action:"created",at:f}),{created:!0,uid:M.uid,item:{uid:M.uid,title:e.title,kind:h.name,status:b.name,priority:E==null?void 0:E.name,project:g.uid,component:y.uid,createdAt:f,assignee:e.assignee,author:j.name,...r!==void 0?{gitContext:r}:{}},...c.length>0?{duplicateCandidates:c}:{}}});if(u){const d=qi(t,{action:"upsert",subjectRowid:u.rowid,subjectUid:u.uid,actor:e.by,content:xl(e.title,e.body)});e.awaitEmbed?await d:d.catch(()=>{})}return l}function ci(t,e){if(typeof e!="string"||e.trim().length===0)throw new oe(t,"is required")}async function Bq(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`update: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`update: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await sn(t,r.src);if(!o||o.kind!=="project"||o.tInvalid!==null)throw new Error(`update: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}function Fq(t,e){if(t.length>0&&!t.includes(e))throw new oe("kind",`"${e}" is not in this project's allowed kind set`)}function qq(t,e){for(const n of t){if(!(n in e))continue;const r=e[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new oe(n,"is required by this project's field policy")}}async function Sg(t,e,n,r){const o=[],s=[];n.name!==void 0&&(o.push("name = ?"),s.push(n.name)),n.metadata!==void 0&&(o.push("meta = ?"),s.push(JSON.stringify(n.metadata))),o.push("t_updated = ?"),s.push(r);const i=await t.executeRun(`UPDATE node SET ${o.join(", ")} WHERE rowid = ?`,[...s,e]);if(i.rowsAffected!==1)throw new Error(`update: touch UPDATE affected ${i.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function ui(t,e,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const o=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[n.oldSrcRowid,n.rel]);let s=n.override;if(!s&&o){const a=await sn(t,o.dst);a&&a.tInvalid===null&&(s={rowid:a.rowid,uid:a.uid,kind:a.kind,name:a.name??""})}if(!s){if(n.required)throw new Error(`update: issue rowid=${n.oldSrcRowid} has no live "${n.rel}" edge — graph invariant violation (every live issue must carry exactly one live ${n.rel}).`);return}o&&await Sr(t,{srcRowid:n.oldSrcRowid,dstRowid:o.dst,rel:n.rel,reason:n.reason,at:n.at});const i=await Te(t,n.rel);await Re(t,{at:n.at,srcRowid:n.newSrcRowid,srcUid:n.newSrcUid,srcKind:"issue",dstRowid:s.rowid,dstUid:s.uid,dstKind:s.kind,rel:n.rel,rule:i,typePolicy:e.typePolicy})}async function Kq(t,e,n){if(n.oldIssueRowid===n.newIssueRowid)return;const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!r)throw new Error(`update: issue rowid=${n.oldIssueRowid} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const o=await sn(t,r.src);if(!o||o.kind!=="component"||o.tInvalid!==null)throw new Error(`update: resolved component rowid=${r.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await Sr(t,{srcRowid:r.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const s=await Te(t,"owns_component");await Re(t,{at:n.at,srcRowid:r.src,srcUid:o.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:s,typePolicy:e.typePolicy})}const _g=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Vq(t,e){if(e.oldIssueRowid===e.newIssueRowid)return;const n=_g.map(()=>"?").join(", ");for(const r of["outgoing","incoming"]){const o=r==="outgoing"?"src":"dst",s=r==="outgoing"?"dst":"src",{rows:i}=await t.executeAll(`SELECT ${s} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${o} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[e.oldIssueRowid,..._g]);for(const a of i){const c=r==="outgoing"?e.oldIssueRowid:a.other,u=r==="outgoing"?a.other:e.oldIssueRowid,l=r==="outgoing"?e.newIssueRowid:a.other,d=r==="outgoing"?a.other:e.newIssueRowid;await Sr(t,{srcRowid:c,dstRowid:u,rel:a.rel,reason:`superseded — "${a.rel}" carried forward to the new node`,at:e.at}),await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, confidence, origin, meta, t_created, t_valid)
|
|
513
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
514
|
+
ON CONFLICT(src, dst, rel) DO UPDATE SET
|
|
515
|
+
weight = excluded.weight, confidence = excluded.confidence,
|
|
516
|
+
origin = excluded.origin, meta = excluded.meta,
|
|
517
|
+
t_invalid = NULL, t_valid = excluded.t_valid`,[l,d,a.rel,a.weight,a.confidence,a.origin,a.meta,e.at,e.at])}}}function Gq(t){const e=[];return t.title!==void 0&&e.push("title"),t.body!==void 0&&e.push("body"),t.kind!==void 0&&e.push("kind"),t.priority!==void 0&&e.push("priority"),t.assignee!==void 0&&e.push("assignee"),t.author!==void 0&&e.push("author"),e}function zq(t,e){const n=["title","body","kind","priority","assignee","author"];for(const r of n)if(t[r]!==void 0&&!e.includes(r))throw new Error(`update: patch key "${r}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function Wq(t,e){if(ci("uid",e.uid),ci("by",e.by),jt("by",e.by),e.status!==void 0)throw new Er("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");e.title!==void 0&&ci("title",e.title),e.body!==void 0&&ci("body",e.body);const r=Gq(e);if(r.length===0)throw new oe("patch","update requires at least one of title/body/kind/priority/assignee/author");zq(e,r);let o;const s=await lt(t,async i=>{const a=He(),c=await _n(i,e.uid),u=await Bq(i,c.rowid),l=Zr(u);let d;if(e.kind!==void 0){const v=await mn(i,{catalogKind:"kind",ref:e.kind,at:a});Fq(l.allowedKinds,v.name),d={rowid:v.rowid,uid:v.uid,kind:"kind",name:v.name}}let f;if(e.priority!==void 0){const v=await mn(i,{catalogKind:"priority",ref:e.priority,at:a,mintMetadata:async b=>({rank:await vy(b)})});f={rowid:v.rowid,uid:v.uid,kind:"priority",name:v.name}}let g;if(e.author!==void 0){const v=await mn(i,{catalogKind:"agent",ref:e.author,at:a});g={rowid:v.rowid,uid:v.uid,kind:"agent",name:v.name}}const p={...e};d&&(p.kind=d.name),f&&(p.priority=f.name),g&&(p.author=g.name),qq(l.requiredFields,p);let y=c.rowid,w=c.uid,h=!1;if(e.body!==void 0){if((await i.executeRun("UPDATE node SET is_superseded = 1 WHERE rowid = ? AND is_superseded = 0",[c.rowid])).rowsAffected!==1)throw new da(e.uid);const b=e.title??c.name??void 0,E={...c.metadata??{}};e.assignee!==void 0&&(E.assignee=e.assignee);const N=await ct(i,{kind:"issue",name:b,content:e.body,metadata:E,at:a});await i.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
|
|
518
|
+
VALUES (?, ?, 'SUPERSEDES', 1.0, 'user_asserted', NULL, ?, ?)
|
|
519
|
+
ON CONFLICT(src, dst, rel) DO UPDATE SET
|
|
520
|
+
meta = excluded.meta, weight = excluded.weight,
|
|
521
|
+
t_invalid = NULL, t_valid = excluded.t_valid`,[N.rowid,c.rowid,a,a]),await Sg(i,N.rowid,{},a),o={oldRowid:c.rowid,oldUid:c.uid,newRowid:N.rowid,newUid:N.uid,newTitle:b??"",newBody:e.body},y=N.rowid,w=N.uid,h=!0}else{const v=e.assignee!==void 0?{...c.metadata??{},assignee:e.assignee}:void 0;await Sg(i,c.rowid,{name:e.title,metadata:v},a)}return await Kq(i,t,{oldIssueRowid:c.rowid,newIssueRowid:y,newIssueUid:w,at:a}),await ui(i,t,{rel:"has_status",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,reason:"superseded — status carried forward to the new node (update never changes status)",at:a,required:!0}),await ui(i,t,{rel:"has_kind",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,override:d,reason:"kind changed via update",at:a}),await ui(i,t,{rel:"has_priority",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,override:f,reason:"priority changed via update",at:a}),await ui(i,t,{rel:"authored_by",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,override:g,reason:"author changed via update",at:a}),await Vq(i,{oldIssueRowid:c.rowid,newIssueRowid:y,at:a}),await Pe({tx:i,typePolicy:t.typePolicy,subjectRowid:y,subjectUid:w,subjectKind:"issue",actor:e.by,action:"updated",from:h?c.uid:void 0,to:h?w:void 0,note:`fields changed: ${r.join(", ")}`,at:a}),{uid:w,changed:r}});if(o){const{oldRowid:i,oldUid:a,newRowid:c,newUid:u,newTitle:l,newBody:d}=o,f=Promise.all([qi(t,{action:"delete",subjectRowid:i,subjectUid:a,actor:e.by}),qi(t,{action:"upsert",subjectRowid:c,subjectUid:u,actor:e.by,content:xl(l,d)})]);e.awaitEmbed?await f:f.catch(()=>{})}return s}function mb(t){const e=t??{};return{claimedBy:typeof e.claimedBy=="string"?e.claimedBy:void 0,claimedAt:typeof e.claimedAt=="string"?e.claimedAt:void 0}}function gb(t,e){return t!==void 0?(Date.parse(e)-Date.parse(t))/6e4:Number.POSITIVE_INFINITY}function yb(t,e,n){return gb(t,e)>=n}async function wb(t,e,n){const r=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[e,"has_status"]);if(!r)throw new Error(`${n}: issue rowid=${e} has no live "has_status" edge — graph invariant violation (every live issue must carry exactly one live status).`);const o=await sn(t,r.dst);if(!o||o.kind!=="status"||o.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${r.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return o}function li(t,e){if(typeof e!="string"||e.trim().length===0)throw new oe(t,"is required")}async function Ng(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`transition: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`transition: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await sn(t,r.src);if(!o||o.kind!=="project"||o.tInvalid!==null)throw new Error(`transition: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}async function Hq(t,e){if(!ha(t))return"unverified";const n=L.resolve(t.metadata.path),r=L.isAbsolute(e)?L.resolve(e):L.resolve(n,e),o=L.relative(n,r);if(o===".."||o.startsWith("../")||o.startsWith("..\\")||L.isAbsolute(o))return"unverified";try{const i=await sl.readFile(r);return kn.createHash("sha256").update(i).digest("hex")}catch(i){const a=i==null?void 0:i.code;if(a==="ENOENT"||a==="ENOTDIR")return"unverified";throw new kl(i)}}function Jq(t,e){if(t.length>0&&!t.includes(e))throw new oe("toStatus",`"${e}" is not in this project's allowed status set`)}function Qq(t,e){for(const n of t){if(!(n in e))continue;const r=e[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new oe(n,"is required by this project's field policy")}}async function Yq(t,e){li("uid",e.uid),li("by",e.by),jt("by",e.by),li("toStatus",e.toStatus),hb(e.gitContext);const n=e.citations??[];n.forEach((o,s)=>li(`citations[${s}].file`,o.file));const r=[];if(n.length>0){const o=await pa(t.adapter,e.uid);if(!o||o.kind!=="issue"||o.tInvalid!==null)throw new fa(e.uid);const s=await Ng(t.adapter,o.rowid),i=Zr(s);for(const a of n){const c=await Hq(s,a.file);if(c==="unverified"&&i.citationRequiresSha){if(ha(s))throw new jl(a.file);console.error(`transition: citation_requires_sha waived for path-less project uid="${s.uid}" — cannot verify citation "${a.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}r.push(c)}}return lt(t,async o=>{var M;const s=He(),i=await _n(o,e.uid),a=await Ng(o,i.rowid),c=Zr(a),{claimedBy:u,claimedAt:l}=mb(i.metadata);if(u!==void 0&&u!==e.by&&!yb(l,s,c.claimStaleAfterMin))throw new Bi(u,l??s);const d=await wb(o,i.rowid,"transition"),f=d.name??"",g=await mn(o,{catalogKind:"status",ref:e.toStatus,at:s,mintMetadata:async()=>({terminal:!1})});Jq(c.allowedStatuses,g.name),Qq(c.requiredFields,{status:g.name,note:e.note});const p=await sn(o,g.rowid),y=((M=p==null?void 0:p.metadata)==null?void 0:M.terminal)===!0;if(!(typeof e.note=="string"&&e.note.trim().length>0)&&c.transitionRequiresNote)throw new py(i.uid);if(y&&c.citationRequired&&n.length===0)throw new hy(i.uid);const h={target_uid:i.uid,from:f,to:g.name,agent:e.by,note:e.note??null,at:s},v=Al(yy(h)),b=await ct(o,{kind:"transition",content:e.note??"",metadata:{from_status:f,to_status:g.name,agent:e.by,note:e.note??null,sha:v,at:s},at:s}),E=await Te(o,"has_transition");await Re(o,{at:s,srcRowid:i.rowid,srcUid:i.uid,srcKind:"issue",dstRowid:b.rowid,dstUid:b.uid,dstKind:"transition",rel:"has_transition",rule:E,typePolicy:t.typePolicy}),await Sr(o,{srcRowid:i.rowid,dstRowid:d.rowid,rel:"has_status",reason:`transitioned to "${g.name}"`,at:s});const N=await Te(o,"has_status");if(await Re(o,{at:s,srcRowid:i.rowid,srcUid:i.uid,srcKind:"issue",dstRowid:g.rowid,dstUid:g.uid,dstKind:"status",rel:"has_status",rule:N,typePolicy:t.typePolicy}),n.length>0){const C=await Te(o,"has_citation");for(let G=0;G<n.length;G+=1){const H=n[G],Z=r[G],ue=await ct(o,{at:s,kind:"citation",name:H.file,content:H.context??H.file,metadata:{target:H.file,target_type:"path",sha:Z,line:H.lines??null,at:s,symbol:H.symbol??null,blastRadius:H.blastRadius??null}});await Re(o,{at:s,srcRowid:i.rowid,srcUid:i.uid,srcKind:"issue",dstRowid:ue.rowid,dstUid:ue.uid,dstKind:"citation",rel:"has_citation",rule:C,typePolicy:t.typePolicy})}}const j={...i.metadata??{}};y?j.closedAt=s:delete j.closedAt,typeof e.gitContext=="string"&&e.gitContext.trim().length>0&&(j.gitContext=e.gitContext);const T=await o.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(j),s,i.rowid]);if(T.rowsAffected!==1)throw new Error(`transition: closedAt touch UPDATE affected ${T.rowsAffected} rows for rowid=${i.rowid}, expected exactly 1.`);return await Pe({tx:o,typePolicy:t.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:e.by,action:"transitioned",from:f,to:g.name,note:e.note,at:s}),{uid:i.uid,fromStatus:f,toStatus:g.name,closedAt:y?s:void 0,transitionUid:b.uid}})}function Og(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function Zq(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`claim: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`claim: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await sn(t,r.src);if(!o||o.kind!=="project"||o.tInvalid!==null)throw new Error(`claim: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const s={rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata};return Zr(s)}async function Oo(t,e,n,r){const o=await t.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),r,e]);if(o.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${o.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function Xq(t,e){if(Og("uid",e.uid),Og("by",e.by),jt("by",e.by),e.action!=="claim"&&e.action!=="release"&&e.action!=="renew")throw new oe("action",`must be "claim", "release", or "renew" (got ${JSON.stringify(e.action)})`);const n=e.force===!0;return lt(t,async r=>{var u;const o=He(),s=await _n(r,e.uid),i={...s.metadata??{}},{claimedBy:a,claimedAt:c}=mb(i);if(e.action==="claim"){const l=await wb(r,s.rowid,"claim");if(((u=l.metadata)==null?void 0:u.terminal)===!0)throw new fy(s.uid,l.name??"");if(a===void 0){const y={...i,claimedBy:e.by,claimedAt:o};return await Oo(r,s.rowid,y,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"claimed",to:e.by,at:o}),{uid:s.uid,status:"claimed",claimedBy:e.by,claimedAt:o}}if(a===e.by){const y={...i,claimedAt:o};return await Oo(r,s.rowid,y,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"claimed",from:e.by,to:e.by,note:"re-affirmed (held)",at:o}),{uid:s.uid,status:"held",heldBy:e.by,claimedBy:e.by,claimedAt:o}}const d=await Zq(r,s.rowid),f=gb(c,o),g=yb(c,o,d.claimStaleAfterMin);if(!g&&!n)throw new Bi(a,c??o);const p={...i,claimedBy:e.by,claimedAt:o,previousClaimant:a};return await Oo(r,s.rowid,p,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"reclaimed-stale",from:a,to:e.by,note:g?`stale claim reclaimed after ~${Math.floor(f)}min (threshold ${d.claimStaleAfterMin}min)`:"force override of a non-stale claim",at:o}),{uid:s.uid,status:"reclaimed-stale",claimedBy:e.by,claimedAt:o,previousClaimant:a}}if(e.action==="release"){if(a===e.by){const l={...i};return delete l.claimedBy,delete l.claimedAt,await Oo(r,s.rowid,l,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"released",from:e.by,at:o}),{uid:s.uid,status:"released"}}return{uid:s.uid,status:"release-noop",wasClaimedBy:a}}if(a===e.by){const l={...i,claimedAt:o};return await Oo(r,s.rowid,l,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"renewed",from:e.by,to:e.by,at:o}),{uid:s.uid,status:"renewed",claimedBy:e.by,claimedAt:o}}throw new Bi(a??"",c??"")})}const kg=["relates_to","supersedes","blocks","duplicate_of","part_of"];function jc(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function eK(t,e,n,r){const o=await t.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e,n,r]);return o?o.rowid:null}async function tK(t,e){if(jc("sourceUid",e.sourceUid),jc("targetUid",e.targetUid),jc("by",e.by),jt("by",e.by),!kg.includes(e.rel))throw new oe("rel",`must be one of ${kg.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.rel)})`);if(e.action!=="add"&&e.action!=="remove")throw new oe("action",`must be "add" or "remove" (got ${JSON.stringify(e.action)})`);if(e.sourceUid===e.targetUid)throw new oe("targetUid","a self-relation (sourceUid === targetUid) is never allowed");return lt(t,async n=>{const r=He(),o=await _n(n,e.sourceUid),s=await _n(n,e.targetUid),i=await eK(n,o.rowid,s.rowid,e.rel);if(e.action==="add"){if(i!==null)return{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"add",noop:!0};const a=await Te(n,e.rel);return await Re(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"issue",dstRowid:s.rowid,dstUid:s.uid,dstKind:"issue",rel:e.rel,rule:a,typePolicy:t.typePolicy}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"related",to:s.uid,note:e.rel,at:r}),{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"add",noop:!1}}return i===null?{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"remove",noop:!0}:(await Sr(n,{srcRowid:o.rowid,dstRowid:s.rowid,rel:e.rel,reason:`relate: removed by "${e.by}"`,at:r}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"unrelated",to:s.uid,note:e.rel,at:r}),{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"remove",noop:!1})})}function jg(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function nK(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`move: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await sn(t,n.src);if(!r||r.kind!=="component"||r.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function rK(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_project"]);if(!n)throw new Error(`move: component rowid=${e} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const r=await sn(t,n.src);if(!r||r.kind!=="project"||r.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function oK(t,e){return jg("uid",e.uid),jg("by",e.by),jt("by",e.by),lt(t,async n=>{const r=He(),o=await _n(n,e.uid),s=await nK(n,o.rowid),i=await rK(n,s.rowid);let a;if(e.toProject!==void 0){const l=await rs(n,e.toProject);a={rowid:l.rowid,uid:l.uid,name:l.name}}else a=i;let c;if(e.toComponent!==void 0?c=await Pl(n,{projectUid:a.uid,ref:e.toComponent}):c=await wy(n,{projectRowid:a.rowid}),c.rowid===s.rowid)return{uid:o.uid,noop:!0,fromProject:i.uid,toProject:a.uid,fromComponent:s.uid,toComponent:c.uid};await Sr(n,{srcRowid:s.rowid,dstRowid:o.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:r});const u=await Te(n,"owns_component");return await Re(n,{at:r,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:o.rowid,dstUid:o.uid,dstKind:"issue",rel:"owns_component",rule:u,typePolicy:t.typePolicy}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"moved",from:s.uid,to:c.uid,at:r}),{uid:o.uid,noop:!1,fromProject:i.uid,toProject:a.uid,fromComponent:s.uid,toComponent:c.uid}})}function Ac(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function sK(t,e){Ac("uid",e.uid),Ac("by",e.by),jt("by",e.by),Ac("reason",e.reason);let n;const r=await lt(t,async o=>{const s=He(),i=await _n(o,e.uid);n={rowid:i.rowid,uid:i.uid};const a={...i.metadata??{},invalidatedReason:e.reason,invalidatedAt:s},c=await o.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[s,JSON.stringify(a),i.rowid]);if(c.rowsAffected!==1)throw new Error(`deleteIssue: invalidate UPDATE affected ${c.rowsAffected} rows for uid="${e.uid}", expected exactly 1.`);return await Pe({tx:o,typePolicy:t.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:e.by,action:"deleted",note:e.reason,at:s}),{uid:i.uid,invalidated:!0}});if(n){const o=qi(t,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:e.by});e.awaitEmbed?await o:o.catch(()=>{})}return r}async function vb(t){return Eq(t.store.adapter,t.store.graph,t.env.config.embedding)}async function At(t,e){await Ol(t.store.adapter);const{search:n,embedding:r}=e.needsSemantic?await vb(t):{};return{adapter:t.store.adapter,typePolicy:t.store.typePolicy,graph:t.store.graph,...n!==void 0?{search:n}:{},...r!==void 0?{embedding:r}:{}}}async function za(t,e){const{search:n}=e.needsSemantic?await vb(t):{},r=n!==void 0&&e.probeSpace?await n.spacePopulated():void 0;return{graph:t.store.graph,assertVocabulary:()=>Ol(t.store.adapter),...n!==void 0?{search:n}:{},...r!==void 0?{spacePopulated:r}:{}}}const iK=[[fa,"item_not_found"],[Xe,"not_found"],[oe,"invalid_argument"],[Bi,"conflict"],[Qc,"conflict"],[da,"conflict"],[fy,"precondition_failed"],[hy,"precondition_failed"],[py,"precondition_failed"],[jl,"precondition_failed"],[dy,"store_busy"],[ub,"rag_not_configured"]],aK={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function $b(t){for(const[e,n]of iK)if(t instanceof e){const r=t instanceof Ke?{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}:void 0;return pr(n,t.message,r)}return t instanceof Ke?pr(aK[t.code]??"internal",t.message,{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}):pr("internal",t instanceof Error?t.message:String(t))}async function Je(t){try{return ap(await t())}catch(e){return $b(e)}}async function bb(t,e){return Je(()=>"registry"in e?e.registry==="project"?kc(t.store.graph,{registry:"project",name:e.name}):e.registry==="component"?kc(t.store.graph,{registry:"component",name:e.name,filter:e.filter}):kc(t.store.graph,{registry:"location",name:e.name}):_q(t.store.graph,e))}async function Eb(t,e){try{const{result:n,meta:r}=await gq(await za(t,{needsSemantic:fq(e),probeSpace:e.text!==void 0}),e);return ap(n,r?{meta:r}:void 0)}catch(n){return $b(n)}}async function Sb(t,e){return Je(async()=>Aq(await za(t,{needsSemantic:!1,probeSpace:!1}),e))}async function _b(t,e){return Je(async()=>Pq(await za(t,{needsSemantic:!1,probeSpace:!1}),e))}async function Nb(t,e){return Je(async()=>Cq(await za(t,{needsSemantic:!1,probeSpace:!1}),e))}async function Ob(t,e){return Je(()=>HF(t.store.graph,e.q))}async function kb(t,e){return Je(async()=>Uq(await At(t,{needsSemantic:!0}),e))}async function jb(t,e){return Je(async()=>Wq(await At(t,{needsSemantic:!0}),e))}async function Ab(t,e){return Je(async()=>Yq(await At(t,{needsSemantic:!1}),e))}async function Ib(t,e){return Je(async()=>Xq(await At(t,{needsSemantic:!1}),e))}async function Pb(t,e){return Je(async()=>tK(await At(t,{needsSemantic:!1}),e))}async function xb(t,e){return Je(async()=>oK(await At(t,{needsSemantic:!1}),e))}async function Rb(t,e){return Je(async()=>sK(await At(t,{needsSemantic:!1}),e))}async function Tb(t,e){return Je(async()=>uN(await At(t,{needsSemantic:!1}),e))}async function Cb(t,e){return Je(async()=>dN(await At(t,{needsSemantic:!1}),e))}async function Mb(t,e){return Je(async()=>pN(await At(t,{needsSemantic:!1}),e))}async function Lb(t,e){return Je(async()=>hN(await At(t,{needsSemantic:!1}),e))}const cK=Object.freeze(Object.defineProperty({__proto__:null,claim:Ib,create:kb,delete:Rb,get:bb,lookup:Ob,move:xb,openCurve:Nb,partOfRollup:_b,priorityMatrix:Sb,query:Eb,relate:Pb,rmLocation:Lb,transition:Ab,update:jb,upsertComponent:Cb,upsertLocation:Mb,upsertProject:Tb},Symbol.toStringTag,{value:"Module"}));function uK(){const t=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)),e=L.join(t,"package.json");return J.existsSync(e)?e:L.join(t,"..","package.json")}function cp(){const t=uK(),e=JSON.parse(J.readFileSync(t,"utf8"));return{name:e.name,version:e.version}}function ol(t){if(!t.run)throw new Error(`@adhd/backlog: apigen plugin "${t.id}" declares no run() — cannot mount live`);return t.run}function Db(){if(!process.env.VITEST)return;const t=()=>{},e={info:t,error:t,debug:t,fatal:t,warn:t,trace:t};return e.child=()=>e,e}const Ag=["install","install-skill","serve"];function Ub(t){return t.filter(e=>e.kind==="action").map(e=>{const n=la(e);return{id:e.id,cliCommand:n.cli.path.join(" "),cliPath:n.cli.path,mcpTool:n.mcp.name,httpVerb:n.http.verb,httpRoute:n.http.route}}).sort((e,n)=>e.id.localeCompare(n.id))}function lK(t){const e=t.filter(n=>{const r=n.cliPath[n.cliPath.length-1]??"";return Ag.includes(r)||Ag.some(o=>n.mcpTool.endsWith(`_${o.replace(/-/g,"_")}`))});if(e.length>0)throw new Error(`@adhd/backlog: host-command carve-out violated (SPEC.md §6.6) — ${e.map(n=>n.id).join(", ")} was mounted as a data operation. install/install-skill must never open the store (DEBT-BACKLOG-CLI-EAGER-STORE-OPEN-001) and serve must never be reachable as a tool — it has a completely different lifecycle than a mounted data operation. Keep them host commands in cli.ts.`)}function dK(t,e=[Ui]){const n=Ub(t),r=new Set(n.map(s=>s.mcpTool)),o={host:"backlog",operations:t};for(const s of e){const i=s.capabilities.mount;if(i)for(const a of i.operations(o,void 0,void 0))r.add(la(a).mcp.name)}return[...r].sort()}function Bb(){const t=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href));return J.existsSync(L.join(t,"api.d.ts"))?t:L.join(t,"..","dist")}function Ig(t){if(!t||typeof t!="object")return t;const e={},n=o=>{if(Array.isArray(o)){for(const i of o)n(i);return}if(!o||typeof o!="object")return;const s=o;for(const i of["definitions","$defs"]){const a=s[i];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,u]of Object.entries(a))c in e||(e[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(t),n(e),Object.keys(e).length===0)return t;const r=(o,s)=>{if(Array.isArray(o))return o.map(u=>r(u,s));if(!o||typeof o!="object")return o;const i=o,a=i.$ref;if(typeof a=="string"){const u=a.replace(/^#\/(?:definitions|\$defs)\//,"");return s.has(u)||!(u in e)?{}:r(e[u],new Set([...s,u]))}const c={};for(const[u,l]of Object.entries(i))u==="definitions"||u==="$defs"||(c[u]=r(l,s));return c};return r(t,new Set)}const fK=Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href),pK=fK("@adhd/apigen-core-client/package.json").version;function hK(t={}){return _P(t)}function mK(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function gK(t={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:Ix({cache:hK(t),extractorVersion:pK})}}}}let Pg;function yK(t={}){return Pg??(Pg=$x(mK()?[gK(t)]:[],e=>{var n;return lx({sourceFile:e.source,namespace:e.namespace,tsconfig:typeof((n=e.extractorOptions)==null?void 0:n.tsconfig)=="string"?e.extractorOptions.tsconfig:void 0,dropFileSegment:!0})})),Pg}async function wK(t={}){const e=L.join(Bb(),"api.d.ts");if(!J.existsSync(e))throw new Error(`@adhd/backlog: cannot mount — ${e} does not exist. Run "nx build backlog" first (extract() needs the built .d.ts for type information).`);return yK(t)({source:e,host:"ts",namespace:"backlog",extractorOptions:{}})}async function up(t,e={}){const n=typeof t=="function"?t:()=>t,r=await wK(e),o={schemas:Object.fromEntries(r.filter(c=>c.kind==="action").map(c=>{var u;return[((u=c.path[c.path.length-1])==null?void 0:u.raw)??"",{input:Ig(c.input),output:Ig(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},s=RP(o,[]),i=Ub(r);lK(i);const{version:a}=cp();return{pkg:{id:"backlog",version:a,schemas:s,importPath:L.join(Bb(),"api.js"),fns:cK,createClient:async()=>n()},operations:r,surface:i}}async function Fb(t){const e=Go({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace});e.ensureDirs();let n,r;const o=zo(e),s=()=>(n||(n=Zc(r)),n),i=wN()?void 0:by(s);try{r=await Ki(o,e.config.db.busyTimeoutMs)}catch(c){throw i==null||i.dispose(),c}const a={store:r,env:e};try{const{pkg:c,operations:u}=await up(a,{adhdRoot:t.adhdRoot}),l=Db(),d=[];(t.transport==="http"||t.transport==="both")&&d.push(ol(w2)({packages:[c],outputDir:"",options:{port:t.port??3300,host:t.host??"127.0.0.1",usePlugins:[x2,Ui]},signal:t.signal,operations:u,logger:l})),(t.transport==="mcp"||t.transport==="both")&&d.push(ol(pF)({packages:[c],outputDir:"",options:{transport:"stdio",usePlugins:[Ui]},signal:t.signal,operations:u,logger:l})),await Promise.all(d)}finally{i==null||i.dispose(),await s()}}const Yr=["claude","codex","opencode"],vK={claude:".claude",codex:".codex",opencode:".opencode"};function qb(t,e){return e?L.join(t,".codex"):process.env.CODEX_HOME??L.join(t,".codex")}function $K(t,e,n,r){if(e==="project")return L.join(n,vK[t],"skills");const o=r??mt.homedir();return t==="claude"?L.join(o,".claude","skills"):t==="codex"?L.join(qb(o,r),"skills"):L.join(o,".config","opencode","skills")}function bK(){const t=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)),e=L.join(t,"skill","SKILL.md");return J.existsSync(e)?e:L.join(t,"..","skill","SKILL.md")}class ht extends Error{constructor(e){super(e),this.name="BacklogUsageError"}}function lp(t,e){console.error(JSON.stringify({code:"invalid_argument",message:t.message})),console.error(""),console.error(e),process.exitCode=2}const xg=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
|
|
522
|
+
|
|
523
|
+
Copies the packaged backlog SKILL.md into an agent host's skills directory.
|
|
524
|
+
(\`backlog install\` is the richer successor — it also registers the MCP server.)
|
|
525
|
+
|
|
526
|
+
--host <name> claude | codex | opencode | all (default: all)
|
|
527
|
+
--scope <name> user | project (default: user)
|
|
528
|
+
"user" is the machine-wide install (~/.claude/skills/...);
|
|
529
|
+
there is no "global" — that is spelled "user" here.
|
|
530
|
+
|
|
531
|
+
Examples:
|
|
532
|
+
backlog install-skill
|
|
533
|
+
backlog install-skill --host opencode --scope user
|
|
534
|
+
backlog install-skill --host claude --scope project
|
|
535
|
+
`;function EK(t){let e="all",n="user";for(let o=0;o<t.length;o++){const s=t[o];if(s==="--host")e=t[++o]??"all";else if(s==="--scope")n=t[++o]??"user";else throw new ht(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const o=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new ht(`backlog install-skill: --scope must be "user" or "project", got "${n}"${o}`)}const r=e==="all"?[...Yr]:[e];for(const o of r)if(!Yr.includes(o))throw new ht(`backlog install-skill: --host must be one of ${Yr.join("|")}|all, got "${e}"`);return{hosts:r,scope:n}}function Kb(t,e=process.cwd(),n){const{hosts:r,scope:o}=EK(t);return Vb(r,o,e,n)}function Vb(t,e,n,r){const o=bK();if(!J.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const s=J.readFileSync(o,"utf8"),i=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)),a=L.join(i,"package.json"),c=J.existsSync(a)?a:L.join(i,"..","package.json"),u=JSON.parse(J.readFileSync(c,"utf8")),l=[];for(const d of t){const f=L.join($K(d,e,n,r),"backlog");J.mkdirSync(f,{recursive:!0});const g=L.join(f,"SKILL.md");J.writeFileSync(g,s,"utf8"),J.writeFileSync(L.join(f,"extension.json"),JSON.stringify({name:u.name,version:u.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
|
|
536
|
+
`,"utf8"),l.push({host:d,scope:e,path:g})}return l}async function Gb(t){if(t.includes("--help")||t.includes("-h")){console.log(xg);return}let e;try{e=Kb(t)}catch(n){if(n instanceof ht)return lp(n,xg);throw n}console.log(JSON.stringify({installed:e}))}const dp=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function SK(t){if(!J.existsSync(t))return{};const e=J.readFileSync(t,"utf8").trim();if(e==="")return{};const n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${t} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function zb(t,e,n,r){const o=SK(t),s=o[e],i=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:{};i[n]=r,o[e]=i,J.mkdirSync(L.dirname(t),{recursive:!0}),J.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
537
|
+
`,"utf8")}function _K(t,e,n){if(t==="project")return L.join(e,".mcp.json");const r=mt.homedir();return L.join(r,".claude.json")}function NK(t,e,n){if(t==="project")return L.join(e,"opencode.json");const r=mt.homedir();return L.join(r,".config","opencode","opencode.json")}function OK(t,e,n){if(t==="project")return L.join(e,".codex","config.toml");const r=mt.homedir();return L.join(qb(r,n),"config.toml")}function kK(t,e,n){var u,l;const r=`[${e}]`,o=t.length>0?t.split(`
|
|
538
|
+
`):[],s=o.findIndex(d=>d.trim()===r),i=[r,...n];if(s===-1){if(o.length===0||o.every(d=>d.trim()===""))return i.join(`
|
|
203
539
|
`)+`
|
|
204
540
|
`;for(;o.length>0&&((u=o[o.length-1])==null?void 0:u.trim())==="";)o.pop();return[...o,"",...i].join(`
|
|
205
541
|
`)+`
|
|
206
542
|
`}let a=s+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,s),...i,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
|
|
207
543
|
`)+`
|
|
208
|
-
`}function
|
|
544
|
+
`}function jK(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}function AK(t,e,n){const r=_K(t,e);return zb(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...dp]}),{host:"claude",scope:t,configPath:r,status:"written"}}function IK(t,e,n){const r=NK(t,e);return zb(r,"mcp","backlog",{type:"local",command:["npx",...dp]}),{host:"opencode",scope:t,configPath:r,status:"written"}}function PK(t,e,n){const r=OK(t,e,n),o=J.existsSync(r)?J.readFileSync(r,"utf8"):"",s=kK(o,"mcp_servers.backlog",['command = "npx"',`args = ${jK(dp)}`]);return J.mkdirSync(L.dirname(r),{recursive:!0}),J.writeFileSync(r,s,"utf8"),{host:"codex",scope:t,configPath:r,status:"written"}}function xK(t,e,n,r){return t==="claude"?AK(e,n):t==="opencode"?IK(e,n):PK(e,n,r)}function RK(t,e){let n="all",r="user",o=!1,s=!1;for(let a=0;a<t.length;a++){const c=t[a];if(c==="--host")n=t[++a]??"all";else if(c==="--scope")r=t[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")s=!0;else throw new ht(`backlog ${e}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&s)throw new ht(`backlog ${e}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project"){const a=r==="global"?' — the machine-wide scope is spelled "user"':"";throw new ht(`backlog ${e}: --scope must be "user" or "project", got "${r}"${a}`)}const i=n==="all"?[...Yr]:[n];for(const a of i)if(!Yr.includes(a))throw new ht(`backlog ${e}: --host must be one of ${Yr.join("|")}|all, got "${n}"`);return{hosts:i,scope:r,skillOnly:o,mcpOnly:s}}const Rg=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
|
|
209
545
|
|
|
210
546
|
Installs the backlog skill AND registers the backlog MCP server into an agent
|
|
211
547
|
host's config, in one step.
|
|
@@ -222,4 +558,26 @@ Examples:
|
|
|
222
558
|
|
|
223
559
|
Back-compat: \`backlog install-skill\` remains available and behaves exactly
|
|
224
560
|
like \`backlog install --skill-only\` (original --host/--scope grammar only).
|
|
225
|
-
`;function
|
|
561
|
+
`;function TK(t,e=process.cwd(),n){const{hosts:r,scope:o,skillOnly:s,mcpOnly:i}=RK(t,"install"),a=i?[]:Vb(r,o,e,n),c=s?[]:r.map(u=>xK(u,o,e,n));return{skill:a,mcp:c}}async function CK(t){if(t.includes("--help")||t.includes("-h")){console.log(Rg);return}let e;try{e=TK(t)}catch(n){if(n instanceof ht)return lp(n,Rg);throw n}for(const n of e.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of e.mcp){const r=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${r}`)}console.log(JSON.stringify(e))}const Tg=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
|
|
562
|
+
|
|
563
|
+
Starts the long-lived backlog server (MCP and/or HTTP), matching one of the
|
|
564
|
+
process's own configured transports to the way an agent host or a script
|
|
565
|
+
expects to reach it.
|
|
566
|
+
|
|
567
|
+
--transport <name> mcp | http | both (default: mcp)
|
|
568
|
+
--port <N> HTTP listen port (default: 3300; ignored for mcp-only)
|
|
569
|
+
--host <name> HTTP listen host (default: 127.0.0.1; ignored for mcp-only)
|
|
570
|
+
|
|
571
|
+
Examples:
|
|
572
|
+
backlog serve
|
|
573
|
+
backlog serve --transport http --port 3300
|
|
574
|
+
backlog serve --transport both --host 0.0.0.0
|
|
575
|
+
`;function MK(t){let e="mcp",n,r;for(let s=0;s<t.length;s++){const i=t[s];if(i==="--transport")e=t[++s];else if(i==="--port")n=Number(t[++s]);else if(i==="--host")r=t[++s];else throw new ht(`backlog serve: unknown argument "${i}" (expected --transport/--port/--host)`)}if(e!=="mcp"&&e!=="http"&&e!=="both")throw new ht(`backlog serve: --transport must be mcp|http|both, got "${e}"`);const o={transport:e};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function Wb(t,e={}){if(t.includes("--help")||t.includes("-h")){console.log(Tg);return}let n;try{n=MK(t)}catch(i){if(i instanceof ht)return lp(i,Tg);throw i}const r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort());const o=Fb({...n,...e,signal:r.signal}),s=e.namespace==="sandbox"?J.mkdtempSync(L.join(mt.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Lg.initTelemetry({service:"backlog",role:"live-service",logSink:"file",...s!==void 0?{logDir:s}:{}})}catch(i){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${i instanceof Error?i.message:String(i)}); telemetry records will be silently dropped this process`)}await o}const fp=["limit","offset","sort","direction"],Hb=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],pp=["status","priority"],Wa=["fields"],LK={"claimed-by":"claimedBy","project-path":"projectPath"},Jb=[...fp,...Wa,...Hb,...pp].map(t=>`--${t}`).sort(),DK=new Set([...fp,...Wa]),UK=new Set([...pp,...Wa]),BK=new Set([...fp,...Wa,...Hb,...pp]),FK=new Set(["limit","offset"]),Qb=['backlog search "<natural-language query>" [flags]',"",'Shorthand for `backlog query --input \'{"text": "<query>", ...}\'` — the same',"command, the same JSON envelope, the same exit codes. The query text is","matched semantically when the embedding space is populated, and by keyword","(FTS) when it is not.","","Paging / ranking:"," --limit <n> max items to return"," --offset <n> skip the first n"," --sort <s> override the derived default (relevance / textMatch)"," --direction <d> asc | desc"," --fields <a,b,c> projection; add _score to see ranking scores","","Filters (all compose with the query text):"," --status <s> open | closed | OPEN,IN_PROGRESS | …"," --priority <p> CRITICAL | HIGH | MEDIUM | LOW (comma-separated for several)"," --kind <k> BUG | DEBT | FEAT | …"," --project-path <p> component's repo-relative path (component.meta.path)"," --plan <uid|title> the parent plan issue this item is filed under (part_of)"," --assignee <a> durable owner"," --claimed-by <c> ephemeral claim holder"," --grep <q> extra keyword predicate. Composes with the query text ONLY"," once the embedding space is populated — without it the query"," text IS the keyword query and the two collide (§2.1b step 1).","","More-like-this:",' --anchor <ID> nearest neighbours of an EXISTING item (view:"similar").'," Replaces the positional query rather than refining it."].join(`
|
|
576
|
+
`);function Cg(t,e,n,r){if(!r){t[e]=n;return}const o=t[e]??[];t[e]=[...o,...n.split(",").map(s=>s.trim()).filter(s=>s.length>0)]}function Yb(t){if(t.includes("--help")||t.includes("-h"))return{kind:"help",text:Qb};const e={},n={};let r,o=0;for(;o<t.length;){const a=t[o];if(!a.startsWith("--")){if(r!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};r=a,o+=1;continue}let c=a.slice(2),u;const l=c.indexOf("=");if(l!==-1&&(u=c.slice(l+1),c=c.slice(0,l)),c==="input")return{kind:"error",message:"Unknown option: --input. `search` takes the query as a positional argument; for the raw JSON form use `backlog query --input '{...}'`"};if(!BK.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${Jb.join(", ")}`};o+=1;let d;if(u!==void 0)d=u;else{if(o>=t.length)return{kind:"error",message:`Missing value for --${c}`};d=t[o],o+=1}const f=UK.has(c);DK.has(c)?Cg(e,c,d,f):Cg(n,LK[c]??c,d,f)}for(const a of["status","priority"]){const c=n[a];c!==void 0&&c.length===1&&(n[a]=c[0])}for(const a of FK){const c=e[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(e[a]=Number(c))}const s=n.anchor;if(s!==void 0&&r!==void 0)return{kind:"error",message:`Validation failed: --anchor and a positional query are mutually exclusive — --anchor ranks by an EXISTING item's vector (view:"similar"), so there is no query text to also match (mount-surface spec §2.1)`};if(s===void 0&&r===void 0)return{kind:"error",message:`Validation failed: /data must have required property 'text' — Example: {"data":{"text":"flaky publish gate"}}`};const i={...e};return s!==void 0?i.view="similar":i.text=r,Object.keys(n).length>0&&(i.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(i)]}}function Zb(t){const e=t.find(n=>n.kind==="action");if(!e)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return la(e).cli.path.slice(0,-1)}const Mg=[Ui];function qK(t,e,n){const r={host:n,operations:e},o=new Set;for(const s of t){const i=s.capabilities.mount;if(!i)continue;const a=i.operations(r,void 0,void 0);for(const c of a){const[u]=la(c).cli.path;u!==void 0&&o.add(u)}}return o}function Xb(t,e,n){var o;return t.length===0?[...t]:(o=t[0])!=null&&o.startsWith("-")?[...t]:t[0]!==void 0&&n.has(t[0])?[...t]:e.length>0&&e.every((s,i)=>t[i]===s)?[...t]:[...e,...t]}function hp(t){const e=[],n=[];let r=!1;for(let s=0;s<t.length;s++){const i=t[s];if(i!==void 0){if(i.startsWith("--namespace=")){const a=i.slice(12);a===""?r=!0:e.push(a);continue}if(i==="--namespace"){const a=t[s+1];a===void 0||a.startsWith("-")?r=!0:(e.push(a),s++);continue}n.push(i)}}const o=new Set(e);return{argv:n,namespace:e[e.length-1],missingValue:r,conflicting:o.size>1}}async function eE(t,e={}){var w;const{argv:n,namespace:r,missingValue:o,conflicting:s}=hp(t??process.argv.slice(2)),i={...e};if(o){const h=pr("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(h)),process.exitCode=Co(h);return}if(s){const h=t??process.argv.slice(2),v=new Set;for(let E=0;E<h.length;E++){const N=h[E];N!==void 0&&(N.startsWith("--namespace=")?v.add(N.slice(12)):N==="--namespace"&&h[E+1]!==void 0&&v.add(h[E+1]))}const b=pr("invalid_argument",`Invalid argument "namespace": conflicting values ${[...v].map(E=>`"${E}"`).join(", ")}`);console.log(JSON.stringify(b)),process.exitCode=Co(b);return}if(r!==void 0&&!((w=ls.namespaces)!=null&&w.includes(r))){const h=ls.namespaces??[],v=tb(r,h),b=`must be one of ${h.map(N=>`"${N}"`).join(", ")}`+(v.length>0?` (did you mean ${v.map(N=>`"${N}"`).join(" or ")}?)`:""),E=pr("invalid_argument",`Invalid argument "namespace": ${b}`);console.log(JSON.stringify(E)),process.exitCode=Co(E);return}r!==void 0&&(i.namespace=r);const a=i.namespace??"production";i.adhdRoot===void 0&&process.env.ADHD_ROOT&&(i.adhdRoot=process.env.ADHD_ROOT);const c=h=>h.includes(`${L.sep}backlog-sandbox-`);if(a==="sandbox"){i.adhdRoot!==void 0&&!c(i.adhdRoot)&&(console.error(`[backlog] --namespace sandbox: ADHD_ROOT=${i.adhdRoot} is set but is not a sandbox this tool created — ignoring it and minting a fresh isolated store instead, so --namespace sandbox never writes into an unrecognized (possibly production) location.`),i.adhdRoot=void 0),i.adhdRoot===void 0&&(i.adhdRoot=J.mkdtempSync(L.join(mt.tmpdir(),"backlog-sandbox-")),console.error(`[backlog] --namespace sandbox: isolated store at ${i.adhdRoot} (not auto-deleted — pass ADHD_ROOT=${i.adhdRoot} to reuse it, or remove it yourself when done)`)),i.namespace="sandbox";const h=L.join(i.adhdRoot,"backlog","sandbox");J.mkdirSync(h,{recursive:!0}),J.writeFileSync(L.join(h,"config.yaml"),`# Written by --namespace sandbox on every invocation — DELIBERATE, not
|
|
577
|
+
# an absence-of-file default. embedding.enabled is off so a sandboxed
|
|
578
|
+
# run never pays a real model-load cost or opens a real vector store.
|
|
579
|
+
embedding:
|
|
580
|
+
enabled: false
|
|
581
|
+
`)}if(i.adhdRoot!==void 0&&process.env.APIGEN_IR_CACHE_FILE===void 0&&(process.env.APIGEN_IR_CACHE_FILE=L.join(i.adhdRoot,"ir-cache","backlog-client.ir.json")),n[0]==="sandbox-path"){const h=Go({scope:i.scope,adhdRoot:i.adhdRoot,cwd:i.cwd,namespace:i.namespace});console.log(JSON.stringify({adhdRoot:i.adhdRoot,namespace:i.namespace??"production",dbPath:zo(h),embeddingEnabled:h.config.embedding.enabled}));return}if(n[0]==="store-check"){const h=Go({scope:i.scope,adhdRoot:i.adhdRoot,cwd:i.cwd,namespace:i.namespace});h.ensureDirs();const v=zo(h);let b;try{b=await Ki(v,h.config.db.busyTimeoutMs);const{total:E,observed:N}=await uy(b.adapter);console.log(JSON.stringify({ok:!0,dbPath:v,total:E,kinds:N,expectedKinds:[...Nl]}));return}catch(E){if(E instanceof cy){console.error(JSON.stringify({ok:!1,dbPath:v,error:{code:"store_vocabulary_mismatch",message:E.message},observed:E.observed,expectedKinds:E.recognized})),process.exitCode=1;return}throw E}finally{b&&await Zc(b)}}if((n.length===0||n[0]==="--help"||n[0]==="-h")&&(console.log("Special commands (handled before the apigen command table):"),console.log(" install-skill [options] Install the backlog skill for a host (alias: install)"),console.log(" serve [options] Start the long-lived HTTP/MCP server (--transport http|mcp|both)"),console.log(' search "<query>" [flags] Natural-language search — `query --input` with the options as flags'),console.log(" sandbox-path Report the resolved store path (store-free) — see --namespace below"),console.log(" store-check Report the store vocabulary this build expects vs. the kinds present; non-zero on a mismatch"),console.log(""),console.log(" --namespace <value> Global flag, valid before ANY command: selects which"),console.log(' declared store instance to use — "production" (default),'),console.log(' "test" (a persisted, non-ephemeral store), or "sandbox"'),console.log(" (a fresh throwaway store minted per invocation, never"),console.log(" the live production one)."),console.log("")),n[0]==="install-skill"){await Gb(n.slice(1));return}if(n[0]==="install"){await CK(n.slice(1));return}if(n[0]==="serve"){await Wb(n.slice(1),i);return}if(n[0]==="version"){console.log(JSON.stringify(cp()));return}let l;if(n[0]==="search"){const h=Yb(n.slice(1));if(h.kind==="help"){console.log(h.text);return}if(h.kind==="error"){console.error(JSON.stringify({code:"invalid_argument",message:h.message})),process.exitCode=2;return}l=h.argv}let d;const f=async()=>{if(!d){const h=Go({scope:i.scope,adhdRoot:i.adhdRoot,cwd:i.cwd,namespace:i.namespace});h.ensureDirs();const v=await Ki(zo(h),h.config.db.busyTimeoutMs);d={store:v,ctx:{store:v,env:h}}}return d.ctx};let g;const p=()=>(g||(g=Zc(d==null?void 0:d.store)),g),y=by(p);try{const{pkg:h,operations:v}=await up(f,{adhdRoot:i.adhdRoot}),b=l??n,E=Zb(v),N=qK(Mg,v,h.id);await ol(GS)({packages:[h],operations:v,outputDir:"",options:{argv:Xb(b,E,N),usePlugins:[...Mg],exitCode:T=>cb(T)?Co(T):void 0},signal:i.signal??new AbortController().signal,logger:Db()});const j=b.length>1&&b[0]!=="batch"&&(b.includes("--help")||b.includes("-h"));j&&console.log("See also: `adhd-backlog batch action` — run this SAME operation over many items in one call instead of N one-at-a-time invocations (skill/SKILL.md §5)."),j&&b[0]==="query"&&console.log(`Notes:
|
|
582
|
+
- view:"similar" additionally requires filter.anchor (uid of the reference issue) OR filter.semantic (free text) — neither given throws invalid_argument.
|
|
583
|
+
- view:"projects" | "components" | "locations" list the project/component/location registry (optionally scoped by filter.project/filter.component) — see skill/SKILL.md §3a for worked examples.`)}finally{y.dispose(),await p()}}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)===$s.pathToFileURL(J.realpathSync(process.argv[1])).href){const{namespace:t}=hp(process.argv.slice(2)),e=t==="sandbox"?J.mkdtempSync(L.join(mt.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Lg.initTelemetry({service:"backlog",role:"cli",logSink:"file",...e!==void 0?{logDir:e}:{}})}catch(n){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${n instanceof Error?n.message:String(n)}); telemetry records will be silently dropped this process`)}eE().catch(n=>{console.error(n instanceof Error?n.stack??n.message:String(n)),process.exitCode=1})}exports.BACKLOG_ERROR_CODES=ib;exports.BACKLOG_EXIT_CODE=ip;exports.RagNotConfiguredError=ub;exports.SEARCH_FLAGS=Jb;exports.SEARCH_HELP=Qb;exports.backlogEnvironmentSpec=ls;exports.buildBacklogApigenPackage=up;exports.buildBacklogEnv=Go;exports.buildSearchArgv=Yb;exports.claim=Ib;exports.closeGraphBacklogStore=$y;exports.create=kb;exports.delete=Rb;exports.errorEnvelope=pr;exports.exitCodeForEnvelope=Co;exports.get=bb;exports.installSkill=Kb;exports.isBacklogErrorCode=ab;exports.isOutcomeEnvelope=cb;exports.isOutcomeError=vq;exports.isOutcomeOk=wq;exports.lookup=Ob;exports.move=xb;exports.okEnvelope=ap;exports.openCurve=Nb;exports.openGraphBacklogStore=Ki;exports.partOfRollup=_b;exports.prefixCommand=Xb;exports.priorityMatrix=Sb;exports.query=Eb;exports.readBacklogVersionInfo=cp;exports.relate=Pb;exports.resolveBacklogDbPath=zo;exports.resolveBacklogScope=_v;exports.resolveCommandPrefix=Zb;exports.resolveExpectedMcpToolNames=dK;exports.rmLocation=Lb;exports.runBacklogCli=eE;exports.runInstallSkillCommand=Gb;exports.runServeCommand=Wb;exports.startBacklogServer=Fb;exports.stripNamespaceFlag=hp;exports.suggestClaimantIdentity=SP;exports.transition=Ab;exports.update=jb;exports.upsertComponent=Cb;exports.upsertLocation=Mb;exports.upsertProject=Tb;
|