@adhd/backlog 0.1.1 → 0.1.2

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/index.js CHANGED
@@ -1,191 +1,216 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Lp=Object.create;var da=Object.defineProperty;var Up=Object.getOwnPropertyDescriptor;var Bp=Object.getOwnPropertyNames;var Fp=Object.getPrototypeOf,Vp=Object.prototype.hasOwnProperty;var qp=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Bp(t))!Vp.call(e,o)&&o!==n&&da(e,o,{get:()=>t[o],enumerable:!(r=Up(t,o))||r.enumerable});return e};var Kp=(e,t,n)=>(n=e!=null?Lp(Fp(e)):{},qp(t||!e||!e.__esModule?da(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("node:fs"),wr=require("node:url"),pa=require("ts-morph"),q=require("node:path"),St=require("ts-json-schema-generator"),Pe=require("pino"),br=require("ajv"),Sr=require("ajv-formats"),zp=require("better-sqlite3"),Gp=require("@adhd/sox-graph-store"),Qt=require("node:os"),Cu=require("node:crypto"),Hp=require("fastify"),ha=require("node:http"),Jp=require("@modelcontextprotocol/sdk/server/index.js"),Wp=require("@modelcontextprotocol/sdk/server/stdio.js"),Qp=require("@modelcontextprotocol/sdk/server/sse.js"),Yp=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),ma=require("@modelcontextprotocol/sdk/types.js"),ga=require("yaml");var Te=typeof document<"u"?document.currentScript:null;function Zp(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 $o=Zp(q),vo="$apigen";let ya=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Xp(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new ya(`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 ya("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 $s="x-apigen-logical",vs="x-apigen-codec",wo="x-apigen-ctor",bo="x-apigen-tojson",eh="0.1.0";function $a(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=Ru(e,s,t);return Dt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Gr(e,t,n);const a=t.items;if(!a)return e.map(u=>Et(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Et(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 Gr(e,t,n);const a=t.properties;if(!a)return Et(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?Gr(e,t,n):Et(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=Ru(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?th(e,n):e}function Ru(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 Gr(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{[vo]:r,v:s}}catch{}}return Et(e)}function th(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&vo in e){const n=e,r=n[vo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Et(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Et);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Et(r));return t}return null}function nh(e){return{encode(t,n,r){const o=$a(e,r);return Dt(t,n,o)},decode(t,n,r){const o=$a(e,r);return Lt(t,n,o)}}}const ws={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)}},bs={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)}},Ss={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}},Es={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"))}},rh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ns={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"&&!rh.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},So="NaN",Eo="Infinity",No="-Infinity",oh=new Set([So,Eo,No]),Os={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)?So:e===1/0?Eo:e===-1/0?No:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===So)return NaN;if(e===Eo)return 1/0;if(e===No)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 ${[...oh].join(", ")}.`);return NaN}},sh=[ws,bs,Ss,Es,Ns,Os];function ih(e,t={}){for(const n of sh)e.register(n,{override:t.override??!1})}ws.id,bs.id,Ss.id,Es.id,Ns.id,Os.id;const Mu=Xp();ih(Mu);const Du=nh(Mu.freeze());function Lu(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Oo(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 ah(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 ch(e,t){return t===void 0||e===void 0?e:Du.decode(e,t)}function Hr(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Du.encode(e,n)}async function uh(e,t,n,r,o,s){const i=Oo(n).map(c=>ch(s[c],ah(n,c)));if(Lu(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Hr(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Hr(u,n)}const a=await e[r](...i);return Hr(a,n)}let Uu=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 lh(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=()=>uh(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const fh={"decimal.js":"Decimal"};function dh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(fh).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${dh(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ph(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}}},Pe(s);const i=n?Pe.destination({dest:e.destination,mkdir:!0,sync:!0}):Pe.destination(2);return Pe(s,i)}function Bu(e){return e?e.type==="array"?`${Bu(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function hh(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:Bu(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let mh=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 Er=new br({allErrors:!0});Sr(Er);for(const e of[$s,vs,wo,bo,"discriminator"])Er.addKeyword({keyword:e,valid:!0});Er.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function gh(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function yh(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=Er.compile(o.input);if(!i(s)){const a=i.errors??[];throw new mh("invalid_argument",`Validation failed: ${gh(a)}`,a)}return n()}}function $h(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let dt=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function Jr(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 Fu(e,t){const n=e[vs];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function vh(e,t,n){const r=Fu(t,n);return r?r.encode(e,t,n):e}function wh(e,t,n){const r=Fu(t,n);return r?r.decode(e,t,n):e}function bh(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[$s]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Jr(r)!==void 0},encode(r,o,s){const i=Jr(o);if(!i)throw new dt("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 dt("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 dt("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 vh(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 dt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Jr(o);if(!a)throw new dt("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 dt("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 dt("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 wh(r,h,{...s,path:`${s.path}[${f}]`})}}}const Sh="x-apigen-instances";let Tn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function va(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Eh(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function wa(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function Nh(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function Oh(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[$s]==="nominal"?!0:o[vs]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Tn("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=va(s),c=typeof s[bo]=="string"?s[bo]:"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[g,$]of Object.entries(d))m[g]=wa($,a[g],{...i,path:`${i.path}/${g}`});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]=wa(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 Tn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of Eh(s))if(!(l in a))throw new Tn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Sh]===!1)throw new Tn("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=va(s),u={};for(const[l,f]of Object.entries(a))u[l]=Nh(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[wo]=="string"?s[wo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const _h=[ws,bs,Ss,Es,Ns,Os],Ah={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},ba=Oh({id:"ts.NominalSentinel",schema:Ah}),kh={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Sa=bh({id:"ts.UnionSentinel",schema:kh});function jh(){const e=[..._h.map(t=>[t.id,t]),[ba.id,ba],[Sa.id,Sa]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:eh,codecs:jh()});const Ea=new Set(["string","number","boolean","integer"]);function Ih(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"?Ea.has(n):Array.isArray(n)?n.every(r=>Ea.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function xh(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(Ih)}const Ph={"decimal.js":"Decimal"};function Th(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ph).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Th(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Na(e){return e.words.join("-")}function Oa(e){return e.words.map(Lh).join("")}function _a(e){return e.words.join("_")}function Ch(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||xh(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=>Na(h)).join("/"),c=o.map(h=>_a(h)).join("_"),u=o.map(h=>_a(h)).slice(0,-1).join("."),l=Oa(o[o.length-2]??o[0]),f=Oa(o[o.length-1]),p=o.map(h=>Na(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Rh(e,t){return`x-${e}-${t}`}function Mh(e,t){return`--${e}-${t}`}function Dh(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Lh(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Vu(e){return e.anyOf??e.oneOf}function Uh(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Vu(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 Bh(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Vu(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Fh(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Vh(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 Aa(e){return typeof e.handler=="function"}function qh(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=Rh(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:Mh(i,s),envVar:Dh(i,s)})}return o}function Kh(e,t){const n=new Map,{props:r}=Vh(e);for(const[o,s]of Object.entries(r)){let i="string";Bh(s)?i="boolean":Uh(s)&&(i="json"),n.set(Fh(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 qu(e){const{op:t,schema:n,transport:r,projection:o}=e,s=Ch(t,o),i=n?qh(n):[],a=n?Kh(n,i):new Map,c=n?hh(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:Aa(t)};if(Aa(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function zh(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Gh(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Hh(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Wr(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(Hh(s))}return r.push(yh(e)),lh(r)}function Jh(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const Wh={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function ka(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Uu};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:Jh(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:Wh}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const Qh={"decimal.js":"Decimal"};function Yh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Qh).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Yh(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Zh(e,t){return`--${e}-${t}`}function Xh(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function _o(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const em=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],ja={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let fr=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 Ia(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&em.includes(e.code)&&typeof e.toJSON=="function"}function Ku(e){return e.anyOf??e.oneOf}function tm(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:Zh(i,s),envVar:Xh(i,s)})}return o}function Ao(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Ku(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 nm(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Ku(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function xa(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 rm(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function om(e){const t=_s(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return t.length>0?t.toLowerCase():"branch"}function Qr(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=rm(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:om(a),props:f,required:p})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function _s(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function sm(e,t){if(!$o.isAbsolute(t))return t;const n=$o.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const im=["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 zu(e,t,n){for(const r of t){const o=r.flag.replace(/^--/,"");e.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!t.some(r=>r.field==="session")&&e.push(" .option('--session <key>', 'Session key')")}function Gu(e,t,n,r){var o;for(const s of t){const i=_s(s),a=nm(n[s]),c=r.includes(s);a?(e.push(` .option('--${i}')`),((o=n[s])==null?void 0:o.default)===!0&&e.push(` .option('--no-${i}')`)):c?e.push(` .requiredOption('--${i} <${i}>')`):e.push(` .option('--${i} <${i}>')`)}}function Hu(e,t,n){return`${e}:${t}::${n}`}function Ju(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,paramNames:a,schemaProps:c,literalDomainArgs:u}=t,l=t.dispatchSchemaKey??`${r}:${o}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const f=Object.entries(u??{}).map(([h,d])=>`'${h}': ${d}`),p=a.map(h=>Ao(c[h])?`'${h}': __apigenParseJsonArg('${_s(h)}', opts['${h}'])`:`'${h}': opts['${h}']`);if(e.push(` const domainArgs: Record<string, unknown> = { ${[...f,...p].join(", ")} }`),s.length>0){const h=s.map(d=>{const m=d.flag.replace(/^--/,"").replace(/-([a-z])/g,(g,$)=>$.toUpperCase());return`'${d.field}': opts['${m}'] ?? process.env['${d.envVar}']`});e.push(` const envelope: Record<string, unknown> = { ${h.join(", ")} }`)}else i?e.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):e.push(" const envelope: Record<string, unknown> = {}");e.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),e.push(" console.log(JSON.stringify(result))"),e.push(" })")}function am(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,rootUnion:a}=t,c=_o(`${r}_${o}_cmd`);e.push(`const ${c} = program.command('${o}')`);for(const u of a.branches){const l=Object.keys(u.props).filter(p=>p!==a.discriminatorProperty),f=u.required.filter(p=>p!==a.discriminatorProperty);e.push(`${c}`),e.push(` .command('${u.commandName}')`),zu(e,s,i),Gu(e,l,u.props,f),Ju(e,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Hu(r,o,u.commandName),bindings:s,needsSession:i,paramNames:l,schemaProps:u.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(u.value)}})}}function cm(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(i=>Object.values(i.schemas).some(a=>{const c=Qr(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(f=>f!==c.discriminatorProperty).some(f=>Ao(l.props[f])));const{props:u}=xa(a);return Oo(a).some(l=>Ao(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 e.packages){const a=_o(i.id),c=sm(e.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(im),o.push(""));const s=Object.fromEntries(e.packages.flatMap(i=>Object.entries(i.schemas).map(([a,c])=>[`${i.id}:${a}`,c])));for(const i of e.packages)for(const[a,c]of Object.entries(i.schemas)){const u=Qr(c);if(u)for(const l of u.branches){const f=Hu(i.id,a,l.commandName);s[f]={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('${t}').version('${n}')`),o.push("");for(const i of e.packages){const a=_o(i.id);for(const[c,u]of Object.entries(i.schemas)){const l=Lu(u,"session"),f=tm(u),p=Qr(u);if(p){am(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,rootUnion:p});continue}const h=Oo(u),{props:d,required:m}=xa(u);o.push("program"),o.push(` .command('${c}')`),zu(o,f,l),Gu(o,h,d,m),Ju(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,paramNames:h,schemaProps:d})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
- `)}]}}function um(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function lm(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?um(t):process.argv.slice(2)}function fm(e,t){return{id:e,host:"ts",namespace:{raw:e,words:[e]},path:[],kind:"action",async:!1,streaming:!1,safe:t["x-apigen-safe"]??!1,input:t.input??{},output:t.output??{},envelope:{},typeText:null}}function dm(e){const t=new Map;for(const r of e.operations??[]){const o=r.path[r.path.length-1];o&&t.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of e.packages)for(const[o,s]of Object.entries(r.schemas)){const i=t.get(`${r.id}:${o}`)??fm(o,s),a=qu({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 pm(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=t.get(e.slice(0,r).join(" "));if(o)return{entry:o,rest:e.slice(r)}}return null}function Wu(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function Pa(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const s=Wu(o.params);t.push(` ${r}${s?` { ${s} }`:""}`)}return t.join(`
5
- `)}function Cn(e){return new fr("invalid_argument",e)}function hm(e,t){var n;const r={},o={};let s=0;for(;s<e.length;){const i=e[s];if(!i.startsWith("--"))throw Cn(`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,f=a;a.startsWith("no-")&&((n=t.get(a.slice(3)))==null?void 0:n.valueKind)==="boolean"&&(l=!0,f=a.slice(3));const p=t.get(f);if(!p)throw Cn(`Unknown option: --${a}. Available: ${[...t.keys()].sort().map(d=>`--${d}`).join(", ")}`);s++;let h;if(p.valueKind==="boolean")l?h=!1:c===void 0?h=!0:h=c!=="false";else{const d=c!==void 0?c:e[s++];if(d===void 0)throw Cn(`Missing value for --${a}`);if(p.valueKind==="json")try{h=JSON.parse(d)}catch(m){throw Cn(`Invalid JSON for --${a}: ${m.message}`)}else h=d}p.kind==="domain"?r[p.camelKey]=h:o[p.camelKey]=h}for(const i of t.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 Qu(e){const t=Ia(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=Ia(e)?ja[e.code]:ja.internal}class mm{constructor(t){this.signal=t,this.routes=new Map}registerRoute(t,n){this.routes.set(t.cli.path.join(" "),{plan:t,dispatch:n})}routeTable(){return this.routes}readCall(t,n){const{domainArgs:r,envelope:o}=hm(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){if($h(n))throw new fr("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))}writeError(t,n,r){Qu(n)}}function gm(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("cli")||i.push(f)}return i}async function ym(e){var t,n,r;const o=e.logger??ph();if((t=e.signal)!=null&&t.aborted){o.info("cli run: signal already aborted before dispatch — skipping");return}let s=lm(e.options);s[0]==="--"&&(s=s.slice(1));const i=zh(e.options),a=Gh(e.options),c=new mm(e.signal),u=dm(e),l=new Map;for(const L of u.values()){const V=l.get(L.pkgId);V?V.push(L):l.set(L.pkgId,[L])}const f={},p={};for(const L of e.packages){const V=l.get(L.id);if(!V||V.length===0)continue;if(!L.fns)throw new Error(`apigen-plugin-cli-output: package "${L.id}" has no functions`);const H=L.fns,Q={},ee={};for(const ue of V)Q[ue.plan.op.id]=ue.schema,ee[ue.plan.op.id]=H[ue.fnName],f[ue.plan.op.id]=ue.schema,p[ue.plan.op.id]=H[ue.fnName];const oe=Wr(Q,i),Oe={fns:ee,createClient:L.createClient,schemas:Q};for(const ue of V)c.registerRoute(ue.plan,tt=>ka(ue.plan,oe,tt,Oe))}const h=((n=e.packages[0])==null?void 0:n.id)??"ts",d=Wr(f,i),m={invoke:(L,V,H)=>d(L,{operation:{id:L},ctx:new Uu,domainArgs:V.domainArgs,envelope:V.envelope,signal:V.signal},H),invokeOptions:{fns:p,schemas:f,createClient:(r=e.packages[0])==null?void 0:r.createClient}},g=gm(i,a,h,e.operations??[],m);if(g.length>0){const L=Wr({},i),V={fns:{},schemas:{}};for(const H of g){const Q=qu({op:H,transport:"cli"});c.registerRoute(Q,ee=>ka(Q,L,ee,V))}}const $=c.routeTable();if(s.length===0||s[0]==="--help"||s[0]==="-h"){console.log(Pa($));return}const v=pm(s,$);if(!v){Qu(new fr("not_found",`Unknown command: ${s.join(" ")}
2
+ "use strict";var $h=Object.create;var ja=Object.defineProperty;var vh=Object.getOwnPropertyDescriptor;var wh=Object.getOwnPropertyNames;var bh=Object.getPrototypeOf,Eh=Object.prototype.hasOwnProperty;var Sh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wh(t))!Eh.call(e,o)&&o!==n&&ja(e,o,{get:()=>t[o],enumerable:!(r=vh(t,o))||r.enumerable});return e};var Nh=(e,t,n)=>(n=e!=null?$h(bh(e)):{},Sh(t||!e||!e.__esModule?ja(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("node:fs"),vr=require("node:url"),Ia=require("ts-morph"),T=require("node:path"),$t=require("ts-json-schema-generator"),_e=require("pino"),wr=require("ajv"),br=require("ajv-formats"),Oh=require("better-sqlite3"),_h=require("@adhd/sox-graph-store"),We=require("node:os"),Wu=require("node:crypto"),kh=require("fastify"),Pa=require("node:http"),Ah=require("@modelcontextprotocol/sdk/server/index.js"),jh=require("@modelcontextprotocol/sdk/server/stdio.js"),Ih=require("@modelcontextprotocol/sdk/server/sse.js"),Ph=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),xa=require("@modelcontextprotocol/sdk/types.js"),Ta=require("yaml");var ke=typeof document<"u"?document.currentScript:null;function xh(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 jo=xh(T),Io="$apigen";let Ca=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Th(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Ca(`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 Ca("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 js="x-apigen-logical",Is="x-apigen-codec",Po="x-apigen-ctor",xo="x-apigen-tojson",Ch="0.1.0";function Ra(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 Tt(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 Tt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ju(e,s,t);return Tt(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=>vt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?vt(u):Tt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Tt(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 vt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Tt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?ro(e,t,n):vt(e)}function Ct(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 Ct(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ju(e,s,t);return Ct(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:Ct(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ct(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]=Ct(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Rh(e,n):e}function Ju(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{[Io]:r,v:s}}catch{}}return vt(e)}function Rh(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Io in e){const n=e,r=n[Io],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function vt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(vt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=vt(r));return t}return null}function Mh(e){return{encode(t,n,r){const o=Ra(e,r);return Tt(t,n,o)},decode(t,n,r){const o=Ra(e,r);return Ct(t,n,o)}}}const Ps={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)}},xs={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)}},Ts={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}},Cs={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"))}},Dh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Rs={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"&&!Dh.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},To="NaN",Co="Infinity",Ro="-Infinity",Lh=new Set([To,Co,Ro]),Ms={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)?To:e===1/0?Co:e===-1/0?Ro:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===To)return NaN;if(e===Co)return 1/0;if(e===Ro)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 ${[...Lh].join(", ")}.`);return NaN}},Bh=[Ps,xs,Ts,Cs,Rs,Ms];function Uh(e,t={}){for(const n of Bh)e.register(n,{override:t.override??!1})}Ps.id,xs.id,Ts.id,Cs.id,Rs.id,Ms.id;const Hu=Th();Uh(Hu);const Yu=Mh(Hu.freeze());function Qu(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Mo(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 Fh(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 Vh(e,t){return t===void 0||e===void 0?e:Yu.decode(e,t)}function oo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Yu.encode(e,n)}async function qh(e,t,n,r,o,s){const i=Mo(n).map(c=>Vh(s[c],Fh(n,c)));if(Qu(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return oo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return oo(u,n)}const a=await e[r](...i);return oo(a,n)}let Zu=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 Kh(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=()=>qh(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const Gh={"decimal.js":"Decimal"};function zh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Gh).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${zh(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Wh(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}}},_e(s);const i=n?_e.destination({dest:e.destination,mkdir:!0,sync:!0}):_e.destination(2);return _e(s,i)}function Xu(e){return e?e.type==="array"?`${Xu(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Jh(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:Xu(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let Hh=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 Er=new wr({allErrors:!0});br(Er);for(const e of[js,Is,Po,xo,"discriminator"])Er.addKeyword({keyword:e,valid:!0});Er.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Yh(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Qh(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=Er.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Hh("invalid_argument",`Validation failed: ${Yh(a)}`,a)}return n()}}function Zh(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let ct=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function so(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 el(e,t){const n=e[Is];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Xh(e,t,n){const r=el(t,n);return r?r.encode(e,t,n):e}function em(e,t,n){const r=el(t,n);return r?r.decode(e,t,n):e}function tm(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[js]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:so(r)!==void 0},encode(r,o,s){const i=so(o);if(!i)throw new ct("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 ct("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 ct("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 Xh(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 ct("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=so(o);if(!a)throw new ct("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 ct("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 ct("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 em(r,h,{...s,path:`${s.path}[${f}]`})}}}const nm="x-apigen-instances";let xn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Ma(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function rm(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Da(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function om(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function sm(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[js]==="nominal"?!0:o[Is]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new xn("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Ma(s),c=typeof s[xo]=="string"?s[xo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const g={};for(const[y,$]of Object.entries(d))g[y]=Da($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=Da(g,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 xn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of rm(s))if(!(l in a))throw new xn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[nm]===!1)throw new xn("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Ma(s),u={};for(const[l,f]of Object.entries(a))u[l]=om(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Po]=="string"?s[Po]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const im=[Ps,xs,Ts,Cs,Rs,Ms],am={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},La=sm({id:"ts.NominalSentinel",schema:am}),cm={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Ba=tm({id:"ts.UnionSentinel",schema:cm});function um(){const e=[...im.map(t=>[t.id,t]),[La.id,La],[Ba.id,Ba]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Ch,codecs:um()});const Ua=new Set(["string","number","boolean","integer"]);function lm(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"?Ua.has(n):Array.isArray(n)?n.every(r=>Ua.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function fm(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(lm)}const dm={"decimal.js":"Decimal"};function pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(dm).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${pm(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Fa(e){return e.words.join("-")}function Va(e){return e.words.map($m).join("")}function qa(e){return e.words.join("_")}function hm(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||fm(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=>Fa(h)).join("/"),c=o.map(h=>qa(h)).join("_"),u=o.map(h=>qa(h)).slice(0,-1).join("."),l=Va(o[o.length-2]??o[0]),f=Va(o[o.length-1]),p=o.map(h=>Fa(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function mm(e,t){return`x-${e}-${t}`}function gm(e,t){return`--${e}-${t}`}function ym(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function $m(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function tl(e){return e.anyOf??e.oneOf}function vm(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=tl(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 wm(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=tl(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function bm(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Em(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 Ka(e){return typeof e.handler=="function"}function Sm(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=mm(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:gm(i,s),envVar:ym(i,s)})}return o}function Nm(e,t){const n=new Map,{props:r}=Em(e);for(const[o,s]of Object.entries(r)){let i="string";wm(s)?i="boolean":vm(s)&&(i="json"),n.set(bm(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 nl(e){const{op:t,schema:n,transport:r,projection:o}=e,s=hm(t,o),i=n?Sm(n):[],a=n?Nm(n,i):new Map,c=n?Jh(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:Ka(t)};if(Ka(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function Om(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function _m(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function km(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function io(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(km(s))}return r.push(Qh(e)),Kh(r)}function Am(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const jm={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Ga(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Zu};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:Am(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:jm}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const Im={"decimal.js":"Decimal"};function Pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Im).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Pm(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function xm(e,t){return`--${e}-${t}`}function Tm(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Do(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const Cm=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],za={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let ur=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 Wa(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&Cm.includes(e.code)&&typeof e.toJSON=="function"}function rl(e){return e.anyOf??e.oneOf}function Rm(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:xm(i,s),envVar:Tm(i,s)})}return o}function Lo(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=rl(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 Mm(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=rl(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Ja(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 Dm(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function Lm(e){const t=Ds(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return t.length>0?t.toLowerCase():"branch"}function ao(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=Dm(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:Lm(a),props:f,required:p})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function Ds(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Bm(e,t){if(!jo.isAbsolute(t))return t;const n=jo.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Um=["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 ol(e,t,n){for(const r of t){const o=r.flag.replace(/^--/,"");e.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!t.some(r=>r.field==="session")&&e.push(" .option('--session <key>', 'Session key')")}function sl(e,t,n,r){var o;for(const s of t){const i=Ds(s),a=Mm(n[s]),c=r.includes(s);a?(e.push(` .option('--${i}')`),((o=n[s])==null?void 0:o.default)===!0&&e.push(` .option('--no-${i}')`)):c?e.push(` .requiredOption('--${i} <${i}>')`):e.push(` .option('--${i} <${i}>')`)}}function il(e,t,n){return`${e}:${t}::${n}`}function al(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,paramNames:a,schemaProps:c,literalDomainArgs:u}=t,l=t.dispatchSchemaKey??`${r}:${o}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const f=Object.entries(u??{}).map(([h,d])=>`'${h}': ${d}`),p=a.map(h=>Lo(c[h])?`'${h}': __apigenParseJsonArg('${Ds(h)}', opts['${h}'])`:`'${h}': opts['${h}']`);if(e.push(` const domainArgs: Record<string, unknown> = { ${[...f,...p].join(", ")} }`),s.length>0){const h=s.map(d=>{const g=d.flag.replace(/^--/,"").replace(/-([a-z])/g,(y,$)=>$.toUpperCase());return`'${d.field}': opts['${g}'] ?? process.env['${d.envVar}']`});e.push(` const envelope: Record<string, unknown> = { ${h.join(", ")} }`)}else i?e.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):e.push(" const envelope: Record<string, unknown> = {}");e.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),e.push(" console.log(JSON.stringify(result))"),e.push(" })")}function Fm(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,rootUnion:a}=t,c=Do(`${r}_${o}_cmd`);e.push(`const ${c} = program.command('${o}')`);for(const u of a.branches){const l=Object.keys(u.props).filter(p=>p!==a.discriminatorProperty),f=u.required.filter(p=>p!==a.discriminatorProperty);e.push(`${c}`),e.push(` .command('${u.commandName}')`),ol(e,s,i),sl(e,l,u.props,f),al(e,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:il(r,o,u.commandName),bindings:s,needsSession:i,paramNames:l,schemaProps:u.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(u.value)}})}}function Vm(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(i=>Object.values(i.schemas).some(a=>{const c=ao(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(f=>f!==c.discriminatorProperty).some(f=>Lo(l.props[f])));const{props:u}=Ja(a);return Mo(a).some(l=>Lo(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 e.packages){const a=Do(i.id),c=Bm(e.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(Um),o.push(""));const s=Object.fromEntries(e.packages.flatMap(i=>Object.entries(i.schemas).map(([a,c])=>[`${i.id}:${a}`,c])));for(const i of e.packages)for(const[a,c]of Object.entries(i.schemas)){const u=ao(c);if(u)for(const l of u.branches){const f=il(i.id,a,l.commandName);s[f]={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('${t}').version('${n}')`),o.push("");for(const i of e.packages){const a=Do(i.id);for(const[c,u]of Object.entries(i.schemas)){const l=Qu(u,"session"),f=Rm(u),p=ao(u);if(p){Fm(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,rootUnion:p});continue}const h=Mo(u),{props:d,required:g}=Ja(u);o.push("program"),o.push(` .command('${c}')`),ol(o,f,l),sl(o,h,d,g),al(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,paramNames:h,schemaProps:d})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
+ `)}]}}function qm(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function Km(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?qm(t):process.argv.slice(2)}function Gm(e,t){return{id:e,host:"ts",namespace:{raw:e,words:[e]},path:[],kind:"action",async:!1,streaming:!1,safe:t["x-apigen-safe"]??!1,input:t.input??{},output:t.output??{},envelope:{},typeText:null}}function zm(e){const t=new Map;for(const r of e.operations??[]){const o=r.path[r.path.length-1];o&&t.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of e.packages)for(const[o,s]of Object.entries(r.schemas)){const i=t.get(`${r.id}:${o}`)??Gm(o,s),a=nl({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 Wm(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=t.get(e.slice(0,r).join(" "));if(o)return{entry:o,rest:e.slice(r)}}return null}function cl(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function Ha(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const s=cl(o.params);t.push(` ${r}${s?` { ${s} }`:""}`)}return t.join(`
5
+ `)}function Tn(e){return new ur("invalid_argument",e)}function Jm(e,t){var n;const r={},o={};let s=0;for(;s<e.length;){const i=e[s];if(!i.startsWith("--"))throw Tn(`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,f=a;a.startsWith("no-")&&((n=t.get(a.slice(3)))==null?void 0:n.valueKind)==="boolean"&&(l=!0,f=a.slice(3));const p=t.get(f);if(!p)throw Tn(`Unknown option: --${a}. Available: ${[...t.keys()].sort().map(d=>`--${d}`).join(", ")}`);s++;let h;if(p.valueKind==="boolean")l?h=!1:c===void 0?h=!0:h=c!=="false";else{const d=c!==void 0?c:e[s++];if(d===void 0)throw Tn(`Missing value for --${a}`);if(p.valueKind==="json")try{h=JSON.parse(d)}catch(g){throw Tn(`Invalid JSON for --${a}: ${g.message}`)}else h=d}p.kind==="domain"?r[p.camelKey]=h:o[p.camelKey]=h}for(const i of t.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 ul(e){const t=Wa(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=Wa(e)?za[e.code]:za.internal}let Hm=class{constructor(t){this.signal=t,this.routes=new Map}registerRoute(t,n){this.routes.set(t.cli.path.join(" "),{plan:t,dispatch:n})}routeTable(){return this.routes}readCall(t,n){const{domainArgs:r,envelope:o}=Jm(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){if(Zh(n))throw new ur("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))}writeError(t,n,r){ul(n)}};function Ym(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("cli")||i.push(f)}return i}async function Qm(e){var t,n,r;const o=e.logger??Wh();if((t=e.signal)!=null&&t.aborted){o.info("cli run: signal already aborted before dispatch — skipping");return}let s=Km(e.options);s[0]==="--"&&(s=s.slice(1));const i=Om(e.options),a=_m(e.options),c=new Hm(e.signal),u=zm(e),l=new Map;for(const B of u.values()){const q=l.get(B.pkgId);q?q.push(B):l.set(B.pkgId,[B])}const f={},p={};for(const B of e.packages){const q=l.get(B.id);if(!q||q.length===0)continue;if(!B.fns)throw new Error(`apigen-plugin-cli-output: package "${B.id}" has no functions`);const Z=B.fns,Q={},ve={};for(const fe of q)Q[fe.plan.op.id]=fe.schema,ve[fe.plan.op.id]=Z[fe.fnName],f[fe.plan.op.id]=fe.schema,p[fe.plan.op.id]=Z[fe.fnName];const Ne=io(Q,i),Ue={fns:ve,createClient:B.createClient,schemas:Q};for(const fe of q)c.registerRoute(fe.plan,tn=>Ga(fe.plan,Ne,tn,Ue))}const h=((n=e.packages[0])==null?void 0:n.id)??"ts",d=io(f,i),g={invoke:(B,q,Z)=>d(B,{operation:{id:B},ctx:new Zu,domainArgs:q.domainArgs,envelope:q.envelope,signal:q.signal},Z),invokeOptions:{fns:p,schemas:f,createClient:(r=e.packages[0])==null?void 0:r.createClient}},y=Ym(i,a,h,e.operations??[],g);if(y.length>0){const B=io({},i),q={fns:{},schemas:{}};for(const Z of y){const Q=nl({op:Z,transport:"cli"});c.registerRoute(Q,ve=>Ga(Q,B,ve,q))}}const $=c.routeTable();if(s.length===0||s[0]==="--help"||s[0]==="-h"){console.log(Ha($));return}const v=Wm(s,$);if(!v){ul(new ur("not_found",`Unknown command: ${s.join(" ")}
6
6
 
7
- ${Pa($)}`));return}const{entry:w,rest:S}=v,{plan:N,dispatch:I}=w,T=N.cli.path.join(" ");if(S.includes("--help")||S.includes("-h")){const L=Wu(N.params);console.log(`${T}${L?` { ${L} }`:""}`);return}const K={rest:S};try{if(N.streaming)throw new fr("invalid_argument",`Command "${T}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const L=await c.readCall(K,N),V=Date.now(),H=await I(L);await c.writeResult(K,H,N),o.info({command:T,ms:Date.now()-V},`→ ${T}`)}catch(L){o.error({command:T,err:L},`✗ ${T}`),await c.writeError(K,L,N)}}const $m={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 cm(e)},run(e){return ym(e)}},Ta=new Set(["string","number","boolean","integer"]);function vm(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"?Ta.has(n):Array.isArray(n)?n.every(r=>Ta.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function wm(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(vm)}const bm={"decimal.js":"Decimal"};function Sm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(bm).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Sm(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ca(e){return e.words.join("-")}function Ra(e){return e.words.map(Nm).join("")}function Ma(e){return e.words.join("_")}function Em(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||wm(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=>Ca(h)).join("/"),c=o.map(h=>Ma(h)).join("_"),u=o.map(h=>Ma(h)).slice(0,-1).join("."),l=Ra(o[o.length-2]??o[0]),f=Ra(o[o.length-1]),p=o.map(h=>Ca(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Nm(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function As(e,t=5e3){e!==":memory:"&&Y.mkdirSync(q.dirname(e),{recursive:!0});const n=new zp(e);if(n.pragma("journal_mode = WAL"),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const r=Gp.createGraphBackend(n);return r.applySchema(),n.pragma(`busy_timeout = ${t}`),{db:n,graph:r}}function ks(e){e.db.close()}const Om=[".git",".adhd","adhd.environment.yaml"];function Yr(e){let t=q.resolve(e);const{root:n}=q.parse(t);for(;;){for(const o of Om)if(Y.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=q.dirname(t);if(r===t)return;t=r}}const _m=new Set(["system","global","project"]);function Am(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:Yr(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&_m.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:Yr(n)??n}:{scope:s}}const o=Yr(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function Da(e){return`.${e}`}function km(e){const t=Qt.homedir();if(process.platform==="darwin")return q.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??q.join(t,"AppData","Roaming");return q.join(r,e)}const n=process.env.XDG_DATA_HOME??q.join(t,".local","share");return q.join(n,e)}function jm(e){const t=e.orgNamespace,n=e.adhdRoot??q.join(Qt.homedir(),Da(t)),r=e.adhdRoot??km(t),o={system:q.join(r,e.project,e.namespace),global:q.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=q.join(e.projectRoot,Da(t),e.project,e.namespace)),o}function Yu(e,t){return t==="project"?e.project??e.global:e[t]}function Im(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function xm(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 ce={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},j={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"},Yn="tag:yaml.org,2002:",it={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function La(e){const t=[0];let n=e.indexOf(`
7
+ ${Ha($)}`));return}const{entry:b,rest:S}=v,{plan:O,dispatch:j}=b,C=O.cli.path.join(" ");if(S.includes("--help")||S.includes("-h")){const B=cl(O.params);console.log(`${C}${B?` { ${B} }`:""}`);return}const W={rest:S};try{if(O.streaming)throw new ur("invalid_argument",`Command "${C}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const B=await c.readCall(W,O),q=Date.now(),Z=await j(B);await c.writeResult(W,Z,O),o.info({command:C,ms:Date.now()-q},`→ ${C}`)}catch(B){o.error({command:C,err:B},`✗ ${C}`),await c.writeError(W,B,O)}}const Zm={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 Vm(e)},run(e){return Qm(e)}},Ya=new Set(["string","number","boolean","integer"]);function Xm(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"?Ya.has(n):Array.isArray(n)?n.every(r=>Ya.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function eg(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Xm)}const tg={"decimal.js":"Decimal"};function ng(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(tg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ng(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Qa(e){return e.words.join("-")}function Za(e){return e.words.map(og).join("")}function Xa(e){return e.words.join("_")}function rg(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||eg(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=>Qa(h)).join("/"),c=o.map(h=>Xa(h)).join("_"),u=o.map(h=>Xa(h)).slice(0,-1).join("."),l=Za(o[o.length-2]??o[0]),f=Za(o[o.length-1]),p=o.map(h=>Qa(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function og(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ls(e,t=5e3){e!==":memory:"&&U.mkdirSync(T.dirname(e),{recursive:!0});const n=new Oh(e);if(n.pragma("journal_mode = WAL"),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const r=_h.createGraphBackend(n);return r.applySchema(),n.pragma(`busy_timeout = ${t}`),{db:n,graph:r}}function Bs(e){e.db.close()}const sg=[".git",".adhd","adhd.environment.yaml"];function co(e){let t=T.resolve(e);const{root:n}=T.parse(t);for(;;){for(const o of sg)if(U.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=T.dirname(t);if(r===t)return;t=r}}const ig=new Set(["system","global","project"]);function ag(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:co(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&ig.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:co(n)??n}:{scope:s}}const o=co(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function ec(e){return`.${e}`}function cg(e){const t=We.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 ug(e){const t=e.orgNamespace,n=e.adhdRoot??T.join(We.homedir(),ec(t)),r=e.adhdRoot??cg(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,ec(t),e.project,e.namespace)),o}function ll(e,t){return t==="project"?e.project??e.global:e[t]}function lg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function fg(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 re={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},k={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"},Hn="tag:yaml.org,2002:",nt={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function tc(e){const t=[0];let n=e.indexOf(`
8
8
  `);for(;n!==-1;)n+=1,t.push(n),n=e.indexOf(`
9
- `,n);return t}function Zu(e){let t,n;return typeof e=="string"?(t=La(e),n=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=La(e.context.src)),t=e.lineStarts,n=e.context.src)),{lineStarts:t,src:n}}function ko(e,t){if(typeof e!="number"||e<0)return null;const{lineStarts:n,src:r}=Zu(t);if(!n||!r||e>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(e<i)return{line:s,col:e-n[s-1]+1};if(e===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:e-n[o-1]+1}}function Pm(e,t){const{lineStarts:n,src:r}=Zu(t);if(!n||!(e>=1)||e>n.length)return null;const o=n[e-1];let s=n[e];for(;s&&s>o&&r[s-1]===`
10
- `;)--s;return r.slice(o,s)}function Tm({start:e,end:t},n,r=80){let o=Pm(e.line,n);if(!o)return null;let{col:s}=e;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="";t&&(t.line===e.line&&s+(t.col-e.col)<=r+1?i=t.col-e.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
11
- ${c}${u}${a}`}let ie=class Xu{static copy(t){return new Xu(t.start,t.end)}constructor(t,n){this.start=t,this.end=n||t}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(t,n){const{start:r,end:o}=this;if(t.length===0||o<=t[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<t.length&&!(t[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<t.length&&!(t[s]>=o);)++s;return this.origEnd=o+s,i}},M=class Je{static addStringTerminator(t,n,r){if(r[r.length-1]===`
12
- `)return r;const o=Je.endOfWhiteSpace(t,n);return o>=t.length||t[o]===`
9
+ `,n);return t}function fl(e){let t,n;return typeof e=="string"?(t=tc(e),n=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=tc(e.context.src)),t=e.lineStarts,n=e.context.src)),{lineStarts:t,src:n}}function Bo(e,t){if(typeof e!="number"||e<0)return null;const{lineStarts:n,src:r}=fl(t);if(!n||!r||e>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(e<i)return{line:s,col:e-n[s-1]+1};if(e===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:e-n[o-1]+1}}function dg(e,t){const{lineStarts:n,src:r}=fl(t);if(!n||!(e>=1)||e>n.length)return null;const o=n[e-1];let s=n[e];for(;s&&s>o&&r[s-1]===`
10
+ `;)--s;return r.slice(o,s)}function pg({start:e,end:t},n,r=80){let o=dg(e.line,n);if(!o)return null;let{col:s}=e;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="";t&&(t.line===e.line&&s+(t.col-e.col)<=r+1?i=t.col-e.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
11
+ ${c}${u}${a}`}let te=class dl{static copy(t){return new dl(t.start,t.end)}constructor(t,n){this.start=t,this.end=n||t}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(t,n){const{start:r,end:o}=this;if(t.length===0||o<=t[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<t.length&&!(t[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<t.length&&!(t[s]>=o);)++s;return this.origEnd=o+s,i}},I=class Fe{static addStringTerminator(t,n,r){if(r[r.length-1]===`
12
+ `)return r;const o=Fe.endOfWhiteSpace(t,n);return o>=t.length||t[o]===`
13
13
  `?r+`
14
14
  `:r}static atDocumentBoundary(t,n,r){const o=t[n];if(!o)return!0;const s=t[n-1];if(s&&s!==`
15
- `)return!1;if(r){if(o!==r)return!1}else if(o!==ce.DIRECTIVES_END&&o!==ce.DOCUMENT_END)return!1;const i=t[n+1],a=t[n+2];if(i!==o||a!==o)return!1;const c=t[n+3];return!c||c===`
15
+ `)return!1;if(r){if(o!==r)return!1}else if(o!==re.DIRECTIVES_END&&o!==re.DOCUMENT_END)return!1;const i=t[n+1],a=t[n+2];if(i!==o||a!==o)return!1;const c=t[n+3];return!c||c===`
16
16
  `||c===" "||c===" "}static endOfIdentifier(t,n){let r=t[n];const o=r==="<",s=o?[`
17
17
  `," "," ",">"]:[`
18
18
  `," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=t[n+=1];return o&&r===">"&&(n+=1),n}static endOfIndent(t,n){let r=t[n];for(;r===" ";)r=t[n+=1];return n}static endOfLine(t,n){let r=t[n];for(;r&&r!==`
19
19
  `;)r=t[n+=1];return n}static endOfWhiteSpace(t,n){let r=t[n];for(;r===" "||r===" ";)r=t[n+=1];return n}static startOfLine(t,n){let r=t[n-1];if(r===`
20
20
  `)return n;for(;r&&r!==`
21
- `;)r=t[n-=1];return n+1}static endOfBlockIndent(t,n,r){const o=Je.endOfIndent(t,r);if(o>r+n)return o;{const s=Je.endOfWhiteSpace(t,o),i=t[s];if(!i||i===`
21
+ `;)r=t[n-=1];return n+1}static endOfBlockIndent(t,n,r){const o=Fe.endOfIndent(t,r);if(o>r+n)return o;{const s=Fe.endOfWhiteSpace(t,o),i=t[s];if(!i||i===`
22
22
  `)return s}return null}static atBlank(t,n,r){const o=t[n];return o===`
23
23
  `||o===" "||o===" "||r&&!o}static nextNodeIsIndented(t,n,r){return!t||n<0?!1:n>0?!0:r&&t==="-"}static normalizeOffset(t,n){const r=t[n];return r?r!==`
24
24
  `&&t[n-1]===`
25
- `?n-1:Je.endOfWhiteSpace(t,n):n}static foldNewline(t,n,r){let o=0,s=!1,i="",a=t[n+1];for(;a===" "||a===" "||a===`
25
+ `?n-1:Fe.endOfWhiteSpace(t,n):n}static foldNewline(t,n,r){let o=0,s=!1,i="",a=t[n+1];for(;a===" "||a===" "||a===`
26
26
  `;){switch(a){case`
27
27
  `:o=0,n+=1,i+=`
28
- `;break;case" ":o<=r&&(s=!0),n=Je.endOfWhiteSpace(t,n+2)-1;break;case" ":o+=1,n+=1;break}a=t[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(t,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=t,this.value=null}getPropValue(t,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[t];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,ce.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const t=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,ce.COMMENT,!0);r!=null&&t.push(r)}return t.length>0?t.join(`
29
- `):null}commentHasRequiredWhitespace(t){const{src:n}=this.context;if(this.header&&t===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return t!==r||Je.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]===ce.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]!==ce.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[j.FLOW_MAP,j.FLOW_SEQ,j.QUOTE_DOUBLE,j.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const t=ko(this.range.start,this.context.root);if(!t)return;const n=ko(this.range.end,this.context.root);return{start:t,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:t,end:n}=this.valueRange;return this.context.src.slice(t,n)}get tag(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,ce.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:t,end:n}=this.valueRange,{src:r}=this.context;for(let o=t;o<n;++o)if(r[o]===`
30
- `)return!0;return!1}parseComment(t){const{src:n}=this.context;if(n[t]===ce.COMMENT){const r=Je.endOfLine(n,t+1),o=new ie(t,r);return this.props.push(o),r}return t}setOrigRanges(t,n){return this.range&&(n=this.range.setOrigRange(t,n)),this.valueRange&&this.valueRange.setOrigRange(t,n),this.props.forEach(r=>r.setOrigRange(t,n)),n}toString(){const{context:{src:t},range:n,value:r}=this;if(r!=null)return r;const o=t.slice(n.start,n.end);return Je.addStringTerminator(t,n.end,o)}},jt=class extends Error{constructor(t,n,r){if(!r||!(n instanceof M))throw new Error(`Invalid arguments for new ${t}`);super(),this.name=t,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const t=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new ie(this.offset,this.offset+1);const n=t&&ko(this.offset,t);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=t&&Tm(this.linePos,t);o&&(this.message+=`:
28
+ `;break;case" ":o<=r&&(s=!0),n=Fe.endOfWhiteSpace(t,n+2)-1;break;case" ":o+=1,n+=1;break}a=t[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(t,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=t,this.value=null}getPropValue(t,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[t];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,re.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const t=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,re.COMMENT,!0);r!=null&&t.push(r)}return t.length>0?t.join(`
29
+ `):null}commentHasRequiredWhitespace(t){const{src:n}=this.context;if(this.header&&t===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return t!==r||Fe.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]===re.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]!==re.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[k.FLOW_MAP,k.FLOW_SEQ,k.QUOTE_DOUBLE,k.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const t=Bo(this.range.start,this.context.root);if(!t)return;const n=Bo(this.range.end,this.context.root);return{start:t,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:t,end:n}=this.valueRange;return this.context.src.slice(t,n)}get tag(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,re.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:t,end:n}=this.valueRange,{src:r}=this.context;for(let o=t;o<n;++o)if(r[o]===`
30
+ `)return!0;return!1}parseComment(t){const{src:n}=this.context;if(n[t]===re.COMMENT){const r=Fe.endOfLine(n,t+1),o=new te(t,r);return this.props.push(o),r}return t}setOrigRanges(t,n){return this.range&&(n=this.range.setOrigRange(t,n)),this.valueRange&&this.valueRange.setOrigRange(t,n),this.props.forEach(r=>r.setOrigRange(t,n)),n}toString(){const{context:{src:t},range:n,value:r}=this;if(r!=null)return r;const o=t.slice(n.start,n.end);return Fe.addStringTerminator(t,n.end,o)}},Ot=class extends Error{constructor(t,n,r){if(!r||!(n instanceof I))throw new Error(`Invalid arguments for new ${t}`);super(),this.name=t,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const t=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new te(this.offset,this.offset+1);const n=t&&Bo(this.offset,t);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=t&&pg(this.linePos,t);o&&(this.message+=`:
31
31
 
32
32
  ${o}
33
- `)}delete this.source}},Sn=class extends jt{constructor(t,n){super("YAMLReferenceError",t,n)}},z=class extends jt{constructor(t,n){super("YAMLSemanticError",t,n)}},ye=class extends jt{constructor(t,n){super("YAMLSyntaxError",t,n)}},en=class extends jt{constructor(t,n){super("YAMLWarning",t,n)}};function $e(e,t,n){return(t=Rm(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Cm(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Rm(e){var t=Cm(e,"string");return typeof t=="symbol"?t:t+""}let el=class jo extends M{static endOfLine(t,n,r){let o=t[n],s=n;for(;o&&o!==`
33
+ `)}delete this.source}},vn=class extends Ot{constructor(t,n){super("YAMLReferenceError",t,n)}},F=class extends Ot{constructor(t,n){super("YAMLSemanticError",t,n)}},le=class extends Ot{constructor(t,n){super("YAMLSyntaxError",t,n)}},Qt=class extends Ot{constructor(t,n){super("YAMLWarning",t,n)}};function pe(e,t,n){return(t=mg(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hg(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function mg(e){var t=hg(e,"string");return typeof t=="symbol"?t:t+""}let pl=class Uo extends I{static endOfLine(t,n,r){let o=t[n],s=n;for(;o&&o!==`
34
34
  `&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=t[s+1];if(o===":"&&(!i||i===`
35
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:t,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;t<n&&(o===`
36
36
  `||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=t;a<n;++a){const c=r[a];if(c===`
37
- `){const{fold:u,offset:l}=M.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!==`
38
- `&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[t];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new z(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new z(this,a)],str:s}}default:return s}}parseBlockValue(t){const{indent:n,inFlow:r,src:o}=this.context;let s=t,i=t;for(let a=o[s];a===`
39
- `&&!M.atDocumentBoundary(o,s+1);a=o[s]){const c=M.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
40
- `?s=c:(i=jo.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=t),this.valueRange.end=i,i}parse(t,n){this.context=t;const{inFlow:r,src:o}=t;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
41
- `&&(s=jo.endOfLine(o,n,r)),this.valueRange=new ie(n,s),s=M.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}},En=class extends M{constructor(){super(j.BLANK_LINE)}get includesTrailingLines(){return!0}parse(t,n){return this.context=t,this.range=new ie(n,n+1),n+1}};class js extends M{constructor(t,n){super(t,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{atLineStart:s,lineStart:i}=t;!s&&this.type===j.SEQ_ITEM&&(this.error=new z(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:t.indent;let c=M.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",f=[];let p=null;for(;u===`
42
- `||u==="#";){if(u==="#"){const d=M.endOfLine(o,c+1);f.push(new ie(c,d)),c=d}else{s=!0,i=c+1;const d=M.endOfWhiteSpace(o,i);o[d]===`
43
- `&&f.length===0&&(p=new En,i=p.parse({src:o},i)),c=M.endOfIndent(o,i)}u=o[c]}if(M.nextNodeIsIndented(u,c-(i+a),this.type!==j.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(p){const d=t.parent.items||t.parent.contents;d&&d.push(p)}f.length&&Array.prototype.push.apply(this.props,f),c=this.node.range.end}else if(l){const d=f[0];this.props.push(d),c=d.end}else c=M.endOfLine(o,n+1);const h=this.node?this.node.valueRange.end:c;return this.valueRange=new ie(n,h),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.node?this.node.setOrigRanges(t,n):n}toString(){const{context:{src:t},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?t.slice(r.start,n.range.start)+String(n):t.slice(r.start,r.end);return M.addStringTerminator(t,r.end,s)}}class gn extends M{constructor(){super(j.COMMENT)}parse(t,n){this.context=t;const r=this.parseComment(n);return this.range=new ie(n,r),r}}function Io(e){let t=e;for(;t instanceof js;)t=t.node;if(!(t instanceof tl))return null;const n=t.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=t.items[i];if(a.type===j.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===j.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=t.items.splice(r,n-r),s=o[0].range.start;for(;t.range.end=s,t.valueRange&&t.valueRange.end>s&&(t.valueRange.end=s),t!==e;)t=t.context.parent;return o}let tl=class xo extends M{static nextContentHasIndent(t,n,r){const o=M.endOfLine(t,n)+1;n=M.endOfWhiteSpace(t,o);const s=t[n];return s?n>=o+r?!0:s!=="#"&&s!==`
44
- `?!1:xo.nextContentHasIndent(t,n,r):!1}constructor(t){super(t.type===j.SEQ_ITEM?j.SEQ:j.MAP);for(let r=t.props.length-1;r>=0;--r)if(t.props[r].start<t.context.lineStart){this.props=t.props.slice(0,r+1),t.props=t.props.slice(r+1);const o=t.props[0]||t.valueRange;t.range.start=o.start;break}this.items=[t];const n=Io(t);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let s=M.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=ie.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=M.normalizeOffset(o,c);let u=o[c],l=M.endOfWhiteSpace(o,s)===c,f=!1;for(;u;){for(;u===`
37
+ `){const{fold:u,offset:l}=I.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!==`
38
+ `&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[t];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new F(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new F(this,a)],str:s}}default:return s}}parseBlockValue(t){const{indent:n,inFlow:r,src:o}=this.context;let s=t,i=t;for(let a=o[s];a===`
39
+ `&&!I.atDocumentBoundary(o,s+1);a=o[s]){const c=I.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
40
+ `?s=c:(i=Uo.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=t),this.valueRange.end=i,i}parse(t,n){this.context=t;const{inFlow:r,src:o}=t;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
41
+ `&&(s=Uo.endOfLine(o,n,r)),this.valueRange=new te(n,s),s=I.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}},wn=class extends I{constructor(){super(k.BLANK_LINE)}get includesTrailingLines(){return!0}parse(t,n){return this.context=t,this.range=new te(n,n+1),n+1}};class Us extends I{constructor(t,n){super(t,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{atLineStart:s,lineStart:i}=t;!s&&this.type===k.SEQ_ITEM&&(this.error=new F(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:t.indent;let c=I.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",f=[];let p=null;for(;u===`
42
+ `||u==="#";){if(u==="#"){const d=I.endOfLine(o,c+1);f.push(new te(c,d)),c=d}else{s=!0,i=c+1;const d=I.endOfWhiteSpace(o,i);o[d]===`
43
+ `&&f.length===0&&(p=new wn,i=p.parse({src:o},i)),c=I.endOfIndent(o,i)}u=o[c]}if(I.nextNodeIsIndented(u,c-(i+a),this.type!==k.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(p){const d=t.parent.items||t.parent.contents;d&&d.push(p)}f.length&&Array.prototype.push.apply(this.props,f),c=this.node.range.end}else if(l){const d=f[0];this.props.push(d),c=d.end}else c=I.endOfLine(o,n+1);const h=this.node?this.node.valueRange.end:c;return this.valueRange=new te(n,h),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.node?this.node.setOrigRanges(t,n):n}toString(){const{context:{src:t},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?t.slice(r.start,n.range.start)+String(n):t.slice(r.start,r.end);return I.addStringTerminator(t,r.end,s)}}class dn extends I{constructor(){super(k.COMMENT)}parse(t,n){this.context=t;const r=this.parseComment(n);return this.range=new te(n,r),r}}function Fo(e){let t=e;for(;t instanceof Us;)t=t.node;if(!(t instanceof hl))return null;const n=t.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=t.items[i];if(a.type===k.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===k.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=t.items.splice(r,n-r),s=o[0].range.start;for(;t.range.end=s,t.valueRange&&t.valueRange.end>s&&(t.valueRange.end=s),t!==e;)t=t.context.parent;return o}let hl=class Vo extends I{static nextContentHasIndent(t,n,r){const o=I.endOfLine(t,n)+1;n=I.endOfWhiteSpace(t,o);const s=t[n];return s?n>=o+r?!0:s!=="#"&&s!==`
44
+ `?!1:Vo.nextContentHasIndent(t,n,r):!1}constructor(t){super(t.type===k.SEQ_ITEM?k.SEQ:k.MAP);for(let r=t.props.length-1;r>=0;--r)if(t.props[r].start<t.context.lineStart){this.props=t.props.slice(0,r+1),t.props=t.props.slice(r+1);const o=t.props[0]||t.valueRange;t.range.start=o.start;break}this.items=[t];const n=Fo(t);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let s=I.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=te.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=I.normalizeOffset(o,c);let u=o[c],l=I.endOfWhiteSpace(o,s)===c,f=!1;for(;u;){for(;u===`
45
45
  `||u==="#";){if(l&&u===`
46
- `&&!f){const d=new En;if(c=d.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(d),c-=1}else if(u==="#"){if(c<s+a&&!xo.nextContentHasIndent(o,c,a))return c;const d=new gn;if(c=d.parse({indent:a,lineStart:s,src:o},c),this.items.push(d),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=M.endOfIndent(o,s),M.atBlank(o,c)){const d=M.endOfWhiteSpace(o,c),m=o[d];(!m||m===`
47
- `||m==="#")&&(c=d)}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 d="All collection items must start at the same column";this.error=new ye(this,d)}}if(i.type===j.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const d=o[c+1];if(!d||d===`
48
- `||d===" "||d===" "){const m="A collection cannot be both a mapping and a sequence";this.error=new ye(this,m)}}const p=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!p)return c;if(this.items.push(p),this.valueRange.end=p.valueRange.end,c=M.normalizeOffset(o,p.range.end),u=o[c],l=!1,f=p.includesTrailingLines,u){let d=c-1,m=o[d];for(;m===" "||m===" ";)m=o[--d];m===`
49
- `&&(s=d+1,l=!0)}const h=Io(p);h&&Array.prototype.push.apply(this.items,h)}return c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{n=r.setOrigRanges(t,n)}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;let s=t.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 M.addStringTerminator(t,r.end,s)}};class Mm extends M{constructor(){super(j.DIRECTIVE),this.name=null}get parameters(){const t=this.rawValue;return t?t.trim().split(/[ \t]+/):[]}parseName(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
46
+ `&&!f){const d=new wn;if(c=d.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(d),c-=1}else if(u==="#"){if(c<s+a&&!Vo.nextContentHasIndent(o,c,a))return c;const d=new dn;if(c=d.parse({indent:a,lineStart:s,src:o},c),this.items.push(d),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=I.endOfIndent(o,s),I.atBlank(o,c)){const d=I.endOfWhiteSpace(o,c),g=o[d];(!g||g===`
47
+ `||g==="#")&&(c=d)}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 d="All collection items must start at the same column";this.error=new le(this,d)}}if(i.type===k.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const d=o[c+1];if(!d||d===`
48
+ `||d===" "||d===" "){const g="A collection cannot be both a mapping and a sequence";this.error=new le(this,g)}}const p=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!p)return c;if(this.items.push(p),this.valueRange.end=p.valueRange.end,c=I.normalizeOffset(o,p.range.end),u=o[c],l=!1,f=p.includesTrailingLines,u){let d=c-1,g=o[d];for(;g===" "||g===" ";)g=o[--d];g===`
49
+ `&&(s=d+1,l=!0)}const h=Fo(p);h&&Array.prototype.push.apply(this.items,h)}return c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{n=r.setOrigRanges(t,n)}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;let s=t.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 I.addStringTerminator(t,r.end,s)}};class gg extends I{constructor(){super(k.DIRECTIVE),this.name=null}get parameters(){const t=this.rawValue;return t?t.trim().split(/[ \t]+/):[]}parseName(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
50
50
  `&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(t,r),r}parseParameters(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
51
- `&&o!=="#";)o=n[r+=1];return this.valueRange=new ie(t,r),r}parse(t,n){this.context=t;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new ie(n,r),r}}let Dm=class Po extends M{static startCommentOrEndBlankLine(t,n){const r=M.endOfWhiteSpace(t,n),o=t[r];return o==="#"||o===`
52
- `?r:n}constructor(){super(j.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(t){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=t;for(;!M.atDocumentBoundary(n,s,ce.DIRECTIVES_END);)switch(s=Po.startCommentOrEndBlankLine(n,s),n[s]){case`
53
- `:if(r){const i=new En;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new gn;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new Mm;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new z(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new ie(s,s+3),s+3):(o?this.error=new z(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(t){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=t;for(;r[o-1]==="-";)o-=1;let s=M.endOfWhiteSpace(r,t),i=o===t;for(this.valueRange=new ie(s);!M.atDocumentBoundary(r,s,ce.DOCUMENT_END);){switch(r[s]){case`
54
- `:if(i){const a=new En;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 gn;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=M.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=Io(c);u&&Array.prototype.push.apply(this.contents,u)}}s=Po.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new ie(s,s+3),s+=3,r[s])){if(s=M.endOfWhiteSpace(r,s),r[s]==="#"){const a=new gn;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
55
- `:s+=1;break;case void 0:break;default:this.error=new ye(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(t,n){t.root=this,this.context=t;const{src:r}=t;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.directives.forEach(r=>{n=r.setOrigRanges(t,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(t,n)),this.contents.forEach(r=>{n=r.setOrigRanges(t,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(t,n)),n}toString(){const{contents:t,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return t.length>0&&((n.length>0||t[0].type===j.COMMENT)&&(o+=`---
51
+ `&&o!=="#";)o=n[r+=1];return this.valueRange=new te(t,r),r}parse(t,n){this.context=t;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new te(n,r),r}}let yg=class qo extends I{static startCommentOrEndBlankLine(t,n){const r=I.endOfWhiteSpace(t,n),o=t[r];return o==="#"||o===`
52
+ `?r:n}constructor(){super(k.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(t){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=t;for(;!I.atDocumentBoundary(n,s,re.DIRECTIVES_END);)switch(s=qo.startCommentOrEndBlankLine(n,s),n[s]){case`
53
+ `:if(r){const i=new wn;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new dn;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new gg;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new F(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new te(s,s+3),s+3):(o?this.error=new F(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(t){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=t;for(;r[o-1]==="-";)o-=1;let s=I.endOfWhiteSpace(r,t),i=o===t;for(this.valueRange=new te(s);!I.atDocumentBoundary(r,s,re.DOCUMENT_END);){switch(r[s]){case`
54
+ `:if(i){const a=new wn;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 dn;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=I.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=Fo(c);u&&Array.prototype.push.apply(this.contents,u)}}s=qo.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new te(s,s+3),s+=3,r[s])){if(s=I.endOfWhiteSpace(r,s),r[s]==="#"){const a=new dn;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
55
+ `:s+=1;break;case void 0:break;default:this.error=new le(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(t,n){t.root=this,this.context=t;const{src:r}=t;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.directives.forEach(r=>{n=r.setOrigRanges(t,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(t,n)),this.contents.forEach(r=>{n=r.setOrigRanges(t,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(t,n)),n}toString(){const{contents:t,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return t.length>0&&((n.length>0||t[0].type===k.COMMENT)&&(o+=`---
56
56
  `),o+=t.join("")),o[o.length-1]!==`
57
57
  `&&(o+=`
58
- `),o}},Lm=class extends M{parse(e,t){this.context=e;const{src:n}=e;let r=M.endOfIdentifier(n,t+1);return this.valueRange=new ie(t+1,r),r=M.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const nt={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class Um extends M{constructor(t,n){super(t,n),this.blockIndent=null,this.chomping=nt.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===nt.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:t,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===`
59
- `||i===" "||i===" ";){if(n-=1,n<=t){if(this.chomping===nt.KEEP)break;return""}i===`
60
- `&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===nt.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===j.BLOCK_FOLDED;let l=!0,f="",p="",h=!1;for(let d=t;d<n;++d){for(let g=0;g<c&&o[d]===" ";++g)d+=1;const m=o[d];if(m===`
58
+ `),o}},$g=class extends I{parse(e,t){this.context=e;const{src:n}=e;let r=I.endOfIdentifier(n,t+1);return this.valueRange=new te(t+1,r),r=I.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const Qe={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class vg extends I{constructor(t,n){super(t,n),this.blockIndent=null,this.chomping=Qe.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===Qe.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:t,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===`
59
+ `||i===" "||i===" ";){if(n-=1,n<=t){if(this.chomping===Qe.KEEP)break;return""}i===`
60
+ `&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===Qe.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===k.BLOCK_FOLDED;let l=!0,f="",p="",h=!1;for(let d=t;d<n;++d){for(let y=0;y<c&&o[d]===" ";++y)d+=1;const g=o[d];if(g===`
61
61
  `)p===`
62
62
  `?f+=`
63
63
  `:p=`
64
- `;else{const g=M.endOfLine(o,d),$=o.slice(d,g);d=g,u&&(m===" "||m===" ")&&d<a?(p===" "?p=`
64
+ `;else{const y=I.endOfLine(o,d),$=o.slice(d,y);d=y,u&&(g===" "||g===" ")&&d<a?(p===" "?p=`
65
65
  `:!h&&!l&&p===`
66
66
  `&&(p=`
67
67
 
68
- `),f+=p+$,p=g<n&&o[g]||"",h=!0):(f+=p+$,p=u&&d<a?" ":`
69
- `,h=!1),l&&$!==""&&(l=!1)}}return this.chomping===nt.STRIP?f:f+`
70
- `}parseBlockHeader(t){const{src:n}=this.context;let r=t+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=nt.STRIP;break;case"+":this.chomping=nt.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 ie(t,r),r}r+=1}}parseBlockValue(t){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=t,i=t,a=1;for(let c=r[s];c===`
71
- `&&(s+=1,!M.atDocumentBoundary(r,s));c=r[s]){const u=M.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],f=u-(s+n);if(this.blockIndent){if(l&&l!==`
72
- `&&f<this.blockIndent){if(r[u]==="#")break;if(!this.error){const p=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new z(this,p)}}}else if(r[u]!==`
73
- `){if(f<a){const p="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new z(this,p)}this.blockIndent=f}else f>a&&(a=f);r[u]===`
74
- `?s=u:s=i=M.endOfLine(r,u)}return this.chomping!==nt.KEEP&&(s=r[i]?i+1:i),this.valueRange=new ie(t+1,s),s}parse(t,n){this.context=t;const{src:r}=t;let o=this.parseBlockHeader(n);return o=M.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.header?this.header.setOrigRange(t,n):n}}class Bm extends M{constructor(t,n){super(t,n),this.items=null}prevNodeIsJsonLike(t=this.items.length){const n=this.items[t-1];return!!n&&(n.jsonLike||n.type===j.COMMENT&&this.prevNodeIsJsonLike(t-1))}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{indent:s,lineStart:i}=t,a=o[n];this.items=[{char:a,offset:n}];let c=M.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
75
- `:{i=c+1;const u=M.endOfWhiteSpace(o,i);if(o[u]===`
76
- `){const l=new En;i=l.parse({src:o},i),this.items.push(l)}if(c=M.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new z(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new gn;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
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 ie(n,c),c;this.items.push(u),c=M.normalizeOffset(o,u.range.end)}}c=M.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new ie(n,c+1),a&&(this.items.push({char:a,offset:c}),c=M.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{if(r instanceof M)n=r.setOrigRanges(t,n);else if(t.length===0)r.origOffset=r.offset;else{let o=n;for(;o<t.length&&!(t[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof M);let i="",a=r.start;return s.forEach(c=>{const u=t.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
68
+ `),f+=p+$,p=y<n&&o[y]||"",h=!0):(f+=p+$,p=u&&d<a?" ":`
69
+ `,h=!1),l&&$!==""&&(l=!1)}}return this.chomping===Qe.STRIP?f:f+`
70
+ `}parseBlockHeader(t){const{src:n}=this.context;let r=t+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=Qe.STRIP;break;case"+":this.chomping=Qe.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 te(t,r),r}r+=1}}parseBlockValue(t){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=t,i=t,a=1;for(let c=r[s];c===`
71
+ `&&(s+=1,!I.atDocumentBoundary(r,s));c=r[s]){const u=I.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],f=u-(s+n);if(this.blockIndent){if(l&&l!==`
72
+ `&&f<this.blockIndent){if(r[u]==="#")break;if(!this.error){const p=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new F(this,p)}}}else if(r[u]!==`
73
+ `){if(f<a){const p="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new F(this,p)}this.blockIndent=f}else f>a&&(a=f);r[u]===`
74
+ `?s=u:s=i=I.endOfLine(r,u)}return this.chomping!==Qe.KEEP&&(s=r[i]?i+1:i),this.valueRange=new te(t+1,s),s}parse(t,n){this.context=t;const{src:r}=t;let o=this.parseBlockHeader(n);return o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.header?this.header.setOrigRange(t,n):n}}class wg extends I{constructor(t,n){super(t,n),this.items=null}prevNodeIsJsonLike(t=this.items.length){const n=this.items[t-1];return!!n&&(n.jsonLike||n.type===k.COMMENT&&this.prevNodeIsJsonLike(t-1))}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{indent:s,lineStart:i}=t,a=o[n];this.items=[{char:a,offset:n}];let c=I.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
75
+ `:{i=c+1;const u=I.endOfWhiteSpace(o,i);if(o[u]===`
76
+ `){const l=new wn;i=l.parse({src:o},i),this.items.push(l)}if(c=I.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new F(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new dn;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
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 te(n,c),c;this.items.push(u),c=I.normalizeOffset(o,u.range.end)}}c=I.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new te(n,c+1),a&&(this.items.push({char:a,offset:c}),c=I.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{if(r instanceof I)n=r.setOrigRanges(t,n);else if(t.length===0)r.origOffset=r.offset;else{let o=n;for(;o<t.length&&!(t[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof I);let i="",a=r.start;return s.forEach(c=>{const u=t.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
78
78
  `&&t[a-1]!==`
79
79
  `&&t[a]===`
80
- `&&(a+=1)}),i+=t.slice(a,r.end),M.addStringTerminator(t,r.end,i)}}class Is extends M{static endOfQuote(t,n){let r=t[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=t[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&t.push(new ye(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
81
- `){M.atDocumentBoundary(s,a+1)&&t.push(new z(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=M.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new z(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+=`
80
+ `&&(a+=1)}),i+=t.slice(a,r.end),I.addStringTerminator(t,r.end,i)}}class Fs extends I{static endOfQuote(t,n){let r=t[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=t[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&t.push(new le(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
81
+ `){I.atDocumentBoundary(s,a+1)&&t.push(new F(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=I.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new F(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+=`
82
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,t),a+=2;break;case"u":i+=this.parseCharCode(a+1,4,t),a+=4;break;case"U":i+=this.parseCharCode(a+1,8,t),a+=8;break;case`
83
- `:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:t.push(new ye(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!==`
84
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parseCharCode(t,n,r){const{src:o}=this.context,s=o.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new ye(this,`Invalid escape sequence ${o.substr(t-2,n+2)}`)),o.substr(t-2,n+2)):String.fromCodePoint(i)}parse(t,n){this.context=t;const{src:r}=t;let o=Is.endOfQuote(r,n+1);return this.valueRange=new ie(n,o),o=M.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}class xs extends M{static endOfQuote(t,n){let r=t[n];for(;r;)if(r==="'"){if(t[n+1]!=="'")break;r=t[n+=2]}else r=t[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&t.push(new ye(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
85
- `){M.atDocumentBoundary(s,a+1)&&t.push(new z(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=M.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new z(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&t.push(new ye(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!==`
86
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parse(t,n){this.context=t;const{src:r}=t;let o=xs.endOfQuote(r,n+1);return this.valueRange=new ie(n,o),o=M.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function Fm(e,t){switch(e){case j.ALIAS:return new Lm(e,t);case j.BLOCK_FOLDED:case j.BLOCK_LITERAL:return new Um(e,t);case j.FLOW_MAP:case j.FLOW_SEQ:return new Bm(e,t);case j.MAP_KEY:case j.MAP_VALUE:case j.SEQ_ITEM:return new js(e,t);case j.COMMENT:case j.PLAIN:return new el(e,t);case j.QUOTE_DOUBLE:return new Is(e,t);case j.QUOTE_SINGLE:return new xs(e,t);default:return null}}let Vm=class Zn{static parseType(t,n,r){switch(t[n]){case"*":return j.ALIAS;case">":return j.BLOCK_FOLDED;case"|":return j.BLOCK_LITERAL;case"{":return j.FLOW_MAP;case"[":return j.FLOW_SEQ;case"?":return!r&&M.atBlank(t,n+1,!0)?j.MAP_KEY:j.PLAIN;case":":return!r&&M.atBlank(t,n+1,!0)?j.MAP_VALUE:j.PLAIN;case"-":return!r&&M.atBlank(t,n+1,!0)?j.SEQ_ITEM:j.PLAIN;case'"':return j.QUOTE_DOUBLE;case"'":return j.QUOTE_SINGLE;default:return j.PLAIN}}constructor(t={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){$e(this,"parseNode",(c,u)=>{if(M.atDocumentBoundary(this.src,u))return null;const l=new Zn(this,c),{props:f,type:p,valueStart:h}=l.parseProps(u),d=Fm(p,f);let m=u;try{m=d.parse(l,h)}catch(g){const $=g instanceof Error?g.message:String(g);d.error||(d.error=new ye(d,$))}if(d.range=new ie(u,m),m<=u&&(d.error||(d.error=new Error("Node#parse consumed no characters")),d.error.parseEnd=m,d.error.source=d,d.range.end=u+1),l.nodeStartsCollection(d)){!d.error&&!l.atLineStart&&l.parent.type===j.DOCUMENT&&(d.error=new ye(d,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const g=new tl(d);return m=g.parse(new Zn(l),m),g.range=new ie(u,m),g}return d}),this.atLineStart=n??(t.atLineStart||!1),this.inCollection=r??(t.inCollection||!1),this.inFlow=o??(t.inFlow||!1),this.indent=s??t.indent,this.lineStart=i??t.lineStart,this.parent=a??(t.parent||{}),this.root=t.root,this.src=t.src}nodeStartsCollection(t){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(t instanceof js)return!0;let s=t.range.end;return o[s]===`
83
+ `:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:t.push(new le(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!==`
84
+ `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parseCharCode(t,n,r){const{src:o}=this.context,s=o.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new le(this,`Invalid escape sequence ${o.substr(t-2,n+2)}`)),o.substr(t-2,n+2)):String.fromCodePoint(i)}parse(t,n){this.context=t;const{src:r}=t;let o=Fs.endOfQuote(r,n+1);return this.valueRange=new te(n,o),o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}class Vs extends I{static endOfQuote(t,n){let r=t[n];for(;r;)if(r==="'"){if(t[n+1]!=="'")break;r=t[n+=2]}else r=t[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&t.push(new le(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
85
+ `){I.atDocumentBoundary(s,a+1)&&t.push(new F(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=I.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new F(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&t.push(new le(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!==`
86
+ `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parse(t,n){this.context=t;const{src:r}=t;let o=Vs.endOfQuote(r,n+1);return this.valueRange=new te(n,o),o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function bg(e,t){switch(e){case k.ALIAS:return new $g(e,t);case k.BLOCK_FOLDED:case k.BLOCK_LITERAL:return new vg(e,t);case k.FLOW_MAP:case k.FLOW_SEQ:return new wg(e,t);case k.MAP_KEY:case k.MAP_VALUE:case k.SEQ_ITEM:return new Us(e,t);case k.COMMENT:case k.PLAIN:return new pl(e,t);case k.QUOTE_DOUBLE:return new Fs(e,t);case k.QUOTE_SINGLE:return new Vs(e,t);default:return null}}let Eg=class Yn{static parseType(t,n,r){switch(t[n]){case"*":return k.ALIAS;case">":return k.BLOCK_FOLDED;case"|":return k.BLOCK_LITERAL;case"{":return k.FLOW_MAP;case"[":return k.FLOW_SEQ;case"?":return!r&&I.atBlank(t,n+1,!0)?k.MAP_KEY:k.PLAIN;case":":return!r&&I.atBlank(t,n+1,!0)?k.MAP_VALUE:k.PLAIN;case"-":return!r&&I.atBlank(t,n+1,!0)?k.SEQ_ITEM:k.PLAIN;case'"':return k.QUOTE_DOUBLE;case"'":return k.QUOTE_SINGLE;default:return k.PLAIN}}constructor(t={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){pe(this,"parseNode",(c,u)=>{if(I.atDocumentBoundary(this.src,u))return null;const l=new Yn(this,c),{props:f,type:p,valueStart:h}=l.parseProps(u),d=bg(p,f);let g=u;try{g=d.parse(l,h)}catch(y){const $=y instanceof Error?y.message:String(y);d.error||(d.error=new le(d,$))}if(d.range=new te(u,g),g<=u&&(d.error||(d.error=new Error("Node#parse consumed no characters")),d.error.parseEnd=g,d.error.source=d,d.range.end=u+1),l.nodeStartsCollection(d)){!d.error&&!l.atLineStart&&l.parent.type===k.DOCUMENT&&(d.error=new le(d,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const y=new hl(d);return g=y.parse(new Yn(l),g),y.range=new te(u,g),y}return d}),this.atLineStart=n??(t.atLineStart||!1),this.inCollection=r??(t.inCollection||!1),this.inFlow=o??(t.inFlow||!1),this.indent=s??t.indent,this.lineStart=i??t.lineStart,this.parent=a??(t.parent||{}),this.root=t.root,this.src=t.src}nodeStartsCollection(t){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(t instanceof Us)return!0;let s=t.range.end;return o[s]===`
87
87
  `||o[s-1]===`
88
- `?!1:(s=M.endOfWhiteSpace(o,s),o[s]===":")}parseProps(t){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;t=this.atLineStart?M.endOfIndent(o,t):M.endOfWhiteSpace(o,t);let a=o[t];for(;a===ce.ANCHOR||a===ce.COMMENT||a===ce.TAG||a===`
88
+ `?!1:(s=I.endOfWhiteSpace(o,s),o[s]===":")}parseProps(t){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;t=this.atLineStart?I.endOfIndent(o,t):I.endOfWhiteSpace(o,t);let a=o[t];for(;a===re.ANCHOR||a===re.COMMENT||a===re.TAG||a===`
89
89
  `;){if(a===`
90
- `){let u=t,l;do l=u+1,u=M.endOfIndent(o,l);while(o[u]===`
91
- `);const f=u-(l+this.indent),p=r.type===j.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!M.nextNodeIsIndented(o[u],f,!p))break;this.atLineStart=!0,this.lineStart=l,i=!1,t=u}else if(a===ce.COMMENT){const u=M.endOfLine(o,t+1);s.push(new ie(t,u)),t=u}else{let u=M.endOfIdentifier(o,t+1);a===ce.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(t+1,u+13))&&(u=M.endOfIdentifier(o,u+5)),s.push(new ie(t,u)),i=!0,t=M.endOfWhiteSpace(o,u)}a=o[t]}i&&a===":"&&M.atBlank(o,t+1,!0)&&(t-=1);const c=Zn.parseType(o,t,n);return{props:s,type:c,valueStart:t}}};function Ps(e){const t=[];e.indexOf("\r")!==-1&&(e=e.replace(/\r\n?/g,(o,s)=>(o.length>1&&t.push(s),`
92
- `)));const n=[];let r=0;do{const o=new Dm,s=new Vm({src:e});r=o.parse(s,r),n.push(o)}while(r<e.length);return n.setOrigRanges=()=>{if(t.length===0)return!1;for(let s=1;s<t.length;++s)t[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(t,o);return t.splice(0,t.length),!0},n.toString=()=>n.join(`...
93
- `),n}function qm(e,t,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${t}#`)}
94
- ${t}${e}`:e}function Gt(e,t,n){return n?n.indexOf(`
90
+ `){let u=t,l;do l=u+1,u=I.endOfIndent(o,l);while(o[u]===`
91
+ `);const f=u-(l+this.indent),p=r.type===k.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!I.nextNodeIsIndented(o[u],f,!p))break;this.atLineStart=!0,this.lineStart=l,i=!1,t=u}else if(a===re.COMMENT){const u=I.endOfLine(o,t+1);s.push(new te(t,u)),t=u}else{let u=I.endOfIdentifier(o,t+1);a===re.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(t+1,u+13))&&(u=I.endOfIdentifier(o,u+5)),s.push(new te(t,u)),i=!0,t=I.endOfWhiteSpace(o,u)}a=o[t]}i&&a===":"&&I.atBlank(o,t+1,!0)&&(t-=1);const c=Yn.parseType(o,t,n);return{props:s,type:c,valueStart:t}}};function qs(e){const t=[];e.indexOf("\r")!==-1&&(e=e.replace(/\r\n?/g,(o,s)=>(o.length>1&&t.push(s),`
92
+ `)));const n=[];let r=0;do{const o=new yg,s=new Eg({src:e});r=o.parse(s,r),n.push(o)}while(r<e.length);return n.setOrigRanges=()=>{if(t.length===0)return!1;for(let s=1;s<t.length;++s)t[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(t,o);return t.splice(0,t.length),!0},n.toString=()=>n.join(`...
93
+ `),n}function Sg(e,t,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${t}#`)}
94
+ ${t}${e}`:e}function Vt(e,t,n){return n?n.indexOf(`
95
95
  `)===-1?`${e} #${n}`:`${e}
96
- `+n.replace(/^/gm,`${t||""}#`):e}let Se=class{};function Ue(e,t,n){if(Array.isArray(e))return e.map((r,o)=>Ue(r,String(o),n));if(e&&typeof e.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(e);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=e.toJSON(t,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof e=="bigint"?Number(e):e}let re=class extends Se{constructor(t){super(),this.value=t}toJSON(t,n){return n&&n.keep?this.value:Ue(this.value,t,n)}toString(){return String(this.value)}};function Ua(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){const s=t[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 e.createNode(r,!1)}const dn=e=>e==null||typeof e=="object"&&e[Symbol.iterator]().next().done;let ge=class $t extends Se{constructor(t){super(),$e(this,"items",[]),this.schema=t}addIn(t,n){if(dn(t))this.add(n);else{const[r,...o]=t,s=this.get(r,!0);if(s instanceof $t)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,Ua(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([t,...n]){if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(r instanceof $t)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn([t,...n],r){const o=this.get(t,!0);return n.length===0?!r&&o instanceof re?o.value:o:o instanceof $t?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(t=>{if(!t||t.type!=="PAIR")return!1;const n=t.value;return n==null||n instanceof re&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([t,...n]){if(n.length===0)return this.has(t);const r=this.get(t,!0);return r instanceof $t?r.hasIn(n):!1}setIn([t,...n],r){if(n.length===0)this.set(t,r);else{const o=this.get(t,!0);if(o instanceof $t)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(t,Ua(this.schema,n,r));else throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}}toJSON(){return null}toString(t,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=t,f=this.type===j.FLOW_MAP||this.type===j.FLOW_SEQ||t.inFlow;f&&(s+=u);const p=o&&this.hasAllNullValues();t=Object.assign({},t,{allNullValues:p,indent:s,inFlow:f,type:null});let h=!1,d=!1;const m=this.items.reduce(($,v,w)=>{let S;v&&(!h&&v.spaceBefore&&$.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(I=>{$.push({type:"comment",str:`#${I}`})}),v.comment&&(S=v.comment),f&&(!h&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(d=!0)),h=!1;let N=l(v,t,()=>S=null,()=>h=!0);return f&&!d&&N.includes(`
97
- `)&&(d=!0),f&&w<this.items.length-1&&(N+=","),N=Gt(N,s,S),h&&(S||f)&&(h=!1),$.push({type:"item",str:N}),$},[]);let g;if(m.length===0)g=r.start+r.end;else if(f){const{start:$,end:v}=r,w=m.map(S=>S.str);if(d||w.reduce((S,N)=>S+N.length+2,2)>$t.maxFlowStringSingleLineLength){g=$;for(const S of w)g+=S?`
96
+ `+n.replace(/^/gm,`${t||""}#`):e}let ge=class{};function Pe(e,t,n){if(Array.isArray(e))return e.map((r,o)=>Pe(r,String(o),n));if(e&&typeof e.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(e);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=e.toJSON(t,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof e=="bigint"?Number(e):e}let Y=class extends ge{constructor(t){super(),this.value=t}toJSON(t,n){return n&&n.keep?this.value:Pe(this.value,t,n)}toString(){return String(this.value)}};function nc(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){const s=t[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 e.createNode(r,!1)}const cn=e=>e==null||typeof e=="object"&&e[Symbol.iterator]().next().done;let ue=class pt extends ge{constructor(t){super(),pe(this,"items",[]),this.schema=t}addIn(t,n){if(cn(t))this.add(n);else{const[r,...o]=t,s=this.get(r,!0);if(s instanceof pt)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,nc(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([t,...n]){if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(r instanceof pt)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn([t,...n],r){const o=this.get(t,!0);return n.length===0?!r&&o instanceof Y?o.value:o:o instanceof pt?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(t=>{if(!t||t.type!=="PAIR")return!1;const n=t.value;return n==null||n instanceof Y&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([t,...n]){if(n.length===0)return this.has(t);const r=this.get(t,!0);return r instanceof pt?r.hasIn(n):!1}setIn([t,...n],r){if(n.length===0)this.set(t,r);else{const o=this.get(t,!0);if(o instanceof pt)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(t,nc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}}toJSON(){return null}toString(t,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=t,f=this.type===k.FLOW_MAP||this.type===k.FLOW_SEQ||t.inFlow;f&&(s+=u);const p=o&&this.hasAllNullValues();t=Object.assign({},t,{allNullValues:p,indent:s,inFlow:f,type:null});let h=!1,d=!1;const g=this.items.reduce(($,v,b)=>{let S;v&&(!h&&v.spaceBefore&&$.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(j=>{$.push({type:"comment",str:`#${j}`})}),v.comment&&(S=v.comment),f&&(!h&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(d=!0)),h=!1;let O=l(v,t,()=>S=null,()=>h=!0);return f&&!d&&O.includes(`
97
+ `)&&(d=!0),f&&b<this.items.length-1&&(O+=","),O=Vt(O,s,S),h&&(S||f)&&(h=!1),$.push({type:"item",str:O}),$},[]);let y;if(g.length===0)y=r.start+r.end;else if(f){const{start:$,end:v}=r,b=g.map(S=>S.str);if(d||b.reduce((S,O)=>S+O.length+2,2)>pt.maxFlowStringSingleLineLength){y=$;for(const S of b)y+=S?`
98
98
  ${u}${c}${S}`:`
99
- `;g+=`
100
- ${c}${v}`}else g=`${$} ${w.join(" ")} ${v}`}else{const $=m.map(n);g=$.shift();for(const v of $)g+=v?`
99
+ `;y+=`
100
+ ${c}${v}`}else y=`${$} ${b.join(" ")} ${v}`}else{const $=g.map(n);y=$.shift();for(const v of $)y+=v?`
101
101
  ${c}${v}`:`
102
- `}return this.comment?(g+=`
103
- `+this.comment.replace(/^/gm,`${c}#`),i&&i()):h&&a&&a(),g}};$e(ge,"maxFlowStringSingleLineLength",60);function Rn(e){let t=e instanceof re?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),Number.isInteger(t)&&t>=0?t:null}let qe=class extends ge{add(t){this.items.push(t)}delete(t){const n=Rn(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const r=Rn(t);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof re?o.value:o}has(t){const n=Rn(t);return typeof n=="number"&&n<this.items.length}set(t,n){const r=Rn(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);this.items[r]=n}toJSON(t,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(Ue(s,String(o++),n));return r}toString(t,n,r){return t?super.toString(t,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(t.indent||"")+" "},n,r):JSON.stringify(this)}};const Km=(e,t,n)=>t===null?"":typeof t!="object"?String(t):e instanceof Se&&n&&n.doc?e.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(t);let Z=class nl extends Se{constructor(t,n=null){super(),this.key=t,this.value=n,this.type=nl.Type.PAIR}get commentBefore(){return this.key instanceof Se?this.key.commentBefore:void 0}set commentBefore(t){if(this.key==null&&(this.key=new re(null)),this.key instanceof Se)this.key.commentBefore=t;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(t,n){const r=Ue(this.key,"",t);if(n instanceof Map){const o=Ue(this.value,r,t);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=Km(this.key,r,t),s=Ue(this.value,o,t);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(t,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(t,n,r){if(!t||!t.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=t.doc.options;let{key:a,value:c}=this,u=a instanceof Se&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof ge){const N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let l=!i&&(!a||u||(a instanceof Se?a instanceof ge||a.type===j.BLOCK_FOLDED||a.type===j.BLOCK_LITERAL:typeof a=="object"));const{doc:f,indent:p,indentStep:h,stringify:d}=t;t=Object.assign({},t,{implicitKey:!l,indent:p+h});let m=!1,g=d(a,t,()=>u=null,()=>m=!0);if(g=Gt(g,t.indent,u),!l&&g.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(t.allNullValues&&!i)return this.comment?(g=Gt(g,t.indent,this.comment),n&&n()):m&&!u&&r&&r(),t.inFlow&&!l?g:`? ${g}`;g=l?`? ${g}
104
- ${p}:`:`${g}:`,this.comment&&(g=Gt(g,t.indent,this.comment),n&&n());let $="",v=null;if(c instanceof Se){if(c.spaceBefore&&($=`
105
- `),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${t.indent}#`);$+=`
106
- ${N}`}v=c.comment}else c&&typeof c=="object"&&(c=f.schema.createNode(c,!0));t.implicitKey=!1,!l&&!this.comment&&c instanceof re&&(t.indentAtStart=g.length+1),m=!1,!s&&o>=2&&!t.inFlow&&!l&&c instanceof qe&&c.type!==j.FLOW_SEQ&&!c.tag&&!f.anchors.getName(c)&&(t.indent=t.indent.substr(2));const w=d(c,t,()=>v=null,()=>m=!0);let S=" ";return $||this.comment?S=`${$}
107
- ${t.indent}`:!l&&c instanceof ge?(!(w[0]==="["||w[0]==="{")||w.includes(`
102
+ `}return this.comment?(y+=`
103
+ `+this.comment.replace(/^/gm,`${c}#`),i&&i()):h&&a&&a(),y}};pe(ue,"maxFlowStringSingleLineLength",60);function Cn(e){let t=e instanceof Y?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),Number.isInteger(t)&&t>=0?t:null}let De=class extends ue{add(t){this.items.push(t)}delete(t){const n=Cn(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const r=Cn(t);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof Y?o.value:o}has(t){const n=Cn(t);return typeof n=="number"&&n<this.items.length}set(t,n){const r=Cn(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);this.items[r]=n}toJSON(t,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(Pe(s,String(o++),n));return r}toString(t,n,r){return t?super.toString(t,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(t.indent||"")+" "},n,r):JSON.stringify(this)}};const Ng=(e,t,n)=>t===null?"":typeof t!="object"?String(t):e instanceof ge&&n&&n.doc?e.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(t);let z=class ml extends ge{constructor(t,n=null){super(),this.key=t,this.value=n,this.type=ml.Type.PAIR}get commentBefore(){return this.key instanceof ge?this.key.commentBefore:void 0}set commentBefore(t){if(this.key==null&&(this.key=new Y(null)),this.key instanceof ge)this.key.commentBefore=t;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(t,n){const r=Pe(this.key,"",t);if(n instanceof Map){const o=Pe(this.value,r,t);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=Ng(this.key,r,t),s=Pe(this.value,o,t);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(t,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(t,n,r){if(!t||!t.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=t.doc.options;let{key:a,value:c}=this,u=a instanceof ge&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof ue){const O="With simple keys, collection cannot be used as a key value";throw new Error(O)}}let l=!i&&(!a||u||(a instanceof ge?a instanceof ue||a.type===k.BLOCK_FOLDED||a.type===k.BLOCK_LITERAL:typeof a=="object"));const{doc:f,indent:p,indentStep:h,stringify:d}=t;t=Object.assign({},t,{implicitKey:!l,indent:p+h});let g=!1,y=d(a,t,()=>u=null,()=>g=!0);if(y=Vt(y,t.indent,u),!l&&y.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(t.allNullValues&&!i)return this.comment?(y=Vt(y,t.indent,this.comment),n&&n()):g&&!u&&r&&r(),t.inFlow&&!l?y:`? ${y}`;y=l?`? ${y}
104
+ ${p}:`:`${y}:`,this.comment&&(y=Vt(y,t.indent,this.comment),n&&n());let $="",v=null;if(c instanceof ge){if(c.spaceBefore&&($=`
105
+ `),c.commentBefore){const O=c.commentBefore.replace(/^/gm,`${t.indent}#`);$+=`
106
+ ${O}`}v=c.comment}else c&&typeof c=="object"&&(c=f.schema.createNode(c,!0));t.implicitKey=!1,!l&&!this.comment&&c instanceof Y&&(t.indentAtStart=y.length+1),g=!1,!s&&o>=2&&!t.inFlow&&!l&&c instanceof De&&c.type!==k.FLOW_SEQ&&!c.tag&&!f.anchors.getName(c)&&(t.indent=t.indent.substr(2));const b=d(c,t,()=>v=null,()=>g=!0);let S=" ";return $||this.comment?S=`${$}
107
+ ${t.indent}`:!l&&c instanceof ue?(!(b[0]==="["||b[0]==="{")||b.includes(`
108
108
  `))&&(S=`
109
- ${t.indent}`):w[0]===`
110
- `&&(S=""),m&&!v&&r&&r(),Gt(g+S+w,t.indent,v)}};$e(Z,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const Xn=(e,t)=>{if(e instanceof Ze){const n=t.get(e.source);return n.count*n.aliasCount}else if(e instanceof ge){let n=0;for(const r of e.items){const o=Xn(r,t);o>n&&(n=o)}return n}else if(e instanceof Z){const n=Xn(e.key,t),r=Xn(e.value,t);return Math.max(n,r)}return 1};let Ze=class rl extends Se{static stringify({range:t,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} [${t}]`)}constructor(t){super(),this.source=t,this.type=j.ALIAS}set tag(t){throw new Error("Alias nodes cannot have tags")}toJSON(t,n){if(!n)return Ue(this.source,t,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 Sn(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Xn(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new Sn(this.cstNode,i):new ReferenceError(i)}return s.res}toString(t){return rl.stringify(this,t)}};$e(Ze,"default",!0);function Nt(e,t){const n=t instanceof re?t.value:t;for(const r of e)if(r instanceof Z&&(r.key===t||r.key===n||r.key&&r.key.value===n))return r}let Ee=class extends ge{add(t,n){t?t instanceof Z||(t=new Z(t.key||t,t.value)):t=new Z(t);const r=Nt(this.items,t.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=t.value;else throw new Error(`Key ${t.key} already set`);else if(o){const s=this.items.findIndex(i=>o(t,i)<0);s===-1?this.items.push(t):this.items.splice(s,0,t)}else this.items.push(t)}delete(t){const n=Nt(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const r=Nt(this.items,t),o=r&&r.value;return!n&&o instanceof re?o.value:o}has(t){return!!Nt(this.items,t)}set(t,n){this.add(new Z(t,n),!0)}toJSON(t,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(t,n,r){if(!t)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof Z))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(t,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:t.indent||""},n,r)}};const ol="<<";class sl extends Z{constructor(t){if(t instanceof Z){let n=t.value;n instanceof qe||(n=new qe,n.items.push(t.value),n.range=t.value.range),super(t.key,n),this.range=t.range}else super(new re(ol),new qe);this.type=Z.Type.MERGE_PAIR}addToJSMap(t,n){for(const{source:r}of this.value.items){if(!(r instanceof Ee))throw new Error("Merge sources must be maps");const o=r.toJSON(null,t,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(t,n){const r=this.value;if(r.items.length>1)return super.toString(t,n);this.value=r.items[0];const o=super.toString(t,n);return this.value=r,o}}const yn={defaultType:j.BLOCK_LITERAL,lineWidth:76},Qe={trueStr:"true",falseStr:"false"},ut={asBigInt:!1},Yt={nullStr:"null"},Xe={defaultType:j.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function Ts(e,t,n){for(const{format:r,test:o,resolve:s}of t)if(o){const i=e.match(o);if(i){let a=s.apply(null,i);return a instanceof re||(a=new re(a)),r&&(a.format=r),a}}return n&&(e=n(e)),new re(e)}const il="flow",To="block",er="quoted",Ba=(e,t)=>{let n=e[t+1];for(;n===" "||n===" ";){do n=e[t+=1];while(n&&n!==`
111
- `);n=e[t+1]}return t};function Nr(e,t,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return e;const c=Math.max(1+s,1+o-t.length);if(e.length<=c)return e;const u=[],l={};let f=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):f=o-r);let p,h,d=!1,m=-1,g=-1,$=-1;n===To&&(m=Ba(e,m),m!==-1&&(f=m+c));for(let w;w=e[m+=1];){if(n===er&&w==="\\"){switch(g=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}$=m}if(w===`
112
- `)n===To&&(m=Ba(e,m)),f=m+c,p=void 0;else{if(w===" "&&h&&h!==" "&&h!==`
113
- `&&h!==" "){const S=e[m+1];S&&S!==" "&&S!==`
114
- `&&S!==" "&&(p=m)}if(m>=f)if(p)u.push(p),f=p+c,p=void 0;else if(n===er){for(;h===" "||h===" ";)h=w,w=e[m+=1],d=!0;const S=m>$+1?m-2:g-1;if(l[S])return e;u.push(S),l[S]=!0,f=S+c,p=void 0}else d=!0}h=w}if(d&&a&&a(),u.length===0)return e;i&&i();let v=e.slice(0,u[0]);for(let w=0;w<u.length;++w){const S=u[w],N=u[w+1]||e.length;S===0?v=`
115
- ${t}${e.slice(0,N)}`:(n===er&&l[S]&&(v+=`${e[S]}\\`),v+=`
116
- ${t}${e.slice(S+1,N)}`)}return v}const Cs=({indentAtStart:e})=>e?Object.assign({indentAtStart:e},Xe.fold):Xe.fold,Or=e=>/^(%|---|\.\.\.)/m.test(e);function zm(e,t,n){if(!t||t<0)return!1;const r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`
117
- `){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function kt(e,t){const{implicitKey:n}=t,{jsonEncoding:r,minMultiLineLength:o}=Xe.doubleQuoted,s=JSON.stringify(e);if(r)return s;const i=t.indent||(Or(e)?" ":"");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 f=s.substr(u+2,4);switch(f){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:f.substr(0,2)==="00"?a+="\\x"+f.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)+`
109
+ ${t.indent}`):b[0]===`
110
+ `&&(S=""),g&&!v&&r&&r(),Vt(y+S+b,t.indent,v)}};pe(z,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const Qn=(e,t)=>{if(e instanceof Je){const n=t.get(e.source);return n.count*n.aliasCount}else if(e instanceof ue){let n=0;for(const r of e.items){const o=Qn(r,t);o>n&&(n=o)}return n}else if(e instanceof z){const n=Qn(e.key,t),r=Qn(e.value,t);return Math.max(n,r)}return 1};let Je=class gl extends ge{static stringify({range:t,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} [${t}]`)}constructor(t){super(),this.source=t,this.type=k.ALIAS}set tag(t){throw new Error("Alias nodes cannot have tags")}toJSON(t,n){if(!n)return Pe(this.source,t,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 vn(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Qn(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new vn(this.cstNode,i):new ReferenceError(i)}return s.res}toString(t){return gl.stringify(this,t)}};pe(Je,"default",!0);function wt(e,t){const n=t instanceof Y?t.value:t;for(const r of e)if(r instanceof z&&(r.key===t||r.key===n||r.key&&r.key.value===n))return r}let ye=class extends ue{add(t,n){t?t instanceof z||(t=new z(t.key||t,t.value)):t=new z(t);const r=wt(this.items,t.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=t.value;else throw new Error(`Key ${t.key} already set`);else if(o){const s=this.items.findIndex(i=>o(t,i)<0);s===-1?this.items.push(t):this.items.splice(s,0,t)}else this.items.push(t)}delete(t){const n=wt(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const r=wt(this.items,t),o=r&&r.value;return!n&&o instanceof Y?o.value:o}has(t){return!!wt(this.items,t)}set(t,n){this.add(new z(t,n),!0)}toJSON(t,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(t,n,r){if(!t)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof z))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(t,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:t.indent||""},n,r)}};const yl="<<";class $l extends z{constructor(t){if(t instanceof z){let n=t.value;n instanceof De||(n=new De,n.items.push(t.value),n.range=t.value.range),super(t.key,n),this.range=t.range}else super(new Y(yl),new De);this.type=z.Type.MERGE_PAIR}addToJSMap(t,n){for(const{source:r}of this.value.items){if(!(r instanceof ye))throw new Error("Merge sources must be maps");const o=r.toJSON(null,t,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(t,n){const r=this.value;if(r.items.length>1)return super.toString(t,n);this.value=r.items[0];const o=super.toString(t,n);return this.value=r,o}}const pn={defaultType:k.BLOCK_LITERAL,lineWidth:76},qe={trueStr:"true",falseStr:"false"},it={asBigInt:!1},Wt={nullStr:"null"},He={defaultType:k.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function Ks(e,t,n){for(const{format:r,test:o,resolve:s}of t)if(o){const i=e.match(o);if(i){let a=s.apply(null,i);return a instanceof Y||(a=new Y(a)),r&&(a.format=r),a}}return n&&(e=n(e)),new Y(e)}const vl="flow",Ko="block",Zn="quoted",rc=(e,t)=>{let n=e[t+1];for(;n===" "||n===" ";){do n=e[t+=1];while(n&&n!==`
111
+ `);n=e[t+1]}return t};function Sr(e,t,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return e;const c=Math.max(1+s,1+o-t.length);if(e.length<=c)return e;const u=[],l={};let f=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):f=o-r);let p,h,d=!1,g=-1,y=-1,$=-1;n===Ko&&(g=rc(e,g),g!==-1&&(f=g+c));for(let b;b=e[g+=1];){if(n===Zn&&b==="\\"){switch(y=g,e[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}$=g}if(b===`
112
+ `)n===Ko&&(g=rc(e,g)),f=g+c,p=void 0;else{if(b===" "&&h&&h!==" "&&h!==`
113
+ `&&h!==" "){const S=e[g+1];S&&S!==" "&&S!==`
114
+ `&&S!==" "&&(p=g)}if(g>=f)if(p)u.push(p),f=p+c,p=void 0;else if(n===Zn){for(;h===" "||h===" ";)h=b,b=e[g+=1],d=!0;const S=g>$+1?g-2:y-1;if(l[S])return e;u.push(S),l[S]=!0,f=S+c,p=void 0}else d=!0}h=b}if(d&&a&&a(),u.length===0)return e;i&&i();let v=e.slice(0,u[0]);for(let b=0;b<u.length;++b){const S=u[b],O=u[b+1]||e.length;S===0?v=`
115
+ ${t}${e.slice(0,O)}`:(n===Zn&&l[S]&&(v+=`${e[S]}\\`),v+=`
116
+ ${t}${e.slice(S+1,O)}`)}return v}const Gs=({indentAtStart:e})=>e?Object.assign({indentAtStart:e},He.fold):He.fold,Nr=e=>/^(%|---|\.\.\.)/m.test(e);function Og(e,t,n){if(!t||t<0)return!1;const r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`
117
+ `){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function Nt(e,t){const{implicitKey:n}=t,{jsonEncoding:r,minMultiLineLength:o}=He.doubleQuoted,s=JSON.stringify(e);if(r)return s;const i=t.indent||(Nr(e)?" ":"");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 f=s.substr(u+2,4);switch(f){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:f.substr(0,2)==="00"?a+="\\x"+f.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
118
 
119
119
  `;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:Nr(a,i,er,Cs(t))}function al(e,t){if(t.implicitKey){if(/\n/.test(e))return kt(e,t)}else if(/[ \t]\n|\n[ \t]/.test(e))return kt(e,t);const n=t.indent||(Or(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
121
- ${n}`)+"'";return t.implicitKey?r:Nr(r,n,il,Cs(t))}function tr({comment:e,type:t,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return kt(n,r);const i=r.indent||(r.forceBlockIndent||Or(n)?" ":""),a=i?"2":"1",c=t===j.BLOCK_FOLDED?!1:t===j.BLOCK_LITERAL?!0:!zm(n,Xe.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
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:Sr(a,i,Zn,Gs(t))}function wl(e,t){if(t.implicitKey){if(/\n/.test(e))return Nt(e,t)}else if(/[ \t]\n|\n[ \t]/.test(e))return Nt(e,t);const n=t.indent||(Nr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
121
+ ${n}`)+"'";return t.implicitKey?r:Sr(r,n,vl,Gs(t))}function Xn({comment:e,type:t,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return Nt(n,r);const i=r.indent||(r.forceBlockIndent||Nr(n)?" ":""),a=i?"2":"1",c=t===k.BLOCK_FOLDED?!1:t===k.BLOCK_LITERAL?!0:!Og(n,He.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
122
122
  `;let l="",f="";if(n=n.replace(/[\n\t ]*$/,h=>{const d=h.indexOf(`
123
123
  `);return d===-1?u+="-":(n===h||d!==h.length-1)&&(u+="+",s&&s()),f=h.replace(/\n$/,""),""}).replace(/^[\n ]*/,h=>{h.indexOf(" ")!==-1&&(u+=a);const d=h.match(/ +$/);return d?(l=h.slice(0,-d[0].length),d[0]):(l=h,"")}),f&&(f=f.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),e&&(u+=" #"+e.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
124
124
  ${i}${f}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
125
125
  ${i}${l}${n}${f}`;n=n.replace(/\n+/g,`
126
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const p=Nr(`${l}${n}${f}`,i,To,Xe.fold);return`${u}
127
- ${i}${p}`}function Gm(e,t,n,r){const{comment:o,type:s,value:i}=e,{actualString:a,implicitKey:c,indent:u,inFlow:l}=t;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return kt(i,t);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
128
- `)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?al(i,t):kt(i,t):tr(e,t,n,r);if(!c&&!l&&s!==j.PLAIN&&i.indexOf(`
129
- `)!==-1)return tr(e,t,n,r);if(u===""&&Or(i))return t.forceBlockIndent=!0,tr(e,t,n,r);const f=i.replace(/\n+/g,`$&
130
- ${u}`);if(a){const{tags:h}=t.doc.schema;if(typeof Ts(f,h,h.scalarFallback).value!="string")return kt(i,t)}const p=c?f:Nr(f,u,il,Cs(t));return o&&!l&&(p.indexOf(`
126
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const p=Sr(`${l}${n}${f}`,i,Ko,He.fold);return`${u}
127
+ ${i}${p}`}function _g(e,t,n,r){const{comment:o,type:s,value:i}=e,{actualString:a,implicitKey:c,indent:u,inFlow:l}=t;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return Nt(i,t);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
128
+ `)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?wl(i,t):Nt(i,t):Xn(e,t,n,r);if(!c&&!l&&s!==k.PLAIN&&i.indexOf(`
129
+ `)!==-1)return Xn(e,t,n,r);if(u===""&&Nr(i))return t.forceBlockIndent=!0,Xn(e,t,n,r);const f=i.replace(/\n+/g,`$&
130
+ ${u}`);if(a){const{tags:h}=t.doc.schema;if(typeof Ks(f,h,h.scalarFallback).value!="string")return Nt(i,t)}const p=c?f:Sr(f,u,vl,Gs(t));return o&&!l&&(p.indexOf(`
131
131
  `)!==-1||o.indexOf(`
132
- `)!==-1)?(n&&n(),qm(p,u,o)):p}function Rs(e,t,n,r){const{defaultType:o}=Xe,{implicitKey:s,inFlow:i}=t;let{type:a,value:c}=e;typeof c!="string"&&(c=String(c),e=Object.assign({},e,{value:c}));const u=f=>{switch(f){case j.BLOCK_FOLDED:case j.BLOCK_LITERAL:return tr(e,t,n,r);case j.QUOTE_DOUBLE:return kt(c,t);case j.QUOTE_SINGLE:return al(c,t);case j.PLAIN:return Gm(e,t,n,r);default:return null}};(a!==j.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===j.BLOCK_FOLDED||a===j.BLOCK_LITERAL))&&(a=j.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 Ye({format:e,minFractionDigits:t,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(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=t-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function cl(e,t){let n,r;switch(t.type){case j.FLOW_MAP:n="}",r="flow map";break;case j.FLOW_SEQ:n="]",r="flow sequence";break;default:e.push(new z(t,"Not a flow collection!?"));return}let o;for(let s=t.items.length-1;s>=0;--s){const i=t.items[s];if(!i||i.type!==j.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 z(t,s),i.offset=o.offset+1):(i=new z(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),e.push(i)}}function ul(e,t){const n=t.context.src[t.range.start-1];if(n!==`
133
- `&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";e.push(new z(t,r))}}function ll(e,t){const n=String(t),r=n.substr(0,8)+"..."+n.substr(-8);return new z(e,`The "${r}" key is too long`)}function fl(e,t){for(const{afterKey:n,before:r,comment:o}of t){let s=e.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
132
+ `)!==-1)?(n&&n(),Sg(p,u,o)):p}function zs(e,t,n,r){const{defaultType:o}=He,{implicitKey:s,inFlow:i}=t;let{type:a,value:c}=e;typeof c!="string"&&(c=String(c),e=Object.assign({},e,{value:c}));const u=f=>{switch(f){case k.BLOCK_FOLDED:case k.BLOCK_LITERAL:return Xn(e,t,n,r);case k.QUOTE_DOUBLE:return Nt(c,t);case k.QUOTE_SINGLE:return wl(c,t);case k.PLAIN:return _g(e,t,n,r);default:return null}};(a!==k.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===k.BLOCK_FOLDED||a===k.BLOCK_LITERAL))&&(a=k.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 Ke({format:e,minFractionDigits:t,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(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=t-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function bl(e,t){let n,r;switch(t.type){case k.FLOW_MAP:n="}",r="flow map";break;case k.FLOW_SEQ:n="]",r="flow sequence";break;default:e.push(new F(t,"Not a flow collection!?"));return}let o;for(let s=t.items.length-1;s>=0;--s){const i=t.items[s];if(!i||i.type!==k.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 F(t,s),i.offset=o.offset+1):(i=new F(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),e.push(i)}}function El(e,t){const n=t.context.src[t.range.start-1];if(n!==`
133
+ `&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";e.push(new F(t,r))}}function Sl(e,t){const n=String(t),r=n.substr(0,8)+"..."+n.substr(-8);return new F(e,`The "${r}" key is too long`)}function Nl(e,t){for(const{afterKey:n,before:r,comment:o}of t){let s=e.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
134
134
  `+o:s.commentBefore=o):o!==void 0&&(e.comment?e.comment+=`
135
- `+o:e.comment=o)}}function In(e,t){const n=t.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=t),e.errors.push(r)}),n.str):""}function Hm(e,t){const{handle:n,suffix:r}=t.tag;let o=e.tagPrefixes.find(s=>s.handle===n);if(!o){const s=e.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new z(t,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new z(t,`The ${n} tag has no suffix.`);if(n==="!"&&(e.version||e.options.version)==="1.0"){if(r[0]==="^")return e.warnings.push(new en(t,"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 Jm(e,t){const{tag:n,type:r}=t;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.`;e.errors.push(new z(t,c))}else if(s==="!"&&!i)o=!0;else try{return Hm(e,t)}catch(c){e.errors.push(c)}}switch(r){case j.BLOCK_FOLDED:case j.BLOCK_LITERAL:case j.QUOTE_DOUBLE:case j.QUOTE_SINGLE:return it.STR;case j.FLOW_MAP:case j.MAP:return it.MAP;case j.FLOW_SEQ:case j.SEQ:return it.SEQ;case j.PLAIN:return o?it.STR:null;default:return null}}function Fa(e,t,n){const{tags:r}=e.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(e,t);return a instanceof ge?a:new re(a)}const s=In(e,t);return typeof s=="string"&&o.length>0?Ts(s,o,r.scalarFallback):null}function Wm({type:e}){switch(e){case j.FLOW_MAP:case j.MAP:return it.MAP;case j.FLOW_SEQ:case j.SEQ:return it.SEQ;default:return it.STR}}function Qm(e,t,n){try{const r=Fa(e,t,n);if(r)return n&&t.tag&&(r.tag=n),r}catch(r){if(r instanceof jt)r.source||(r.source=t),e.errors.push(r);else{const o=r instanceof Error?r.message:String(r);e.errors.push(new z(t,o))}return null}try{const r=Wm(t);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;e.warnings.push(new en(t,o));const s=Fa(e,t,r);return s.tag=n,s}catch(r){const o=new Sn(t,r.message);return o.stack=r.stack,e.errors.push(o),null}}const Ym=e=>{if(!e)return!1;const{type:t}=e;return t===j.MAP_KEY||t===j.MAP_VALUE||t===j.SEQ_ITEM};function Zm(e,t){const n={before:[],after:[]};let r=!1,o=!1;const s=Ym(t.context.parent)?t.context.parent.props.concat(t.props):t.props;for(const{start:i,end:a}of s)switch(t.context.src[i]){case ce.COMMENT:{if(!t.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";e.push(new z(t,l))}const{header:c,valueRange:u}=t;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(t.context.src.slice(i+1,a));break}case ce.ANCHOR:if(r){const c="A node can have at most one anchor";e.push(new z(t,c))}r=!0;break;case ce.TAG:if(o){const c="A node can have at most one tag";e.push(new z(t,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function Xm(e,t){const{anchors:n,errors:r,schema:o}=e;if(t.type===j.ALIAS){const i=t.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new Sn(t,u)),null}const c=new Ze(a);return n._cstAliases.push(c),c}const s=Jm(e,t);if(s)return Qm(e,t,s);if(t.type!==j.PLAIN){const i=`Failed to resolve ${t.type} node here`;return r.push(new ye(t,i)),null}try{const i=In(e,t);return Ts(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=t),r.push(i),null}}function ct(e,t){if(!t)return null;t.error&&e.errors.push(t.error);const{comments:n,hasAnchor:r,hasTag:o}=Zm(e.errors,t);if(r){const{anchors:i}=e,a=t.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=t}if(t.type===j.ALIAS&&(r||o)){const i="An alias node must not specify any properties";e.errors.push(new z(t,i))}const s=Xm(e,t);if(s){s.range=[t.range.start,t.range.end],e.options.keepCstNodes&&(s.cstNode=t),e.options.keepNodeTypes&&(s.type=t.type);const i=n.before.join(`
135
+ `+o:e.comment=o)}}function kn(e,t){const n=t.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=t),e.errors.push(r)}),n.str):""}function kg(e,t){const{handle:n,suffix:r}=t.tag;let o=e.tagPrefixes.find(s=>s.handle===n);if(!o){const s=e.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new F(t,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new F(t,`The ${n} tag has no suffix.`);if(n==="!"&&(e.version||e.options.version)==="1.0"){if(r[0]==="^")return e.warnings.push(new Qt(t,"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 Ag(e,t){const{tag:n,type:r}=t;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.`;e.errors.push(new F(t,c))}else if(s==="!"&&!i)o=!0;else try{return kg(e,t)}catch(c){e.errors.push(c)}}switch(r){case k.BLOCK_FOLDED:case k.BLOCK_LITERAL:case k.QUOTE_DOUBLE:case k.QUOTE_SINGLE:return nt.STR;case k.FLOW_MAP:case k.MAP:return nt.MAP;case k.FLOW_SEQ:case k.SEQ:return nt.SEQ;case k.PLAIN:return o?nt.STR:null;default:return null}}function oc(e,t,n){const{tags:r}=e.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(e,t);return a instanceof ue?a:new Y(a)}const s=kn(e,t);return typeof s=="string"&&o.length>0?Ks(s,o,r.scalarFallback):null}function jg({type:e}){switch(e){case k.FLOW_MAP:case k.MAP:return nt.MAP;case k.FLOW_SEQ:case k.SEQ:return nt.SEQ;default:return nt.STR}}function Ig(e,t,n){try{const r=oc(e,t,n);if(r)return n&&t.tag&&(r.tag=n),r}catch(r){if(r instanceof Ot)r.source||(r.source=t),e.errors.push(r);else{const o=r instanceof Error?r.message:String(r);e.errors.push(new F(t,o))}return null}try{const r=jg(t);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;e.warnings.push(new Qt(t,o));const s=oc(e,t,r);return s.tag=n,s}catch(r){const o=new vn(t,r.message);return o.stack=r.stack,e.errors.push(o),null}}const Pg=e=>{if(!e)return!1;const{type:t}=e;return t===k.MAP_KEY||t===k.MAP_VALUE||t===k.SEQ_ITEM};function xg(e,t){const n={before:[],after:[]};let r=!1,o=!1;const s=Pg(t.context.parent)?t.context.parent.props.concat(t.props):t.props;for(const{start:i,end:a}of s)switch(t.context.src[i]){case re.COMMENT:{if(!t.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";e.push(new F(t,l))}const{header:c,valueRange:u}=t;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(t.context.src.slice(i+1,a));break}case re.ANCHOR:if(r){const c="A node can have at most one anchor";e.push(new F(t,c))}r=!0;break;case re.TAG:if(o){const c="A node can have at most one tag";e.push(new F(t,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function Tg(e,t){const{anchors:n,errors:r,schema:o}=e;if(t.type===k.ALIAS){const i=t.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new vn(t,u)),null}const c=new Je(a);return n._cstAliases.push(c),c}const s=Ag(e,t);if(s)return Ig(e,t,s);if(t.type!==k.PLAIN){const i=`Failed to resolve ${t.type} node here`;return r.push(new le(t,i)),null}try{const i=kn(e,t);return Ks(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=t),r.push(i),null}}function ot(e,t){if(!t)return null;t.error&&e.errors.push(t.error);const{comments:n,hasAnchor:r,hasTag:o}=xg(e.errors,t);if(r){const{anchors:i}=e,a=t.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=t}if(t.type===k.ALIAS&&(r||o)){const i="An alias node must not specify any properties";e.errors.push(new F(t,i))}const s=Tg(e,t);if(s){s.range=[t.range.start,t.range.end],e.options.keepCstNodes&&(s.cstNode=t),e.options.keepNodeTypes&&(s.type=t.type);const i=n.before.join(`
136
136
  `);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
137
137
  ${i}`:i);const a=n.after.join(`
138
138
  `);a&&(s.comment=s.comment?`${s.comment}
139
- ${a}`:a)}return t.resolved=s}function dl(e,t){if(t.type!==j.MAP&&t.type!==j.FLOW_MAP){const i=`A ${t.type} node cannot be resolved as a mapping`;return e.errors.push(new ye(t,i)),null}const{comments:n,items:r}=t.type===j.FLOW_MAP?rg(e,t):ng(e,t),o=new Ee;o.items=r,fl(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof ge&&(s=!0),e.schema.merge&&a&&a.value===ol){r[i]=new sl(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof Ze){const{type:f}=l.source;return f===j.MAP||f===j.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&e.errors.push(new z(t,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`;e.errors.push(new z(t,l));break}}}if(s&&!e.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new en(t,i))}return t.resolved=o,o}const eg=({context:{lineStart:e,node:t,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(t&&o>t.valueRange.start||n[o]!==ce.COMMENT)return!1;for(let s=e;s<o;++s)if(n[s]===`
140
- `)return!1;return!0};function tg(e,t){if(!eg(e))return;const n=e.getPropValue(0,ce.COMMENT,!0);let r=!1;const o=t.value.commentBefore;if(o&&o.startsWith(n))t.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=t.value.comment;!e.node&&s&&s.startsWith(n)&&(t.value.comment=s.substr(n.length+1),r=!0)}r&&(t.comment=n)}function ng(e,t){const n=[],r=[];let o,s=null;for(let i=0;i<t.items.length;++i){const a=t.items[i];switch(a.type){case j.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case j.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case j.MAP_KEY:o!==void 0&&r.push(new Z(o)),a.error&&e.errors.push(a.error),o=ct(e,a.node),s=null;break;case j.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&e.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===j.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";e.errors.push(new z(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new el(j.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 f=a.range.origStart+1;c.range.origStart=c.range.origEnd=f,c.valueRange.origStart=c.valueRange.origEnd=f}}const u=new Z(o,ct(e,c));tg(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&e.errors.push(ll(t,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new Z(o)),o=ct(e,a),s=a.range.start,a.error&&e.errors.push(a.error);e:for(let c=i+1;;++c){const u=t.items[c];switch(u&&u.type){case j.BLANK_LINE:case j.COMMENT:continue e;case j.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";e.errors.push(new z(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";e.errors.push(new z(a,c))}}}return o!==void 0&&r.push(new Z(o)),{comments:n,items:r}}function rg(e,t){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<t.items.length;++a){const c=t.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 Z(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===t.items.length-1)continue}else if(u===i){i=":";continue}const f=`Flow map contains an unexpected ${u}`,p=new ye(t,f);p.offset=l,e.errors.push(p)}else c.type===j.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===j.COMMENT?(ul(e.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&e.errors.push(new z(c,"Separator , missing in flow map")),o=ct(e,c)):(i!==","&&e.errors.push(new z(c,"Indicator : missing in flow map entry")),r.push(new Z(o,ct(e,c))),o=void 0,s=!1)}return cl(e.errors,t),o!==void 0&&r.push(new Z(o)),{comments:n,items:r}}function pl(e,t){if(t.type!==j.SEQ&&t.type!==j.FLOW_SEQ){const s=`A ${t.type} node cannot be resolved as a sequence`;return e.errors.push(new ye(t,s)),null}const{comments:n,items:r}=t.type===j.FLOW_SEQ?sg(e,t):og(e,t),o=new qe;if(o.items=r,fl(o,n),!e.options.mapAsMap&&r.some(s=>s instanceof Z&&s.key instanceof ge)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new en(t,s))}return t.resolved=o,o}function og(e,t){const n=[],r=[];for(let o=0;o<t.items.length;++o){const s=t.items[o];switch(s.type){case j.BLANK_LINE:n.push({before:r.length});break;case j.COMMENT:n.push({comment:s.comment,before:r.length});break;case j.SEQ_ITEM:if(s.error&&e.errors.push(s.error),r.push(ct(e,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";e.errors.push(new z(s,i))}break;default:s.error&&e.errors.push(s.error),e.errors.push(new ye(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function sg(e,t){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<t.items.length;++u){const l=t.items[u];if(typeof l.char=="string"){const{char:f,offset:p}=l;if(f!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new Z(s)),o=!1,s=void 0,i=null),f===a)a=null;else if(!a&&f==="?")o=!0;else if(a!=="["&&f===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof Z){const h="Chaining flow sequence pairs is invalid",d=new z(t,h);d.offset=p,e.errors.push(d)}if(!o&&typeof i=="number"){const h=l.range?l.range.start:l.offset;h>i+1024&&e.errors.push(ll(t,s));const{src:d}=c.context;for(let m=i;m<h;++m)if(d[m]===`
141
- `){const g="Implicit keys of flow sequence pairs need to be on a single line";e.errors.push(new z(c,g));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||f!=="]"||u<t.items.length-1){const h=`Flow sequence contains an unexpected ${f}`,d=new ye(t,h);d.offset=p,e.errors.push(d)}}else if(l.type===j.BLANK_LINE)n.push({before:r.length});else if(l.type===j.COMMENT)ul(e.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const p=`Expected a ${a} in flow sequence`;e.errors.push(new z(l,p))}const f=ct(e,l);s===void 0?(r.push(f),c=l):(r.push(new Z(s,f)),s=void 0),i=l.range.start,a=","}}return cl(e.errors,t),s!==void 0&&r.push(new Z(s)),{comments:n,items:r}}const hl={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(e,t)=>{const n=In(e,t);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 e.errors.push(new Sn(t,r)),null}},options:yn,stringify:({comment:e,type:t,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(t||(t=yn.defaultType),t===j.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=yn,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,f=0;l<c;++l,f+=a)u[l]=i.substr(f,a);n=u.join(t===j.BLOCK_LITERAL?`
142
- `:" ")}return Rs({comment:e,type:t,value:n},r,o,s)}};function ml(e,t){const n=pl(e,t);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof Z)){if(o instanceof Ee){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new z(t,i)}const s=o.items[0]||new Z;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
139
+ ${a}`:a)}return t.resolved=s}function Ol(e,t){if(t.type!==k.MAP&&t.type!==k.FLOW_MAP){const i=`A ${t.type} node cannot be resolved as a mapping`;return e.errors.push(new le(t,i)),null}const{comments:n,items:r}=t.type===k.FLOW_MAP?Dg(e,t):Mg(e,t),o=new ye;o.items=r,Nl(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof ue&&(s=!0),e.schema.merge&&a&&a.value===yl){r[i]=new $l(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof Je){const{type:f}=l.source;return f===k.MAP||f===k.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&e.errors.push(new F(t,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`;e.errors.push(new F(t,l));break}}}if(s&&!e.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new Qt(t,i))}return t.resolved=o,o}const Cg=({context:{lineStart:e,node:t,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(t&&o>t.valueRange.start||n[o]!==re.COMMENT)return!1;for(let s=e;s<o;++s)if(n[s]===`
140
+ `)return!1;return!0};function Rg(e,t){if(!Cg(e))return;const n=e.getPropValue(0,re.COMMENT,!0);let r=!1;const o=t.value.commentBefore;if(o&&o.startsWith(n))t.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=t.value.comment;!e.node&&s&&s.startsWith(n)&&(t.value.comment=s.substr(n.length+1),r=!0)}r&&(t.comment=n)}function Mg(e,t){const n=[],r=[];let o,s=null;for(let i=0;i<t.items.length;++i){const a=t.items[i];switch(a.type){case k.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case k.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case k.MAP_KEY:o!==void 0&&r.push(new z(o)),a.error&&e.errors.push(a.error),o=ot(e,a.node),s=null;break;case k.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&e.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===k.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";e.errors.push(new F(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new pl(k.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 f=a.range.origStart+1;c.range.origStart=c.range.origEnd=f,c.valueRange.origStart=c.valueRange.origEnd=f}}const u=new z(o,ot(e,c));Rg(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&e.errors.push(Sl(t,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new z(o)),o=ot(e,a),s=a.range.start,a.error&&e.errors.push(a.error);e:for(let c=i+1;;++c){const u=t.items[c];switch(u&&u.type){case k.BLANK_LINE:case k.COMMENT:continue e;case k.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";e.errors.push(new F(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";e.errors.push(new F(a,c))}}}return o!==void 0&&r.push(new z(o)),{comments:n,items:r}}function Dg(e,t){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<t.items.length;++a){const c=t.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 z(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===t.items.length-1)continue}else if(u===i){i=":";continue}const f=`Flow map contains an unexpected ${u}`,p=new le(t,f);p.offset=l,e.errors.push(p)}else c.type===k.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===k.COMMENT?(El(e.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&e.errors.push(new F(c,"Separator , missing in flow map")),o=ot(e,c)):(i!==","&&e.errors.push(new F(c,"Indicator : missing in flow map entry")),r.push(new z(o,ot(e,c))),o=void 0,s=!1)}return bl(e.errors,t),o!==void 0&&r.push(new z(o)),{comments:n,items:r}}function _l(e,t){if(t.type!==k.SEQ&&t.type!==k.FLOW_SEQ){const s=`A ${t.type} node cannot be resolved as a sequence`;return e.errors.push(new le(t,s)),null}const{comments:n,items:r}=t.type===k.FLOW_SEQ?Bg(e,t):Lg(e,t),o=new De;if(o.items=r,Nl(o,n),!e.options.mapAsMap&&r.some(s=>s instanceof z&&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.";e.warnings.push(new Qt(t,s))}return t.resolved=o,o}function Lg(e,t){const n=[],r=[];for(let o=0;o<t.items.length;++o){const s=t.items[o];switch(s.type){case k.BLANK_LINE:n.push({before:r.length});break;case k.COMMENT:n.push({comment:s.comment,before:r.length});break;case k.SEQ_ITEM:if(s.error&&e.errors.push(s.error),r.push(ot(e,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";e.errors.push(new F(s,i))}break;default:s.error&&e.errors.push(s.error),e.errors.push(new le(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function Bg(e,t){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<t.items.length;++u){const l=t.items[u];if(typeof l.char=="string"){const{char:f,offset:p}=l;if(f!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new z(s)),o=!1,s=void 0,i=null),f===a)a=null;else if(!a&&f==="?")o=!0;else if(a!=="["&&f===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof z){const h="Chaining flow sequence pairs is invalid",d=new F(t,h);d.offset=p,e.errors.push(d)}if(!o&&typeof i=="number"){const h=l.range?l.range.start:l.offset;h>i+1024&&e.errors.push(Sl(t,s));const{src:d}=c.context;for(let g=i;g<h;++g)if(d[g]===`
141
+ `){const y="Implicit keys of flow sequence pairs need to be on a single line";e.errors.push(new F(c,y));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||f!=="]"||u<t.items.length-1){const h=`Flow sequence contains an unexpected ${f}`,d=new le(t,h);d.offset=p,e.errors.push(d)}}else if(l.type===k.BLANK_LINE)n.push({before:r.length});else if(l.type===k.COMMENT)El(e.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const p=`Expected a ${a} in flow sequence`;e.errors.push(new F(l,p))}const f=ot(e,l);s===void 0?(r.push(f),c=l):(r.push(new z(s,f)),s=void 0),i=l.range.start,a=","}}return bl(e.errors,t),s!==void 0&&r.push(new z(s)),{comments:n,items:r}}const kl={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(e,t)=>{const n=kn(e,t);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 e.errors.push(new vn(t,r)),null}},options:pn,stringify:({comment:e,type:t,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(t||(t=pn.defaultType),t===k.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=pn,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,f=0;l<c;++l,f+=a)u[l]=i.substr(f,a);n=u.join(t===k.BLOCK_LITERAL?`
142
+ `:" ")}return zs({comment:e,type:t,value:n},r,o,s)}};function Al(e,t){const n=_l(e,t);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof z)){if(o instanceof ye){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new F(t,i)}const s=o.items[0]||new z;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
143
143
  ${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
144
- ${s.comment}`:o.comment),o=s}n.items[r]=o instanceof Z?o:new Z(o)}}return n}function gl(e,t,n){const r=new qe(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 yl={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ml,createNode:gl};let _r=class $l extends qe{constructor(){super(),$e(this,"add",Ee.prototype.add.bind(this)),$e(this,"delete",Ee.prototype.delete.bind(this)),$e(this,"get",Ee.prototype.get.bind(this)),$e(this,"has",Ee.prototype.has.bind(this)),$e(this,"set",Ee.prototype.set.bind(this)),this.tag=$l.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 Z?(s=Ue(o.key,"",n),i=Ue(o.value,s,n)):s=Ue(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};$e(_r,"tag","tag:yaml.org,2002:omap");function ig(e,t){const n=ml(e,t),r=[];for(const{key:o}of n.items)if(o instanceof re)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new z(t,s)}else r.push(o.value);return Object.assign(new _r,n)}function ag(e,t,n){const r=gl(e,t,n),o=new _r;return o.items=r.items,o}const vl={identify:e=>e instanceof Map,nodeClass:_r,default:!1,tag:"tag:yaml.org,2002:omap",resolve:ig,createNode:ag};class tn extends Ee{constructor(){super(),this.tag=tn.tag}add(t){const n=t instanceof Z?t:new Z(t);Nt(this.items,n.key)||this.items.push(n)}get(t,n){const r=Nt(this.items,t);return!n&&r instanceof Z?r.key instanceof re?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=Nt(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Z(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")}}$e(tn,"tag","tag:yaml.org,2002:set");function cg(e,t){const n=dl(e,t);if(!n.hasAllNullValues())throw new z(t,"Set items must all have null values");return Object.assign(new tn,n)}function ug(e,t,n){const r=new tn;for(const o of t)r.items.push(e.createPair(o,null,n));return r}const wl={identify:e=>e instanceof Set,nodeClass:tn,default:!1,tag:"tag:yaml.org,2002:set",resolve:cg,createNode:ug},Ms=(e,t)=>{const n=t.split(":").reduce((r,o)=>r*60+Number(o),0);return e==="-"?-n:n},bl=({value:e})=>{if(isNaN(e)||!isFinite(e))return Ye(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*$/,"")},Sl={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)=>Ms(t,n.replace(/_/g,"")),stringify:bl},El={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)=>Ms(t,n.replace(/_/g,"")),stringify:bl},Nl={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=Ms(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 Ol(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 _l(e,t){if(Ol(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(e,t):console.warn(t?`${t}: ${e}`:e)}}const Va={};function lg(e,t){if(!Va[e]&&Ol(!0)){Va[e]=!0;let n=`The option '${e}' will be removed in a future release`;n+=`, use '${t}' instead.`,_l(n,"DeprecationWarning")}}function fg(e,t,n){const r=new Ee(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 Nn={createNode:fg,default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve:dl};function dg(e,t,n){const r=new qe(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 Ar={createNode:dg,default:!0,nodeClass:qe,tag:"tag:yaml.org,2002:seq",resolve:pl},pg={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:In,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),Rs(e,t,n,r)},options:Xe},Ds=[Nn,Ar,pg],kr=e=>typeof e=="bigint"||Number.isInteger(e),Ls=(e,t,n)=>ut.asBigInt?BigInt(e):parseInt(t,n);function Al(e,t,n){const{value:r}=e;return kr(r)&&r>=0?n+r.toString(t):Ye(e)}const kl={identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new re(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Yt,stringify:()=>Yt.nullStr},jl={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:Qe,stringify:({value:e})=>e?Qe.trueStr:Qe.falseStr},Il={identify:e=>kr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(e,t)=>Ls(e,t,8),options:ut,stringify:e=>Al(e,8,"0o")},xl={identify:kr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:e=>Ls(e,e,10),options:ut,stringify:Ye},Pl={identify:e=>kr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(e,t)=>Ls(e,t,16),options:ut,stringify:e=>Al(e,16,"0x")},Tl={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:Ye},Cl={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()},Rl={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 re(parseFloat(e));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Ye},hg=Ds.concat([kl,jl,Il,xl,Pl,Tl,Cl,Rl]),qa=e=>typeof e=="bigint"||Number.isInteger(e),Mn=({value:e})=>JSON.stringify(e),Ml=[Nn,Ar,{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:In,stringify:Mn},{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new re(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Mn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:Mn},{identify:qa,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:e=>ut.asBigInt?BigInt(e):parseInt(e,10),stringify:({value:e})=>qa(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:Mn}];Ml.scalarFallback=e=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(e)}`)};const Ka=({value:e})=>e?Qe.trueStr:Qe.falseStr,pn=e=>typeof e=="bigint"||Number.isInteger(e);function Dn(e,t,n){let r=t.replace(/_/g,"");if(ut.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 Zr(e,t,n){const{value:r}=e;if(pn(r)){const o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return Ye(e)}const mg=Ds.concat([{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new re(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Yt,stringify:()=>Yt.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:Qe,stringify:Ka},{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:Qe,stringify:Ka},{identify:pn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(e,t,n)=>Dn(t,n,2),stringify:e=>Zr(e,2,"0b")},{identify:pn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(e,t,n)=>Dn(t,n,8),stringify:e=>Zr(e,8,"0")},{identify:pn,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(e,t,n)=>Dn(t,n,10),stringify:Ye},{identify:pn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(e,t,n)=>Dn(t,n,16),stringify:e=>Zr(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:Ye},{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 re(parseFloat(e.replace(/_/g,"")));if(t){const r=t.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Ye}],hl,vl,yl,wl,Sl,El,Nl),gg={core:hg,failsafe:Ds,json:Ml,yaml11:mg},yg={binary:hl,bool:jl,float:Rl,floatExp:Cl,floatNaN:Tl,floatTime:El,int:xl,intHex:Pl,intOct:Il,intTime:Sl,map:Nn,null:kl,omap:vl,pairs:yl,seq:Ar,set:wl,timestamp:Nl};function $g(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 vg(e,t,n){if(e instanceof Se)return e;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;t&&t.startsWith("!!")&&(t=r+t.slice(2));let c=$g(e,t,i.tags);if(!c){if(typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object")return a?new re(e):e;c=e instanceof Map?Nn:e[Symbol.iterator]?Ar:Nn}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 Ze(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 re(e):e,t&&u.node instanceof Se&&(u.node.tag=t),u.node}function wg(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 bg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;let On=class Dl{constructor({customTags:t,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?bg:o||null,!t&&s&&lg("tags","customTags"),this.tags=wg(gg,yg,t||s,r)}createNode(t,n,r,o){const s={defaultPrefix:Dl.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return vg(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 Z(o,s)}};$e(On,"defaultPrefix",Yn);$e(On,"defaultTags",it);const dr={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"},Sg={get binary(){return yn},set binary(e){Object.assign(yn,e)},get bool(){return Qe},set bool(e){Object.assign(Qe,e)},get int(){return ut},set int(e){Object.assign(ut,e)},get null(){return Yt},set null(e){Object.assign(Yt,e)},get str(){return Xe},set str(e){Object.assign(Xe,e)}},Ll={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:Yn},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Yn}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Yn}]}};function za(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 Eg(e,t){if(t instanceof Ze)return Ze;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 re){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 Ng(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(za(r,e.tag)):t.default||o.push(za(r,t.tag)),o.join(" ")}function Ln(e,t,n,r){const{anchors:o,schema:s}=t.doc;let i;if(!(e instanceof Se)){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 Z)return e.toString(t,n,r);i||(i=Eg(s.tags,e));const a=Ng(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 re?Rs(e,t,n,r):e.toString(t,n,r);return a?e instanceof re||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
145
- ${t.indent}${c}`:c}class Us{static validAnchorNode(t){return t instanceof re||t instanceof qe||t instanceof Ee}constructor(t){$e(this,"map",Object.create(null)),this.prefix=t}createAlias(t,n){return this.setAnchor(t,n),new Ze(t)}createMergePair(...t){const n=new sl;return n.value.items=t.map(r=>{if(r instanceof Ze){if(r.source instanceof Ee)return r}else if(r instanceof Ee)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(t){const{map:n}=this;return Object.keys(n).find(r=>n[r]===t)}getNames(){return Object.keys(this.map)}getNode(t){return this.map[t]}newName(t){t||(t=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${t}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:t,_cstAliases:n}=this;Object.keys(t).forEach(r=>{t[r]=t[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(t,n){if(t!=null&&!Us.validAnchorNode(t))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=t&&Object.keys(r).find(s=>r[s]===t);if(o)if(n)o!==n&&(delete r[o],r[n]=t);else return o;else{if(!n){if(!t)return null;n=this.newName()}r[n]=t}return n}}const nr=(e,t)=>{if(e&&typeof e=="object"){const{tag:n}=e;e instanceof ge?(n&&(t[n]=!0),e.items.forEach(r=>nr(r,t))):e instanceof Z?(nr(e.key,t),nr(e.value,t)):e instanceof re&&n&&(t[n]=!0)}return t},Og=e=>Object.keys(nr(e,{}));function _g(e,t){const n={before:[],after:[]};let r,o=!1;for(const s of t)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";e.errors.push(new ye(s,a));break}const i=ct(e,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===j.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!e.commentBefore&&(e.commentBefore=n.before.join(`
144
+ ${s.comment}`:o.comment),o=s}n.items[r]=o instanceof z?o:new z(o)}}return n}function jl(e,t,n){const r=new De(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 Il={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Al,createNode:jl};let Or=class Pl extends De{constructor(){super(),pe(this,"add",ye.prototype.add.bind(this)),pe(this,"delete",ye.prototype.delete.bind(this)),pe(this,"get",ye.prototype.get.bind(this)),pe(this,"has",ye.prototype.has.bind(this)),pe(this,"set",ye.prototype.set.bind(this)),this.tag=Pl.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 z?(s=Pe(o.key,"",n),i=Pe(o.value,s,n)):s=Pe(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};pe(Or,"tag","tag:yaml.org,2002:omap");function Ug(e,t){const n=Al(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 Or,n)}function Fg(e,t,n){const r=jl(e,t,n),o=new Or;return o.items=r.items,o}const xl={identify:e=>e instanceof Map,nodeClass:Or,default:!1,tag:"tag:yaml.org,2002:omap",resolve:Ug,createNode:Fg};let _r=class Tl extends ye{constructor(){super(),this.tag=Tl.tag}add(t){const n=t instanceof z?t:new z(t);wt(this.items,n.key)||this.items.push(n)}get(t,n){const r=wt(this.items,t);return!n&&r instanceof z?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=wt(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new z(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")}};pe(_r,"tag","tag:yaml.org,2002:set");function Vg(e,t){const n=Ol(e,t);if(!n.hasAllNullValues())throw new F(t,"Set items must all have null values");return Object.assign(new _r,n)}function qg(e,t,n){const r=new _r;for(const o of t)r.items.push(e.createPair(o,null,n));return r}const Cl={identify:e=>e instanceof Set,nodeClass:_r,default:!1,tag:"tag:yaml.org,2002:set",resolve:Vg,createNode:qg},Ws=(e,t)=>{const n=t.split(":").reduce((r,o)=>r*60+Number(o),0);return e==="-"?-n:n},Rl=({value:e})=>{if(isNaN(e)||!isFinite(e))return Ke(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*$/,"")},Ml={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)=>Ws(t,n.replace(/_/g,"")),stringify:Rl},Dl={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)=>Ws(t,n.replace(/_/g,"")),stringify:Rl},Ll={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=Ws(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 Bl(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 Ul(e,t){if(Bl(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(e,t):console.warn(t?`${t}: ${e}`:e)}}const sc={};function Kg(e,t){if(!sc[e]&&Bl(!0)){sc[e]=!0;let n=`The option '${e}' will be removed in a future release`;n+=`, use '${t}' instead.`,Ul(n,"DeprecationWarning")}}function Gg(e,t,n){const r=new ye(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 bn={createNode:Gg,default:!0,nodeClass:ye,tag:"tag:yaml.org,2002:map",resolve:Ol};function zg(e,t,n){const r=new De(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 kr={createNode:zg,default:!0,nodeClass:De,tag:"tag:yaml.org,2002:seq",resolve:_l},Wg={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:kn,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),zs(e,t,n,r)},options:He},Js=[bn,kr,Wg],Ar=e=>typeof e=="bigint"||Number.isInteger(e),Hs=(e,t,n)=>it.asBigInt?BigInt(e):parseInt(t,n);function Fl(e,t,n){const{value:r}=e;return Ar(r)&&r>=0?n+r.toString(t):Ke(e)}const Vl={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:Wt,stringify:()=>Wt.nullStr},ql={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:qe,stringify:({value:e})=>e?qe.trueStr:qe.falseStr},Kl={identify:e=>Ar(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(e,t)=>Hs(e,t,8),options:it,stringify:e=>Fl(e,8,"0o")},Gl={identify:Ar,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:e=>Hs(e,e,10),options:it,stringify:Ke},zl={identify:e=>Ar(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(e,t)=>Hs(e,t,16),options:it,stringify:e=>Fl(e,16,"0x")},Wl={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:Ke},Jl={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()},Hl={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:Ke},Jg=Js.concat([Vl,ql,Kl,Gl,zl,Wl,Jl,Hl]),ic=e=>typeof e=="bigint"||Number.isInteger(e),Rn=({value:e})=>JSON.stringify(e),Yl=[bn,kr,{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:kn,stringify:Rn},{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:Rn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:Rn},{identify:ic,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:e=>it.asBigInt?BigInt(e):parseInt(e,10),stringify:({value:e})=>ic(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:Rn}];Yl.scalarFallback=e=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(e)}`)};const ac=({value:e})=>e?qe.trueStr:qe.falseStr,un=e=>typeof e=="bigint"||Number.isInteger(e);function Mn(e,t,n){let r=t.replace(/_/g,"");if(it.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 uo(e,t,n){const{value:r}=e;if(un(r)){const o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return Ke(e)}const Hg=Js.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:Wt,stringify:()=>Wt.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:qe,stringify:ac},{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:qe,stringify:ac},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(e,t,n)=>Mn(t,n,2),stringify:e=>uo(e,2,"0b")},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(e,t,n)=>Mn(t,n,8),stringify:e=>uo(e,8,"0")},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(e,t,n)=>Mn(t,n,10),stringify:Ke},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(e,t,n)=>Mn(t,n,16),stringify:e=>uo(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:Ke},{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:Ke}],kl,xl,Il,Cl,Ml,Dl,Ll),Yg={core:Jg,failsafe:Js,json:Yl,yaml11:Hg},Qg={binary:kl,bool:ql,float:Hl,floatExp:Jl,floatNaN:Wl,floatTime:Dl,int:Gl,intHex:zl,intOct:Kl,intTime:Ml,map:bn,null:Vl,omap:xl,pairs:Il,seq:kr,set:Cl,timestamp:Ll};function Zg(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 Xg(e,t,n){if(e instanceof ge)return e;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;t&&t.startsWith("!!")&&(t=r+t.slice(2));let c=Zg(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?bn:e[Symbol.iterator]?kr:bn}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 Je(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 ge&&(u.node.tag=t),u.node}function ey(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 ty=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;let En=class Ql{constructor({customTags:t,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?ty:o||null,!t&&s&&Kg("tags","customTags"),this.tags=ey(Yg,Qg,t||s,r)}createNode(t,n,r,o){const s={defaultPrefix:Ql.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return Xg(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 z(o,s)}};pe(En,"defaultPrefix",Hn);pe(En,"defaultTags",nt);const lr={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"},ny={get binary(){return pn},set binary(e){Object.assign(pn,e)},get bool(){return qe},set bool(e){Object.assign(qe,e)},get int(){return it},set int(e){Object.assign(it,e)},get null(){return Wt},set null(e){Object.assign(Wt,e)},get str(){return He},set str(e){Object.assign(He,e)}},Zl={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:Hn},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Hn}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Hn}]}};function cc(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 ry(e,t){if(t instanceof Je)return Je;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 oy(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(cc(r,e.tag)):t.default||o.push(cc(r,t.tag)),o.join(" ")}function Dn(e,t,n,r){const{anchors:o,schema:s}=t.doc;let i;if(!(e instanceof ge)){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 z)return e.toString(t,n,r);i||(i=ry(s.tags,e));const a=oy(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?zs(e,t,n,r):e.toString(t,n,r);return a?e instanceof Y||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
145
+ ${t.indent}${c}`:c}class Ys{static validAnchorNode(t){return t instanceof Y||t instanceof De||t instanceof ye}constructor(t){pe(this,"map",Object.create(null)),this.prefix=t}createAlias(t,n){return this.setAnchor(t,n),new Je(t)}createMergePair(...t){const n=new $l;return n.value.items=t.map(r=>{if(r instanceof Je){if(r.source instanceof ye)return r}else if(r instanceof ye)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(t){const{map:n}=this;return Object.keys(n).find(r=>n[r]===t)}getNames(){return Object.keys(this.map)}getNode(t){return this.map[t]}newName(t){t||(t=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${t}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:t,_cstAliases:n}=this;Object.keys(t).forEach(r=>{t[r]=t[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(t,n){if(t!=null&&!Ys.validAnchorNode(t))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=t&&Object.keys(r).find(s=>r[s]===t);if(o)if(n)o!==n&&(delete r[o],r[n]=t);else return o;else{if(!n){if(!t)return null;n=this.newName()}r[n]=t}return n}}const er=(e,t)=>{if(e&&typeof e=="object"){const{tag:n}=e;e instanceof ue?(n&&(t[n]=!0),e.items.forEach(r=>er(r,t))):e instanceof z?(er(e.key,t),er(e.value,t)):e instanceof Y&&n&&(t[n]=!0)}return t},sy=e=>Object.keys(er(e,{}));function iy(e,t){const n={before:[],after:[]};let r,o=!1;for(const s of t)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";e.errors.push(new le(s,a));break}const i=ot(e,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===k.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!e.commentBefore&&(e.commentBefore=n.before.join(`
146
146
  `),n.before=[]));if(e.contents=r||null,!r)e.comment=n.before.concat(n.after).join(`
147
147
  `)||null;else{const s=n.before.join(`
148
- `);if(s){const i=r instanceof ge&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
148
+ `);if(s){const i=r instanceof ue&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
149
149
  ${i.commentBefore}`:s}e.comment=n.after.join(`
150
- `)||null}}function Ag({tagPrefixes:e},t){const[n,r]=t.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new z(t,o)}if(e.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 z(t,o)}return{handle:n,prefix:r}}function kg(e,t){let[n]=t.parameters;if(t.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new z(t,r)}if(!Ll[n]){const r=`Document will be parsed as YAML ${e.version||e.options.version} rather than YAML ${n}`;e.warnings.push(new en(t,r))}return n}function jg(e,t,n){const r=[];let o=!1;for(const s of t){const{comment:i,name:a}=s;switch(a){case"TAG":try{e.tagPrefixes.push(Ag(e,s))}catch(c){e.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(e.version){const c="The %YAML directive must only be given at most once per document.";e.errors.push(new z(s,c))}try{e.version=kg(e,s)}catch(c){e.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;e.warnings.push(new en(s,c))}}i&&r.push(i)}if(n&&!o&&(e.version||n.version||e.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});e.tagPrefixes=n.tagPrefixes.map(s),e.version=n.version}e.commentBefore=r.join(`
151
- `)||null}function Rt(e){if(e instanceof ge)return!0;throw new Error("Expected a YAML collection as document contents")}let Bs=class Co{constructor(t){this.anchors=new Us(t.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=t,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(t){return Rt(this.contents),this.contents.add(t)}addIn(t,n){Rt(this.contents),this.contents.addIn(t,n)}delete(t){return Rt(this.contents),this.contents.delete(t)}deleteIn(t){return dn(t)?this.contents==null?!1:(this.contents=null,!0):(Rt(this.contents),this.contents.deleteIn(t))}getDefaults(){return Co.defaults[this.version]||Co.defaults[this.options.version]||{}}get(t,n){return this.contents instanceof ge?this.contents.get(t,n):void 0}getIn(t,n){return dn(t)?!n&&this.contents instanceof re?this.contents.value:this.contents:this.contents instanceof ge?this.contents.getIn(t,n):void 0}has(t){return this.contents instanceof ge?this.contents.has(t):!1}hasIn(t){return dn(t)?this.contents!==void 0:this.contents instanceof ge?this.contents.hasIn(t):!1}set(t,n){Rt(this.contents),this.contents.set(t,n)}setIn(t,n){dn(t)?this.contents=n:(Rt(this.contents),this.contents.setIn(t,n))}setSchema(t,n){if(!t&&!n&&this.schema)return;typeof t=="number"&&(t=t.toFixed(1)),t==="1.0"||t==="1.1"||t==="1.2"?(this.version?this.version=t:this.options.version=t,delete this.options.schema):t&&typeof t=="string"&&(this.options.schema=t),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new On(r)}parse(t,n){this.options.keepCstNodes&&(this.cstNode=t),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=t;if(i&&(i.source||(i.source=this),this.errors.push(i)),jg(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],_g(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof jt&&c.makePretty();for(const c of this.warnings)c instanceof jt&&c.makePretty()}return this}listNonDefaultTags(){return Og(this.contents).filter(t=>t.indexOf(On.defaultPrefix)!==0)}setTagPrefix(t,n){if(t[0]!=="!"||t[t.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===t);r?r.prefix=n:this.tagPrefixes.push({handle:t,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==t)}toJSON(t,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof t!="string"||!(this.contents instanceof re)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Ln},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=Ue(this.contents,t,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:f}of a.anchors.values())n(f,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const t=this.options.indent;if(!Number.isInteger(t)||t<=0){const c=JSON.stringify(t);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(t),stringify:Ln};let i=!1,a=null;if(this.contents){this.contents instanceof Se&&(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=Ln(this.contents,s,()=>a=null,c);n.push(Gt(u,"",a))}else this.contents!==void 0&&n.push(Ln(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
150
+ `)||null}}function ay({tagPrefixes:e},t){const[n,r]=t.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new F(t,o)}if(e.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 F(t,o)}return{handle:n,prefix:r}}function cy(e,t){let[n]=t.parameters;if(t.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new F(t,r)}if(!Zl[n]){const r=`Document will be parsed as YAML ${e.version||e.options.version} rather than YAML ${n}`;e.warnings.push(new Qt(t,r))}return n}function uy(e,t,n){const r=[];let o=!1;for(const s of t){const{comment:i,name:a}=s;switch(a){case"TAG":try{e.tagPrefixes.push(ay(e,s))}catch(c){e.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(e.version){const c="The %YAML directive must only be given at most once per document.";e.errors.push(new F(s,c))}try{e.version=cy(e,s)}catch(c){e.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;e.warnings.push(new Qt(s,c))}}i&&r.push(i)}if(n&&!o&&(e.version||n.version||e.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});e.tagPrefixes=n.tagPrefixes.map(s),e.version=n.version}e.commentBefore=r.join(`
151
+ `)||null}function It(e){if(e instanceof ue)return!0;throw new Error("Expected a YAML collection as document contents")}let Qs=class Go{constructor(t){this.anchors=new Ys(t.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=t,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(t){return It(this.contents),this.contents.add(t)}addIn(t,n){It(this.contents),this.contents.addIn(t,n)}delete(t){return It(this.contents),this.contents.delete(t)}deleteIn(t){return cn(t)?this.contents==null?!1:(this.contents=null,!0):(It(this.contents),this.contents.deleteIn(t))}getDefaults(){return Go.defaults[this.version]||Go.defaults[this.options.version]||{}}get(t,n){return this.contents instanceof ue?this.contents.get(t,n):void 0}getIn(t,n){return cn(t)?!n&&this.contents instanceof Y?this.contents.value:this.contents:this.contents instanceof ue?this.contents.getIn(t,n):void 0}has(t){return this.contents instanceof ue?this.contents.has(t):!1}hasIn(t){return cn(t)?this.contents!==void 0:this.contents instanceof ue?this.contents.hasIn(t):!1}set(t,n){It(this.contents),this.contents.set(t,n)}setIn(t,n){cn(t)?this.contents=n:(It(this.contents),this.contents.setIn(t,n))}setSchema(t,n){if(!t&&!n&&this.schema)return;typeof t=="number"&&(t=t.toFixed(1)),t==="1.0"||t==="1.1"||t==="1.2"?(this.version?this.version=t:this.options.version=t,delete this.options.schema):t&&typeof t=="string"&&(this.options.schema=t),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new En(r)}parse(t,n){this.options.keepCstNodes&&(this.cstNode=t),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=t;if(i&&(i.source||(i.source=this),this.errors.push(i)),uy(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],iy(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof Ot&&c.makePretty();for(const c of this.warnings)c instanceof Ot&&c.makePretty()}return this}listNonDefaultTags(){return sy(this.contents).filter(t=>t.indexOf(En.defaultPrefix)!==0)}setTagPrefix(t,n){if(t[0]!=="!"||t[t.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===t);r?r.prefix=n:this.tagPrefixes.push({handle:t,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==t)}toJSON(t,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof t!="string"||!(this.contents instanceof Y)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Dn},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=Pe(this.contents,t,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:f}of a.anchors.values())n(f,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const t=this.options.indent;if(!Number.isInteger(t)||t<=0){const c=JSON.stringify(t);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(t),stringify:Dn};let i=!1,a=null;if(this.contents){this.contents instanceof ge&&(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=Dn(this.contents,s,()=>a=null,c);n.push(Vt(u,"",a))}else this.contents!==void 0&&n.push(Dn(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
152
152
  `)+`
153
- `}};$e(Bs,"defaults",Ll);function Ig(e,t=!0,n){n===void 0&&typeof t=="string"&&(n=t,t=!0);const r=Object.assign({},Bs.defaults[dr.version],dr);return new On(r).createNode(e,t,n)}class jr extends Bs{constructor(t){super(Object.assign({},dr,t))}}function xg(e,t){const n=[];let r;for(const o of Ps(e)){const s=new jr(t);s.parse(o,r),n.push(s),r=s}return n}function Ul(e,t){const n=Ps(e),r=new jr(t).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new z(n[1],o))}return r}function Pg(e,t){const n=Ul(e,t);if(n.warnings.forEach(r=>_l(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function Tg(e,t){const n=new jr(t);return n.contents=e,String(n)}const Cg={createNode:Ig,defaultOptions:dr,Document:jr,parse:Pg,parseAllDocuments:xg,parseCST:Ps,parseDocument:Ul,scalarOptions:Sg,stringify:Tg},Rg=Object.freeze(Object.defineProperty({__proto__:null,YAML:Cg},Symbol.toStringTag,{value:"Module"})),Mg=xm(Rg);var Dg=Mg.YAML;const Lg="1.0.0-redesign.1",Ug="adhd",Bg="default",Fg="adhd-environment.json",Xr="config.yaml",Vg="config.local.yaml",qg={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class Ga extends Error{constructor(t,n){super(`contentHash: lone surrogate in ${t} (not well-formed Unicode)`),this.location=t,this.offending=n,this.name="LoneSurrogateError"}}function Ha(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const r=t+1<e.length?e.charCodeAt(t+1):0;if(r<56320||r>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function Bl(e,t){const n=Array.from(e),r=Array.from(t),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 Ja(e){return new TextEncoder().encode(e).length}function Kg(e){const t=Object.keys(e).sort(Bl);let n="";for(const r of t){const o=e[r];if(Ha(r))throw new Ga("key",r);if(Ha(o))throw new Ga("value",o);n+=`${Ja(r)}:${r}=${Ja(o)}:${o}
154
- `}return`sha256-${Fl(n)}`}function zg(e){const t=[...e].sort((n,r)=>Bl(n.name,r.name)).map(n=>`${n.name}:${n.kind}:${n.scope}`).join(`
155
- `);return`sha256-${Fl(t)}`}function Gg(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function Hg(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Jg(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]=Wg(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 Wg(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 Qg="adhd-env-ref:";function Yg(e){return`${Qg}${e}`}const Zg=[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],Xg=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Fe(e,t){return(e>>>t|e<<32-t)>>>0}function ey(e){const t=Uint32Array.from(Xg),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 S=0;S<16;S++)c[S]=a.getUint32(f+S*4,!1);for(let S=16;S<64;S++){const N=c[S-15],I=c[S-2],T=Fe(N,7)^Fe(N,18)^N>>>3,K=Fe(I,17)^Fe(I,19)^I>>>10;c[S]=c[S-16]+T+c[S-7]+K>>>0}let p=t[0],h=t[1],d=t[2],m=t[3],g=t[4],$=t[5],v=t[6],w=t[7];for(let S=0;S<64;S++){const N=Fe(g,6)^Fe(g,11)^Fe(g,25),I=g&$^~g&v,T=w+N+I+Zg[S]+c[S]>>>0,K=Fe(p,2)^Fe(p,13)^Fe(p,22),L=p&h^p&d^h&d,V=K+L>>>0;w=v,v=$,$=g,g=m+T>>>0,m=d,d=h,h=p,p=T+V>>>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]+g>>>0,t[5]=t[5]+$>>>0,t[6]=t[6]+v>>>0,t[7]=t[7]+w>>>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 ty(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function Fl(e){const t=new TextEncoder().encode(e);return ty(ey(t))}function Vl(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,Vl(o,s)):n[s]=o}return n}function Un(e){if(Y.existsSync(e))try{const t=Y.readFileSync(e,"utf8"),n=Dg.parse(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:Vl(n)}catch{return}}function ny(e){return{system:Un(q.join(e.system,Xr)),global:Un(q.join(e.global,Xr)),project:e.project?Un(q.join(e.project,Xr)):void 0,local:e.project?Un(q.join(e.project,Vg)):void 0}}function ry(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function Ro(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 ql(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 oy=[["system","system"],["global","global"],["project","project"],["local","local"]];function sy(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:Hg(r.prefix,c),f=u.at==="runtime"||u.secret===!0,p=u.scope??r.activeScope;let h=u.default,d="default";for(const[w,S]of oy){const N=t[w];N&&Object.prototype.hasOwnProperty.call(N,c)&&(h=Ro(N[c],u.type),d=S)}const m=n[l];let g,$,v;m!==void 0?(g=Ro(m,u.type),$="env",v=l):(g=h,$=d),o[c]=f?Yg(l):g,s[c]=g,i[c]=ry(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:ql(o),typedRaw:s,provenance:i,fields:a}}function iy(e,t){return e.replace(/\$\{HOME\}/g,Qt.homedir()).replace(/\$HOME\b/g,Qt.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function ay(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=o.scope??t.activeScope,i=o.share??qg[o.kind],a=o.path?iy(o.path,t):q.join(Yu(t.roots,s),r),c=i==="per-instance"?q.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function cy(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:q.join(s.path,o.name),share:o.share??"shared"}}return n}var Mo={exports:{}},Kl={},ze={},pt={},Wa={},W={},_n={};(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((w,S)=>`${w}${S}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((w,S)=>(S instanceof n&&(w[S.str]=(w[S.str]||0)+1),w),{})}}e._Code=r,e.nil=new r("");function o($,...v){const w=[$[0]];let S=0;for(;S<v.length;)a(w,v[S]),w.push($[++S]);return new r(w)}e._=o;const s=new r("+");function i($,...v){const w=[h($[0])];let S=0;for(;S<v.length;)w.push(s),a(w,v[S]),w.push(s,h($[++S]));return c(w),new r(w)}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 w=u($[v-1],$[v+1]);if(w!==void 0){$.splice(v-1,3,w);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 g($){return new r($.toString())}e.regexpCode=g})(_n);var Do={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=_n;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 g=this._scope[h]||(this._scope[h]=[]),$=g.length;return g[$]=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 g=f[d]=f[d]||new Map;m.forEach($=>{if(g.has($))return;g.set($,r.Started);let v=l($);if(v){const w=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${w} ${$} = ${v};${this.opts._n}`}else if(v=p==null?void 0:p($))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new n($);g.set($,r.Completed)})}return h}}e.ValueScope=a})(Do);(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=_n,n=Do;var r=_n;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=Do;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(y,b){return this}}class i extends s{constructor(y,b,k){super(),this.varKind=y,this.name=b,this.rhs=k}render({es5:y,_n:b}){const k=y?n.varKinds.var:this.varKind,U=this.rhs===void 0?"":` = ${this.rhs}`;return`${k} ${this.name}${U};`+b}optimizeNames(y,b){if(y[this.name.str])return this.rhs&&(this.rhs=oe(this.rhs,y,b)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(y,b,k){super(),this.lhs=y,this.rhs=b,this.sideEffects=k}render({_n:y}){return`${this.lhs} = ${this.rhs};`+y}optimizeNames(y,b){if(!(this.lhs instanceof t.Name&&!y[this.lhs.str]&&!this.sideEffects))return this.rhs=oe(this.rhs,y,b),this}get names(){const y=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ee(y,this.rhs)}}class c extends a{constructor(y,b,k,U){super(y,k,U),this.op=b}render({_n:y}){return`${this.lhs} ${this.op}= ${this.rhs};`+y}}class u extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`${this.label}:`+y}}class l extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`break${this.label?` ${this.label}`:""};`+y}}class f extends s{constructor(y){super(),this.error=y}render({_n:y}){return`throw ${this.error};`+y}get names(){return this.error.names}}class p extends s{constructor(y){super(),this.code=y}render({_n:y}){return`${this.code};`+y}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(y,b){return this.code=oe(this.code,y,b),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(y=[]){super(),this.nodes=y}render(y){return this.nodes.reduce((b,k)=>b+k.render(y),"")}optimizeNodes(){const{nodes:y}=this;let b=y.length;for(;b--;){const k=y[b].optimizeNodes();Array.isArray(k)?y.splice(b,1,...k):k?y[b]=k:y.splice(b,1)}return y.length>0?this:void 0}optimizeNames(y,b){const{nodes:k}=this;let U=k.length;for(;U--;){const F=k[U];F.optimizeNames(y,b)||(Oe(y,F.names),k.splice(U,1))}return k.length>0?this:void 0}get names(){return this.nodes.reduce((y,b)=>Q(y,b.names),{})}}class d extends h{render(y){return"{"+y._n+super.render(y)+"}"+y._n}}class m extends h{}class g extends d{}g.kind="else";class $ extends d{constructor(y,b){super(b),this.condition=y}render(y){let b=`if(${this.condition})`+super.render(y);return this.else&&(b+="else "+this.else.render(y)),b}optimizeNodes(){super.optimizeNodes();const y=this.condition;if(y===!0)return this.nodes;let b=this.else;if(b){const k=b.optimizeNodes();b=this.else=Array.isArray(k)?new g(k):k}if(b)return y===!1?b instanceof $?b:b.nodes:this.nodes.length?this:new $(ue(y),b instanceof $?[b]:b.nodes);if(!(y===!1||!this.nodes.length))return this}optimizeNames(y,b){var k;if(this.else=(k=this.else)===null||k===void 0?void 0:k.optimizeNames(y,b),!!(super.optimizeNames(y,b)||this.else))return this.condition=oe(this.condition,y,b),this}get names(){const y=super.names;return ee(y,this.condition),this.else&&Q(y,this.else.names),y}}$.kind="if";class v extends d{}v.kind="for";class w extends v{constructor(y){super(),this.iteration=y}render(y){return`for(${this.iteration})`+super.render(y)}optimizeNames(y,b){if(super.optimizeNames(y,b))return this.iteration=oe(this.iteration,y,b),this}get names(){return Q(super.names,this.iteration.names)}}class S extends v{constructor(y,b,k,U){super(),this.varKind=y,this.name=b,this.from=k,this.to=U}render(y){const b=y.es5?n.varKinds.var:this.varKind,{name:k,from:U,to:F}=this;return`for(${b} ${k}=${U}; ${k}<${F}; ${k}++)`+super.render(y)}get names(){const y=ee(super.names,this.from);return ee(y,this.to)}}class N extends v{constructor(y,b,k,U){super(),this.loop=y,this.varKind=b,this.name=k,this.iterable=U}render(y){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(y)}optimizeNames(y,b){if(super.optimizeNames(y,b))return this.iterable=oe(this.iterable,y,b),this}get names(){return Q(super.names,this.iterable.names)}}class I extends d{constructor(y,b,k){super(),this.name=y,this.args=b,this.async=k}render(y){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(y)}}I.kind="func";class T extends h{render(y){return"return "+super.render(y)}}T.kind="return";class K extends d{render(y){let b="try"+super.render(y);return this.catch&&(b+=this.catch.render(y)),this.finally&&(b+=this.finally.render(y)),b}optimizeNodes(){var y,b;return super.optimizeNodes(),(y=this.catch)===null||y===void 0||y.optimizeNodes(),(b=this.finally)===null||b===void 0||b.optimizeNodes(),this}optimizeNames(y,b){var k,U;return super.optimizeNames(y,b),(k=this.catch)===null||k===void 0||k.optimizeNames(y,b),(U=this.finally)===null||U===void 0||U.optimizeNames(y,b),this}get names(){const y=super.names;return this.catch&&Q(y,this.catch.names),this.finally&&Q(y,this.finally.names),y}}class L extends d{constructor(y){super(),this.error=y}render(y){return`catch(${this.error})`+super.render(y)}}L.kind="catch";class V extends d{render(y){return"finally"+super.render(y)}}V.kind="finally";class H{constructor(y,b={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...b,_n:b.lines?`
156
- `:""},this._extScope=y,this._scope=new n.Scope({parent:y}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(y){return this._scope.name(y)}scopeName(y){return this._extScope.name(y)}scopeValue(y,b){const k=this._extScope.value(y,b);return(this._values[k.prefix]||(this._values[k.prefix]=new Set)).add(k),k}getScopeValue(y,b){return this._extScope.getValue(y,b)}scopeRefs(y){return this._extScope.scopeRefs(y,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(y,b,k,U){const F=this._scope.toName(b);return k!==void 0&&U&&(this._constants[F.str]=k),this._leafNode(new i(y,F,k)),F}const(y,b,k){return this._def(n.varKinds.const,y,b,k)}let(y,b,k){return this._def(n.varKinds.let,y,b,k)}var(y,b,k){return this._def(n.varKinds.var,y,b,k)}assign(y,b,k){return this._leafNode(new a(y,b,k))}add(y,b){return this._leafNode(new c(y,e.operators.ADD,b))}code(y){return typeof y=="function"?y():y!==t.nil&&this._leafNode(new p(y)),this}object(...y){const b=["{"];for(const[k,U]of y)b.length>1&&b.push(","),b.push(k),(k!==U||this.opts.es5)&&(b.push(":"),(0,t.addCodeArg)(b,U));return b.push("}"),new t._Code(b)}if(y,b,k){if(this._blockNode(new $(y)),b&&k)this.code(b).else().code(k).endIf();else if(b)this.code(b).endIf();else if(k)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(y){return this._elseNode(new $(y))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode($,g)}_for(y,b){return this._blockNode(y),b&&this.code(b).endFor(),this}for(y,b){return this._for(new w(y),b)}forRange(y,b,k,U,F=this.opts.es5?n.varKinds.var:n.varKinds.let){const te=this._scope.toName(y);return this._for(new S(F,te,b,k),()=>U(te))}forOf(y,b,k,U=n.varKinds.const){const F=this._scope.toName(y);if(this.opts.es5){const te=b instanceof t.Name?b:this.var("_arr",b);return this.forRange("_i",0,(0,t._)`${te}.length`,X=>{this.var(F,(0,t._)`${te}[${X}]`),k(F)})}return this._for(new N("of",U,F,b),()=>k(F))}forIn(y,b,k,U=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(y,(0,t._)`Object.keys(${b})`,k);const F=this._scope.toName(y);return this._for(new N("in",U,F,b),()=>k(F))}endFor(){return this._endBlockNode(v)}label(y){return this._leafNode(new u(y))}break(y){return this._leafNode(new l(y))}return(y){const b=new T;if(this._blockNode(b),this.code(y),b.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(y,b,k){if(!b&&!k)throw new Error('CodeGen: "try" without "catch" and "finally"');const U=new K;if(this._blockNode(U),this.code(y),b){const F=this.name("e");this._currNode=U.catch=new L(F),b(F)}return k&&(this._currNode=U.finally=new V,this.code(k)),this._endBlockNode(L,V)}throw(y){return this._leafNode(new f(y))}block(y,b){return this._blockStarts.push(this._nodes.length),y&&this.code(y).endBlock(b),this}endBlock(y){const b=this._blockStarts.pop();if(b===void 0)throw new Error("CodeGen: not in self-balancing block");const k=this._nodes.length-b;if(k<0||y!==void 0&&k!==y)throw new Error(`CodeGen: wrong number of nodes: ${k} vs ${y} expected`);return this._nodes.length=b,this}func(y,b=t.nil,k,U){return this._blockNode(new I(y,b,k)),U&&this.code(U).endFunc(),this}endFunc(){return this._endBlockNode(I)}optimize(y=1){for(;y-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(y){return this._currNode.nodes.push(y),this}_blockNode(y){this._currNode.nodes.push(y),this._nodes.push(y)}_endBlockNode(y,b){const k=this._currNode;if(k instanceof y||b&&k instanceof b)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${b?`${y.kind}/${b.kind}`:y.kind}"`)}_elseNode(y){const b=this._currNode;if(!(b instanceof $))throw new Error('CodeGen: "else" without "if"');return this._currNode=b.else=y,this}get _root(){return this._nodes[0]}get _currNode(){const y=this._nodes;return y[y.length-1]}set _currNode(y){const b=this._nodes;b[b.length-1]=y}}e.CodeGen=H;function Q(A,y){for(const b in y)A[b]=(A[b]||0)+(y[b]||0);return A}function ee(A,y){return y instanceof t._CodeOrName?Q(A,y.names):A}function oe(A,y,b){if(A instanceof t.Name)return k(A);if(!U(A))return A;return new t._Code(A._items.reduce((F,te)=>(te instanceof t.Name&&(te=k(te)),te instanceof t._Code?F.push(...te._items):F.push(te),F),[]));function k(F){const te=b[F.str];return te===void 0||y[F.str]!==1?F:(delete y[F.str],te)}function U(F){return F instanceof t._Code&&F._items.some(te=>te instanceof t.Name&&y[te.str]===1&&b[te.str]!==void 0)}}function Oe(A,y){for(const b in y)A[b]=(A[b]||0)-(y[b]||0)}function ue(A){return typeof A=="boolean"||typeof A=="number"||A===null?!A:(0,t._)`!${P(A)}`}e.not=ue;const tt=O(e.operators.AND);function sn(...A){return A.reduce(tt)}e.and=sn;const Tt=O(e.operators.OR);function R(...A){return A.reduce(Tt)}e.or=R;function O(A){return(y,b)=>y===t.nil?b:b===t.nil?y:(0,t._)`${P(y)} ${A} ${P(b)}`}function P(A){return A instanceof t.Name?A:(0,t._)`(${A})`}})(W);var D={};Object.defineProperty(D,"__esModule",{value:!0});D.checkStrictMode=D.getErrorPath=D.Type=D.useFunc=D.setEvaluated=D.evaluatedPropsToName=D.mergeEvaluated=D.eachItem=D.unescapeJsonPointer=D.escapeJsonPointer=D.escapeFragment=D.unescapeFragment=D.schemaRefOrVal=D.schemaHasRulesButRef=D.schemaHasRules=D.checkUnknownRules=D.alwaysValidSchema=D.toHash=void 0;const se=W,uy=_n;function ly(e){const t={};for(const n of e)t[n]=!0;return t}D.toHash=ly;function fy(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(zl(e,t),!Gl(t,e.self.RULES.all))}D.alwaysValidSchema=fy;function zl(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]||Wl(e,`unknown keyword: "${s}"`)}D.checkUnknownRules=zl;function Gl(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}D.schemaHasRules=Gl;function dy(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}D.schemaHasRulesButRef=dy;function py({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,se._)`${n}`}return(0,se._)`${e}${t}${(0,se.getProperty)(r)}`}D.schemaRefOrVal=py;function hy(e){return Hl(decodeURIComponent(e))}D.unescapeFragment=hy;function my(e){return encodeURIComponent(Fs(e))}D.escapeFragment=my;function Fs(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}D.escapeJsonPointer=Fs;function Hl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}D.unescapeJsonPointer=Hl;function gy(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}D.eachItem=gy;function Qa({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof se.Name?(s instanceof se.Name?e(o,s,i):t(o,s,i),i):s instanceof se.Name?(t(o,i,s),s):n(s,i);return a===se.Name&&!(c instanceof se.Name)?r(o,c):c}}D.mergeEvaluated={props:Qa({mergeNames:(e,t,n)=>e.if((0,se._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,se._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,se._)`${n} || {}`).code((0,se._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,se._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,se._)`${n} || {}`),Vs(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Jl}),items:Qa({mergeNames:(e,t,n)=>e.if((0,se._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,se._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,se._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,se._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Jl(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,se._)`{}`);return t!==void 0&&Vs(e,n,t),n}D.evaluatedPropsToName=Jl;function Vs(e,t,n){Object.keys(n).forEach(r=>e.assign((0,se._)`${t}${(0,se.getProperty)(r)}`,!0))}D.setEvaluated=Vs;const Ya={};function yy(e,t){return e.scopeValue("func",{ref:t,code:Ya[t.code]||(Ya[t.code]=new uy._Code(t.code))})}D.useFunc=yy;var Lo;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Lo||(D.Type=Lo={}));function $y(e,t,n){if(e instanceof se.Name){const r=t===Lo.Num;return n?r?(0,se._)`"[" + ${e} + "]"`:(0,se._)`"['" + ${e} + "']"`:r?(0,se._)`"/" + ${e}`:(0,se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,se.getProperty)(e).toString():"/"+Fs(e)}D.getErrorPath=$y;function Wl(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}D.checkStrictMode=Wl;var Bn={},Za;function lt(){if(Za)return Bn;Za=1,Object.defineProperty(Bn,"__esModule",{value:!0});const e=W,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Bn.default=t,Bn}var Xa;function Ir(){return Xa||(Xa=1,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=W,n=D,r=lt();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:$})=>$?(0,t.str)`"${g}" keyword must be ${$} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function o(g,$=e.keywordError,v,w){const{it:S}=g,{gen:N,compositeRule:I,allErrors:T}=S,K=f(g,$,v);w??(I||T)?c(N,K):u(S,(0,t._)`[${K}]`)}e.reportError=o;function s(g,$=e.keywordError,v){const{it:w}=g,{gen:S,compositeRule:N,allErrors:I}=w,T=f(g,$,v);c(S,T),N||I||u(w,r.default.vErrors)}e.reportExtraError=s;function i(g,$){g.assign(r.default.errors,$),g.if((0,t._)`${r.default.vErrors} !== null`,()=>g.if($,()=>g.assign((0,t._)`${r.default.vErrors}.length`,$),()=>g.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:g,keyword:$,schemaValue:v,data:w,errsCount:S,it:N}){if(S===void 0)throw new Error("ajv implementation error");const I=g.name("err");g.forRange("i",S,r.default.errors,T=>{g.const(I,(0,t._)`${r.default.vErrors}[${T}]`),g.if((0,t._)`${I}.instancePath === undefined`,()=>g.assign((0,t._)`${I}.instancePath`,(0,t.strConcat)(r.default.instancePath,N.errorPath))),g.assign((0,t._)`${I}.schemaPath`,(0,t.str)`${N.errSchemaPath}/${$}`),N.opts.verbose&&(g.assign((0,t._)`${I}.schema`,v),g.assign((0,t._)`${I}.data`,w))})}e.extendErrors=a;function c(g,$){const v=g.const("err",$);g.if((0,t._)`${r.default.vErrors} === null`,()=>g.assign(r.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${r.default.vErrors}.push(${v})`),g.code((0,t._)`${r.default.errors}++`)}function u(g,$){const{gen:v,validateName:w,schemaEnv:S}=g;S.$async?v.throw((0,t._)`new ${g.ValidationError}(${$})`):(v.assign((0,t._)`${w}.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(g,$,v){const{createErrors:w}=g.it;return w===!1?(0,t._)`{}`:p(g,$,v)}function p(g,$,v={}){const{gen:w,it:S}=g,N=[h(S,v),d(g,v)];return m(g,$,N),w.object(...N)}function h({errorPath:g},{instancePath:$}){const v=$?(0,t.str)`${g}${(0,n.getErrorPath)($,n.Type.Str)}`:g;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,v)]}function d({keyword:g,it:{errSchemaPath:$}},{schemaPath:v,parentSchema:w}){let S=w?$:(0,t.str)`${$}/${g}`;return v&&(S=(0,t.str)`${S}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,S]}function m(g,{params:$,message:v},w){const{keyword:S,data:N,schemaValue:I,it:T}=g,{opts:K,propertyName:L,topSchemaRef:V,schemaPath:H}=T;w.push([l.keyword,S],[l.params,typeof $=="function"?$(g):$||(0,t._)`{}`]),K.messages&&w.push([l.message,typeof v=="function"?v(g):v]),K.verbose&&w.push([l.schema,I],[l.parentSchema,(0,t._)`${V}${H}`],[r.default.data,N]),L&&w.push([l.propertyName,L])}}(Wa)),Wa}var ec;function vy(){if(ec)return pt;ec=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.boolOrEmptySchema=pt.topBoolOrEmptySchema=void 0;const e=Ir(),t=W,n=lt(),r={message:"boolean schema is false"};function o(a){const{gen:c,schema:u,validateName:l}=a;u===!1?i(a,!1):typeof u=="object"&&u.$async===!0?c.return(n.default.data):(c.assign((0,t._)`${l}.errors`,null),c.return(!0))}pt.topBoolOrEmptySchema=o;function s(a,c){const{gen:u,schema:l}=a;l===!1?(u.var(c,!1),i(a)):u.var(c,!0)}pt.boolOrEmptySchema=s;function i(a,c){const{gen:u,data:l}=a,f={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(f,r,void 0,c)}return pt}var le={},It={};Object.defineProperty(It,"__esModule",{value:!0});It.getRules=It.isJSONType=void 0;const wy=["string","number","integer","boolean","null","object","array"],by=new Set(wy);function Sy(e){return typeof e=="string"&&by.has(e)}It.isJSONType=Sy;function Ey(){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=Ey;var Ge={},tc;function Ql(){if(tc)return Ge;tc=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.shouldUseRule=Ge.shouldUseGroup=Ge.schemaHasRulesForType=void 0;function e({schema:r,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(r,i)}Ge.schemaHasRulesForType=e;function t(r,o){return o.rules.some(s=>n(r,s))}Ge.shouldUseGroup=t;function n(r,o){var s;return r[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(i=>r[i]!==void 0))}return Ge.shouldUseRule=n,Ge}Object.defineProperty(le,"__esModule",{value:!0});le.reportTypeError=le.checkDataTypes=le.checkDataType=le.coerceAndCheckDataType=le.getJSONTypes=le.getSchemaTypes=le.DataType=void 0;const Ny=It,Oy=Ql(),_y=Ir(),G=W,Yl=D;var Jt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Jt||(le.DataType=Jt={}));function Ay(e){const t=Zl(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}le.getSchemaTypes=Ay;function Zl(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Ny.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}le.getJSONTypes=Zl;function ky(e,t){const{gen:n,data:r,opts:o}=e,s=jy(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Oy.schemaHasRulesForType)(e,t[0]));if(i){const a=qs(t,r,o.strictNumbers,Jt.Wrong);n.if(a,()=>{s.length?Iy(e,t,s):Ks(e)})}return i}le.coerceAndCheckDataType=ky;const Xl=new Set(["string","number","integer","boolean","null"]);function jy(e,t){return t?e.filter(n=>Xl.has(n)||t==="array"&&n==="array"):[]}function Iy(e,t,n){const{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,G._)`typeof ${o}`),a=r.let("coerced",(0,G._)`undefined`);s.coerceTypes==="array"&&r.if((0,G._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,G._)`${o}[0]`).assign(i,(0,G._)`typeof ${o}`).if(qs(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,G._)`${a} !== undefined`);for(const u of n)(Xl.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Ks(e),r.endIf(),r.if((0,G._)`${a} !== undefined`,()=>{r.assign(o,a),xy(e,a)});function c(u){switch(u){case"string":r.elseIf((0,G._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,G._)`"" + ${o}`).elseIf((0,G._)`${o} === null`).assign(a,(0,G._)`""`);return;case"number":r.elseIf((0,G._)`${i} == "boolean" || ${o} === null
157
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,G._)`+${o}`);return;case"integer":r.elseIf((0,G._)`${i} === "boolean" || ${o} === null
158
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,G._)`+${o}`);return;case"boolean":r.elseIf((0,G._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,G._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,G._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,G._)`${i} === "string" || ${i} === "number"
159
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,G._)`[${o}]`)}}}function xy({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,G._)`${t} !== undefined`,()=>e.assign((0,G._)`${t}[${n}]`,r))}function Uo(e,t,n,r=Jt.Correct){const o=r===Jt.Correct?G.operators.EQ:G.operators.NEQ;let s;switch(e){case"null":return(0,G._)`${t} ${o} null`;case"array":s=(0,G._)`Array.isArray(${t})`;break;case"object":s=(0,G._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,G._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,G._)`typeof ${t} ${o} ${e}`}return r===Jt.Correct?s:(0,G.not)(s);function i(a=G.nil){return(0,G.and)((0,G._)`typeof ${t} == "number"`,a,n?(0,G._)`isFinite(${t})`:G.nil)}}le.checkDataType=Uo;function qs(e,t,n,r){if(e.length===1)return Uo(e[0],t,n,r);let o;const s=(0,Yl.toHash)(e);if(s.array&&s.object){const i=(0,G._)`typeof ${t} != "object"`;o=s.null?i:(0,G._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=G.nil;s.number&&delete s.integer;for(const i in s)o=(0,G.and)(o,Uo(i,t,n,r));return o}le.checkDataTypes=qs;const Py={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,G._)`{type: ${e}}`:(0,G._)`{type: ${t}}`};function Ks(e){const t=Ty(e);(0,_y.reportError)(t,Py)}le.reportTypeError=Ks;function Ty(e){const{gen:t,data:n,schema:r}=e,o=(0,Yl.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var cn={},nc;function Cy(){if(nc)return cn;nc=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.assignDefaults=void 0;const e=W,t=D;function n(o,s){const{properties:i,items:a}=o.schema;if(s==="object"&&i)for(const c in i)r(o,c,i[c].default);else s==="array"&&Array.isArray(a)&&a.forEach((c,u)=>r(o,u,c.default))}cn.assignDefaults=n;function r(o,s,i){const{gen:a,compositeRule:c,data:u,opts:l}=o;if(i===void 0)return;const f=(0,e._)`${u}${(0,e.getProperty)(s)}`;if(c){(0,t.checkStrictMode)(o,`default is ignored for: ${f}`);return}let p=(0,e._)`${f} === undefined`;l.useDefaults==="empty"&&(p=(0,e._)`${p} || ${f} === null || ${f} === ""`),a.if(p,(0,e._)`${f} = ${(0,e.stringify)(i)}`)}return cn}var Re={},ne={},rc;function Be(){if(rc)return ne;rc=1,Object.defineProperty(ne,"__esModule",{value:!0}),ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;const e=W,t=D,n=lt(),r=D;function o(v,w){const{gen:S,data:N,it:I}=v;S.if(l(S,N,w,I.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${w}`},!0),v.error()})}ne.checkReportMissingProp=o;function s({gen:v,data:w,it:{opts:S}},N,I){return(0,e.or)(...N.map(T=>(0,e.and)(l(v,w,T,S.ownProperties),(0,e._)`${I} = ${T}`)))}ne.checkMissingProp=s;function i(v,w){v.setParams({missingProperty:w},!0),v.error()}ne.reportMissingProp=i;function a(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}ne.hasPropFunc=a;function c(v,w,S){return(0,e._)`${a(v)}.call(${w}, ${S})`}ne.isOwnProperty=c;function u(v,w,S,N){const I=(0,e._)`${w}${(0,e.getProperty)(S)} !== undefined`;return N?(0,e._)`${I} && ${c(v,w,S)}`:I}ne.propertyInData=u;function l(v,w,S,N){const I=(0,e._)`${w}${(0,e.getProperty)(S)} === undefined`;return N?(0,e.or)(I,(0,e.not)(c(v,w,S))):I}ne.noPropertyInData=l;function f(v){return v?Object.keys(v).filter(w=>w!=="__proto__"):[]}ne.allSchemaProperties=f;function p(v,w){return f(w).filter(S=>!(0,t.alwaysValidSchema)(v,w[S]))}ne.schemaProperties=p;function h({schemaCode:v,data:w,it:{gen:S,topSchemaRef:N,schemaPath:I,errorPath:T},it:K},L,V,H){const Q=H?(0,e._)`${v}, ${w}, ${N}${I}`:w,ee=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,T)],[n.default.parentData,K.parentData],[n.default.parentDataProperty,K.parentDataProperty],[n.default.rootData,n.default.rootData]];K.opts.dynamicRef&&ee.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);const oe=(0,e._)`${Q}, ${S.object(...ee)}`;return V!==e.nil?(0,e._)`${L}.call(${V}, ${oe})`:(0,e._)`${L}(${oe})`}ne.callValidateCode=h;const d=(0,e._)`new RegExp`;function m({gen:v,it:{opts:w}},S){const N=w.unicodeRegExp?"u":"",{regExp:I}=w.code,T=I(S,N);return v.scopeValue("pattern",{key:T.toString(),ref:T,code:(0,e._)`${I.code==="new RegExp"?d:(0,r.useFunc)(v,I)}(${S}, ${N})`})}ne.usePattern=m;function g(v){const{gen:w,data:S,keyword:N,it:I}=v,T=w.name("valid");if(I.allErrors){const L=w.let("valid",!0);return K(()=>w.assign(L,!1)),L}return w.var(T,!0),K(()=>w.break()),T;function K(L){const V=w.const("len",(0,e._)`${S}.length`);w.forRange("i",0,V,H=>{v.subschema({keyword:N,dataProp:H,dataPropType:t.Type.Num},T),w.if((0,e.not)(T),L)})}}ne.validateArray=g;function $(v){const{gen:w,schema:S,keyword:N,it:I}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(L=>(0,t.alwaysValidSchema)(I,L))&&!I.opts.unevaluated)return;const T=w.let("valid",!1),K=w.name("_valid");w.block(()=>S.forEach((L,V)=>{const H=v.subschema({keyword:N,schemaProp:V,compositeRule:!0},K);w.assign(T,(0,e._)`${T} || ${K}`),v.mergeValidEvaluated(H,K)||w.if((0,e.not)(T))})),v.result(T,()=>v.reset(),()=>v.error(!0))}return ne.validateUnion=$,ne}var oc;function Ry(){if(oc)return Re;oc=1,Object.defineProperty(Re,"__esModule",{value:!0}),Re.validateKeywordUsage=Re.validSchemaType=Re.funcKeywordCode=Re.macroKeywordCode=void 0;const e=W,t=lt(),n=Be(),r=Ir();function o(p,h){const{gen:d,keyword:m,schema:g,parentSchema:$,it:v}=p,w=h.macro.call(v.self,g,$,v),S=u(d,m,w);v.opts.validateSchema!==!1&&v.self.validateSchema(w,!0);const N=d.name("valid");p.subschema({schema:w,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${m}`,topSchemaRef:S,compositeRule:!0},N),p.pass(N,()=>p.error(!0))}Re.macroKeywordCode=o;function s(p,h){var d;const{gen:m,keyword:g,schema:$,parentSchema:v,$data:w,it:S}=p;c(S,h);const N=!w&&h.compile?h.compile.call(S.self,$,v,S):h.validate,I=u(m,g,N),T=m.let("valid");p.block$data(T,K),p.ok((d=h.valid)!==null&&d!==void 0?d:T);function K(){if(h.errors===!1)H(),h.modifying&&i(p),Q(()=>p.error());else{const ee=h.async?L():V();h.modifying&&i(p),Q(()=>a(p,ee))}}function L(){const ee=m.let("ruleErrs",null);return m.try(()=>H((0,e._)`await `),oe=>m.assign(T,!1).if((0,e._)`${oe} instanceof ${S.ValidationError}`,()=>m.assign(ee,(0,e._)`${oe}.errors`),()=>m.throw(oe))),ee}function V(){const ee=(0,e._)`${I}.errors`;return m.assign(ee,null),H(e.nil),ee}function H(ee=h.async?(0,e._)`await `:e.nil){const oe=S.opts.passContext?t.default.this:t.default.self,Oe=!("compile"in h&&!w||h.schema===!1);m.assign(T,(0,e._)`${ee}${(0,n.callValidateCode)(p,I,oe,Oe)}`,h.modifying)}function Q(ee){var oe;m.if((0,e.not)((oe=h.valid)!==null&&oe!==void 0?oe:T),ee)}}Re.funcKeywordCode=s;function i(p){const{gen:h,data:d,it:m}=p;h.if(m.parentData,()=>h.assign(d,(0,e._)`${m.parentData}[${m.parentDataProperty}]`))}function a(p,h){const{gen:d}=p;d.if((0,e._)`Array.isArray(${h})`,()=>{d.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${h} : ${t.default.vErrors}.concat(${h})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,r.extendErrors)(p)},()=>p.error())}function c({schemaEnv:p},h){if(h.async&&!p.$async)throw new Error("async keyword in sync schema")}function u(p,h,d){if(d===void 0)throw new Error(`keyword "${h}" failed to compile`);return p.scopeValue("keyword",typeof d=="function"?{ref:d}:{ref:d,code:(0,e.stringify)(d)})}function l(p,h,d=!1){return!h.length||h.some(m=>m==="array"?Array.isArray(p):m==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==m||d&&typeof p>"u")}Re.validSchemaType=l;function f({schema:p,opts:h,self:d,errSchemaPath:m},g,$){if(Array.isArray(g.keyword)?!g.keyword.includes($):g.keyword!==$)throw new Error("ajv implementation error");const v=g.dependencies;if(v!=null&&v.some(w=>!Object.prototype.hasOwnProperty.call(p,w)))throw new Error(`parent schema must have dependencies of ${$}: ${v.join(",")}`);if(g.validateSchema&&!g.validateSchema(p[$])){const w=`keyword "${$}" value is invalid at path "${m}": `+d.errorsText(g.validateSchema.errors);if(h.validateSchema==="log")d.logger.error(w);else throw new Error(w)}}return Re.validateKeywordUsage=f,Re}var He={},sc;function My(){if(sc)return He;sc=1,Object.defineProperty(He,"__esModule",{value:!0}),He.extendSubschemaMode=He.extendSubschemaData=He.getSubschema=void 0;const e=W,t=D;function n(s,{keyword:i,schemaProp:a,schema:c,schemaPath:u,errSchemaPath:l,topSchemaRef:f}){if(i!==void 0&&c!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const p=s.schema[i];return a===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${i}`}:{schema:p[a],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${i}/${(0,t.escapeFragment)(a)}`}}if(c!==void 0){if(u===void 0||l===void 0||f===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:u,topSchemaRef:f,errSchemaPath:l}}throw new Error('either "keyword" or "schema" must be passed')}He.getSubschema=n;function r(s,i,{dataProp:a,dataPropType:c,data:u,dataTypes:l,propertyName:f}){if(u!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(a!==void 0){const{errorPath:d,dataPathArr:m,opts:g}=i,$=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);h($),s.errorPath=(0,e.str)`${d}${(0,t.getErrorPath)(a,c,g.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,s.dataPathArr=[...m,s.parentDataProperty]}if(u!==void 0){const d=u instanceof e.Name?u:p.let("data",u,!0);h(d),f!==void 0&&(s.propertyName=f)}l&&(s.dataTypes=l);function h(d){s.data=d,s.dataLevel=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,d]}}He.extendSubschemaData=r;function o(s,{jtdDiscriminator:i,jtdMetadata:a,compositeRule:c,createErrors:u,allErrors:l}){c!==void 0&&(s.compositeRule=c),u!==void 0&&(s.createErrors=u),l!==void 0&&(s.allErrors=l),s.jtdDiscriminator=i,s.jtdMetadata=a}return He.extendSubschemaMode=o,He}var me={},ef=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},tf={exports:{}},at=tf.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(){};rr(t,r,o,e,"",e)};at.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};at.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};at.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};at.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 rr(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 at.arrayKeywords)for(var p=0;p<f.length;p++)rr(e,t,n,f[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in at.propsKeywords){if(f&&typeof f=="object")for(var h in f)rr(e,t,n,f[h],o+"/"+l+"/"+Dy(h),s,o,l,r,h)}else(l in at.keywords||e.allKeys&&!(l in at.skipKeywords))&&rr(e,t,n,f,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function Dy(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Ly=tf.exports;Object.defineProperty(me,"__esModule",{value:!0});me.getSchemaRefs=me.resolveUrl=me.normalizeId=me._getFullPath=me.getFullPath=me.inlineRef=void 0;const Uy=D,By=ef,Fy=Ly,Vy=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function qy(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Bo(e):t?nf(e)<=t:!1}me.inlineRef=qy;const Ky=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Bo(e){for(const t in e){if(Ky.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(Bo)||typeof n=="object"&&Bo(n))return!0}return!1}function nf(e){let t=0;for(const n in e)if(n==="$ref"||(t++,!Vy.has(n)&&(typeof e[n]=="object"&&(0,Uy.eachItem)(e[n],r=>t+=nf(r)),t===1/0)))return 1/0;return t}function rf(e,t="",n){n!==!1&&(t=Wt(t));const r=e.parse(t);return of(e,r)}me.getFullPath=rf;function of(e,t){return e.serialize(t).split("#")[0]+"#"}me._getFullPath=of;const zy=/#\/?$/;function Wt(e){return e?e.replace(zy,""):""}me.normalizeId=Wt;function Gy(e,t,n){return n=Wt(n),e.resolve(t,n)}me.resolveUrl=Gy;const Hy=/^[a-z_][-a-z0-9._]*$/i;function Jy(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Wt(e[n]||t),s={"":o},i=rf(r,o,!1),a={},c=new Set;return Fy(e,{allKeys:!0},(f,p,h,d)=>{if(d===void 0)return;const m=i+p;let g=s[d];typeof f[n]=="string"&&(g=$.call(this,f[n])),v.call(this,f.$anchor),v.call(this,f.$dynamicAnchor),s[p]=g;function $(w){const S=this.opts.uriResolver.resolve;if(w=Wt(g?S(g,w):w),c.has(w))throw l(w);c.add(w);let N=this.refs[w];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(f,N.schema,w):w!==Wt(m)&&(w[0]==="#"?(u(f,a[w],w),a[w]=f):this.refs[w]=m),w}function v(w){if(typeof w=="string"){if(!Hy.test(w))throw new Error(`invalid anchor "${w}"`);$.call(this,`#${w}`)}}}),a;function u(f,p,h){if(p!==void 0&&!By(f,p))throw l(h)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}me.getSchemaRefs=Jy;var ic;function xr(){if(ic)return ze;ic=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.getData=ze.KeywordCxt=ze.validateFunctionCode=void 0;const e=vy(),t=le,n=Ql(),r=le,o=Cy(),s=Ry(),i=My(),a=W,c=lt(),u=me,l=D,f=Ir();function p(E){if(N(E)&&(T(E),S(E))){g(E);return}h(E,()=>(0,e.topBoolOrEmptySchema)(E))}ze.validateFunctionCode=p;function h({gen:E,validateName:_,schema:x,schemaEnv:C,opts:B},J){B.code.es5?E.func(_,(0,a._)`${c.default.data}, ${c.default.valCxt}`,C.$async,()=>{E.code((0,a._)`"use strict"; ${v(x,B)}`),m(E,B),E.code(J)}):E.func(_,(0,a._)`${c.default.data}, ${d(B)}`,C.$async,()=>E.code(v(x,B)).code(J))}function d(E){return(0,a._)`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${E.dynamicRef?(0,a._)`, ${c.default.dynamicAnchors}={}`:a.nil}}={}`}function m(E,_){E.if(c.default.valCxt,()=>{E.var(c.default.instancePath,(0,a._)`${c.default.valCxt}.${c.default.instancePath}`),E.var(c.default.parentData,(0,a._)`${c.default.valCxt}.${c.default.parentData}`),E.var(c.default.parentDataProperty,(0,a._)`${c.default.valCxt}.${c.default.parentDataProperty}`),E.var(c.default.rootData,(0,a._)`${c.default.valCxt}.${c.default.rootData}`),_.dynamicRef&&E.var(c.default.dynamicAnchors,(0,a._)`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{E.var(c.default.instancePath,(0,a._)`""`),E.var(c.default.parentData,(0,a._)`undefined`),E.var(c.default.parentDataProperty,(0,a._)`undefined`),E.var(c.default.rootData,c.default.data),_.dynamicRef&&E.var(c.default.dynamicAnchors,(0,a._)`{}`)})}function g(E){const{schema:_,opts:x,gen:C}=E;h(E,()=>{x.$comment&&_.$comment&&ee(E),V(E),C.let(c.default.vErrors,null),C.let(c.default.errors,0),x.unevaluated&&$(E),K(E),oe(E)})}function $(E){const{gen:_,validateName:x}=E;E.evaluated=_.const("evaluated",(0,a._)`${x}.evaluated`),_.if((0,a._)`${E.evaluated}.dynamicProps`,()=>_.assign((0,a._)`${E.evaluated}.props`,(0,a._)`undefined`)),_.if((0,a._)`${E.evaluated}.dynamicItems`,()=>_.assign((0,a._)`${E.evaluated}.items`,(0,a._)`undefined`))}function v(E,_){const x=typeof E=="object"&&E[_.schemaId];return x&&(_.code.source||_.code.process)?(0,a._)`/*# sourceURL=${x} */`:a.nil}function w(E,_){if(N(E)&&(T(E),S(E))){I(E,_);return}(0,e.boolOrEmptySchema)(E,_)}function S({schema:E,self:_}){if(typeof E=="boolean")return!E;for(const x in E)if(_.RULES.all[x])return!0;return!1}function N(E){return typeof E.schema!="boolean"}function I(E,_){const{schema:x,gen:C,opts:B}=E;B.$comment&&x.$comment&&ee(E),H(E),Q(E);const J=C.const("_errs",c.default.errors);K(E,J),C.var(_,(0,a._)`${J} === ${c.default.errors}`)}function T(E){(0,l.checkUnknownRules)(E),L(E)}function K(E,_){if(E.opts.jtd)return ue(E,[],!1,_);const x=(0,t.getSchemaTypes)(E.schema),C=(0,t.coerceAndCheckDataType)(E,x);ue(E,x,!C,_)}function L(E){const{schema:_,errSchemaPath:x,opts:C,self:B}=E;_.$ref&&C.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(_,B.RULES)&&B.logger.warn(`$ref: keywords ignored in schema at path "${x}"`)}function V(E){const{schema:_,opts:x}=E;_.default!==void 0&&x.useDefaults&&x.strictSchema&&(0,l.checkStrictMode)(E,"default is ignored in the schema root")}function H(E){const _=E.schema[E.opts.schemaId];_&&(E.baseId=(0,u.resolveUrl)(E.opts.uriResolver,E.baseId,_))}function Q(E){if(E.schema.$async&&!E.schemaEnv.$async)throw new Error("async schema in sync schema")}function ee({gen:E,schemaEnv:_,schema:x,errSchemaPath:C,opts:B}){const J=x.$comment;if(B.$comment===!0)E.code((0,a._)`${c.default.self}.logger.log(${J})`);else if(typeof B.$comment=="function"){const de=(0,a.str)`${C}/$comment`,Ce=E.scopeValue("root",{ref:_.root});E.code((0,a._)`${c.default.self}.opts.$comment(${J}, ${de}, ${Ce}.schema)`)}}function oe(E){const{gen:_,schemaEnv:x,validateName:C,ValidationError:B,opts:J}=E;x.$async?_.if((0,a._)`${c.default.errors} === 0`,()=>_.return(c.default.data),()=>_.throw((0,a._)`new ${B}(${c.default.vErrors})`)):(_.assign((0,a._)`${C}.errors`,c.default.vErrors),J.unevaluated&&Oe(E),_.return((0,a._)`${c.default.errors} === 0`))}function Oe({gen:E,evaluated:_,props:x,items:C}){x instanceof a.Name&&E.assign((0,a._)`${_}.props`,x),C instanceof a.Name&&E.assign((0,a._)`${_}.items`,C)}function ue(E,_,x,C){const{gen:B,schema:J,data:de,allErrors:Ce,opts:ve,self:we}=E,{RULES:pe}=we;if(J.$ref&&(ve.ignoreKeywordsWithRef||!(0,l.schemaHasRulesButRef)(J,pe))){B.block(()=>U(E,"$ref",pe.all.$ref.definition));return}ve.jtd||sn(E,_),B.block(()=>{for(const Ie of pe.rules)Ct(Ie);Ct(pe.post)});function Ct(Ie){(0,n.shouldUseGroup)(J,Ie)&&(Ie.type?(B.if((0,r.checkDataType)(Ie.type,de,ve.strictNumbers)),tt(E,Ie),_.length===1&&_[0]===Ie.type&&x&&(B.else(),(0,r.reportTypeError)(E)),B.endIf()):tt(E,Ie),Ce||B.if((0,a._)`${c.default.errors} === ${C||0}`))}}function tt(E,_){const{gen:x,schema:C,opts:{useDefaults:B}}=E;B&&(0,o.assignDefaults)(E,_.type),x.block(()=>{for(const J of _.rules)(0,n.shouldUseRule)(C,J)&&U(E,J.keyword,J.definition,_.type)})}function sn(E,_){E.schemaEnv.meta||!E.opts.strictTypes||(Tt(E,_),E.opts.allowUnionTypes||R(E,_),O(E,E.dataTypes))}function Tt(E,_){if(_.length){if(!E.dataTypes.length){E.dataTypes=_;return}_.forEach(x=>{A(E.dataTypes,x)||b(E,`type "${x}" not allowed by context "${E.dataTypes.join(",")}"`)}),y(E,_)}}function R(E,_){_.length>1&&!(_.length===2&&_.includes("null"))&&b(E,"use allowUnionTypes to allow union type keyword")}function O(E,_){const x=E.self.RULES.all;for(const C in x){const B=x[C];if(typeof B=="object"&&(0,n.shouldUseRule)(E.schema,B)){const{type:J}=B.definition;J.length&&!J.some(de=>P(_,de))&&b(E,`missing type "${J.join(",")}" for keyword "${C}"`)}}}function P(E,_){return E.includes(_)||_==="number"&&E.includes("integer")}function A(E,_){return E.includes(_)||_==="integer"&&E.includes("number")}function y(E,_){const x=[];for(const C of E.dataTypes)A(_,C)?x.push(C):_.includes("integer")&&C==="number"&&x.push("integer");E.dataTypes=x}function b(E,_){const x=E.schemaEnv.baseId+E.errSchemaPath;_+=` at "${x}" (strictTypes)`,(0,l.checkStrictMode)(E,_,E.opts.strictTypes)}class k{constructor(_,x,C){if((0,s.validateKeywordUsage)(_,x,C),this.gen=_.gen,this.allErrors=_.allErrors,this.keyword=C,this.data=_.data,this.schema=_.schema[C],this.$data=x.$data&&_.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(_,this.schema,C,this.$data),this.schemaType=x.schemaType,this.parentSchema=_.schema,this.params={},this.it=_,this.def=x,this.$data)this.schemaCode=_.gen.const("vSchema",X(this.$data,_));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,x.schemaType,x.allowUndefined))throw new Error(`${C} value must be ${JSON.stringify(x.schemaType)}`);("code"in x?x.trackErrors:x.errors!==!1)&&(this.errsCount=_.gen.const("_errs",c.default.errors))}result(_,x,C){this.failResult((0,a.not)(_),x,C)}failResult(_,x,C){this.gen.if(_),C?C():this.error(),x?(this.gen.else(),x(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(_,x){this.failResult((0,a.not)(_),void 0,x)}fail(_){if(_===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(_),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(_){if(!this.$data)return this.fail(_);const{schemaCode:x}=this;this.fail((0,a._)`${x} !== undefined && (${(0,a.or)(this.invalid$data(),_)})`)}error(_,x,C){if(x){this.setParams(x),this._error(_,C),this.setParams({});return}this._error(_,C)}_error(_,x){(_?f.reportExtraError:f.reportError)(this,this.def.error,x)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(_){this.allErrors||this.gen.if(_)}setParams(_,x){x?Object.assign(this.params,_):this.params=_}block$data(_,x,C=a.nil){this.gen.block(()=>{this.check$data(_,C),x()})}check$data(_=a.nil,x=a.nil){if(!this.$data)return;const{gen:C,schemaCode:B,schemaType:J,def:de}=this;C.if((0,a.or)((0,a._)`${B} === undefined`,x)),_!==a.nil&&C.assign(_,!0),(J.length||de.validateSchema)&&(C.elseIf(this.invalid$data()),this.$dataError(),_!==a.nil&&C.assign(_,!1)),C.else()}invalid$data(){const{gen:_,schemaCode:x,schemaType:C,def:B,it:J}=this;return(0,a.or)(de(),Ce());function de(){if(C.length){if(!(x instanceof a.Name))throw new Error("ajv implementation error");const ve=Array.isArray(C)?C:[C];return(0,a._)`${(0,r.checkDataTypes)(ve,x,J.opts.strictNumbers,r.DataType.Wrong)}`}return a.nil}function Ce(){if(B.validateSchema){const ve=_.scopeValue("validate$data",{ref:B.validateSchema});return(0,a._)`!${ve}(${x})`}return a.nil}}subschema(_,x){const C=(0,i.getSubschema)(this.it,_);(0,i.extendSubschemaData)(C,this.it,_),(0,i.extendSubschemaMode)(C,_);const B={...this.it,...C,items:void 0,props:void 0};return w(B,x),B}mergeEvaluated(_,x){const{it:C,gen:B}=this;C.opts.unevaluated&&(C.props!==!0&&_.props!==void 0&&(C.props=l.mergeEvaluated.props(B,_.props,C.props,x)),C.items!==!0&&_.items!==void 0&&(C.items=l.mergeEvaluated.items(B,_.items,C.items,x)))}mergeValidEvaluated(_,x){const{it:C,gen:B}=this;if(C.opts.unevaluated&&(C.props!==!0||C.items!==!0))return B.if(x,()=>this.mergeEvaluated(_,a.Name)),!0}}ze.KeywordCxt=k;function U(E,_,x,C){const B=new k(E,x,_);"code"in x?x.code(B,C):B.$data&&x.validate?(0,s.funcKeywordCode)(B,x):"macro"in x?(0,s.macroKeywordCode)(B,x):(x.compile||x.validate)&&(0,s.funcKeywordCode)(B,x)}const F=/^\/(?:[^~]|~0|~1)*$/,te=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function X(E,{dataLevel:_,dataNames:x,dataPathArr:C}){let B,J;if(E==="")return c.default.rootData;if(E[0]==="/"){if(!F.test(E))throw new Error(`Invalid JSON-pointer: ${E}`);B=E,J=c.default.rootData}else{const we=te.exec(E);if(!we)throw new Error(`Invalid JSON-pointer: ${E}`);const pe=+we[1];if(B=we[2],B==="#"){if(pe>=_)throw new Error(ve("property/index",pe));return C[_-pe]}if(pe>_)throw new Error(ve("data",pe));if(J=x[_-pe],!B)return J}let de=J;const Ce=B.split("/");for(const we of Ce)we&&(J=(0,a._)`${J}${(0,a.getProperty)((0,l.unescapeJsonPointer)(we))}`,de=(0,a._)`${de} && ${J}`);return de;function ve(we,pe){return`Cannot access ${we} ${pe} levels up, current level is ${_}`}}return ze.getData=X,ze}var xn={};Object.defineProperty(xn,"__esModule",{value:!0});let Wy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xn.default=Wy;var nn={};Object.defineProperty(nn,"__esModule",{value:!0});const eo=me;class Qy extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,eo.resolveUrl)(t,n,r),this.missingSchema=(0,eo.normalizeId)((0,eo.getFullPath)(t,this.missingRef))}}nn.default=Qy;var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.resolveSchema=Ne.getCompilingSchema=Ne.resolveRef=Ne.compileSchema=Ne.SchemaEnv=void 0;const Me=W,Yy=xn,ht=lt(),Le=me,ac=D,Zy=xr();class Pr{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,Le.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={}}}Ne.SchemaEnv=Pr;function zs(e){const t=sf.call(this,e);if(t)return t;const n=(0,Le.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Me.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:Yy.default,code:(0,Me._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:ht.default.data,parentData:ht.default.parentData,parentDataProperty:ht.default.parentDataProperty,dataNames:[ht.default.data],dataPathArr:[Me.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Me.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Me.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Me._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Zy.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(ht.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const p=new Function(`${ht.default.self}`,`${ht.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 Me.Name?void 0:h,items:d instanceof Me.Name?void 0:d,dynamicProps:h instanceof Me.Name,dynamicItems:d instanceof Me.Name},p.source&&(p.source.evaluated=(0,Me.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)}}Ne.compileSchema=zs;function Xy(e,t,n){var r;n=(0,Le.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=n$.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 Pr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=e$.call(this,s)}Ne.resolveRef=Xy;function e$(e){return(0,Le.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:zs.call(this,e)}function sf(e){for(const t of this._compilations)if(t$(t,e))return t}Ne.getCompilingSchema=sf;function t$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function n$(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Tr.call(this,e,t)}function Tr(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Le._getFullPath)(this.opts.uriResolver,n);let o=(0,Le.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return to.call(this,n,e);const s=(0,Le.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Tr.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:to.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||zs.call(this,i),s===(0,Le.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Le.resolveUrl)(this.opts.uriResolver,o,u)),new Pr({schema:a,schemaId:c,root:e,baseId:o})}return to.call(this,n,i)}}Ne.resolveSchema=Tr;const r$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function to(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,ac.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!r$.has(a)&&u&&(t=(0,Le.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,ac.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Le.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Tr.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Pr({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const o$="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",s$="Meta-schema for $data reference (JSON AnySchema extension proposal)",i$="object",a$=["$data"],c$={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},u$=!1,l$={$id:o$,description:s$,type:i$,required:a$,properties:c$,additionalProperties:u$};var Gs={},Cr={exports:{}};const f$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),af=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),Hs=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),cf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),d$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function uf(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 p$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cc(e){return e.length=0,!0}function h$(e,t,n){if(e.length){const r=uf(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function m$(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=h$;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=cc}else{o.push(u);continue}}return o.length&&(a===cc?n.zone=o.join(""):i?r.push(o.join("")):r.push(uf(o))),n.address=r.join(""),n}function lf(e){if(g$(e,":")<2)return{host:e,isIPV6:!1};const t=m$(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 g$(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function y$(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 $$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},v$=/[@/?#:]/g,w$=/[@/?#]/g;function ff(e,t){const n=t?w$:v$;return n.lastIndex=0,e.replace(n,r=>$$[r])}function b$(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(Hs(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&cf(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function S$(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(Hs(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&cf(s)?t+=s:t+="%"+o,n+=2;continue}}d$(e[n])?t+=e[n]:t+=escape(e[n])}return t}function E$(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(Hs(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function N$(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!af(n)){const r=lf(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=ff(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 df={nonSimpleDomain:p$,recomposeAuthority:N$,reescapeHostDelimiters:ff,normalizePercentEncoding:b$,normalizePathEncoding:S$,escapePreservingEscapes:E$,removeDotSegments:y$,isIPv4:af,isUUID:f$,normalizeIPv6:lf};const{isUUID:O$}=df,_$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function pf(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 hf(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function mf(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 A$(e){return e.secure=pf(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function k$(e){if((e.port===(pf(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 j$(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(_$);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=Js(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function I$(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=Js(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 x$(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!O$(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function P$(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const gf={scheme:"http",domainHost:!0,parse:hf,serialize:mf},T$={scheme:"https",domainHost:gf.domainHost,parse:hf,serialize:mf},or={scheme:"ws",domainHost:!0,parse:A$,serialize:k$},C$={scheme:"wss",domainHost:or.domainHost,parse:or.parse,serialize:or.serialize},R$={scheme:"urn",parse:j$,serialize:I$,skipNormalize:!0},M$={scheme:"urn:uuid",parse:x$,serialize:P$,skipNormalize:!0},pr={http:gf,https:T$,ws:or,wss:C$,urn:R$,"urn:uuid":M$};Object.setPrototypeOf(pr,null);function Js(e){return e&&(pr[e]||pr[e.toLowerCase()])||void 0}var D$={SCHEMES:pr,getSchemeHandler:Js};const{normalizeIPv6:L$,removeDotSegments:hn,recomposeAuthority:U$,normalizePercentEncoding:B$,normalizePathEncoding:F$,escapePreservingEscapes:V$,reescapeHostDelimiters:q$,isIPv4:K$,nonSimpleDomain:z$}=df,{SCHEMES:G$,getSchemeHandler:yf}=D$;function H$(e,t){return typeof e=="string"?e=Z$(e,t):typeof e=="object"&&(e=Zt(xt(e,t),t)),e}function J$(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=$f(Zt(e,r),Zt(t,r),r,!0);return r.skipEscape=!0,xt(o,r)}function $f(e,t,n,r){const o={};return r||(e=Zt(xt(e,n),n),t=Zt(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=hn(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=hn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=hn(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=hn(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 W$(e,t,n){const r=uc(e,n),o=uc(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=yf(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=B$(n.path):(n.path=V$(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=U$(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=hn(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 Q$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Y$(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 vf(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(Q$);if(i){r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]);const a=Y$(r,i);if(a!==void 0&&(r.error=r.error||a,o=!0),r.host)if(K$(r.host)===!1){const u=L$(r.host);r.host=u.host.toLowerCase(),s=u.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 c=yf(n.scheme||r.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&r.host&&(n.domainHost||c&&c.domainHost)&&s===!1&&z$(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(u){r.error=r.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=q$(unescape(r.host),s))),r.path&&(r.path=F$(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}c&&c.parse&&c.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function Zt(e,t){return vf(e,t).parsed}function Z$(e,t){return wf(e,t).normalized}function wf(e,t){const{parsed:n,malformedAuthorityOrPort:r}=vf(e,t);return{normalized:r?e:xt(n,t),malformedAuthorityOrPort:r}}function uc(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=wf(e,t);return r?void 0:n}if(typeof e=="object")return xt(e,t)}const Ws={SCHEMES:G$,normalize:H$,resolve:J$,resolveComponent:$f,equal:W$,serialize:xt,parse:Zt};Cr.exports=Ws;Cr.exports.default=Ws;Cr.exports.fastUri=Ws;var X$=Cr.exports;Object.defineProperty(Gs,"__esModule",{value:!0});const bf=X$;bf.code='require("ajv/dist/runtime/uri").default';Gs.default=bf;(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=xr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W;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=xn,o=nn,s=It,i=Ne,a=W,c=me,u=le,l=D,f=l$,p=Gs,h=(R,O)=>new RegExp(R,O);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"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function w(R){var O,P,A,y,b,k,U,F,te,X,E,_,x,C,B,J,de,Ce,ve,we,pe,Ct,Ie,qr,Kr;const an=R.strict,zr=(O=R.code)===null||O===void 0?void 0:O.optimize,la=zr===!0||zr===void 0?1:zr||0,fa=(A=(P=R.code)===null||P===void 0?void 0:P.regExp)!==null&&A!==void 0?A:h,Dp=(y=R.uriResolver)!==null&&y!==void 0?y:p.default;return{strictSchema:(k=(b=R.strictSchema)!==null&&b!==void 0?b:an)!==null&&k!==void 0?k:!0,strictNumbers:(F=(U=R.strictNumbers)!==null&&U!==void 0?U:an)!==null&&F!==void 0?F:!0,strictTypes:(X=(te=R.strictTypes)!==null&&te!==void 0?te:an)!==null&&X!==void 0?X:"log",strictTuples:(_=(E=R.strictTuples)!==null&&E!==void 0?E:an)!==null&&_!==void 0?_:"log",strictRequired:(C=(x=R.strictRequired)!==null&&x!==void 0?x:an)!==null&&C!==void 0?C:!1,code:R.code?{...R.code,optimize:la,regExp:fa}:{optimize:la,regExp:fa},loopRequired:(B=R.loopRequired)!==null&&B!==void 0?B:v,loopEnum:(J=R.loopEnum)!==null&&J!==void 0?J:v,meta:(de=R.meta)!==null&&de!==void 0?de:!0,messages:(Ce=R.messages)!==null&&Ce!==void 0?Ce:!0,inlineRefs:(ve=R.inlineRefs)!==null&&ve!==void 0?ve:!0,schemaId:(we=R.schemaId)!==null&&we!==void 0?we:"$id",addUsedSchema:(pe=R.addUsedSchema)!==null&&pe!==void 0?pe:!0,validateSchema:(Ct=R.validateSchema)!==null&&Ct!==void 0?Ct:!0,validateFormats:(Ie=R.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(qr=R.unicodeRegExp)!==null&&qr!==void 0?qr:!0,int32range:(Kr=R.int32range)!==null&&Kr!==void 0?Kr:!0,uriResolver:Dp}}class S{constructor(O={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,O=this.opts={...O,...w(O)};const{es5:P,lines:A}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:m,es5:P,lines:A}),this.logger=Q(O.logger);const y=O.validateFormats;O.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,g,O,"NOT SUPPORTED"),N.call(this,$,O,"DEPRECATED","warn"),this._metaOpts=V.call(this),O.formats&&K.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),O.keywords&&L.call(this,O.keywords),typeof O.meta=="object"&&this.addMetaSchema(O.meta),T.call(this),O.validateFormats=y}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:O,meta:P,schemaId:A}=this.opts;let y=f;A==="id"&&(y={...f},y.id=y.$id,delete y.$id),P&&O&&this.addMetaSchema(y,y[A],!1)}defaultMeta(){const{meta:O,schemaId:P}=this.opts;return this.opts.defaultMeta=typeof O=="object"?O[P]||O:void 0}validate(O,P){let A;if(typeof O=="string"){if(A=this.getSchema(O),!A)throw new Error(`no schema with key or ref "${O}"`)}else A=this.compile(O);const y=A(P);return"$async"in A||(this.errors=A.errors),y}compile(O,P){const A=this._addSchema(O,P);return A.validate||this._compileSchemaEnv(A)}compileAsync(O,P){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:A}=this.opts;return y.call(this,O,P);async function y(X,E){await b.call(this,X.$schema);const _=this._addSchema(X,E);return _.validate||k.call(this,_)}async function b(X){X&&!this.getSchema(X)&&await y.call(this,{$ref:X},!0)}async function k(X){try{return this._compileSchemaEnv(X)}catch(E){if(!(E instanceof o.default))throw E;return U.call(this,E),await F.call(this,E.missingSchema),k.call(this,X)}}function U({missingSchema:X,missingRef:E}){if(this.refs[X])throw new Error(`AnySchema ${X} is loaded but ${E} cannot be resolved`)}async function F(X){const E=await te.call(this,X);this.refs[X]||await b.call(this,E.$schema),this.refs[X]||this.addSchema(E,X,P)}async function te(X){const E=this._loading[X];if(E)return E;try{return await(this._loading[X]=A(X))}finally{delete this._loading[X]}}}addSchema(O,P,A,y=this.opts.validateSchema){if(Array.isArray(O)){for(const k of O)this.addSchema(k,void 0,A,y);return this}let b;if(typeof O=="object"){const{schemaId:k}=this.opts;if(b=O[k],b!==void 0&&typeof b!="string")throw new Error(`schema ${k} must be string`)}return P=(0,c.normalizeId)(P||b),this._checkUnique(P),this.schemas[P]=this._addSchema(O,A,P,y,!0),this}addMetaSchema(O,P,A=this.opts.validateSchema){return this.addSchema(O,P,!0,A),this}validateSchema(O,P){if(typeof O=="boolean")return!0;let A;if(A=O.$schema,A!==void 0&&typeof A!="string")throw new Error("$schema must be a string");if(A=A||this.opts.defaultMeta||this.defaultMeta(),!A)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const y=this.validate(A,O);if(!y&&P){const b="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(b);else throw new Error(b)}return y}getSchema(O){let P;for(;typeof(P=I.call(this,O))=="string";)O=P;if(P===void 0){const{schemaId:A}=this.opts,y=new i.SchemaEnv({schema:{},schemaId:A});if(P=i.resolveSchema.call(this,y,O),!P)return;this.refs[O]=P}return P.validate||this._compileSchemaEnv(P)}removeSchema(O){if(O instanceof RegExp)return this._removeAllSchemas(this.schemas,O),this._removeAllSchemas(this.refs,O),this;switch(typeof O){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const P=I.call(this,O);return typeof P=="object"&&this._cache.delete(P.schema),delete this.schemas[O],delete this.refs[O],this}case"object":{const P=O;this._cache.delete(P);let A=O[this.opts.schemaId];return A&&(A=(0,c.normalizeId)(A),delete this.schemas[A],delete this.refs[A]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(O){for(const P of O)this.addKeyword(P);return this}addKeyword(O,P){let A;if(typeof O=="string")A=O,typeof P=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),P.keyword=A);else if(typeof O=="object"&&P===void 0){if(P=O,A=P.keyword,Array.isArray(A)&&!A.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(oe.call(this,A,P),!P)return(0,l.eachItem)(A,b=>Oe.call(this,b)),this;tt.call(this,P);const y={...P,type:(0,u.getJSONTypes)(P.type),schemaType:(0,u.getJSONTypes)(P.schemaType)};return(0,l.eachItem)(A,y.type.length===0?b=>Oe.call(this,b,y):b=>y.type.forEach(k=>Oe.call(this,b,y,k))),this}getKeyword(O){const P=this.RULES.all[O];return typeof P=="object"?P.definition:!!P}removeKeyword(O){const{RULES:P}=this;delete P.keywords[O],delete P.all[O];for(const A of P.rules){const y=A.rules.findIndex(b=>b.keyword===O);y>=0&&A.rules.splice(y,1)}return this}addFormat(O,P){return typeof P=="string"&&(P=new RegExp(P)),this.formats[O]=P,this}errorsText(O=this.errors,{separator:P=", ",dataVar:A="data"}={}){return!O||O.length===0?"No errors":O.map(y=>`${A}${y.instancePath} ${y.message}`).reduce((y,b)=>y+P+b)}$dataMetaSchema(O,P){const A=this.RULES.all;O=JSON.parse(JSON.stringify(O));for(const y of P){const b=y.split("/").slice(1);let k=O;for(const U of b)k=k[U];for(const U in A){const F=A[U];if(typeof F!="object")continue;const{$data:te}=F.definition,X=k[U];te&&X&&(k[U]=Tt(X))}}return O}_removeAllSchemas(O,P){for(const A in O){const y=O[A];(!P||P.test(A))&&(typeof y=="string"?delete O[A]:y&&!y.meta&&(this._cache.delete(y.schema),delete O[A]))}}_addSchema(O,P,A,y=this.opts.validateSchema,b=this.opts.addUsedSchema){let k;const{schemaId:U}=this.opts;if(typeof O=="object")k=O[U];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof O!="boolean")throw new Error("schema must be object or boolean")}let F=this._cache.get(O);if(F!==void 0)return F;A=(0,c.normalizeId)(k||A);const te=c.getSchemaRefs.call(this,O,A);return F=new i.SchemaEnv({schema:O,schemaId:U,meta:P,baseId:A,localRefs:te}),this._cache.set(F.schema,F),b&&!A.startsWith("#")&&(A&&this._checkUnique(A),this.refs[A]=F),y&&this.validateSchema(O,!0),F}_checkUnique(O){if(this.schemas[O]||this.refs[O])throw new Error(`schema with key or id "${O}" already exists`)}_compileSchemaEnv(O){if(O.meta?this._compileMetaSchema(O):i.compileSchema.call(this,O),!O.validate)throw new Error("ajv implementation error");return O.validate}_compileMetaSchema(O){const P=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,O)}finally{this.opts=P}}}S.ValidationError=r.default,S.MissingRefError=o.default,e.default=S;function N(R,O,P,A="error"){for(const y in R){const b=y;b in O&&this.logger[A](`${P}: option ${y}. ${R[b]}`)}}function I(R){return R=(0,c.normalizeId)(R),this.schemas[R]||this.refs[R]}function T(){const R=this.opts.schemas;if(R)if(Array.isArray(R))this.addSchema(R);else for(const O in R)this.addSchema(R[O],O)}function K(){for(const R in this.opts.formats){const O=this.opts.formats[R];O&&this.addFormat(R,O)}}function L(R){if(Array.isArray(R)){this.addVocabulary(R);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const O in R){const P=R[O];P.keyword||(P.keyword=O),this.addKeyword(P)}}function V(){const R={...this.opts};for(const O of d)delete R[O];return R}const H={log(){},warn(){},error(){}};function Q(R){if(R===!1)return H;if(R===void 0)return console;if(R.log&&R.warn&&R.error)return R;throw new Error("logger must implement log, warn and error methods")}const ee=/^[a-z_$][a-z0-9_$:-]*$/i;function oe(R,O){const{RULES:P}=this;if((0,l.eachItem)(R,A=>{if(P.keywords[A])throw new Error(`Keyword ${A} is already defined`);if(!ee.test(A))throw new Error(`Keyword ${A} has invalid name`)}),!!O&&O.$data&&!("code"in O||"validate"in O))throw new Error('$data keyword must have "code" or "validate" function')}function Oe(R,O,P){var A;const y=O==null?void 0:O.post;if(P&&y)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:b}=this;let k=y?b.post:b.rules.find(({type:F})=>F===P);if(k||(k={type:P,rules:[]},b.rules.push(k)),b.keywords[R]=!0,!O)return;const U={keyword:R,definition:{...O,type:(0,u.getJSONTypes)(O.type),schemaType:(0,u.getJSONTypes)(O.schemaType)}};O.before?ue.call(this,k,U,O.before):k.rules.push(U),b.all[R]=U,(A=O.implements)===null||A===void 0||A.forEach(F=>this.addKeyword(F))}function ue(R,O,P){const A=R.rules.findIndex(y=>y.keyword===P);A>=0?R.rules.splice(A,0,O):(R.rules.push(O),this.logger.warn(`rule ${P} is not defined`))}function tt(R){let{metaSchema:O}=R;O!==void 0&&(R.$data&&this.opts.$data&&(O=Tt(O)),R.validateSchema=this.compile(O,!0))}const sn={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Tt(R){return{anyOf:[R,sn]}}})(Kl);var Qs={},Ys={},Zs={};Object.defineProperty(Zs,"__esModule",{value:!0});const ev={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Zs.default=ev;var Pt={};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.callRef=Pt.getValidate=void 0;const tv=nn,lc=Be(),be=W,Mt=lt(),fc=Ne,Fn=D,nv={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=fc.resolveRef.call(c,u,o,n);if(l===void 0)throw new tv.default(r.opts.uriResolver,o,n);if(l instanceof fc.SchemaEnv)return p(l);return h(l);function f(){if(s===u)return sr(e,i,s,s.$async);const d=t.scopeValue("root",{ref:u});return sr(e,(0,be._)`${d}.validate`,u,u.$async)}function p(d){const m=Sf(e,d);sr(e,m,d,d.$async)}function h(d){const m=t.scopeValue("schema",a.code.source===!0?{ref:d,code:(0,be.stringify)(d)}:{ref:d}),g=t.name("valid"),$=e.subschema({schema:d,dataTypes:[],schemaPath:be.nil,topSchemaRef:m,errSchemaPath:n},g);e.mergeEvaluated($),e.ok(g)}}};function Sf(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,be._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Pt.getValidate=Sf;function sr(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Mt.default.this:be.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,be._)`await ${(0,lc.callValidateCode)(e,t,u)}`),h(t),i||o.assign(d,!0)},m=>{o.if((0,be._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(d,!1)}),e.ok(d)}function f(){e.result((0,lc.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(d){const m=(0,be._)`${d}.errors`;o.assign(Mt.default.vErrors,(0,be._)`${Mt.default.vErrors} === null ? ${m} : ${Mt.default.vErrors}.concat(${m})`),o.assign(Mt.default.errors,(0,be._)`${Mt.default.vErrors}.length`)}function h(d){var m;if(!s.opts.unevaluated)return;const g=(m=n==null?void 0:n.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Fn.mergeEvaluated.props(o,g.props,s.props));else{const $=o.var("props",(0,be._)`${d}.evaluated.props`);s.props=Fn.mergeEvaluated.props(o,$,s.props,be.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Fn.mergeEvaluated.items(o,g.items,s.items));else{const $=o.var("items",(0,be._)`${d}.evaluated.items`);s.items=Fn.mergeEvaluated.items(o,$,s.items,be.Name)}}}Pt.callRef=sr;Pt.default=nv;Object.defineProperty(Ys,"__esModule",{value:!0});const rv=Zs,ov=Pt,sv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rv.default,ov.default];Ys.default=sv;var Xs={},ei={};Object.defineProperty(ei,"__esModule",{value:!0});const hr=W,rt=hr.operators,mr={maximum:{okStr:"<=",ok:rt.LTE,fail:rt.GT},minimum:{okStr:">=",ok:rt.GTE,fail:rt.LT},exclusiveMaximum:{okStr:"<",ok:rt.LT,fail:rt.GTE},exclusiveMinimum:{okStr:">",ok:rt.GT,fail:rt.LTE}},iv={message:({keyword:e,schemaCode:t})=>(0,hr.str)`must be ${mr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,hr._)`{comparison: ${mr[e].okStr}, limit: ${t}}`},av={keyword:Object.keys(mr),type:"number",schemaType:"number",$data:!0,error:iv,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,hr._)`${n} ${mr[t].fail} ${r} || isNaN(${n})`)}};ei.default=av;var ti={};Object.defineProperty(ti,"__esModule",{value:!0});const $n=W,cv={message:({schemaCode:e})=>(0,$n.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,$n._)`{multipleOf: ${e}}`},uv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:cv,code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,$n._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,$n._)`${i} !== parseInt(${i})`;e.fail$data((0,$n._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};ti.default=uv;var ni={},ri={};Object.defineProperty(ri,"__esModule",{value:!0});function Ef(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}ri.default=Ef;Ef.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(ni,"__esModule",{value:!0});const wt=W,lv=D,fv=ri,dv={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,wt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,wt._)`{limit: ${e}}`},pv={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:dv,code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?wt.operators.GT:wt.operators.LT,i=o.opts.unicode===!1?(0,wt._)`${n}.length`:(0,wt._)`${(0,lv.useFunc)(e.gen,fv.default)}(${n})`;e.fail$data((0,wt._)`${i} ${s} ${r}`)}};ni.default=pv;var oi={};Object.defineProperty(oi,"__esModule",{value:!0});const hv=Be(),mv=D,Ht=W,gv={message:({schemaCode:e})=>(0,Ht.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Ht._)`{pattern: ${e}}`},yv={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gv,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,mv.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,hv.usePattern)(e,o);e.fail$data((0,Ht._)`!${c}.test(${n})`)}}};oi.default=yv;var si={};Object.defineProperty(si,"__esModule",{value:!0});const vn=W,$v={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,vn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,vn._)`{limit: ${e}}`},vv={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$v,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?vn.operators.GT:vn.operators.LT;e.fail$data((0,vn._)`Object.keys(${n}).length ${o} ${r}`)}};si.default=vv;var ii={};Object.defineProperty(ii,"__esModule",{value:!0});const un=Be(),wn=W,wv=D,bv={message:({params:{missingProperty:e}})=>(0,wn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,wn._)`{missingProperty: ${e}}`},Sv={keyword:"required",type:"object",schemaType:"array",$data:!0,error:bv,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 g=i.schemaEnv.baseId+i.errSchemaPath,$=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,wv.checkStrictMode)(i,$,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(wn.nil,f);else for(const h of n)(0,un.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,un.checkMissingProp)(e,n,h)),(0,un.reportMissingProp)(e,h),t.else()}function f(){t.forOf("prop",r,h=>{e.setParams({missingProperty:h}),t.if((0,un.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,d){e.setParams({missingProperty:h}),t.forOf(h,r,()=>{t.assign(d,(0,un.propertyInData)(t,o,h,a.ownProperties)),t.if((0,wn.not)(d),()=>{e.error(),t.break()})},wn.nil)}}};ii.default=Sv;var ai={};Object.defineProperty(ai,"__esModule",{value:!0});const bn=W,Ev={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,bn.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,bn._)`{limit: ${e}}`},Nv={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Ev,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?bn.operators.GT:bn.operators.LT;e.fail$data((0,bn._)`${n}.length ${o} ${r}`)}};ai.default=Nv;var ci={},Pn={};Object.defineProperty(Pn,"__esModule",{value:!0});const Nf=ef;Nf.code='require("ajv/dist/runtime/equal").default';Pn.default=Nf;Object.defineProperty(ci,"__esModule",{value:!0});const no=le,he=W,Ov=D,_v=Pn,Av={message:({params:{i:e,j:t}})=>(0,he.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,he._)`{i: ${e}, j: ${t}}`},kv={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Av,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,no.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,he._)`${i} === false`),e.ok(c);function l(){const d=t.let("i",(0,he._)`${n}.length`),m=t.let("j");e.setParams({i:d,j:m}),t.assign(c,!0),t.if((0,he._)`${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 g=t.name("item"),$=(0,no.checkDataTypes)(u,g,a.opts.strictNumbers,no.DataType.Wrong),v=t.const("indices",(0,he._)`{}`);t.for((0,he._)`;${d}--;`,()=>{t.let(g,(0,he._)`${n}[${d}]`),t.if($,(0,he._)`continue`),u.length>1&&t.if((0,he._)`typeof ${g} == "string"`,(0,he._)`${g} += "_"`),t.if((0,he._)`typeof ${v}[${g}] == "number"`,()=>{t.assign(m,(0,he._)`${v}[${g}]`),e.error(),t.assign(c,!1).break()}).code((0,he._)`${v}[${g}] = ${d}`)})}function h(d,m){const g=(0,Ov.useFunc)(t,_v.default),$=t.name("outer");t.label($).for((0,he._)`;${d}--;`,()=>t.for((0,he._)`${m} = ${d}; ${m}--;`,()=>t.if((0,he._)`${g}(${n}[${d}], ${n}[${m}])`,()=>{e.error(),t.assign(c,!1).break($)})))}}};ci.default=kv;var ui={};Object.defineProperty(ui,"__esModule",{value:!0});const Fo=W,jv=D,Iv=Pn,xv={message:"must be equal to constant",params:({schemaCode:e})=>(0,Fo._)`{allowedValue: ${e}}`},Pv={keyword:"const",$data:!0,error:xv,code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,Fo._)`!${(0,jv.useFunc)(t,Iv.default)}(${n}, ${o})`):e.fail((0,Fo._)`${s} !== ${n}`)}};ui.default=Pv;var li={};Object.defineProperty(li,"__esModule",{value:!0});const mn=W,Tv=D,Cv=Pn,Rv={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,mn._)`{allowedValues: ${e}}`},Mv={keyword:"enum",schemaType:"array",$data:!0,error:Rv,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,Tv.useFunc)(t,Cv.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,mn.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,mn._)`${u()}(${n}, ${h})`,()=>t.assign(l,!0).break()))}function p(h,d){const m=o[d];return typeof m=="object"&&m!==null?(0,mn._)`${u()}(${n}, ${h}[${d}])`:(0,mn._)`${n} === ${m}`}}};li.default=Mv;Object.defineProperty(Xs,"__esModule",{value:!0});const Dv=ei,Lv=ti,Uv=ni,Bv=oi,Fv=si,Vv=ii,qv=ai,Kv=ci,zv=ui,Gv=li,Hv=[Dv.default,Lv.default,Uv.default,Bv.default,Fv.default,Vv.default,qv.default,Kv.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},zv.default,Gv.default];Xs.default=Hv;var fi={},rn={};Object.defineProperty(rn,"__esModule",{value:!0});rn.validateAdditionalItems=void 0;const bt=W,Vo=D,Jv={message:({params:{len:e}})=>(0,bt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,bt._)`{limit: ${e}}`},Wv={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Jv,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,Vo.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Of(e,r)}};function Of(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,bt._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,bt._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,Vo.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,bt._)`${a} <= ${t.length}`);n.if((0,bt.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Vo.Type.Num},u),i.allErrors||n.if((0,bt.not)(u),()=>n.break())})}}rn.validateAdditionalItems=Of;rn.default=Wv;var di={},on={};Object.defineProperty(on,"__esModule",{value:!0});on.validateTuple=void 0;const dc=W,ir=D,Qv=Be(),Yv={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return _f(e,"additionalItems",t);n.items=!0,!(0,ir.alwaysValidSchema)(n,t)&&e.ok((0,Qv.validateArray)(e))}};function _f(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=ir.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,dc._)`${s}.length`);n.forEach((f,p)=>{(0,ir.alwaysValidSchema)(a,f)||(r.if((0,dc._)`${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 g=`"${i}" is ${d}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,ir.checkStrictMode)(a,g,p.strictTuples)}}}on.validateTuple=_f;on.default=Yv;Object.defineProperty(di,"__esModule",{value:!0});const Zv=on,Xv={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Zv.validateTuple)(e,"items")};di.default=Xv;var pi={};Object.defineProperty(pi,"__esModule",{value:!0});const pc=W,e0=D,t0=Be(),n0=rn,r0={message:({params:{len:e}})=>(0,pc.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,pc._)`{limit: ${e}}`},o0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:r0,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,e0.alwaysValidSchema)(r,t)&&(o?(0,n0.validateAdditionalItems)(e,o):e.ok((0,t0.validateArray)(e)))}};pi.default=o0;var hi={};Object.defineProperty(hi,"__esModule",{value:!0});const xe=W,Vn=D,s0={message:({params:{min:e,max:t}})=>t===void 0?(0,xe.str)`must contain at least ${e} valid item(s)`:(0,xe.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,xe._)`{minContains: ${e}}`:(0,xe._)`{minContains: ${e}, maxContains: ${t}}`},i0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:s0,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,xe._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Vn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Vn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Vn.alwaysValidSchema)(s,n)){let m=(0,xe._)`${l} >= ${i}`;a!==void 0&&(m=(0,xe._)`${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,xe._)`${o}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset());function p(){const m=t.name("_valid"),g=t.let("count",0);h(m,()=>t.if(m,()=>d(g)))}function h(m,g){t.forRange("i",0,l,$=>{e.subschema({keyword:"contains",dataProp:$,dataPropType:Vn.Type.Num,compositeRule:!0},m),g()})}function d(m){t.code((0,xe._)`${m}++`),a===void 0?t.if((0,xe._)`${m} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,xe._)`${m} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,xe._)`${m} >= ${i}`,()=>t.assign(f,!0)))}}};hi.default=i0;var Af={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=W,n=D,r=Be();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},
153
+ `}};pe(Qs,"defaults",Zl);function ly(e,t=!0,n){n===void 0&&typeof t=="string"&&(n=t,t=!0);const r=Object.assign({},Qs.defaults[lr.version],lr);return new En(r).createNode(e,t,n)}class jr extends Qs{constructor(t){super(Object.assign({},lr,t))}}function fy(e,t){const n=[];let r;for(const o of qs(e)){const s=new jr(t);s.parse(o,r),n.push(s),r=s}return n}function Xl(e,t){const n=qs(e),r=new jr(t).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new F(n[1],o))}return r}function dy(e,t){const n=Xl(e,t);if(n.warnings.forEach(r=>Ul(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function py(e,t){const n=new jr(t);return n.contents=e,String(n)}const hy={createNode:ly,defaultOptions:lr,Document:jr,parse:dy,parseAllDocuments:fy,parseCST:qs,parseDocument:Xl,scalarOptions:ny,stringify:py},my=Object.freeze(Object.defineProperty({__proto__:null,YAML:hy},Symbol.toStringTag,{value:"Module"})),gy=fg(my);var yy=gy.YAML;const $y="1.0.0-redesign.1",vy="adhd",wy="default",by="adhd-environment.json",lo="config.yaml",Ey="config.local.yaml",Sy={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class uc extends Error{constructor(t,n){super(`contentHash: lone surrogate in ${t} (not well-formed Unicode)`),this.location=t,this.offending=n,this.name="LoneSurrogateError"}}function lc(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const r=t+1<e.length?e.charCodeAt(t+1):0;if(r<56320||r>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function ef(e,t){const n=Array.from(e),r=Array.from(t),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 fc(e){return new TextEncoder().encode(e).length}function Ny(e){const t=Object.keys(e).sort(ef);let n="";for(const r of t){const o=e[r];if(lc(r))throw new uc("key",r);if(lc(o))throw new uc("value",o);n+=`${fc(r)}:${r}=${fc(o)}:${o}
154
+ `}return`sha256-${tf(n)}`}function Oy(e){const t=[...e].sort((n,r)=>ef(n.name,r.name)).map(n=>`${n.name}:${n.kind}:${n.scope}`).join(`
155
+ `);return`sha256-${tf(t)}`}function _y(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function ky(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Ay(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]=jy(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 jy(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 Iy="adhd-env-ref:";function Py(e){return`${Iy}${e}`}const xy=[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],Ty=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Te(e,t){return(e>>>t|e<<32-t)>>>0}function Cy(e){const t=Uint32Array.from(Ty),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 S=0;S<16;S++)c[S]=a.getUint32(f+S*4,!1);for(let S=16;S<64;S++){const O=c[S-15],j=c[S-2],C=Te(O,7)^Te(O,18)^O>>>3,W=Te(j,17)^Te(j,19)^j>>>10;c[S]=c[S-16]+C+c[S-7]+W>>>0}let p=t[0],h=t[1],d=t[2],g=t[3],y=t[4],$=t[5],v=t[6],b=t[7];for(let S=0;S<64;S++){const O=Te(y,6)^Te(y,11)^Te(y,25),j=y&$^~y&v,C=b+O+j+xy[S]+c[S]>>>0,W=Te(p,2)^Te(p,13)^Te(p,22),B=p&h^p&d^h&d,q=W+B>>>0;b=v,v=$,$=y,y=g+C>>>0,g=d,d=h,h=p,p=C+q>>>0}t[0]=t[0]+p>>>0,t[1]=t[1]+h>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+g>>>0,t[4]=t[4]+y>>>0,t[5]=t[5]+$>>>0,t[6]=t[6]+v>>>0,t[7]=t[7]+b>>>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 Ry(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function tf(e){const t=new TextEncoder().encode(e);return Ry(Cy(t))}function nf(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,nf(o,s)):n[s]=o}return n}function Ln(e){if(U.existsSync(e))try{const t=U.readFileSync(e,"utf8"),n=yy.parse(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:nf(n)}catch{return}}function My(e){return{system:Ln(T.join(e.system,lo)),global:Ln(T.join(e.global,lo)),project:e.project?Ln(T.join(e.project,lo)):void 0,local:e.project?Ln(T.join(e.project,Ey)):void 0}}function Dy(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function zo(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 rf(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 Ly=[["system","system"],["global","global"],["project","project"],["local","local"]];function By(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:ky(r.prefix,c),f=u.at==="runtime"||u.secret===!0,p=u.scope??r.activeScope;let h=u.default,d="default";for(const[b,S]of Ly){const O=t[b];O&&Object.prototype.hasOwnProperty.call(O,c)&&(h=zo(O[c],u.type),d=S)}const g=n[l];let y,$,v;g!==void 0?(y=zo(g,u.type),$="env",v=l):(y=h,$=d),o[c]=f?Py(l):y,s[c]=y,i[c]=Dy(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:rf(o),typedRaw:s,provenance:i,fields:a}}function Uy(e,t){return e.replace(/\$\{HOME\}/g,We.homedir()).replace(/\$HOME\b/g,We.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function Fy(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=o.scope??t.activeScope,i=o.share??Sy[o.kind],a=o.path?Uy(o.path,t):T.join(ll(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 Vy(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 Wo={exports:{}},of={},xe={},Jt={},An={},G={},Sn={};(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((b,S)=>`${b}${S}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((b,S)=>(S instanceof n&&(b[S.str]=(b[S.str]||0)+1),b),{})}}e._Code=r,e.nil=new r("");function o($,...v){const b=[$[0]];let S=0;for(;S<v.length;)a(b,v[S]),b.push($[++S]);return new r(b)}e._=o;const s=new r("+");function i($,...v){const b=[h($[0])];let S=0;for(;S<v.length;)b.push(s),a(b,v[S]),b.push(s,h($[++S]));return c(b),new r(b)}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 b=u($[v-1],$[v+1]);if(b!==void 0){$.splice(v-1,3,b);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 g($){if(typeof $=="string"&&e.IDENTIFIER.test($))return new r(`${$}`);throw new Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}e.getEsmExportName=g;function y($){return new r($.toString())}e.regexpCode=y})(Sn);var Jo={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Sn;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 g=this._values[h];if(g){const v=g.get(d);if(v)return v}else g=this._values[h]=new Map;g.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 g=u[d];if(!g)continue;const y=f[d]=f[d]||new Map;g.forEach($=>{if(y.has($))return;y.set($,r.Started);let v=l($);if(v){const b=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${b} ${$} = ${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})(Jo);(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=Sn,n=Jo;var r=Sn;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=Jo;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(m,w){return this}}class i extends s{constructor(m,w,_){super(),this.varKind=m,this.name=w,this.rhs=_}render({es5:m,_n:w}){const _=m?n.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${_} ${this.name}${M};`+w}optimizeNames(m,w){if(m[this.name.str])return this.rhs&&(this.rhs=Ne(this.rhs,m,w)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(m,w,_){super(),this.lhs=m,this.rhs=w,this.sideEffects=_}render({_n:m}){return`${this.lhs} = ${this.rhs};`+m}optimizeNames(m,w){if(!(this.lhs instanceof t.Name&&!m[this.lhs.str]&&!this.sideEffects))return this.rhs=Ne(this.rhs,m,w),this}get names(){const m=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ve(m,this.rhs)}}class c extends a{constructor(m,w,_,M){super(m,_,M),this.op=w}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 f extends s{constructor(m){super(),this.error=m}render({_n:m}){return`throw ${this.error};`+m}get names(){return this.error.names}}class p extends s{constructor(m){super(),this.code=m}render({_n:m}){return`${this.code};`+m}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(m,w){return this.code=Ne(this.code,m,w),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(m=[]){super(),this.nodes=m}render(m){return this.nodes.reduce((w,_)=>w+_.render(m),"")}optimizeNodes(){const{nodes:m}=this;let w=m.length;for(;w--;){const _=m[w].optimizeNodes();Array.isArray(_)?m.splice(w,1,..._):_?m[w]=_:m.splice(w,1)}return m.length>0?this:void 0}optimizeNames(m,w){const{nodes:_}=this;let M=_.length;for(;M--;){const D=_[M];D.optimizeNames(m,w)||(Ue(m,D.names),_.splice(M,1))}return _.length>0?this:void 0}get names(){return this.nodes.reduce((m,w)=>Q(m,w.names),{})}}class d extends h{render(m){return"{"+m._n+super.render(m)+"}"+m._n}}class g extends h{}class y extends d{}y.kind="else";class $ extends d{constructor(m,w){super(w),this.condition=m}render(m){let w=`if(${this.condition})`+super.render(m);return this.else&&(w+="else "+this.else.render(m)),w}optimizeNodes(){super.optimizeNodes();const m=this.condition;if(m===!0)return this.nodes;let w=this.else;if(w){const _=w.optimizeNodes();w=this.else=Array.isArray(_)?new y(_):_}if(w)return m===!1?w instanceof $?w:w.nodes:this.nodes.length?this:new $(fe(m),w instanceof $?[w]:w.nodes);if(!(m===!1||!this.nodes.length))return this}optimizeNames(m,w){var _;if(this.else=(_=this.else)===null||_===void 0?void 0:_.optimizeNames(m,w),!!(super.optimizeNames(m,w)||this.else))return this.condition=Ne(this.condition,m,w),this}get names(){const m=super.names;return ve(m,this.condition),this.else&&Q(m,this.else.names),m}}$.kind="if";class v extends d{}v.kind="for";class b extends v{constructor(m){super(),this.iteration=m}render(m){return`for(${this.iteration})`+super.render(m)}optimizeNames(m,w){if(super.optimizeNames(m,w))return this.iteration=Ne(this.iteration,m,w),this}get names(){return Q(super.names,this.iteration.names)}}class S extends v{constructor(m,w,_,M){super(),this.varKind=m,this.name=w,this.from=_,this.to=M}render(m){const w=m.es5?n.varKinds.var:this.varKind,{name:_,from:M,to:D}=this;return`for(${w} ${_}=${M}; ${_}<${D}; ${_}++)`+super.render(m)}get names(){const m=ve(super.names,this.from);return ve(m,this.to)}}class O extends v{constructor(m,w,_,M){super(),this.loop=m,this.varKind=w,this.name=_,this.iterable=M}render(m){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(m)}optimizeNames(m,w){if(super.optimizeNames(m,w))return this.iterable=Ne(this.iterable,m,w),this}get names(){return Q(super.names,this.iterable.names)}}class j extends d{constructor(m,w,_){super(),this.name=m,this.args=w,this.async=_}render(m){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(m)}}j.kind="func";class C extends h{render(m){return"return "+super.render(m)}}C.kind="return";class W extends d{render(m){let w="try"+super.render(m);return this.catch&&(w+=this.catch.render(m)),this.finally&&(w+=this.finally.render(m)),w}optimizeNodes(){var m,w;return super.optimizeNodes(),(m=this.catch)===null||m===void 0||m.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(m,w){var _,M;return super.optimizeNames(m,w),(_=this.catch)===null||_===void 0||_.optimizeNames(m,w),(M=this.finally)===null||M===void 0||M.optimizeNames(m,w),this}get names(){const m=super.names;return this.catch&&Q(m,this.catch.names),this.finally&&Q(m,this.finally.names),m}}class B extends d{constructor(m){super(),this.error=m}render(m){return`catch(${this.error})`+super.render(m)}}B.kind="catch";class q extends d{render(m){return"finally"+super.render(m)}}q.kind="finally";class Z{constructor(m,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
156
+ `:""},this._extScope=m,this._scope=new n.Scope({parent:m}),this._nodes=[new g]}toString(){return this._root.render(this.opts)}name(m){return this._scope.name(m)}scopeName(m){return this._extScope.name(m)}scopeValue(m,w){const _=this._extScope.value(m,w);return(this._values[_.prefix]||(this._values[_.prefix]=new Set)).add(_),_}getScopeValue(m,w){return this._extScope.getValue(m,w)}scopeRefs(m){return this._extScope.scopeRefs(m,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(m,w,_,M){const D=this._scope.toName(w);return _!==void 0&&M&&(this._constants[D.str]=_),this._leafNode(new i(m,D,_)),D}const(m,w,_){return this._def(n.varKinds.const,m,w,_)}let(m,w,_){return this._def(n.varKinds.let,m,w,_)}var(m,w,_){return this._def(n.varKinds.var,m,w,_)}assign(m,w,_){return this._leafNode(new a(m,w,_))}add(m,w){return this._leafNode(new c(m,e.operators.ADD,w))}code(m){return typeof m=="function"?m():m!==t.nil&&this._leafNode(new p(m)),this}object(...m){const w=["{"];for(const[_,M]of m)w.length>1&&w.push(","),w.push(_),(_!==M||this.opts.es5)&&(w.push(":"),(0,t.addCodeArg)(w,M));return w.push("}"),new t._Code(w)}if(m,w,_){if(this._blockNode(new $(m)),w&&_)this.code(w).else().code(_).endIf();else if(w)this.code(w).endIf();else if(_)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(m){return this._elseNode(new $(m))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode($,y)}_for(m,w){return this._blockNode(m),w&&this.code(w).endFor(),this}for(m,w){return this._for(new b(m),w)}forRange(m,w,_,M,D=this.opts.es5?n.varKinds.var:n.varKinds.let){const H=this._scope.toName(m);return this._for(new S(D,H,w,_),()=>M(H))}forOf(m,w,_,M=n.varKinds.const){const D=this._scope.toName(m);if(this.opts.es5){const H=w instanceof t.Name?w:this.var("_arr",w);return this.forRange("_i",0,(0,t._)`${H}.length`,J=>{this.var(D,(0,t._)`${H}[${J}]`),_(D)})}return this._for(new O("of",M,D,w),()=>_(D))}forIn(m,w,_,M=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(m,(0,t._)`Object.keys(${w})`,_);const D=this._scope.toName(m);return this._for(new O("in",M,D,w),()=>_(D))}endFor(){return this._endBlockNode(v)}label(m){return this._leafNode(new u(m))}break(m){return this._leafNode(new l(m))}return(m){const w=new C;if(this._blockNode(w),this.code(m),w.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(m,w,_){if(!w&&!_)throw new Error('CodeGen: "try" without "catch" and "finally"');const M=new W;if(this._blockNode(M),this.code(m),w){const D=this.name("e");this._currNode=M.catch=new B(D),w(D)}return _&&(this._currNode=M.finally=new q,this.code(_)),this._endBlockNode(B,q)}throw(m){return this._leafNode(new f(m))}block(m,w){return this._blockStarts.push(this._nodes.length),m&&this.code(m).endBlock(w),this}endBlock(m){const w=this._blockStarts.pop();if(w===void 0)throw new Error("CodeGen: not in self-balancing block");const _=this._nodes.length-w;if(_<0||m!==void 0&&_!==m)throw new Error(`CodeGen: wrong number of nodes: ${_} vs ${m} expected`);return this._nodes.length=w,this}func(m,w=t.nil,_,M){return this._blockNode(new j(m,w,_)),M&&this.code(M).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,w){const _=this._currNode;if(_ instanceof m||w&&_ instanceof w)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${w?`${m.kind}/${w.kind}`:m.kind}"`)}_elseNode(m){const w=this._currNode;if(!(w instanceof $))throw new Error('CodeGen: "else" without "if"');return this._currNode=w.else=m,this}get _root(){return this._nodes[0]}get _currNode(){const m=this._nodes;return m[m.length-1]}set _currNode(m){const w=this._nodes;w[w.length-1]=m}}e.CodeGen=Z;function Q(N,m){for(const w in m)N[w]=(N[w]||0)+(m[w]||0);return N}function ve(N,m){return m instanceof t._CodeOrName?Q(N,m.names):N}function Ne(N,m,w){if(N instanceof t.Name)return _(N);if(!M(N))return N;return new t._Code(N._items.reduce((D,H)=>(H instanceof t.Name&&(H=_(H)),H instanceof t._Code?D.push(...H._items):D.push(H),D),[]));function _(D){const H=w[D.str];return H===void 0||m[D.str]!==1?D:(delete m[D.str],H)}function M(D){return D instanceof t._Code&&D._items.some(H=>H instanceof t.Name&&m[H.str]===1&&w[H.str]!==void 0)}}function Ue(N,m){for(const w in m)N[w]=(N[w]||0)-(m[w]||0)}function fe(N){return typeof N=="boolean"||typeof N=="number"||N===null?!N:(0,t._)`!${A(N)}`}e.not=fe;const tn=E(e.operators.AND);function Vr(...N){return N.reduce(tn)}e.and=Vr;const Pn=E(e.operators.OR);function P(...N){return N.reduce(Pn)}e.or=P;function E(N){return(m,w)=>m===t.nil?w:w===t.nil?m:(0,t._)`${A(m)} ${N} ${A(w)}`}function A(N){return N instanceof t.Name?N:(0,t._)`(${N})`}})(G);var x={};Object.defineProperty(x,"__esModule",{value:!0});x.checkStrictMode=x.getErrorPath=x.Type=x.useFunc=x.setEvaluated=x.evaluatedPropsToName=x.mergeEvaluated=x.eachItem=x.unescapeJsonPointer=x.escapeJsonPointer=x.escapeFragment=x.unescapeFragment=x.schemaRefOrVal=x.schemaHasRulesButRef=x.schemaHasRules=x.checkUnknownRules=x.alwaysValidSchema=x.toHash=void 0;const X=G,qy=Sn;function Ky(e){const t={};for(const n of e)t[n]=!0;return t}x.toHash=Ky;function Gy(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(sf(e,t),!af(t,e.self.RULES.all))}x.alwaysValidSchema=Gy;function sf(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]||lf(e,`unknown keyword: "${s}"`)}x.checkUnknownRules=sf;function af(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}x.schemaHasRules=af;function zy(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}x.schemaHasRulesButRef=zy;function Wy({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)}`}x.schemaRefOrVal=Wy;function Jy(e){return cf(decodeURIComponent(e))}x.unescapeFragment=Jy;function Hy(e){return encodeURIComponent(Zs(e))}x.escapeFragment=Hy;function Zs(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}x.escapeJsonPointer=Zs;function cf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}x.unescapeJsonPointer=cf;function Yy(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}x.eachItem=Yy;function dc({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}}x.mergeEvaluated={props:dc({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} || {}`),Xs(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:uf}),items:dc({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 uf(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,X._)`{}`);return t!==void 0&&Xs(e,n,t),n}x.evaluatedPropsToName=uf;function Xs(e,t,n){Object.keys(n).forEach(r=>e.assign((0,X._)`${t}${(0,X.getProperty)(r)}`,!0))}x.setEvaluated=Xs;const pc={};function Qy(e,t){return e.scopeValue("func",{ref:t,code:pc[t.code]||(pc[t.code]=new qy._Code(t.code))})}x.useFunc=Qy;var Ho;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ho||(x.Type=Ho={}));function Zy(e,t,n){if(e instanceof X.Name){const r=t===Ho.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():"/"+Zs(e)}x.getErrorPath=Zy;function lf(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}x.checkStrictMode=lf;var Be={};Object.defineProperty(Be,"__esModule",{value:!0});const de=G,Xy={data:new de.Name("data"),valCxt:new de.Name("valCxt"),instancePath:new de.Name("instancePath"),parentData:new de.Name("parentData"),parentDataProperty:new de.Name("parentDataProperty"),rootData:new de.Name("rootData"),dynamicAnchors:new de.Name("dynamicAnchors"),vErrors:new de.Name("vErrors"),errors:new de.Name("errors"),this:new de.Name("this"),self:new de.Name("self"),scope:new de.Name("scope"),json:new de.Name("json"),jsonPos:new de.Name("jsonPos"),jsonLen:new de.Name("jsonLen"),jsonPart:new de.Name("jsonPart")};Be.default=Xy;(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=x,r=Be;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,b){const{it:S}=y,{gen:O,compositeRule:j,allErrors:C}=S,W=f(y,$,v);b??(j||C)?c(O,W):u(S,(0,t._)`[${W}]`)}e.reportError=o;function s(y,$=e.keywordError,v){const{it:b}=y,{gen:S,compositeRule:O,allErrors:j}=b,C=f(y,$,v);c(S,C),O||j||u(b,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:b,errsCount:S,it:O}){if(S===void 0)throw new Error("ajv implementation error");const j=y.name("err");y.forRange("i",S,r.default.errors,C=>{y.const(j,(0,t._)`${r.default.vErrors}[${C}]`),y.if((0,t._)`${j}.instancePath === undefined`,()=>y.assign((0,t._)`${j}.instancePath`,(0,t.strConcat)(r.default.instancePath,O.errorPath))),y.assign((0,t._)`${j}.schemaPath`,(0,t.str)`${O.errSchemaPath}/${$}`),O.opts.verbose&&(y.assign((0,t._)`${j}.schema`,v),y.assign((0,t._)`${j}.data`,b))})}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:b,schemaEnv:S}=y;S.$async?v.throw((0,t._)`new ${y.ValidationError}(${$})`):(v.assign((0,t._)`${b}.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:b}=y.it;return b===!1?(0,t._)`{}`:p(y,$,v)}function p(y,$,v={}){const{gen:b,it:S}=y,O=[h(S,v),d(y,v)];return g(y,$,O),b.object(...O)}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:b}){let S=b?$:(0,t.str)`${$}/${y}`;return v&&(S=(0,t.str)`${S}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,S]}function g(y,{params:$,message:v},b){const{keyword:S,data:O,schemaValue:j,it:C}=y,{opts:W,propertyName:B,topSchemaRef:q,schemaPath:Z}=C;b.push([l.keyword,S],[l.params,typeof $=="function"?$(y):$||(0,t._)`{}`]),W.messages&&b.push([l.message,typeof v=="function"?v(y):v]),W.verbose&&b.push([l.schema,j],[l.parentSchema,(0,t._)`${q}${Z}`],[r.default.data,O]),B&&b.push([l.propertyName,B])}})(An);Object.defineProperty(Jt,"__esModule",{value:!0});Jt.boolOrEmptySchema=Jt.topBoolOrEmptySchema=void 0;const e$=An,t$=G,n$=Be,r$={message:"boolean schema is false"};function o$(e){const{gen:t,schema:n,validateName:r}=e;n===!1?ff(e,!1):typeof n=="object"&&n.$async===!0?t.return(n$.default.data):(t.assign((0,t$._)`${r}.errors`,null),t.return(!0))}Jt.topBoolOrEmptySchema=o$;function s$(e,t){const{gen:n,schema:r}=e;r===!1?(n.var(t,!1),ff(e)):n.var(t,!0)}Jt.boolOrEmptySchema=s$;function ff(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,e$.reportError)(o,r$,void 0,t)}var oe={},_t={};Object.defineProperty(_t,"__esModule",{value:!0});_t.getRules=_t.isJSONType=void 0;const i$=["string","number","integer","boolean","null","object","array"],a$=new Set(i$);function c$(e){return typeof e=="string"&&a$.has(e)}_t.isJSONType=c$;function u$(){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:{}}}_t.getRules=u$;var Ge={};Object.defineProperty(Ge,"__esModule",{value:!0});Ge.shouldUseRule=Ge.shouldUseGroup=Ge.schemaHasRulesForType=void 0;function l$({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&df(e,r)}Ge.schemaHasRulesForType=l$;function df(e,t){return t.rules.some(n=>pf(e,n))}Ge.shouldUseGroup=df;function pf(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))}Ge.shouldUseRule=pf;Object.defineProperty(oe,"__esModule",{value:!0});oe.reportTypeError=oe.checkDataTypes=oe.checkDataType=oe.coerceAndCheckDataType=oe.getJSONTypes=oe.getSchemaTypes=oe.DataType=void 0;const f$=_t,d$=Ge,p$=An,V=G,hf=x;var Kt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Kt||(oe.DataType=Kt={}));function h$(e){const t=mf(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}oe.getSchemaTypes=h$;function mf(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(f$.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}oe.getJSONTypes=mf;function m$(e,t){const{gen:n,data:r,opts:o}=e,s=g$(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,d$.schemaHasRulesForType)(e,t[0]));if(i){const a=ei(t,r,o.strictNumbers,Kt.Wrong);n.if(a,()=>{s.length?y$(e,t,s):ti(e)})}return i}oe.coerceAndCheckDataType=m$;const gf=new Set(["string","number","integer","boolean","null"]);function g$(e,t){return t?e.filter(n=>gf.has(n)||t==="array"&&n==="array"):[]}function y$(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(ei(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,V._)`${a} !== undefined`);for(const u of n)(gf.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),ti(e),r.endIf(),r.if((0,V._)`${a} !== undefined`,()=>{r.assign(o,a),$$(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,V._)`+${o}`);return;case"integer":r.elseIf((0,V._)`${i} === "boolean" || ${o} === null
158
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,V._)`+${o}`);return;case"boolean":r.elseIf((0,V._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,V._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,V._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,V._)`${i} === "string" || ${i} === "number"
159
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function $$({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,V._)`${t} !== undefined`,()=>e.assign((0,V._)`${t}[${n}]`,r))}function Yo(e,t,n,r=Kt.Correct){const o=r===Kt.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===Kt.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)}}oe.checkDataType=Yo;function ei(e,t,n,r){if(e.length===1)return Yo(e[0],t,n,r);let o;const s=(0,hf.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,Yo(i,t,n,r));return o}oe.checkDataTypes=ei;const v$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,V._)`{type: ${e}}`:(0,V._)`{type: ${t}}`};function ti(e){const t=w$(e);(0,p$.reportError)(t,v$)}oe.reportTypeError=ti;function w$(e){const{gen:t,data:n,schema:r}=e,o=(0,hf.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var Ir={};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.assignDefaults=void 0;const Pt=G,b$=x;function E$(e,t){const{properties:n,items:r}=e.schema;if(t==="object"&&n)for(const o in n)hc(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>hc(e,s,o.default))}Ir.assignDefaults=E$;function hc(e,t,n){const{gen:r,compositeRule:o,data:s,opts:i}=e;if(n===void 0)return;const a=(0,Pt._)`${s}${(0,Pt.getProperty)(t)}`;if(o){(0,b$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Pt._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Pt._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Pt._)`${a} = ${(0,Pt.stringify)(n)}`)}var Re={},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,ni=x,Ze=Be,S$=x;function N$(e,t){const{gen:n,data:r,it:o}=e;n.if(oi(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=N$;function O$({gen:e,data:t,it:{opts:n}},r,o){return(0,ee.or)(...r.map(s=>(0,ee.and)(oi(e,t,s,n.ownProperties),(0,ee._)`${o} = ${s}`)))}K.checkMissingProp=O$;function _$(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=_$;function yf(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=yf;function ri(e,t,n){return(0,ee._)`${yf(e)}.call(${t}, ${n})`}K.isOwnProperty=ri;function k$(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} !== undefined`;return r?(0,ee._)`${o} && ${ri(e,t,n)}`:o}K.propertyInData=k$;function oi(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} === undefined`;return r?(0,ee.or)(o,(0,ee.not)(ri(e,t,n))):o}K.noPropertyInData=oi;function $f(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=$f;function A$(e,t){return $f(t).filter(n=>!(0,ni.alwaysValidSchema)(e,t[n]))}K.schemaProperties=A$;function j$({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=[[Ze.default.instancePath,(0,ee.strConcat)(Ze.default.instancePath,s)],[Ze.default.parentData,i.parentData],[Ze.default.parentDataProperty,i.parentDataProperty],[Ze.default.rootData,Ze.default.rootData]];i.opts.dynamicRef&&f.push([Ze.default.dynamicAnchors,Ze.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=j$;const I$=(0,ee._)`new RegExp`;function P$({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"?I$:(0,S$.useFunc)(e,o)}(${n}, ${r})`})}K.usePattern=P$;function x$(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:ni.Type.Num},s),t.if((0,ee.not)(s),a)})}}K.validateArray=x$;function T$(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,ni.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=T$;Object.defineProperty(Re,"__esModule",{value:!0});Re.validateKeywordUsage=Re.validSchemaType=Re.funcKeywordCode=Re.macroKeywordCode=void 0;const he=G,mt=Be,C$=K,R$=An;function M$(e,t){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=vf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");e.subschema({schema:a,schemaPath:he.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Re.macroKeywordCode=M$;function D$(e,t){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;B$(c,t);const u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=vf(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)g(),t.modifying&&mc(e),y(()=>e.error());else{const $=t.async?h():d();t.modifying&&mc(e),y(()=>L$(e,$))}}function h(){const $=r.let("ruleErrs",null);return r.try(()=>g((0,he._)`await `),v=>r.assign(f,!1).if((0,he._)`${v} instanceof ${c.ValidationError}`,()=>r.assign($,(0,he._)`${v}.errors`),()=>r.throw(v))),$}function d(){const $=(0,he._)`${l}.errors`;return r.assign($,null),g(he.nil),$}function g($=t.async?(0,he._)`await `:he.nil){const v=c.opts.passContext?mt.default.this:mt.default.self,b=!("compile"in t&&!a||t.schema===!1);r.assign(f,(0,he._)`${$}${(0,C$.callValidateCode)(e,l,v,b)}`,t.modifying)}function y($){var v;r.if((0,he.not)((v=t.valid)!==null&&v!==void 0?v:f),$)}}Re.funcKeywordCode=D$;function mc(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,he._)`${r.parentData}[${r.parentDataProperty}]`))}function L$(e,t){const{gen:n}=e;n.if((0,he._)`Array.isArray(${t})`,()=>{n.assign(mt.default.vErrors,(0,he._)`${mt.default.vErrors} === null ? ${t} : ${mt.default.vErrors}.concat(${t})`).assign(mt.default.errors,(0,he._)`${mt.default.vErrors}.length`),(0,R$.extendErrors)(e)},()=>e.error())}function B$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function vf(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,he.stringify)(n)})}function U$(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")}Re.validSchemaType=U$;function F$({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)}}Re.validateKeywordUsage=F$;var st={};Object.defineProperty(st,"__esModule",{value:!0});st.extendSubschemaMode=st.extendSubschemaData=st.getSubschema=void 0;const Ce=G,wf=x;function V$(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,Ce._)`${e.schemaPath}${(0,Ce.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,Ce._)`${e.schemaPath}${(0,Ce.getProperty)(t)}${(0,Ce.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,wf.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')}st.getSubschema=V$;function q$(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,Ce._)`${t.data}${(0,Ce.getProperty)(n)}`,!0);c(p),e.errorPath=(0,Ce.str)`${u}${(0,wf.getErrorPath)(n,r,f.jsPropertySyntax)}`,e.parentDataProperty=(0,Ce._)`${n}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){const u=o instanceof Ce.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]}}st.extendSubschemaData=q$;function K$(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}st.extendSubschemaMode=K$;var ce={},bf=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},Ef={exports:{}},rt=Ef.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(){};tr(t,r,o,e,"",e)};rt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};rt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};rt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};rt.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 tr(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 rt.arrayKeywords)for(var p=0;p<f.length;p++)tr(e,t,n,f[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in rt.propsKeywords){if(f&&typeof f=="object")for(var h in f)tr(e,t,n,f[h],o+"/"+l+"/"+G$(h),s,o,l,r,h)}else(l in rt.keywords||e.allKeys&&!(l in rt.skipKeywords))&&tr(e,t,n,f,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function G$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var z$=Ef.exports;Object.defineProperty(ce,"__esModule",{value:!0});ce.getSchemaRefs=ce.resolveUrl=ce.normalizeId=ce._getFullPath=ce.getFullPath=ce.inlineRef=void 0;const W$=x,J$=bf,H$=z$,Y$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Q$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Qo(e):t?Sf(e)<=t:!1}ce.inlineRef=Q$;const Z$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qo(e){for(const t in e){if(Z$.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(Qo)||typeof n=="object"&&Qo(n))return!0}return!1}function Sf(e){let t=0;for(const n in e)if(n==="$ref"||(t++,!Y$.has(n)&&(typeof e[n]=="object"&&(0,W$.eachItem)(e[n],r=>t+=Sf(r)),t===1/0)))return 1/0;return t}function Nf(e,t="",n){n!==!1&&(t=Gt(t));const r=e.parse(t);return Of(e,r)}ce.getFullPath=Nf;function Of(e,t){return e.serialize(t).split("#")[0]+"#"}ce._getFullPath=Of;const X$=/#\/?$/;function Gt(e){return e?e.replace(X$,""):""}ce.normalizeId=Gt;function ev(e,t,n){return n=Gt(n),e.resolve(t,n)}ce.resolveUrl=ev;const tv=/^[a-z_][-a-z0-9._]*$/i;function nv(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Gt(e[n]||t),s={"":o},i=Nf(r,o,!1),a={},c=new Set;return H$(e,{allKeys:!0},(f,p,h,d)=>{if(d===void 0)return;const g=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 $(b){const S=this.opts.uriResolver.resolve;if(b=Gt(y?S(y,b):b),c.has(b))throw l(b);c.add(b);let O=this.refs[b];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?u(f,O.schema,b):b!==Gt(g)&&(b[0]==="#"?(u(f,a[b],b),a[b]=f):this.refs[b]=g),b}function v(b){if(typeof b=="string"){if(!tv.test(b))throw new Error(`invalid anchor "${b}"`);$.call(this,`#${b}`)}}}),a;function u(f,p,h){if(p!==void 0&&!J$(f,p))throw l(h)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ce.getSchemaRefs=nv;Object.defineProperty(xe,"__esModule",{value:!0});xe.getData=xe.KeywordCxt=xe.validateFunctionCode=void 0;const _f=Jt,gc=oe,si=Ge,fr=oe,rv=Ir,hn=Re,fo=st,R=G,L=Be,ov=ce,ze=x,rn=An;function sv(e){if(jf(e)&&(If(e),Af(e))){cv(e);return}kf(e,()=>(0,_f.topBoolOrEmptySchema)(e))}xe.validateFunctionCode=sv;function kf({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,R._)`${L.default.data}, ${L.default.valCxt}`,r.$async,()=>{e.code((0,R._)`"use strict"; ${yc(n,o)}`),av(e,o),e.code(s)}):e.func(t,(0,R._)`${L.default.data}, ${iv(o)}`,r.$async,()=>e.code(yc(n,o)).code(s))}function iv(e){return(0,R._)`{${L.default.instancePath}="", ${L.default.parentData}, ${L.default.parentDataProperty}, ${L.default.rootData}=${L.default.data}${e.dynamicRef?(0,R._)`, ${L.default.dynamicAnchors}={}`:R.nil}}={}`}function av(e,t){e.if(L.default.valCxt,()=>{e.var(L.default.instancePath,(0,R._)`${L.default.valCxt}.${L.default.instancePath}`),e.var(L.default.parentData,(0,R._)`${L.default.valCxt}.${L.default.parentData}`),e.var(L.default.parentDataProperty,(0,R._)`${L.default.valCxt}.${L.default.parentDataProperty}`),e.var(L.default.rootData,(0,R._)`${L.default.valCxt}.${L.default.rootData}`),t.dynamicRef&&e.var(L.default.dynamicAnchors,(0,R._)`${L.default.valCxt}.${L.default.dynamicAnchors}`)},()=>{e.var(L.default.instancePath,(0,R._)`""`),e.var(L.default.parentData,(0,R._)`undefined`),e.var(L.default.parentDataProperty,(0,R._)`undefined`),e.var(L.default.rootData,L.default.data),t.dynamicRef&&e.var(L.default.dynamicAnchors,(0,R._)`{}`)})}function cv(e){const{schema:t,opts:n,gen:r}=e;kf(e,()=>{n.$comment&&t.$comment&&xf(e),pv(e),r.let(L.default.vErrors,null),r.let(L.default.errors,0),n.unevaluated&&uv(e),Pf(e),gv(e)})}function uv(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,R._)`${n}.evaluated`),t.if((0,R._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,R._)`${e.evaluated}.props`,(0,R._)`undefined`)),t.if((0,R._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,R._)`${e.evaluated}.items`,(0,R._)`undefined`))}function yc(e,t){const n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,R._)`/*# sourceURL=${n} */`:R.nil}function lv(e,t){if(jf(e)&&(If(e),Af(e))){fv(e,t);return}(0,_f.boolOrEmptySchema)(e,t)}function Af({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 jf(e){return typeof e.schema!="boolean"}function fv(e,t){const{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&xf(e),hv(e),mv(e);const s=r.const("_errs",L.default.errors);Pf(e,s),r.var(t,(0,R._)`${s} === ${L.default.errors}`)}function If(e){(0,ze.checkUnknownRules)(e),dv(e)}function Pf(e,t){if(e.opts.jtd)return $c(e,[],!1,t);const n=(0,gc.getSchemaTypes)(e.schema),r=(0,gc.coerceAndCheckDataType)(e,n);$c(e,n,!r,t)}function dv(e){const{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,ze.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function pv(e){const{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ze.checkStrictMode)(e,"default is ignored in the schema root")}function hv(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,ov.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function mv(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function xf({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)e.code((0,R._)`${L.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,R.str)`${r}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,R._)`${L.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function gv(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,R._)`${L.default.errors} === 0`,()=>t.return(L.default.data),()=>t.throw((0,R._)`new ${o}(${L.default.vErrors})`)):(t.assign((0,R._)`${r}.errors`,L.default.vErrors),s.unevaluated&&yv(e),t.return((0,R._)`${L.default.errors} === 0`))}function yv({gen:e,evaluated:t,props:n,items:r}){n instanceof R.Name&&e.assign((0,R._)`${t}.props`,n),r instanceof R.Name&&e.assign((0,R._)`${t}.items`,r)}function $c(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,ze.schemaHasRulesButRef)(s,l))){o.block(()=>Rf(e,"$ref",l.all.$ref.definition));return}c.jtd||$v(e,t),o.block(()=>{for(const p of l.rules)f(p);f(l.post)});function f(p){(0,si.shouldUseGroup)(s,p)&&(p.type?(o.if((0,fr.checkDataType)(p.type,i,c.strictNumbers)),vc(e,p),t.length===1&&t[0]===p.type&&n&&(o.else(),(0,fr.reportTypeError)(e)),o.endIf()):vc(e,p),a||o.if((0,R._)`${L.default.errors} === ${r||0}`))}}function vc(e,t){const{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,rv.assignDefaults)(e,t.type),n.block(()=>{for(const s of t.rules)(0,si.shouldUseRule)(r,s)&&Rf(e,s.keyword,s.definition,t.type)})}function $v(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(vv(e,t),e.opts.allowUnionTypes||wv(e,t),bv(e,e.dataTypes))}function vv(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{Tf(e.dataTypes,n)||ii(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),Sv(e,t)}}function wv(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&ii(e,"use allowUnionTypes to allow union type keyword")}function bv(e,t){const n=e.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,si.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>Ev(t,i))&&ii(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function Ev(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Tf(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Sv(e,t){const n=[];for(const r of e.dataTypes)Tf(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function ii(e,t){const n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,ze.checkStrictMode)(e,t,e.opts.strictTypes)}class Cf{constructor(t,n,r){if((0,hn.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,ze.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",Mf(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,hn.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",L.default.errors))}result(t,n,r){this.failResult((0,R.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,R.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,R._)`${n} !== undefined && (${(0,R.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?rn.reportExtraError:rn.reportError)(this,this.def.error,n)}$dataError(){(0,rn.reportError)(this,this.def.$dataError||rn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,rn.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=R.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=R.nil,n=R.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,R.or)((0,R._)`${o} === undefined`,n)),t!==R.nil&&r.assign(t,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==R.nil&&r.assign(t,!1)),r.else()}invalid$data(){const{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,R.or)(i(),a());function i(){if(r.length){if(!(n instanceof R.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,R._)`${(0,fr.checkDataTypes)(c,n,s.opts.strictNumbers,fr.DataType.Wrong)}`}return R.nil}function a(){if(o.validateSchema){const c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,R._)`!${c}(${n})`}return R.nil}}subschema(t,n){const r=(0,fo.getSubschema)(this.it,t);(0,fo.extendSubschemaData)(r,this.it,t),(0,fo.extendSubschemaMode)(r,t);const o={...this.it,...r,items:void 0,props:void 0};return lv(o,n),o}mergeEvaluated(t,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=ze.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=ze.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,R.Name)),!0}}xe.KeywordCxt=Cf;function Rf(e,t,n,r){const o=new Cf(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,hn.funcKeywordCode)(o,n):"macro"in n?(0,hn.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,hn.funcKeywordCode)(o,n)}const Nv=/^\/(?:[^~]|~0|~1)*$/,Ov=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Mf(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return L.default.rootData;if(e[0]==="/"){if(!Nv.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=L.default.rootData}else{const u=Ov.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,R._)`${s}${(0,R.getProperty)((0,ze.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}xe.getData=Mf;var jn={};Object.defineProperty(jn,"__esModule",{value:!0});let _v=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};jn.default=_v;var Zt={};Object.defineProperty(Zt,"__esModule",{value:!0});const po=ce;class kv extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,po.resolveUrl)(t,n,r),this.missingSchema=(0,po.normalizeId)((0,po.getFullPath)(t,this.missingRef))}}Zt.default=kv;var $e={};Object.defineProperty($e,"__esModule",{value:!0});$e.resolveSchema=$e.getCompilingSchema=$e.resolveRef=$e.compileSchema=$e.SchemaEnv=void 0;const Ae=G,Av=jn,ut=Be,Ie=ce,wc=x,jv=xe;class Pr{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,Ie.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={}}}$e.SchemaEnv=Pr;function ai(e){const t=Df.call(this,e);if(t)return t;const n=(0,Ie.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ae.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:Av.default,code:(0,Ae._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:ut.default.data,parentData:ut.default.parentData,parentDataProperty:ut.default.parentDataProperty,dataNames:[ut.default.data],dataPathArr:[Ae.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ae.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ae.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ae._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,jv.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(ut.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const p=new Function(`${ut.default.self}`,`${ut.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 Ae.Name?void 0:h,items:d instanceof Ae.Name?void 0:d,dynamicProps:h instanceof Ae.Name,dynamicItems:d instanceof Ae.Name},p.source&&(p.source.evaluated=(0,Ae.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)}}$e.compileSchema=ai;function Iv(e,t,n){var r;n=(0,Ie.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=Tv.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 Pr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=Pv.call(this,s)}$e.resolveRef=Iv;function Pv(e){return(0,Ie.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ai.call(this,e)}function Df(e){for(const t of this._compilations)if(xv(t,e))return t}$e.getCompilingSchema=Df;function xv(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Tv(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||xr.call(this,e,t)}function xr(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Ie._getFullPath)(this.opts.uriResolver,n);let o=(0,Ie.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return ho.call(this,n,e);const s=(0,Ie.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=xr.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:ho.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||ai.call(this,i),s===(0,Ie.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Ie.resolveUrl)(this.opts.uriResolver,o,u)),new Pr({schema:a,schemaId:c,root:e,baseId:o})}return ho.call(this,n,i)}}$e.resolveSchema=xr;const Cv=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ho(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,wc.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!Cv.has(a)&&u&&(t=(0,Ie.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,wc.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Ie.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=xr.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Pr({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const Rv="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Mv="Meta-schema for $data reference (JSON AnySchema extension proposal)",Dv="object",Lv=["$data"],Bv={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},Uv=!1,Fv={$id:Rv,description:Mv,type:Dv,required:Lv,properties:Bv,additionalProperties:Uv};var ci={},Tr={exports:{}};const Vv=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Lf=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),ui=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Bf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),qv=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Uf(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 Kv=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function bc(e){return e.length=0,!0}function Gv(e,t,n){if(e.length){const r=Uf(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function zv(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=Gv;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=bc}else{o.push(u);continue}}return o.length&&(a===bc?n.zone=o.join(""):i?r.push(o.join("")):r.push(Uf(o))),n.address=r.join(""),n}function Ff(e){if(Wv(e,":")<2)return{host:e,isIPV6:!1};const t=zv(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 Wv(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function Jv(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 Hv={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Yv=/[@/?#:]/g,Qv=/[@/?#]/g;function Vf(e,t){const n=t?Qv:Yv;return n.lastIndex=0,e.replace(n,r=>Hv[r])}function Zv(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(ui(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Bf(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function Xv(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(ui(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Bf(s)?t+=s:t+="%"+o,n+=2;continue}}qv(e[n])?t+=e[n]:t+=escape(e[n])}return t}function e0(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(ui(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function t0(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!Lf(n)){const r=Ff(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Vf(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 qf={nonSimpleDomain:Kv,recomposeAuthority:t0,reescapeHostDelimiters:Vf,normalizePercentEncoding:Zv,normalizePathEncoding:Xv,escapePreservingEscapes:e0,removeDotSegments:Jv,isIPv4:Lf,isUUID:Vv,normalizeIPv6:Ff};const{isUUID:n0}=qf,r0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function Kf(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 Gf(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function zf(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 o0(e){return e.secure=Kf(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function s0(e){if((e.port===(Kf(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 i0(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(r0);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=li(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function a0(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=li(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 c0(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!n0(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function u0(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Wf={scheme:"http",domainHost:!0,parse:Gf,serialize:zf},l0={scheme:"https",domainHost:Wf.domainHost,parse:Gf,serialize:zf},nr={scheme:"ws",domainHost:!0,parse:o0,serialize:s0},f0={scheme:"wss",domainHost:nr.domainHost,parse:nr.parse,serialize:nr.serialize},d0={scheme:"urn",parse:i0,serialize:a0,skipNormalize:!0},p0={scheme:"urn:uuid",parse:c0,serialize:u0,skipNormalize:!0},dr={http:Wf,https:l0,ws:nr,wss:f0,urn:d0,"urn:uuid":p0};Object.setPrototypeOf(dr,null);function li(e){return e&&(dr[e]||dr[e.toLowerCase()])||void 0}var h0={SCHEMES:dr,getSchemeHandler:li};const{normalizeIPv6:m0,removeDotSegments:ln,recomposeAuthority:g0,normalizePercentEncoding:y0,normalizePathEncoding:$0,escapePreservingEscapes:v0,reescapeHostDelimiters:w0,isIPv4:b0,nonSimpleDomain:E0}=qf,{SCHEMES:S0,getSchemeHandler:Jf}=h0;function N0(e,t){return typeof e=="string"?e=j0(e,t):typeof e=="object"&&(e=Ht(kt(e,t),t)),e}function O0(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Hf(Ht(e,r),Ht(t,r),r,!0);return r.skipEscape=!0,kt(o,r)}function Hf(e,t,n,r){const o={};return r||(e=Ht(kt(e,n),n),t=Ht(kt(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=ln(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=ln(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=ln(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=ln(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 _0(e,t,n){const r=Ec(e,n),o=Ec(t,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function kt(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=Jf(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=y0(n.path):(n.path=v0(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=g0(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=ln(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 k0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function A0(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 Yf(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(k0);if(i){r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]);const a=A0(r,i);if(a!==void 0&&(r.error=r.error||a,o=!0),r.host)if(b0(r.host)===!1){const u=m0(r.host);r.host=u.host.toLowerCase(),s=u.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 c=Jf(n.scheme||r.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&r.host&&(n.domainHost||c&&c.domainHost)&&s===!1&&E0(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(u){r.error=r.error||"Host's domain name can not be converted to ASCII: "+u}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=w0(unescape(r.host),s))),r.path&&(r.path=$0(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}c&&c.parse&&c.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function Ht(e,t){return Yf(e,t).parsed}function j0(e,t){return Qf(e,t).normalized}function Qf(e,t){const{parsed:n,malformedAuthorityOrPort:r}=Yf(e,t);return{normalized:r?e:kt(n,t),malformedAuthorityOrPort:r}}function Ec(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=Qf(e,t);return r?void 0:n}if(typeof e=="object")return kt(e,t)}const fi={SCHEMES:S0,normalize:N0,resolve:O0,resolveComponent:Hf,equal:_0,serialize:kt,parse:Ht};Tr.exports=fi;Tr.exports.default=fi;Tr.exports.fastUri=fi;var I0=Tr.exports;Object.defineProperty(ci,"__esModule",{value:!0});const Zf=I0;Zf.code='require("ajv/dist/runtime/uri").default';ci.default=Zf;(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=xe;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=jn,o=Zt,s=_t,i=$e,a=G,c=ce,u=oe,l=x,f=Fv,p=ci,h=(P,E)=>new RegExp(P,E);h.code="new RegExp";const d=["removeAdditional","useDefaults","coerceTypes"],g=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 b(P){var E,A,N,m,w,_,M,D,H,J,ie,jt,qr,Kr,Gr,zr,Wr,Jr,Hr,Yr,Qr,Zr,Xr,eo,to;const nn=P.strict,no=(E=P.code)===null||E===void 0?void 0:E.optimize,ka=no===!0||no===void 0?1:no||0,Aa=(N=(A=P.code)===null||A===void 0?void 0:A.regExp)!==null&&N!==void 0?N:h,yh=(m=P.uriResolver)!==null&&m!==void 0?m:p.default;return{strictSchema:(_=(w=P.strictSchema)!==null&&w!==void 0?w:nn)!==null&&_!==void 0?_:!0,strictNumbers:(D=(M=P.strictNumbers)!==null&&M!==void 0?M:nn)!==null&&D!==void 0?D:!0,strictTypes:(J=(H=P.strictTypes)!==null&&H!==void 0?H:nn)!==null&&J!==void 0?J:"log",strictTuples:(jt=(ie=P.strictTuples)!==null&&ie!==void 0?ie:nn)!==null&&jt!==void 0?jt:"log",strictRequired:(Kr=(qr=P.strictRequired)!==null&&qr!==void 0?qr:nn)!==null&&Kr!==void 0?Kr:!1,code:P.code?{...P.code,optimize:ka,regExp:Aa}:{optimize:ka,regExp:Aa},loopRequired:(Gr=P.loopRequired)!==null&&Gr!==void 0?Gr:v,loopEnum:(zr=P.loopEnum)!==null&&zr!==void 0?zr:v,meta:(Wr=P.meta)!==null&&Wr!==void 0?Wr:!0,messages:(Jr=P.messages)!==null&&Jr!==void 0?Jr:!0,inlineRefs:(Hr=P.inlineRefs)!==null&&Hr!==void 0?Hr:!0,schemaId:(Yr=P.schemaId)!==null&&Yr!==void 0?Yr:"$id",addUsedSchema:(Qr=P.addUsedSchema)!==null&&Qr!==void 0?Qr:!0,validateSchema:(Zr=P.validateSchema)!==null&&Zr!==void 0?Zr:!0,validateFormats:(Xr=P.validateFormats)!==null&&Xr!==void 0?Xr:!0,unicodeRegExp:(eo=P.unicodeRegExp)!==null&&eo!==void 0?eo:!0,int32range:(to=P.int32range)!==null&&to!==void 0?to:!0,uriResolver:yh}}class S{constructor(E={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,E=this.opts={...E,...b(E)};const{es5:A,lines:N}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:g,es5:A,lines:N}),this.logger=Q(E.logger);const m=E.validateFormats;E.validateFormats=!1,this.RULES=(0,s.getRules)(),O.call(this,y,E,"NOT SUPPORTED"),O.call(this,$,E,"DEPRECATED","warn"),this._metaOpts=q.call(this),E.formats&&W.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),E.keywords&&B.call(this,E.keywords),typeof E.meta=="object"&&this.addMetaSchema(E.meta),C.call(this),E.validateFormats=m}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:E,meta:A,schemaId:N}=this.opts;let m=f;N==="id"&&(m={...f},m.id=m.$id,delete m.$id),A&&E&&this.addMetaSchema(m,m[N],!1)}defaultMeta(){const{meta:E,schemaId:A}=this.opts;return this.opts.defaultMeta=typeof E=="object"?E[A]||E:void 0}validate(E,A){let N;if(typeof E=="string"){if(N=this.getSchema(E),!N)throw new Error(`no schema with key or ref "${E}"`)}else N=this.compile(E);const m=N(A);return"$async"in N||(this.errors=N.errors),m}compile(E,A){const N=this._addSchema(E,A);return N.validate||this._compileSchemaEnv(N)}compileAsync(E,A){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:N}=this.opts;return m.call(this,E,A);async function m(J,ie){await w.call(this,J.$schema);const jt=this._addSchema(J,ie);return jt.validate||_.call(this,jt)}async function w(J){J&&!this.getSchema(J)&&await m.call(this,{$ref:J},!0)}async function _(J){try{return this._compileSchemaEnv(J)}catch(ie){if(!(ie instanceof o.default))throw ie;return M.call(this,ie),await D.call(this,ie.missingSchema),_.call(this,J)}}function M({missingSchema:J,missingRef:ie}){if(this.refs[J])throw new Error(`AnySchema ${J} is loaded but ${ie} cannot be resolved`)}async function D(J){const ie=await H.call(this,J);this.refs[J]||await w.call(this,ie.$schema),this.refs[J]||this.addSchema(ie,J,A)}async function H(J){const ie=this._loading[J];if(ie)return ie;try{return await(this._loading[J]=N(J))}finally{delete this._loading[J]}}}addSchema(E,A,N,m=this.opts.validateSchema){if(Array.isArray(E)){for(const _ of E)this.addSchema(_,void 0,N,m);return this}let w;if(typeof E=="object"){const{schemaId:_}=this.opts;if(w=E[_],w!==void 0&&typeof w!="string")throw new Error(`schema ${_} must be string`)}return A=(0,c.normalizeId)(A||w),this._checkUnique(A),this.schemas[A]=this._addSchema(E,N,A,m,!0),this}addMetaSchema(E,A,N=this.opts.validateSchema){return this.addSchema(E,A,!0,N),this}validateSchema(E,A){if(typeof E=="boolean")return!0;let N;if(N=E.$schema,N!==void 0&&typeof N!="string")throw new Error("$schema must be a string");if(N=N||this.opts.defaultMeta||this.defaultMeta(),!N)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const m=this.validate(N,E);if(!m&&A){const w="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(w);else throw new Error(w)}return m}getSchema(E){let A;for(;typeof(A=j.call(this,E))=="string";)E=A;if(A===void 0){const{schemaId:N}=this.opts,m=new i.SchemaEnv({schema:{},schemaId:N});if(A=i.resolveSchema.call(this,m,E),!A)return;this.refs[E]=A}return A.validate||this._compileSchemaEnv(A)}removeSchema(E){if(E instanceof RegExp)return this._removeAllSchemas(this.schemas,E),this._removeAllSchemas(this.refs,E),this;switch(typeof E){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const A=j.call(this,E);return typeof A=="object"&&this._cache.delete(A.schema),delete this.schemas[E],delete this.refs[E],this}case"object":{const A=E;this._cache.delete(A);let N=E[this.opts.schemaId];return N&&(N=(0,c.normalizeId)(N),delete this.schemas[N],delete this.refs[N]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(E){for(const A of E)this.addKeyword(A);return this}addKeyword(E,A){let N;if(typeof E=="string")N=E,typeof A=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),A.keyword=N);else if(typeof E=="object"&&A===void 0){if(A=E,N=A.keyword,Array.isArray(N)&&!N.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Ne.call(this,N,A),!A)return(0,l.eachItem)(N,w=>Ue.call(this,w)),this;tn.call(this,A);const m={...A,type:(0,u.getJSONTypes)(A.type),schemaType:(0,u.getJSONTypes)(A.schemaType)};return(0,l.eachItem)(N,m.type.length===0?w=>Ue.call(this,w,m):w=>m.type.forEach(_=>Ue.call(this,w,m,_))),this}getKeyword(E){const A=this.RULES.all[E];return typeof A=="object"?A.definition:!!A}removeKeyword(E){const{RULES:A}=this;delete A.keywords[E],delete A.all[E];for(const N of A.rules){const m=N.rules.findIndex(w=>w.keyword===E);m>=0&&N.rules.splice(m,1)}return this}addFormat(E,A){return typeof A=="string"&&(A=new RegExp(A)),this.formats[E]=A,this}errorsText(E=this.errors,{separator:A=", ",dataVar:N="data"}={}){return!E||E.length===0?"No errors":E.map(m=>`${N}${m.instancePath} ${m.message}`).reduce((m,w)=>m+A+w)}$dataMetaSchema(E,A){const N=this.RULES.all;E=JSON.parse(JSON.stringify(E));for(const m of A){const w=m.split("/").slice(1);let _=E;for(const M of w)_=_[M];for(const M in N){const D=N[M];if(typeof D!="object")continue;const{$data:H}=D.definition,J=_[M];H&&J&&(_[M]=Pn(J))}}return E}_removeAllSchemas(E,A){for(const N in E){const m=E[N];(!A||A.test(N))&&(typeof m=="string"?delete E[N]:m&&!m.meta&&(this._cache.delete(m.schema),delete E[N]))}}_addSchema(E,A,N,m=this.opts.validateSchema,w=this.opts.addUsedSchema){let _;const{schemaId:M}=this.opts;if(typeof E=="object")_=E[M];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof E!="boolean")throw new Error("schema must be object or boolean")}let D=this._cache.get(E);if(D!==void 0)return D;N=(0,c.normalizeId)(_||N);const H=c.getSchemaRefs.call(this,E,N);return D=new i.SchemaEnv({schema:E,schemaId:M,meta:A,baseId:N,localRefs:H}),this._cache.set(D.schema,D),w&&!N.startsWith("#")&&(N&&this._checkUnique(N),this.refs[N]=D),m&&this.validateSchema(E,!0),D}_checkUnique(E){if(this.schemas[E]||this.refs[E])throw new Error(`schema with key or id "${E}" already exists`)}_compileSchemaEnv(E){if(E.meta?this._compileMetaSchema(E):i.compileSchema.call(this,E),!E.validate)throw new Error("ajv implementation error");return E.validate}_compileMetaSchema(E){const A=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,E)}finally{this.opts=A}}}S.ValidationError=r.default,S.MissingRefError=o.default,e.default=S;function O(P,E,A,N="error"){for(const m in P){const w=m;w in E&&this.logger[N](`${A}: option ${m}. ${P[w]}`)}}function j(P){return P=(0,c.normalizeId)(P),this.schemas[P]||this.refs[P]}function C(){const P=this.opts.schemas;if(P)if(Array.isArray(P))this.addSchema(P);else for(const E in P)this.addSchema(P[E],E)}function W(){for(const P in this.opts.formats){const E=this.opts.formats[P];E&&this.addFormat(P,E)}}function B(P){if(Array.isArray(P)){this.addVocabulary(P);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const E in P){const A=P[E];A.keyword||(A.keyword=E),this.addKeyword(A)}}function q(){const P={...this.opts};for(const E of d)delete P[E];return P}const Z={log(){},warn(){},error(){}};function Q(P){if(P===!1)return Z;if(P===void 0)return console;if(P.log&&P.warn&&P.error)return P;throw new Error("logger must implement log, warn and error methods")}const ve=/^[a-z_$][a-z0-9_$:-]*$/i;function Ne(P,E){const{RULES:A}=this;if((0,l.eachItem)(P,N=>{if(A.keywords[N])throw new Error(`Keyword ${N} is already defined`);if(!ve.test(N))throw new Error(`Keyword ${N} has invalid name`)}),!!E&&E.$data&&!("code"in E||"validate"in E))throw new Error('$data keyword must have "code" or "validate" function')}function Ue(P,E,A){var N;const m=E==null?void 0:E.post;if(A&&m)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:w}=this;let _=m?w.post:w.rules.find(({type:D})=>D===A);if(_||(_={type:A,rules:[]},w.rules.push(_)),w.keywords[P]=!0,!E)return;const M={keyword:P,definition:{...E,type:(0,u.getJSONTypes)(E.type),schemaType:(0,u.getJSONTypes)(E.schemaType)}};E.before?fe.call(this,_,M,E.before):_.rules.push(M),w.all[P]=M,(N=E.implements)===null||N===void 0||N.forEach(D=>this.addKeyword(D))}function fe(P,E,A){const N=P.rules.findIndex(m=>m.keyword===A);N>=0?P.rules.splice(N,0,E):(P.rules.push(E),this.logger.warn(`rule ${A} is not defined`))}function tn(P){let{metaSchema:E}=P;E!==void 0&&(P.$data&&this.opts.$data&&(E=Pn(E)),P.validateSchema=this.compile(E,!0))}const Vr={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Pn(P){return{anyOf:[P,Vr]}}})(of);var di={},pi={},hi={};Object.defineProperty(hi,"__esModule",{value:!0});const P0={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};hi.default=P0;var At={};Object.defineProperty(At,"__esModule",{value:!0});At.callRef=At.getValidate=void 0;const x0=Zt,Sc=K,me=G,xt=Be,Nc=$e,Bn=x,T0={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=Nc.resolveRef.call(c,u,o,n);if(l===void 0)throw new x0.default(r.opts.uriResolver,o,n);if(l instanceof Nc.SchemaEnv)return p(l);return h(l);function f(){if(s===u)return rr(e,i,s,s.$async);const d=t.scopeValue("root",{ref:u});return rr(e,(0,me._)`${d}.validate`,u,u.$async)}function p(d){const g=Xf(e,d);rr(e,g,d,d.$async)}function h(d){const g=t.scopeValue("schema",a.code.source===!0?{ref:d,code:(0,me.stringify)(d)}:{ref:d}),y=t.name("valid"),$=e.subschema({schema:d,dataTypes:[],schemaPath:me.nil,topSchemaRef:g,errSchemaPath:n},y);e.mergeEvaluated($),e.ok(y)}}};function Xf(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,me._)`${n.scopeValue("wrapper",{ref:t})}.validate`}At.getValidate=Xf;function rr(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?xt.default.this:me.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,me._)`await ${(0,Sc.callValidateCode)(e,t,u)}`),h(t),i||o.assign(d,!0)},g=>{o.if((0,me._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(d,!1)}),e.ok(d)}function f(){e.result((0,Sc.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(d){const g=(0,me._)`${d}.errors`;o.assign(xt.default.vErrors,(0,me._)`${xt.default.vErrors} === null ? ${g} : ${xt.default.vErrors}.concat(${g})`),o.assign(xt.default.errors,(0,me._)`${xt.default.vErrors}.length`)}function h(d){var g;if(!s.opts.unevaluated)return;const y=(g=n==null?void 0:n.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Bn.mergeEvaluated.props(o,y.props,s.props));else{const $=o.var("props",(0,me._)`${d}.evaluated.props`);s.props=Bn.mergeEvaluated.props(o,$,s.props,me.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Bn.mergeEvaluated.items(o,y.items,s.items));else{const $=o.var("items",(0,me._)`${d}.evaluated.items`);s.items=Bn.mergeEvaluated.items(o,$,s.items,me.Name)}}}At.callRef=rr;At.default=T0;Object.defineProperty(pi,"__esModule",{value:!0});const C0=hi,R0=At,M0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",C0.default,R0.default];pi.default=M0;var mi={},gi={};Object.defineProperty(gi,"__esModule",{value:!0});const pr=G,Xe=pr.operators,hr={maximum:{okStr:"<=",ok:Xe.LTE,fail:Xe.GT},minimum:{okStr:">=",ok:Xe.GTE,fail:Xe.LT},exclusiveMaximum:{okStr:"<",ok:Xe.LT,fail:Xe.GTE},exclusiveMinimum:{okStr:">",ok:Xe.GT,fail:Xe.LTE}},D0={message:({keyword:e,schemaCode:t})=>(0,pr.str)`must be ${hr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,pr._)`{comparison: ${hr[e].okStr}, limit: ${t}}`},L0={keyword:Object.keys(hr),type:"number",schemaType:"number",$data:!0,error:D0,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,pr._)`${n} ${hr[t].fail} ${r} || isNaN(${n})`)}};gi.default=L0;var yi={};Object.defineProperty(yi,"__esModule",{value:!0});const mn=G,B0={message:({schemaCode:e})=>(0,mn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,mn._)`{multipleOf: ${e}}`},U0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:B0,code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,mn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,mn._)`${i} !== parseInt(${i})`;e.fail$data((0,mn._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};yi.default=U0;var $i={},vi={};Object.defineProperty(vi,"__esModule",{value:!0});function ed(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}vi.default=ed;ed.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty($i,"__esModule",{value:!0});const gt=G,F0=x,V0=vi,q0={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,gt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,gt._)`{limit: ${e}}`},K0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:q0,code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?gt.operators.GT:gt.operators.LT,i=o.opts.unicode===!1?(0,gt._)`${n}.length`:(0,gt._)`${(0,F0.useFunc)(e.gen,V0.default)}(${n})`;e.fail$data((0,gt._)`${i} ${s} ${r}`)}};$i.default=K0;var wi={};Object.defineProperty(wi,"__esModule",{value:!0});const G0=K,z0=x,qt=G,W0={message:({schemaCode:e})=>(0,qt.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,qt._)`{pattern: ${e}}`},J0={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:W0,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,qt._)`new RegExp`:(0,z0.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,qt._)`${u}(${s}, ${a}).test(${n})`),()=>t.assign(l,!1)),e.fail$data((0,qt._)`!${l}`)}else{const c=(0,G0.usePattern)(e,o);e.fail$data((0,qt._)`!${c}.test(${n})`)}}};wi.default=J0;var bi={};Object.defineProperty(bi,"__esModule",{value:!0});const gn=G,H0={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,gn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,gn._)`{limit: ${e}}`},Y0={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:H0,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?gn.operators.GT:gn.operators.LT;e.fail$data((0,gn._)`Object.keys(${n}).length ${o} ${r}`)}};bi.default=Y0;var Ei={};Object.defineProperty(Ei,"__esModule",{value:!0});const on=K,yn=G,Q0=x,Z0={message:({params:{missingProperty:e}})=>(0,yn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,yn._)`{missingProperty: ${e}}`},X0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Z0,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 g of n)if((h==null?void 0:h[g])===void 0&&!d.has(g)){const y=i.schemaEnv.baseId+i.errSchemaPath,$=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,Q0.checkStrictMode)(i,$,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(yn.nil,f);else for(const h of n)(0,on.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,on.checkMissingProp)(e,n,h)),(0,on.reportMissingProp)(e,h),t.else()}function f(){t.forOf("prop",r,h=>{e.setParams({missingProperty:h}),t.if((0,on.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,d){e.setParams({missingProperty:h}),t.forOf(h,r,()=>{t.assign(d,(0,on.propertyInData)(t,o,h,a.ownProperties)),t.if((0,yn.not)(d),()=>{e.error(),t.break()})},yn.nil)}}};Ei.default=X0;var Si={};Object.defineProperty(Si,"__esModule",{value:!0});const $n=G,ew={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,$n.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,$n._)`{limit: ${e}}`},tw={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ew,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?$n.operators.GT:$n.operators.LT;e.fail$data((0,$n._)`${n}.length ${o} ${r}`)}};Si.default=tw;var Ni={},In={};Object.defineProperty(In,"__esModule",{value:!0});const td=bf;td.code='require("ajv/dist/runtime/equal").default';In.default=td;Object.defineProperty(Ni,"__esModule",{value:!0});const mo=oe,ae=G,nw=x,rw=In,ow={message:({params:{i:e,j:t}})=>(0,ae.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ae._)`{i: ${e}, j: ${t}}`},sw={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ow,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,mo.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,ae._)`${i} === false`),e.ok(c);function l(){const d=t.let("i",(0,ae._)`${n}.length`),g=t.let("j");e.setParams({i:d,j:g}),t.assign(c,!0),t.if((0,ae._)`${d} > 1`,()=>(f()?p:h)(d,g))}function f(){return u.length>0&&!u.some(d=>d==="object"||d==="array")}function p(d,g){const y=t.name("item"),$=(0,mo.checkDataTypes)(u,y,a.opts.strictNumbers,mo.DataType.Wrong),v=t.const("indices",(0,ae._)`{}`);t.for((0,ae._)`;${d}--;`,()=>{t.let(y,(0,ae._)`${n}[${d}]`),t.if($,(0,ae._)`continue`),u.length>1&&t.if((0,ae._)`typeof ${y} == "string"`,(0,ae._)`${y} += "_"`),t.if((0,ae._)`typeof ${v}[${y}] == "number"`,()=>{t.assign(g,(0,ae._)`${v}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,ae._)`${v}[${y}] = ${d}`)})}function h(d,g){const y=(0,nw.useFunc)(t,rw.default),$=t.name("outer");t.label($).for((0,ae._)`;${d}--;`,()=>t.for((0,ae._)`${g} = ${d}; ${g}--;`,()=>t.if((0,ae._)`${y}(${n}[${d}], ${n}[${g}])`,()=>{e.error(),t.assign(c,!1).break($)})))}}};Ni.default=sw;var Oi={};Object.defineProperty(Oi,"__esModule",{value:!0});const Zo=G,iw=x,aw=In,cw={message:"must be equal to constant",params:({schemaCode:e})=>(0,Zo._)`{allowedValue: ${e}}`},uw={keyword:"const",$data:!0,error:cw,code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,Zo._)`!${(0,iw.useFunc)(t,aw.default)}(${n}, ${o})`):e.fail((0,Zo._)`${s} !== ${n}`)}};Oi.default=uw;var _i={};Object.defineProperty(_i,"__esModule",{value:!0});const fn=G,lw=x,fw=In,dw={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,fn._)`{allowedValues: ${e}}`},pw={keyword:"enum",schemaType:"array",$data:!0,error:dw,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,lw.useFunc)(t,fw.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,fn.or)(...o.map((d,g)=>p(h,g)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",s,h=>t.if((0,fn._)`${u()}(${n}, ${h})`,()=>t.assign(l,!0).break()))}function p(h,d){const g=o[d];return typeof g=="object"&&g!==null?(0,fn._)`${u()}(${n}, ${h}[${d}])`:(0,fn._)`${n} === ${g}`}}};_i.default=pw;Object.defineProperty(mi,"__esModule",{value:!0});const hw=gi,mw=yi,gw=$i,yw=wi,$w=bi,vw=Ei,ww=Si,bw=Ni,Ew=Oi,Sw=_i,Nw=[hw.default,mw.default,gw.default,yw.default,$w.default,vw.default,ww.default,bw.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ew.default,Sw.default];mi.default=Nw;var ki={},Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.validateAdditionalItems=void 0;const yt=G,Xo=x,Ow={message:({params:{len:e}})=>(0,yt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,yt._)`{limit: ${e}}`},_w={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Ow,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,Xo.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}nd(e,r)}};function nd(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,yt._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,yt._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,Xo.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,yt._)`${a} <= ${t.length}`);n.if((0,yt.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Xo.Type.Num},u),i.allErrors||n.if((0,yt.not)(u),()=>n.break())})}}Xt.validateAdditionalItems=nd;Xt.default=_w;var Ai={},en={};Object.defineProperty(en,"__esModule",{value:!0});en.validateTuple=void 0;const Oc=G,or=x,kw=K,Aw={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return rd(e,"additionalItems",t);n.items=!0,!(0,or.alwaysValidSchema)(n,t)&&e.ok((0,kw.validateArray)(e))}};function rd(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=or.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,Oc._)`${s}.length`);n.forEach((f,p)=>{(0,or.alwaysValidSchema)(a,f)||(r.if((0,Oc._)`${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,g=d===f.minItems&&(d===f.maxItems||f[t]===!1);if(p.strictTuples&&!g){const y=`"${i}" is ${d}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,or.checkStrictMode)(a,y,p.strictTuples)}}}en.validateTuple=rd;en.default=Aw;Object.defineProperty(Ai,"__esModule",{value:!0});const jw=en,Iw={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,jw.validateTuple)(e,"items")};Ai.default=Iw;var ji={};Object.defineProperty(ji,"__esModule",{value:!0});const _c=G,Pw=x,xw=K,Tw=Xt,Cw={message:({params:{len:e}})=>(0,_c.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,_c._)`{limit: ${e}}`},Rw={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Cw,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,Pw.alwaysValidSchema)(r,t)&&(o?(0,Tw.validateAdditionalItems)(e,o):e.ok((0,xw.validateArray)(e)))}};ji.default=Rw;var Ii={};Object.defineProperty(Ii,"__esModule",{value:!0});const Oe=G,Un=x,Mw={message:({params:{min:e,max:t}})=>t===void 0?(0,Oe.str)`must contain at least ${e} valid item(s)`:(0,Oe.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Oe._)`{minContains: ${e}}`:(0,Oe._)`{minContains: ${e}, maxContains: ${t}}`},Dw={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Mw,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,Oe._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Un.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Un.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Un.alwaysValidSchema)(s,n)){let g=(0,Oe._)`${l} >= ${i}`;a!==void 0&&(g=(0,Oe._)`${g} && ${l} <= ${a}`),e.pass(g);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,Oe._)`${o}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset());function p(){const g=t.name("_valid"),y=t.let("count",0);h(g,()=>t.if(g,()=>d(y)))}function h(g,y){t.forRange("i",0,l,$=>{e.subschema({keyword:"contains",dataProp:$,dataPropType:Un.Type.Num,compositeRule:!0},g),y()})}function d(g){t.code((0,Oe._)`${g}++`),a===void 0?t.if((0,Oe._)`${g} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,Oe._)`${g} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,Oe._)`${g} >= ${i}`,()=>t.assign(f,!0)))}}};Ii.default=Dw;var od={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=G,n=x,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
160
  missingProperty: ${f},
161
161
  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 g=(0,r.propertyInData)(l,f,d,p.opts.ownProperties);c.setParams({property:d,depsCount:m.length,deps:m.join(", ")}),p.allErrors?l.if(g,()=>{for(const $ of m)(0,r.checkReportMissingProp)(c,$)}):(l.if((0,t._)`${g} && (${(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 g=c.subschema({keyword:p,schemaProp:m},d);c.mergeValidEvaluated(g,d)},()=>l.var(d,!0)),c.ok(d))}e.validateSchemaDeps=a,e.default=o})(Af);var mi={};Object.defineProperty(mi,"__esModule",{value:!0});const kf=W,a0=D,c0={message:"property name must be valid",params:({params:e})=>(0,kf._)`{propertyName: ${e.propertyName}}`},u0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:c0,code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,a0.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,kf.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};mi.default=u0;var Rr={};Object.defineProperty(Rr,"__esModule",{value:!0});const qn=Be(),De=W,l0=lt(),Kn=D,f0={message:"must NOT have additional properties",params:({params:e})=>(0,De._)`{additionalProperty: ${e.additionalProperty}}`},d0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:f0,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,Kn.alwaysValidSchema)(i,n))return;const u=(0,qn.allSchemaProperties)(r.properties),l=(0,qn.allSchemaProperties)(r.patternProperties);f(),e.ok((0,De._)`${s} === ${l0.default.errors}`);function f(){t.forIn("key",o,g=>{!u.length&&!l.length?d(g):t.if(p(g),()=>d(g))})}function p(g){let $;if(u.length>8){const v=(0,Kn.schemaRefOrVal)(i,r.properties,"properties");$=(0,qn.isOwnProperty)(t,v,g)}else u.length?$=(0,De.or)(...u.map(v=>(0,De._)`${g} === ${v}`)):$=De.nil;return l.length&&($=(0,De.or)($,...l.map(v=>(0,De._)`${(0,qn.usePattern)(e,v)}.test(${g})`))),(0,De.not)($)}function h(g){t.code((0,De._)`delete ${o}[${g}]`)}function d(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(g);return}if(n===!1){e.setParams({additionalProperty:g}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,Kn.alwaysValidSchema)(i,n)){const $=t.name("valid");c.removeAdditional==="failing"?(m(g,$,!1),t.if((0,De.not)($),()=>{e.reset(),h(g)})):(m(g,$),a||t.if((0,De.not)($),()=>t.break()))}}function m(g,$,v){const w={keyword:"additionalProperties",dataProp:g,dataPropType:Kn.Type.Str};v===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,$)}}};Rr.default=d0;var gi={};Object.defineProperty(gi,"__esModule",{value:!0});const p0=xr(),hc=Be(),ro=D,mc=Rr,h0={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&&mc.default.code(new p0.KeywordCxt(s,mc.default,"additionalProperties"));const i=(0,hc.allSchemaProperties)(n);for(const f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=ro.mergeEvaluated.props(t,(0,ro.toHash)(i),s.props));const a=i.filter(f=>!(0,ro.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,hc.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)}}};gi.default=h0;var yi={};Object.defineProperty(yi,"__esModule",{value:!0});const gc=Be(),zn=W,yc=D,$c=D,m0={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,gc.allSchemaProperties)(n),c=a.filter(m=>(0,yc.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 zn.Name)&&(s.props=(0,$c.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 g in u)new RegExp(m).test(g)&&(0,yc.checkStrictMode)(s,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function d(m){t.forIn("key",r,g=>{t.if((0,zn._)`${(0,gc.usePattern)(e,m)}.test(${g})`,()=>{const $=c.includes(m);$||e.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:$c.Type.Str},l),s.opts.unevaluated&&f!==!0?t.assign((0,zn._)`${f}[${g}]`,!0):!$&&!s.allErrors&&t.if((0,zn.not)(l),()=>t.break())})})}}};yi.default=m0;var $i={};Object.defineProperty($i,"__esModule",{value:!0});const g0=D,y0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,g0.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"}};$i.default=y0;var vi={};Object.defineProperty(vi,"__esModule",{value:!0});const $0=Be(),v0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:$0.validateUnion,error:{message:"must match a schema in anyOf"}};vi.default=v0;var wi={};Object.defineProperty(wi,"__esModule",{value:!0});const ar=W,w0=D,b0={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ar._)`{passingSchemas: ${e.passing}}`},S0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:b0,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,w0.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,ar._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ar._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),p&&e.mergeEvaluated(p,ar.Name)})})}}};wi.default=S0;var bi={};Object.defineProperty(bi,"__esModule",{value:!0});const E0=D,N0={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,E0.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};bi.default=N0;var Si={};Object.defineProperty(Si,"__esModule",{value:!0});const gr=W,jf=D,O0={message:({params:e})=>(0,gr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,gr._)`{failingKeyword: ${e.ifClause}}`},_0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:O0,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,jf.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=vc(r,"then"),s=vc(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,gr.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,gr._)`${l}`):e.setParams({ifClause:l})}}}};function vc(e,t){const n=e.schema[t];return n!==void 0&&!(0,jf.alwaysValidSchema)(e,n)}Si.default=_0;var Ei={};Object.defineProperty(Ei,"__esModule",{value:!0});const A0=D,k0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,A0.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};Ei.default=k0;Object.defineProperty(fi,"__esModule",{value:!0});const j0=rn,I0=di,x0=on,P0=pi,T0=hi,C0=Af,R0=mi,M0=Rr,D0=gi,L0=yi,U0=$i,B0=vi,F0=wi,V0=bi,q0=Si,K0=Ei;function z0(e=!1){const t=[U0.default,B0.default,F0.default,V0.default,q0.default,K0.default,R0.default,M0.default,C0.default,D0.default,L0.default];return e?t.push(I0.default,P0.default):t.push(j0.default,x0.default),t.push(T0.default),t}fi.default=z0;var Ni={},Oi={};Object.defineProperty(Oi,"__esModule",{value:!0});const ae=W,G0={message:({schemaCode:e})=>(0,ae.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ae._)`{format: ${e}}`},H0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:G0,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,ae._)`${d}[${i}]`),g=n.let("fType"),$=n.let("format");n.if((0,ae._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,ae._)`${m}.type || "string"`).assign($,(0,ae._)`${m}.validate`),()=>n.assign(g,(0,ae._)`"string"`).assign($,m)),e.fail$data((0,ae.or)(v(),w()));function v(){return c.strictSchema===!1?ae.nil:(0,ae._)`${i} && !${$}`}function w(){const S=l.$async?(0,ae._)`(${m}.async ? await ${$}(${r}) : ${$}(${r}))`:(0,ae._)`${$}(${r})`,N=(0,ae._)`(typeof ${$} == "function" ? ${S} : ${$}.test(${r}))`;return(0,ae._)`${$} && ${$} !== true && ${g} === ${t} && !${N}`}}function h(){const d=f.formats[s];if(!d){v();return}if(d===!0)return;const[m,g,$]=w(d);m===t&&e.pass(S());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 w(N){const I=N instanceof RegExp?(0,ae.regexpCode)(N):c.code.formats?(0,ae._)`${c.code.formats}${(0,ae.getProperty)(s)}`:void 0,T=n.scopeValue("formats",{key:s,ref:N,code:I});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,ae._)`${T}.validate`]:["string",N,T]}function S(){if(typeof d=="object"&&!(d instanceof RegExp)&&d.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ae._)`await ${$}(${r})`}return typeof g=="function"?(0,ae._)`${$}(${r})`:(0,ae._)`${$}.test(${r})`}}}};Oi.default=H0;Object.defineProperty(Ni,"__esModule",{value:!0});const J0=Oi,W0=[J0.default];Ni.default=W0;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.contentVocabulary=Xt.metadataVocabulary=void 0;Xt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(Qs,"__esModule",{value:!0});const Q0=Ys,Y0=Xs,Z0=fi,X0=Ni,wc=Xt,ew=[Q0.default,Y0.default,(0,Z0.default)(),X0.default,wc.metadataVocabulary,wc.contentVocabulary];Qs.default=ew;var _i={},Mr={};Object.defineProperty(Mr,"__esModule",{value:!0});Mr.DiscrError=void 0;var bc;(function(e){e.Tag="tag",e.Mapping="mapping"})(bc||(Mr.DiscrError=bc={}));Object.defineProperty(_i,"__esModule",{value:!0});const Ut=W,qo=Mr,Sc=Ne,tw=nn,nw=D,rw={message:({params:{discrError:e,tagName:t}})=>e===qo.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Ut._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},ow={keyword:"discriminator",type:"object",schemaType:"object",error:rw,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,Ut._)`${n}${(0,Ut.getProperty)(a)}`);t.if((0,Ut._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:qo.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,Ut._)`${u} === ${d}`),t.assign(c,f(h[d]));t.else(),e.error(!1,{discrError:qo.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,Ut.Name),d}function p(){var h;const d={},m=$(o);let g=!0;for(let S=0;S<i.length;S++){let N=i[S];if(N!=null&&N.$ref&&!(0,nw.schemaHasRulesButRef)(N,s.self.RULES)){const T=N.$ref;if(N=Sc.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,T),N instanceof Sc.SchemaEnv&&(N=N.schema),N===void 0)throw new tw.default(s.opts.uriResolver,s.baseId,T)}const I=(h=N==null?void 0:N.properties)===null||h===void 0?void 0:h[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||$(N)),v(I,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return d;function $({required:S}){return Array.isArray(S)&&S.includes(a)}function v(S,N){if(S.const)w(S.const,N);else if(S.enum)for(const I of S.enum)w(I,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(S,N){if(typeof S!="string"||S in d)throw new Error(`discriminator: "${a}" values must be unique strings`);d[S]=N}}}};_i.default=ow;const sw="http://json-schema.org/draft-07/schema#",iw="http://json-schema.org/draft-07/schema#",aw="Core schema meta-schema",cw={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:[]}},uw=["object","boolean"],lw={$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:"#"}},fw={$schema:sw,$id:iw,title:aw,definitions:cw,type:uw,properties:lw,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=Kl,r=Qs,o=_i,s=fw,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=xr();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=W;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=xn;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=nn;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Mo,Mo.exports);var dw=Mo.exports;const pw=Im(dw);class If 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 hw(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new pw({allErrors:!0,strict:!1}).compile(n);if(!o(e))throw new If(mw(o.errors??[]))}function mw(e){return e.map(t=>({field:gw(t),message:t.message??"is invalid",keyword:t.keyword}))}function gw(e){var t;return(e.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((t=e.params)==null?void 0:t.missingProperty)??"(root)")}function yw(e,t){return q.join(Yu(e,t),Fg)}const $w=384,vw=448;function ww(e,t,n={}){const r=n.mode??$w,o=n.dirMode??vw,s=q.dirname(e);Y.mkdirSync(s,{recursive:!0,mode:o}),Y.chmodSync(s,o);const i=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{Y.writeFileSync(i,a,{encoding:"utf8",mode:r}),Y.chmodSync(i,r),Y.renameSync(i,e),Y.chmodSync(e,r)}catch(c){try{Y.existsSync(i)&&Y.unlinkSync(i)}catch{}throw c}}const bw="0.1.0";function Ec(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 Sw(){return`${process.pid}-${Cu.randomBytes(3).toString("hex")}`}function xf(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");Ec(e,"project");const r=t.orgNamespace??Ug,o=t.envPrefixOverride??Gg(e),s=t.namespaces&&t.namespaces.length>0?t.namespaces:[Bg],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${e}" (declared: ${s.join(", ")})`);Ec(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=Am({scope:n.scope,cwd:n.cwd},a),l=jm({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 Ew(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=xf(e,t,n),u=n.processEnv??process.env,l=ny(c),f=n.instanceId??Sw(),{raw:p,nested:h,typedRaw:d,provenance:m,fields:g}=sy(t.config,l,u,{prefix:s,activeScope:i}),$={};for(const N of Object.keys(g)){const I=g[N];I.live&&($[N]={env:I.env,type:I.type,fallback:I.secret===!0?void 0:I.fallbackValue})}const v=Jg(t.config);hw(ql(d),v);const w=ay(t.dirs,{roots:c,activeScope:i,instanceId:f,projectRoot:a,namespace:r}),S=cy(t.files,w);return{version:Lg,libraryVersion:bw,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:f,config:h,raw:p,liveFields:$,fieldSchema:v,configHash:Kg(Object.fromEntries(Object.entries(d).map(([N,I])=>[N,String(I)]))),structureHash:zg(Object.values(w).map(N=>({name:N.name,kind:N.kind,scope:N.scope}))),dirs:Object.values(w),files:Object.values(S),provenance:m}}let An=class extends Error{constructor(t){super(t),this.name="EnvironmentError"}};class Nw extends An{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class Ow extends An{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function _w(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 Ko(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Ko(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Ko(r);return t}function Aw(e,t){const n=Ko(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?Ro(c,o.type):o.fallback}})}return n}function kw(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new An(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class Ai{constructor(t,n,r={}){let o,s;try{o=Ew(t,n,r);const i=xf(t,n,r);s=yw(i.roots,o.scope)}catch(i){throw i instanceof If||i instanceof An?i:new An(i instanceof Error?i.message:String(i))}return Nc(this,o,s)}static fromSnapshot(t){if(!Y.existsSync(t))throw new Nw(t);const n=JSON.parse(Y.readFileSync(t,"utf8")),r=Object.create(Ai.prototype);return Nc(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 _w(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"){kw(t);const n=this.paths.run??this._runDirFallback();Y.mkdirSync(n,{recursive:!0});const r=q.join(n,`${t}.lock`);let o;try{o=Y.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new Ow(t,r):i}Y.writeSync(o,`${process.pid}
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 g=u[d];if(g.length===0)continue;const y=(0,r.propertyInData)(l,f,d,p.opts.ownProperties);c.setParams({property:d,depsCount:g.length,deps:g.join(", ")}),p.allErrors?l.if(y,()=>{for(const $ of g)(0,r.checkReportMissingProp)(c,$)}):(l.if((0,t._)`${y} && (${(0,r.checkMissingProp)(c,g,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 g in u)(0,n.alwaysValidSchema)(h,u[g])||(l.if((0,r.propertyInData)(l,f,g,h.opts.ownProperties),()=>{const y=c.subschema({keyword:p,schemaProp:g},d);c.mergeValidEvaluated(y,d)},()=>l.var(d,!0)),c.ok(d))}e.validateSchemaDeps=a,e.default=o})(od);var Pi={};Object.defineProperty(Pi,"__esModule",{value:!0});const sd=G,Lw=x,Bw={message:"property name must be valid",params:({params:e})=>(0,sd._)`{propertyName: ${e.propertyName}}`},Uw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Bw,code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,Lw.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,sd.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Pi.default=Uw;var Cr={};Object.defineProperty(Cr,"__esModule",{value:!0});const Fn=K,je=G,Fw=Be,Vn=x,Vw={message:"must NOT have additional properties",params:({params:e})=>(0,je._)`{additionalProperty: ${e.additionalProperty}}`},qw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Vw,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,Vn.alwaysValidSchema)(i,n))return;const u=(0,Fn.allSchemaProperties)(r.properties),l=(0,Fn.allSchemaProperties)(r.patternProperties);f(),e.ok((0,je._)`${s} === ${Fw.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,Vn.schemaRefOrVal)(i,r.properties,"properties");$=(0,Fn.isOwnProperty)(t,v,y)}else u.length?$=(0,je.or)(...u.map(v=>(0,je._)`${y} === ${v}`)):$=je.nil;return l.length&&($=(0,je.or)($,...l.map(v=>(0,je._)`${(0,Fn.usePattern)(e,v)}.test(${y})`))),(0,je.not)($)}function h(y){t.code((0,je._)`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,Vn.alwaysValidSchema)(i,n)){const $=t.name("valid");c.removeAdditional==="failing"?(g(y,$,!1),t.if((0,je.not)($),()=>{e.reset(),h(y)})):(g(y,$),a||t.if((0,je.not)($),()=>t.break()))}}function g(y,$,v){const b={keyword:"additionalProperties",dataProp:y,dataPropType:Vn.Type.Str};v===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,$)}}};Cr.default=qw;var xi={};Object.defineProperty(xi,"__esModule",{value:!0});const Kw=xe,kc=K,go=x,Ac=Cr,Gw={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&&Ac.default.code(new Kw.KeywordCxt(s,Ac.default,"additionalProperties"));const i=(0,kc.allSchemaProperties)(n);for(const f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=go.mergeEvaluated.props(t,(0,go.toHash)(i),s.props));const a=i.filter(f=>!(0,go.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,kc.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)}}};xi.default=Gw;var Ti={};Object.defineProperty(Ti,"__esModule",{value:!0});const jc=K,qn=G,Ic=x,Pc=x,zw={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,jc.allSchemaProperties)(n),c=a.filter(g=>(0,Ic.alwaysValidSchema)(s,n[g]));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 qn.Name)&&(s.props=(0,Pc.evaluatedPropsToName)(t,s.props));const{props:f}=s;p();function p(){for(const g of a)u&&h(g),s.allErrors?d(g):(t.var(l,!0),d(g),t.if(l))}function h(g){for(const y in u)new RegExp(g).test(y)&&(0,Ic.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function d(g){t.forIn("key",r,y=>{t.if((0,qn._)`${(0,jc.usePattern)(e,g)}.test(${y})`,()=>{const $=c.includes(g);$||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Pc.Type.Str},l),s.opts.unevaluated&&f!==!0?t.assign((0,qn._)`${f}[${y}]`,!0):!$&&!s.allErrors&&t.if((0,qn.not)(l),()=>t.break())})})}}};Ti.default=zw;var Ci={};Object.defineProperty(Ci,"__esModule",{value:!0});const Ww=x,Jw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,Ww.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"}};Ci.default=Jw;var Ri={};Object.defineProperty(Ri,"__esModule",{value:!0});const Hw=K,Yw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Hw.validateUnion,error:{message:"must match a schema in anyOf"}};Ri.default=Yw;var Mi={};Object.defineProperty(Mi,"__esModule",{value:!0});const sr=G,Qw=x,Zw={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,sr._)`{passingSchemas: ${e.passing}}`},Xw={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Zw,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,Qw.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,sr._)`${c} && ${i}`).assign(i,!1).assign(a,(0,sr._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),p&&e.mergeEvaluated(p,sr.Name)})})}}};Mi.default=Xw;var Di={};Object.defineProperty(Di,"__esModule",{value:!0});const eb=x,tb={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,eb.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Di.default=tb;var Li={};Object.defineProperty(Li,"__esModule",{value:!0});const mr=G,id=x,nb={message:({params:e})=>(0,mr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,mr._)`{failingKeyword: ${e.ifClause}}`},rb={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:nb,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,id.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=xc(r,"then"),s=xc(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,mr.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,mr._)`${l}`):e.setParams({ifClause:l})}}}};function xc(e,t){const n=e.schema[t];return n!==void 0&&!(0,id.alwaysValidSchema)(e,n)}Li.default=rb;var Bi={};Object.defineProperty(Bi,"__esModule",{value:!0});const ob=x,sb={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,ob.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};Bi.default=sb;Object.defineProperty(ki,"__esModule",{value:!0});const ib=Xt,ab=Ai,cb=en,ub=ji,lb=Ii,fb=od,db=Pi,pb=Cr,hb=xi,mb=Ti,gb=Ci,yb=Ri,$b=Mi,vb=Di,wb=Li,bb=Bi;function Eb(e=!1){const t=[gb.default,yb.default,$b.default,vb.default,wb.default,bb.default,db.default,pb.default,fb.default,hb.default,mb.default];return e?t.push(ab.default,ub.default):t.push(ib.default,cb.default),t.push(lb.default),t}ki.default=Eb;var Ui={},Fi={};Object.defineProperty(Fi,"__esModule",{value:!0});const ne=G,Sb={message:({schemaCode:e})=>(0,ne.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ne._)`{format: ${e}}`},Nb={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Sb,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}),g=n.const("fDef",(0,ne._)`${d}[${i}]`),y=n.let("fType"),$=n.let("format");n.if((0,ne._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>n.assign(y,(0,ne._)`${g}.type || "string"`).assign($,(0,ne._)`${g}.validate`),()=>n.assign(y,(0,ne._)`"string"`).assign($,g)),e.fail$data((0,ne.or)(v(),b()));function v(){return c.strictSchema===!1?ne.nil:(0,ne._)`${i} && !${$}`}function b(){const S=l.$async?(0,ne._)`(${g}.async ? await ${$}(${r}) : ${$}(${r}))`:(0,ne._)`${$}(${r})`,O=(0,ne._)`(typeof ${$} == "function" ? ${S} : ${$}.test(${r}))`;return(0,ne._)`${$} && ${$} !== true && ${y} === ${t} && !${O}`}}function h(){const d=f.formats[s];if(!d){v();return}if(d===!0)return;const[g,y,$]=b(d);g===t&&e.pass(S());function v(){if(c.strictSchema===!1){f.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(O){const j=O instanceof RegExp?(0,ne.regexpCode)(O):c.code.formats?(0,ne._)`${c.code.formats}${(0,ne.getProperty)(s)}`:void 0,C=n.scopeValue("formats",{key:s,ref:O,code:j});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,ne._)`${C}.validate`]:["string",O,C]}function S(){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})`}}}};Fi.default=Nb;Object.defineProperty(Ui,"__esModule",{value:!0});const Ob=Fi,_b=[Ob.default];Ui.default=_b;var Yt={};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.contentVocabulary=Yt.metadataVocabulary=void 0;Yt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Yt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(di,"__esModule",{value:!0});const kb=pi,Ab=mi,jb=ki,Ib=Ui,Tc=Yt,Pb=[kb.default,Ab.default,(0,jb.default)(),Ib.default,Tc.metadataVocabulary,Tc.contentVocabulary];di.default=Pb;var Vi={},Rr={};Object.defineProperty(Rr,"__esModule",{value:!0});Rr.DiscrError=void 0;var Cc;(function(e){e.Tag="tag",e.Mapping="mapping"})(Cc||(Rr.DiscrError=Cc={}));Object.defineProperty(Vi,"__esModule",{value:!0});const Rt=G,es=Rr,Rc=$e,xb=Zt,Tb=x,Cb={message:({params:{discrError:e,tagName:t}})=>e===es.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Rt._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},Rb={keyword:"discriminator",type:"object",schemaType:"object",error:Cb,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,Rt._)`${n}${(0,Rt.getProperty)(a)}`);t.if((0,Rt._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:es.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,Rt._)`${u} === ${d}`),t.assign(c,f(h[d]));t.else(),e.error(!1,{discrError:es.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(h){const d=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:h},d);return e.mergeEvaluated(g,Rt.Name),d}function p(){var h;const d={},g=$(o);let y=!0;for(let S=0;S<i.length;S++){let O=i[S];if(O!=null&&O.$ref&&!(0,Tb.schemaHasRulesButRef)(O,s.self.RULES)){const C=O.$ref;if(O=Rc.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),O instanceof Rc.SchemaEnv&&(O=O.schema),O===void 0)throw new xb.default(s.opts.uriResolver,s.baseId,C)}const j=(h=O==null?void 0:O.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&&(g||$(O)),v(j,S)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return d;function $({required:S}){return Array.isArray(S)&&S.includes(a)}function v(S,O){if(S.const)b(S.const,O);else if(S.enum)for(const j of S.enum)b(j,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(S,O){if(typeof S!="string"||S in d)throw new Error(`discriminator: "${a}" values must be unique strings`);d[S]=O}}}};Vi.default=Rb;const Mb="http://json-schema.org/draft-07/schema#",Db="http://json-schema.org/draft-07/schema#",Lb="Core schema meta-schema",Bb={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:[]}},Ub=["object","boolean"],Fb={$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:"#"}},Vb={$schema:Mb,$id:Db,title:Lb,definitions:Bb,type:Ub,properties:Fb,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=of,r=di,o=Vi,s=Vb,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=xe;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=jn;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=Zt;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Wo,Wo.exports);var qb=Wo.exports;const Kb=lg(qb);class ad 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 Gb(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new Kb({allErrors:!0,strict:!1}).compile(n);if(!o(e))throw new ad(zb(o.errors??[]))}function zb(e){return e.map(t=>({field:Wb(t),message:t.message??"is invalid",keyword:t.keyword}))}function Wb(e){var t;return(e.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((t=e.params)==null?void 0:t.missingProperty)??"(root)")}function Jb(e,t){return T.join(ll(e,t),by)}const Hb=384,Yb=448;function Qb(e,t,n={}){const r=n.mode??Hb,o=n.dirMode??Yb,s=T.dirname(e);U.mkdirSync(s,{recursive:!0,mode:o}),U.chmodSync(s,o);const i=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{U.writeFileSync(i,a,{encoding:"utf8",mode:r}),U.chmodSync(i,r),U.renameSync(i,e),U.chmodSync(e,r)}catch(c){try{U.existsSync(i)&&U.unlinkSync(i)}catch{}throw c}}const Zb="0.1.0";function Mc(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 Xb(){return`${process.pid}-${Wu.randomBytes(3).toString("hex")}`}function cd(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");Mc(e,"project");const r=t.orgNamespace??vy,o=t.envPrefixOverride??_y(e),s=t.namespaces&&t.namespaces.length>0?t.namespaces:[wy],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${e}" (declared: ${s.join(", ")})`);Mc(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=ag({scope:n.scope,cwd:n.cwd},a),l=ug({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 eE(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=cd(e,t,n),u=n.processEnv??process.env,l=My(c),f=n.instanceId??Xb(),{raw:p,nested:h,typedRaw:d,provenance:g,fields:y}=By(t.config,l,u,{prefix:s,activeScope:i}),$={};for(const O of Object.keys(y)){const j=y[O];j.live&&($[O]={env:j.env,type:j.type,fallback:j.secret===!0?void 0:j.fallbackValue})}const v=Ay(t.config);Gb(rf(d),v);const b=Fy(t.dirs,{roots:c,activeScope:i,instanceId:f,projectRoot:a,namespace:r}),S=Vy(t.files,b);return{version:$y,libraryVersion:Zb,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:f,config:h,raw:p,liveFields:$,fieldSchema:v,configHash:Ny(Object.fromEntries(Object.entries(d).map(([O,j])=>[O,String(j)]))),structureHash:Oy(Object.values(b).map(O=>({name:O.name,kind:O.kind,scope:O.scope}))),dirs:Object.values(b),files:Object.values(S),provenance:g}}let Nn=class extends Error{constructor(t){super(t),this.name="EnvironmentError"}};class tE extends Nn{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class nE extends Nn{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function rE(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 ts(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>ts(n));const t={};for(const[n,r]of Object.entries(e))t[n]=ts(r);return t}function oE(e,t){const n=ts(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?zo(c,o.type):o.fallback}})}return n}function sE(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Nn(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class qi{constructor(t,n,r={}){let o,s;try{o=eE(t,n,r);const i=cd(t,n,r);s=Jb(i.roots,o.scope)}catch(i){throw i instanceof ad||i instanceof Nn?i:new Nn(i instanceof Error?i.message:String(i))}return Dc(this,o,s)}static fromSnapshot(t){if(!U.existsSync(t))throw new tE(t);const n=JSON.parse(U.readFileSync(t,"utf8")),r=Object.create(qi.prototype);return Dc(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 rE(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"){sE(t);const n=this.paths.run??this._runDirFallback();U.mkdirSync(n,{recursive:!0});const r=T.join(n,`${t}.lock`);let o;try{o=U.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new nE(t,r):i}U.writeSync(o,`${process.pid}
163
163
  ${this.instanceId}
164
- `),Y.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{Y.unlinkSync(r)}catch{}}}}_runDirFallback(){return q.join(q.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))Y.mkdirSync(t,{recursive:!0})}write(){return ww(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Nc(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=Aw(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 Pf={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production"],dirs:{data:{kind:"data"}},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 Tf(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 ki(e={}){const t={namespace:"production",scope:Tf(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 Ai("backlog",Pf,t)}function jw(e,t){return`${e}:${t}`}function Oc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Iw(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:Oc(i),path:s.map(Oc),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 Cf=Symbol.for("adhd.apigen.extraction-session");function Rf(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{}Rf(r,t)}}}function Mf(e){try{const t=Y.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const cr=new Map,_c=new Map;function xw(e,t,n){const r=t??"",o=cr.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=_c.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},_c.set(i,a)),a.schemas}function Pw(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[Cf]:!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=cr.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:r?new pa.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new pa.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},cr.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=cr.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]);Rf(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=Mf(r),t.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function Tw(e){const t=e;if(t[Cf]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const yr="x-apigen-logical";function Ac(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 kc=new Set(["string","number","boolean","integer"]);function Cw(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"?kc.has(n):Array.isArray(n)?n.every(r=>kc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Rw(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(Cw)}function Mw(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{Ac(o.input,t),Ac(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function Dw(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 Lw(e,t,n){Mw(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 g of t)if(g.envelope&&i[g.id]!==!1)for(const[$,v]of Object.entries(g.envelope))u[$]=v,f[$]=g.id,l.includes($)||l.push($);const p={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},h=s.safe===!0||Rw(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:Dw(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 Uw=8;function Bw(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let Fw=0;async function Vw(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${Fw++}`;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 Df(e,t,n){if(n>Uw)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=>Df(i,t,n+1))),s=Dr(o);return{oneOf:o,...s?{discriminator:s}:{},[yr]:"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={};for(const c of i){const u=c.getName(),l=c.getDeclarations()[0];let f;if(l)try{f=c.getTypeAtLocation(l)}catch{f=void 0}if(f!==void 0&&f.getCallSignatures().length>0)continue;const p=f!==void 0?Bw(f,l):void 0;a[u]=p!==void 0?await t(p):{}}return Object.keys(a).length>0?{type:"object",properties:a}:{}}return{}}function Dr(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 ur(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=zo[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=zo[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:ur(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=>ur(c,t+1,n)),a=Dr(i);return{oneOf:i,...a?{discriminator:a}:{},[yr]:"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("?","")]=ur(u,t+1,n))}return{type:"object",properties:i}}return{}}function Lf(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 qw(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function Kw(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function zw(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 Lf(n)}async function Gw(e,t){const n=e.trim(),r=qw(n);if(r!==void 0){const i=Lf(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=Kw(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=zw(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 Uf={"decimal.js":"Decimal"},zo={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"}},jc={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Ic(e){var t;const n=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=Uf[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 Hw(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(jc,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 St.AnnotatedType(new St.StringType,{format:jc[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){return new St.AnnotatedType(new St.StringType,{format:"int64"},!1)}})}}let ln;function Jw(){if(ln)return ln;try{const e=q.dirname(require.resolve("ts-json-schema-generator/package.json"));ln=require(require.resolve("typescript",{paths:[e]}))}catch{ln=require("typescript")}return ln}const st=new Map;function Ww(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function Qw(e){const t=st.get(e);return t&&(st.delete(e),st.set(e,t)),t}function Yw(e,t){const n=Ww();if(n!==0)for(st.delete(e),st.set(e,t);st.size>n;){const r=st.keys().next().value;st.delete(r)}}function Zw(e,t){return`${e}\0${t??""}`}const Xw=new Set(["zod",/^zod\/./]);function eb(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of Xw)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function tb(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]}Go(e)}function Go(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&&Go(o,n);else Go(r,n)}}function nb(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=Ho(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 Ho(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(...Ho(s,t));else n.push(...Ho(o,t));return n}function rb(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=Dr(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[yr]:o[yr]??"union"}}function ob(e,t,n){const{DEFAULT_CONFIG:r}=require("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},s=o.path,i=Zw(s,o.tsconfig);let a;a=n?n.statVersion(s):Mf(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??Qw(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=require("ts-json-schema-generator/dist/factory/program.js"),f=Jw(),p=Hw(f.SyntaxKind.BigIntKeyword,f.SyntaxKind.TypeReference),h=l(o),d=St.createParser(h,o,p),m=St.createFormatter(o);if(c=new St.SchemaGenerator(h,d,m,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const g={version:a,gen:c};Yw(i,g),n==null||n.generatorCache.set(i,g)}}const u=c.createSchema(o.type);return tb(u),nb(u),u}function sb(e,t){let n=e.trim();if(n=Ff(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 Bf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const ib=Object.entries(Uf).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Bf(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ff(e){let t=e;for(const{pattern:n,key:r}of ib)t=t.replace(n,r);return t}function ab(e,t){let n=Ff(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${Bf(r)}\\b`,"g"),o);return n}async function kn(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),xc(e,t,n,r,void 0,d)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=xw(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=xc(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 xc(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??Ic(t),p||o.aliasCache.set(t,i)}else i=Ic(t);const a=sb(n,i),c=zo[a];if(c!==void 0)return c;const u=await Gw(a,p=>kn(e,t,p,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(t))??eb(t);if(o&&o.zodImportCache.set(t,l),!l)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},h=ob(p,!0,o);return rb(h)}catch{}try{const p=await Vw(e,t,a,h=>Df(h,d=>kn(e,t,d,r,o,s),0));if(p!==void 0)return p}catch{}const f=ab(a,i);return ur(f,0,i)}function ji(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return cb(n,t)}function cb(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 ub(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 lb(e,t){const n=ub(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})`}async function fb(e){const t=e.session===void 0,n=Tw(e.session??Pw());try{return await db(e,n)}finally{t&&n.dispose()}}async function db(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:s}=e,i=t.projectFor(s),a=t.sourceFileFor(n,s),c=q.basename(n),u=We(gb(c)),l=o?null:u,f=We(r),p=[];for(const[m,g]of a.getExportedDeclarations()){if(m==="default"||Hn(m))continue;const $=$b(g);if($){const N=$.getSignature(),I=Pc(N,$),T=N.getReturnType().getText();p.push(await Gn(i,a,f,l,m,I,T,$.isAsync(),s,t));continue}const v=g.find(N=>N.getKindName()==="VariableDeclaration");if(!v)continue;const w=v.getInitializer(),S=w==null?void 0:w.getKindName();if(w&&["ArrowFunction","FunctionExpression"].includes(S??"")){const N=v.getType().getCallSignatures();if(N.length===0)continue;const I=N[0],T=Tc(I,v,v.getVariableStatement()),K=I.getReturnType().getText(),L=w.isAsync();p.push(await Gn(i,a,f,l,m,T,K,L,s,t))}else if(S==="ObjectLiteralExpression"){const N=v.getType();for(const I of N.getProperties()){const T=I.getName();if(Hn(T))continue;const K=I.getTypeAtLocation(v).getCallSignatures();if(K.length===0)continue;const L=K[0],V=Tc(L,v,v.getVariableStatement()),H=L.getReturnType().getText(),Q=[...l?[l]:[],We(m),We(T)];p.push(await lr(i,a,f,Q,T,V,H,!1,s,t))}}else{const N=v.getType(),I=N.getText();if(vt(N,v)){const T=await kn(i,a,I,s,t);p.push(hb(f,l,m,T))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${m}`)}}const h=a.getDefaultExportSymbol();if(h){const m=a.getExportAssignment(g=>!g.isExportEquals());if(m){const g=m.getExpression(),$=g.getKindName();if(["ArrowFunction","FunctionExpression"].includes($)){const v=g.getType().getCallSignatures();if(v.length>0){const w=v[0],S=oo(w,m),N=w.getReturnType().getText(),I=g.isAsync();p.push(await Gn(i,a,f,l,"default",S,N,I,s,t))}}else{const v=g.getType();for(const w of v.getProperties()){const S=w.getName();if(Hn(S))continue;const N=w.getTypeAtLocation(m).getCallSignatures();if(N.length===0)continue;const I=N[0],T=oo(I,m),K=I.getReturnType().getText(),L=[...l?[l]:[],We("default"),We(S)];p.push(await lr(i,a,f,L,S,T,K,!1,s,t))}}}else{const g=h.getDeclarations();for(const $ of g){if($.getKindName()!=="FunctionDeclaration")continue;const v=$,w=v.getName(),S=w&&w.length>0?w:"default",N=v.getSignature(),I=Pc(N,v),T=N.getReturnType().getText();p.push(await Gn(i,a,f,l,S,I,T,v.isAsync(),s,t))}}}const d=yb(a);if(d.length>0)for(const{name:m,sig:g}of d){if(Hn(m))continue;const $=oo(g),v=g.getReturnType().getText(),w=[...l?[l]:[],We(m)];p.push(await lr(i,a,f,w,m,$,v,!1,s,t))}return p}function pb(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),g=p[h];if(g!==void 0&&JSON.stringify(g)!==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)}async function Gn(e,t,n,r,o,s,i,a,c,u){const l=We(o);return lr(e,t,n,r?[r,l]:[l],o,s,i,a,c,u)}async function lr(e,t,n,r,o,s,i,a,c,u){const l=s.length>0&&s[0].name==="ctx",f=s.filter(v=>v.name!=="ctx"),p=f.filter(v=>!v.optional).map(v=>v.name),h={},d={definitions:{},$defs:{}};for(const v of f){const w=await kn(e,t,v.type,c,u),S=pb(w,d,o,v.name);v.defaultValue!==void 0&&lb(S,v.defaultValue),h[v.name]=S}const m=i.replace(/^Promise<(.+)>$/,"$1").trim(),g=await kn(e,t,m,c,u),$={type:"object",properties:h,required:p,...Object.keys(d.definitions).length>0?{definitions:d.definitions}:{},...Object.keys(d.$defs).length>0?{$defs:d.$defs}:{}};return{id:Vf(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:$,output:g,envelope:{},typeText:{lang:"ts",input:vb(s),output:m},...l?{hasCtx:!0}:{}}}function hb(e,t,n,r){const o=We(n),s=t?[t,o]:[o];return{id:Vf(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 Vf(e,t){return(e.raw?[e,...t]:t).map(n=>n.words.join("-")).join("/")}function mb(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 We(e){return{raw:e,words:mb(e)}}function gb(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function yb(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 $b(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 Pc(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:ji(s,n.getName(),t)}})}function Tc(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:ji(i,r.getName(),n??t)}})}function oo(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:ji(a,n.getName(),t)}})}function vb(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Hn(e){return!!(e==="__samples__"||e.startsWith("__"))}function vt(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?vt(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>vt(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>vt(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>vt(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||vt(a,t,n));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return vt(c,t,n)})}return!1}function wb(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 bb(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:wb(e.output)}}function Sb(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 Cc(e){return{type:"string",enum:[e]}}function Rc(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 Eb(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(bb);if(e.length===1){const[o]=e,[s]=t;return{input:Rc(s,Cc(o.id)),output:{type:"array",items:s.resultSchema}}}const n=e.map((o,s)=>Rc(t[s],Cc(o.id))),r=Dr(n);return{input:{oneOf:n,...r?{discriminator:r}:{}},output:{oneOf:t.map(o=>({type:"array",items:o.resultSchema}))},...r?{discriminator:r}:{}}}function Nb(e,t={}){const n=Sb(e.operations,t),r=[];for(const[o,s]of n){const{input:i,output:a}=Eb(s),c=Iw(`_batch/${o}`,e,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const Ob={"decimal.js":"Decimal"};function _b(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ob).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${_b(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const Ab=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],kb={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let jb=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 Ii(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&Ab.includes(e.code)&&typeof e.toJSON=="function"}const Jo="$apigen";let Mc=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Ib(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Mc(`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 Mc("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 xi="x-apigen-logical",Pi="x-apigen-codec",Wo="x-apigen-ctor",Qo="x-apigen-tojson",xb="0.1.0";function Dc(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 Bt(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 Bt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=qf(e,s,t);return Bt(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=>Ot(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Ot(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 so(e,t,n);const a=t.properties;if(!a)return Ot(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?so(e,t,n):Ot(e)}function Ft(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 Ft(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=qf(e,s,t);return Ft(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:Ft(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ft(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]=Ft(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Pb(e,n):e}function qf(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{[Jo]:r,v:s}}catch{}}return Ot(e)}function Pb(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 Ot(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Ot);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Ot(r));return t}return null}function Tb(e){return{encode(t,n,r){const o=Dc(e,r);return Bt(t,n,o)},decode(t,n,r){const o=Dc(e,r);return Ft(t,n,o)}}}const Ti={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)}},Ri={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}},Mi={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"))}},Cb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Di={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"&&!Cb.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Yo="NaN",Zo="Infinity",Xo="-Infinity",Rb=new Set([Yo,Zo,Xo]),Li={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)?Yo:e===1/0?Zo:e===-1/0?Xo:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Yo)return NaN;if(e===Zo)return 1/0;if(e===Xo)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 ${[...Rb].join(", ")}.`);return NaN}},Mb=[Ti,Ci,Ri,Mi,Di,Li];function Db(e,t={}){for(const n of Mb)e.register(n,{override:t.override??!1})}Ti.id,Ci.id,Ri.id,Mi.id,Di.id,Li.id;const Kf=Ib();Db(Kf);const zf=Tb(Kf.freeze());function Lb(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Ub(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 Bb(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 Fb(e,t){return t===void 0||e===void 0?e:zf.decode(e,t)}function io(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:zf.encode(e,n)}async function Vb(e,t,n,r,o,s){const i=Ub(n).map(c=>Fb(s[c],Bb(n,c)));if(Lb(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return io(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return io(u,n)}const a=await e[r](...i);return io(a,n)}let Gf=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 qb(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=()=>Vb(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const Kb={"decimal.js":"Decimal"};function zb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Kb).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${zb(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Gb(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}}},Pe(s);const i=n?Pe.destination({dest:e.destination,mkdir:!0,sync:!0}):Pe.destination(2);return Pe(s,i)}function Hf(e){return e?e.type==="array"?`${Hf(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Jf(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:Hf(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function Hb(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function Jb(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=Hb(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 Wb=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 Lr=new br({allErrors:!0});Sr(Lr);for(const e of[xi,Pi,Wo,Qo,"discriminator"])Lr.addKeyword({keyword:e,valid:!0});Lr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Qb(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Yb(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=Lr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Wb("invalid_argument",`Validation failed: ${Qb(a)}`,a)}return n()}}function Zb(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let mt=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function ao(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 Wf(e,t){const n=e[Pi];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Xb(e,t,n){const r=Wf(t,n);return r?r.encode(e,t,n):e}function eS(e,t,n){const r=Wf(t,n);return r?r.decode(e,t,n):e}function tS(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[xi]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:ao(r)!==void 0},encode(r,o,s){const i=ao(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 Xb(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=ao(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 eS(r,h,{...s,path:`${s.path}[${f}]`})}}}const nS="x-apigen-instances";let Jn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Lc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function rS(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Uc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function oS(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function sS(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[xi]==="nominal"?!0:o[Pi]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Jn("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=Lc(s),c=typeof s[Qo]=="string"?s[Qo]:"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[g,$]of Object.entries(d))m[g]=Uc($,a[g],{...i,path:`${i.path}/${g}`});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]=Uc(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 Jn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of rS(s))if(!(l in a))throw new Jn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[nS]===!1)throw new Jn("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=Lc(s),u={};for(const[l,f]of Object.entries(a))u[l]=oS(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Wo]=="string"?s[Wo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const iS=[Ti,Ci,Ri,Mi,Di,Li],aS={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Bc=sS({id:"ts.NominalSentinel",schema:aS}),cS={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Fc=tS({id:"ts.UnionSentinel",schema:cS});function uS(){const e=[...iS.map(t=>[t.id,t]),[Bc.id,Bc],[Fc.id,Fc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:xb,codecs:uS()});const Vc=new Set(["string","number","boolean","integer"]);function lS(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"?Vc.has(n):Array.isArray(n)?n.every(r=>Vc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function fS(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(lS)}const dS={"decimal.js":"Decimal"};function pS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(dS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${pS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function qc(e){return e.words.join("-")}function Kc(e){return e.words.map($S).join("")}function zc(e){return e.words.join("_")}function hS(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||fS(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=>qc(h)).join("/"),c=o.map(h=>zc(h)).join("_"),u=o.map(h=>zc(h)).slice(0,-1).join("."),l=Kc(o[o.length-2]??o[0]),f=Kc(o[o.length-1]),p=o.map(h=>qc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function mS(e,t){return`x-${e}-${t}`}function gS(e,t){return`--${e}-${t}`}function yS(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function $S(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Qf(e){return e.anyOf??e.oneOf}function vS(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Qf(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 wS(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Qf(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function bS(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function SS(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 Gc(e){return typeof e.handler=="function"}function ES(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=mS(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:gS(i,s),envVar:yS(i,s)})}return o}function NS(e,t){const n=new Map,{props:r}=SS(e);for(const[o,s]of Object.entries(r)){let i="string";wS(s)?i="boolean":vS(s)&&(i="json"),n.set(bS(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 Hc(e){const{op:t,schema:n,transport:r,projection:o}=e,s=hS(t,o),i=n?ES(n):[],a=n?NS(n,i):new Map,c=n?Jf(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:Gc(t)};if(Gc(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function OS(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function _S(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function AS(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function co(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(AS(s))}return r.push(Yb(e)),qb(r)}function kS(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const jS={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Jc(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Gf};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:kS(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:jS}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const IS={"decimal.js":"Decimal"};function xS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(IS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${xS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function es(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 Wc(e){return{raw:e,words:es(e)}}function PS(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:`${es(e).join("-")}/${es(t).join("-")}`,host:"ts",namespace:Wc(e),path:[Wc(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function TS(e){return`data: ${e}
164
+ `),U.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{U.unlinkSync(r)}catch{}}}}_runDirFallback(){return T.join(T.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))U.mkdirSync(t,{recursive:!0})}write(){return Qb(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Dc(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=oE(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 ud={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production"],dirs:{data:{kind:"data"}},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 ld(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 Ki(e={}){const t={namespace:"production",scope:ld(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 qi("backlog",ud,t)}function iE(e,t){return`${e}:${t}`}function Lc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function aE(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:Lc(i),path:s.map(Lc),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 fd=Symbol.for("adhd.apigen.extraction-session");function dd(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{}dd(r,t)}}}function pd(e){try{const t=U.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const ir=new Map,Bc=new Map;function cE(e,t,n){const r=t??"",o=ir.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=Bc.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},Bc.set(i,a)),a.schemas}function uE(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[fd]:!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=ir.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:r?new Ia.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new Ia.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},ir.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=ir.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]);dd(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=pd(r),t.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function lE(e){const t=e;if(t[fd]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const gr="x-apigen-logical";function Uc(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 Fc=new Set(["string","number","boolean","integer"]);function fE(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"?Fc.has(n):Array.isArray(n)?n.every(r=>Fc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function dE(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(fE)}function pE(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{Uc(o.input,t),Uc(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function hE(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 mE(e,t,n){pE(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||dE(s.input),d=s.input.definitions,g=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:p},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:hE(Object.keys(u),Object.keys(a).length>0),...d?{definitions:d}:{},...g?{$defs:g}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":h,...Object.keys(f).length>0?{"x-apigen-envelope":f}:{}}}return r}const gE=8;function yE(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let $E=0;async function vE(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${$E++}`;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 hd(e,t,n){if(n>gE)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=>hd(i,t,n+1))),s=Mr(o);return{oneOf:o,...s?{discriminator:s}:{},[gr]:"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={};for(const c of i){const u=c.getName(),l=c.getDeclarations()[0];let f;if(l)try{f=c.getTypeAtLocation(l)}catch{f=void 0}if(f!==void 0&&f.getCallSignatures().length>0)continue;const p=f!==void 0?yE(f,l):void 0;a[u]=p!==void 0?await t(p):{}}return Object.keys(a).length>0?{type:"object",properties:a}:{}}return{}}function Mr(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 ar(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=ns[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=ns[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:ar(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=>ar(c,t+1,n)),a=Mr(i);return{oneOf:i,...a?{discriminator:a}:{},[gr]:"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("?","")]=ar(u,t+1,n))}return{type:"object",properties:i}}return{}}function md(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 wE(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function bE(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function EE(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 md(n)}async function SE(e,t){const n=e.trim(),r=wE(n);if(r!==void 0){const i=md(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=bE(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=EE(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 gd={"decimal.js":"Decimal"},ns={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"}},Vc={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function qc(e){var t;const n=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=gd[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 NE(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(Vc,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 $t.AnnotatedType(new $t.StringType,{format:Vc[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){return new $t.AnnotatedType(new $t.StringType,{format:"int64"},!1)}})}}let sn;function OE(){if(sn)return sn;try{const e=T.dirname(require.resolve("ts-json-schema-generator/package.json"));sn=require(require.resolve("typescript",{paths:[e]}))}catch{sn=require("typescript")}return sn}const tt=new Map;function _E(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function kE(e){const t=tt.get(e);return t&&(tt.delete(e),tt.set(e,t)),t}function AE(e,t){const n=_E();if(n!==0)for(tt.delete(e),tt.set(e,t);tt.size>n;){const r=tt.keys().next().value;tt.delete(r)}}function jE(e,t){return`${e}\0${t??""}`}const IE=new Set(["zod",/^zod\/./]);function PE(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of IE)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function xE(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]}rs(e)}function rs(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&&rs(o,n);else rs(r,n)}}function TE(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=os(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 os(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(...os(s,t));else n.push(...os(o,t));return n}function CE(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=Mr(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[gr]:o[gr]??"union"}}function RE(e,t,n){const{DEFAULT_CONFIG:r}=require("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},s=o.path,i=jE(s,o.tsconfig);let a;a=n?n.statVersion(s):pd(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??kE(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=require("ts-json-schema-generator/dist/factory/program.js"),f=OE(),p=NE(f.SyntaxKind.BigIntKeyword,f.SyntaxKind.TypeReference),h=l(o),d=$t.createParser(h,o,p),g=$t.createFormatter(o);if(c=new $t.SchemaGenerator(h,d,g,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const y={version:a,gen:c};AE(i,y),n==null||n.generatorCache.set(i,y)}}const u=c.createSchema(o.type);return xE(u),TE(u),u}function ME(e,t){let n=e.trim();if(n=$d(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 yd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const DE=Object.entries(gd).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${yd(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function $d(e){let t=e;for(const{pattern:n,key:r}of DE)t=t.replace(n,r);return t}function LE(e,t){let n=$d(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${yd(r)}\\b`,"g"),o);return n}async function On(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),Kc(e,t,n,r,void 0,d)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=cE(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=Kc(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 Kc(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??qc(t),p||o.aliasCache.set(t,i)}else i=qc(t);const a=ME(n,i),c=ns[a];if(c!==void 0)return c;const u=await SE(a,p=>On(e,t,p,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(t))??PE(t);if(o&&o.zodImportCache.set(t,l),!l)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},h=RE(p,!0,o);return CE(h)}catch{}try{const p=await vE(e,t,a,h=>hd(h,d=>On(e,t,d,r,o,s),0));if(p!==void 0)return p}catch{}const f=LE(a,i);return ar(f,0,i)}function Gi(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return BE(n,t)}function BE(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 UE(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 FE(e,t){const n=UE(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})`}async function VE(e){const t=e.session===void 0,n=lE(e.session??uE());try{return await qE(e,n)}finally{t&&n.dispose()}}async function qE(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=Ve(WE(c)),l=o?null:u,f=Ve(r),p=[];for(const[g,y]of a.getExportedDeclarations()){if(g==="default"||Gn(g))continue;const $=HE(y);if($){const O=$.getSignature(),j=Gc(O,$),C=O.getReturnType().getText();p.push(await Kn(i,a,f,l,g,j,C,$.isAsync(),s,t));continue}const v=y.find(O=>O.getKindName()==="VariableDeclaration");if(!v)continue;const b=v.getInitializer(),S=b==null?void 0:b.getKindName();if(b&&["ArrowFunction","FunctionExpression"].includes(S??"")){const O=v.getType().getCallSignatures();if(O.length===0)continue;const j=O[0],C=zc(j,v,v.getVariableStatement()),W=j.getReturnType().getText(),B=b.isAsync();p.push(await Kn(i,a,f,l,g,C,W,B,s,t))}else if(S==="ObjectLiteralExpression"){const O=v.getType();for(const j of O.getProperties()){const C=j.getName();if(Gn(C))continue;const W=j.getTypeAtLocation(v).getCallSignatures();if(W.length===0)continue;const B=W[0],q=zc(B,v,v.getVariableStatement()),Z=B.getReturnType().getText(),Q=[...l?[l]:[],Ve(g),Ve(C)];p.push(await cr(i,a,f,Q,C,q,Z,!1,s,t))}}else{const O=v.getType(),j=O.getText();if(ht(O,v)){const C=await On(i,a,j,s,t);p.push(GE(f,l,g,C))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${g}`)}}const h=a.getDefaultExportSymbol();if(h){const g=a.getExportAssignment(y=>!y.isExportEquals());if(g){const y=g.getExpression(),$=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes($)){const v=y.getType().getCallSignatures();if(v.length>0){const b=v[0],S=yo(b,g),O=b.getReturnType().getText(),j=y.isAsync();p.push(await Kn(i,a,f,l,"default",S,O,j,s,t))}}else{const v=y.getType();for(const b of v.getProperties()){const S=b.getName();if(Gn(S))continue;const O=b.getTypeAtLocation(g).getCallSignatures();if(O.length===0)continue;const j=O[0],C=yo(j,g),W=j.getReturnType().getText(),B=[...l?[l]:[],Ve("default"),Ve(S)];p.push(await cr(i,a,f,B,S,C,W,!1,s,t))}}}else{const y=h.getDeclarations();for(const $ of y){if($.getKindName()!=="FunctionDeclaration")continue;const v=$,b=v.getName(),S=b&&b.length>0?b:"default",O=v.getSignature(),j=Gc(O,v),C=O.getReturnType().getText();p.push(await Kn(i,a,f,l,S,j,C,v.isAsync(),s,t))}}}const d=JE(a);if(d.length>0)for(const{name:g,sig:y}of d){if(Gn(g))continue;const $=yo(y),v=y.getReturnType().getText(),b=[...l?[l]:[],Ve(g)];p.push(await cr(i,a,f,b,g,$,v,!1,s,t))}return p}function KE(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 g=s(d),y=p[h];if(y!==void 0&&JSON.stringify(y)!==JSON.stringify(g))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]=g}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(e)}async function Kn(e,t,n,r,o,s,i,a,c,u){const l=Ve(o);return cr(e,t,n,r?[r,l]:[l],o,s,i,a,c,u)}async function cr(e,t,n,r,o,s,i,a,c,u){const l=s.length>0&&s[0].name==="ctx",f=s.filter(v=>v.name!=="ctx"),p=f.filter(v=>!v.optional).map(v=>v.name),h={},d={definitions:{},$defs:{}};for(const v of f){const b=await On(e,t,v.type,c,u),S=KE(b,d,o,v.name);v.defaultValue!==void 0&&FE(S,v.defaultValue),h[v.name]=S}const g=i.replace(/^Promise<(.+)>$/,"$1").trim(),y=await On(e,t,g,c,u),$={type:"object",properties:h,required:p,...Object.keys(d.definitions).length>0?{definitions:d.definitions}:{},...Object.keys(d.$defs).length>0?{$defs:d.$defs}:{}};return{id:vd(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:$,output:y,envelope:{},typeText:{lang:"ts",input:YE(s),output:g},...l?{hasCtx:!0}:{}}}function GE(e,t,n,r){const o=Ve(n),s=t?[t,o]:[o];return{id:vd(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 vd(e,t){return(e.raw?[e,...t]:t).map(n=>n.words.join("-")).join("/")}function zE(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 Ve(e){return{raw:e,words:zE(e)}}function WE(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function JE(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 HE(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 Gc(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:Gi(s,n.getName(),t)}})}function zc(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:Gi(i,r.getName(),n??t)}})}function yo(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:Gi(a,n.getName(),t)}})}function YE(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Gn(e){return!!(e==="__samples__"||e.startsWith("__"))}function ht(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?ht(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>ht(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>ht(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>ht(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||ht(a,t,n));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return ht(c,t,n)})}return!1}function QE(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 ZE(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:QE(e.output)}}function XE(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 Wc(e){return{type:"string",enum:[e]}}function Jc(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 eS(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(ZE);if(e.length===1){const[o]=e,[s]=t;return{input:Jc(s,Wc(o.id)),output:{type:"array",items:s.resultSchema}}}const n=e.map((o,s)=>Jc(t[s],Wc(o.id))),r=Mr(n);return{input:{oneOf:n,...r?{discriminator:r}:{}},output:{oneOf:t.map(o=>({type:"array",items:o.resultSchema}))},...r?{discriminator:r}:{}}}function tS(e,t={}){const n=XE(e.operations,t),r=[];for(const[o,s]of n){const{input:i,output:a}=eS(s),c=aE(`_batch/${o}`,e,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const nS={"decimal.js":"Decimal"};function rS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(nS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${rS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const oS=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],sS={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let iS=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 zi(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&oS.includes(e.code)&&typeof e.toJSON=="function"}const ss="$apigen";let Hc=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function aS(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Hc(`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 Hc("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 Wi="x-apigen-logical",Ji="x-apigen-codec",is="x-apigen-ctor",as="x-apigen-tojson",cS="0.1.0";function Yc(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 Mt(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 Mt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=wd(e,s,t);return Mt(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=>bt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?bt(u):Mt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Mt(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 bt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Mt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?$o(e,t,n):bt(e)}function Dt(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 Dt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=wd(e,s,t);return Dt(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: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 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]=Dt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?uS(e,n):e}function wd(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{[ss]:r,v:s}}catch{}}return bt(e)}function uS(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&ss in e){const n=e,r=n[ss],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function bt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(bt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=bt(r));return t}return null}function lS(e){return{encode(t,n,r){const o=Yc(e,r);return Mt(t,n,o)},decode(t,n,r){const o=Yc(e,r);return Dt(t,n,o)}}}const Hi={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)}},Yi={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)}},Qi={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}},Zi={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"))}},fS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Xi={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"&&!fS.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},cs="NaN",us="Infinity",ls="-Infinity",dS=new Set([cs,us,ls]),ea={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?us:e===-1/0?ls:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===cs)return NaN;if(e===us)return 1/0;if(e===ls)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 ${[...dS].join(", ")}.`);return NaN}},pS=[Hi,Yi,Qi,Zi,Xi,ea];function hS(e,t={}){for(const n of pS)e.register(n,{override:t.override??!1})}Hi.id,Yi.id,Qi.id,Zi.id,Xi.id,ea.id;const bd=aS();hS(bd);const Ed=lS(bd.freeze());function mS(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function gS(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 yS(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 $S(e,t){return t===void 0||e===void 0?e:Ed.decode(e,t)}function vo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Ed.encode(e,n)}async function vS(e,t,n,r,o,s){const i=gS(n).map(c=>$S(s[c],yS(n,c)));if(mS(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 Sd=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 wS(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=()=>vS(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const bS={"decimal.js":"Decimal"};function ES(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(bS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ES(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function SS(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}}},_e(s);const i=n?_e.destination({dest:e.destination,mkdir:!0,sync:!0}):_e.destination(2);return _e(s,i)}function Nd(e){return e?e.type==="array"?`${Nd(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Od(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:Nd(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function NS(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function OS(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=NS(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 _S=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 Dr=new wr({allErrors:!0});br(Dr);for(const e of[Wi,Ji,is,as,"discriminator"])Dr.addKeyword({keyword:e,valid:!0});Dr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function kS(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function AS(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=Dr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new _S("invalid_argument",`Validation failed: ${kS(a)}`,a)}return n()}}function jS(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 _d(e,t){const n=e[Ji];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function IS(e,t,n){const r=_d(t,n);return r?r.encode(e,t,n):e}function PS(e,t,n){const r=_d(t,n);return r?r.decode(e,t,n):e}function xS(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Wi]==="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 IS(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 PS(r,h,{...s,path:`${s.path}[${f}]`})}}}const TS="x-apigen-instances";let zn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Qc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function CS(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Zc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function RS(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function MS(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Wi]==="nominal"?!0:o[Ji]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new zn("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=Qc(s),c=typeof s[as]=="string"?s[as]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const g={};for(const[y,$]of Object.entries(d))g[y]=Zc($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=Zc(g,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 zn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of CS(s))if(!(l in a))throw new zn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[TS]===!1)throw new zn("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=Qc(s),u={};for(const[l,f]of Object.entries(a))u[l]=RS(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[is]=="string"?s[is]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const DS=[Hi,Yi,Qi,Zi,Xi,ea],LS={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Xc=MS({id:"ts.NominalSentinel",schema:LS}),BS={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},eu=xS({id:"ts.UnionSentinel",schema:BS});function US(){const e=[...DS.map(t=>[t.id,t]),[Xc.id,Xc],[eu.id,eu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:cS,codecs:US()});const tu=new Set(["string","number","boolean","integer"]);function FS(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"?tu.has(n):Array.isArray(n)?n.every(r=>tu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function VS(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(FS)}const qS={"decimal.js":"Decimal"};function KS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(qS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${KS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function nu(e){return e.words.join("-")}function ru(e){return e.words.map(HS).join("")}function ou(e){return e.words.join("_")}function GS(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||VS(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=>nu(h)).join("/"),c=o.map(h=>ou(h)).join("_"),u=o.map(h=>ou(h)).slice(0,-1).join("."),l=ru(o[o.length-2]??o[0]),f=ru(o[o.length-1]),p=o.map(h=>nu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function zS(e,t){return`x-${e}-${t}`}function WS(e,t){return`--${e}-${t}`}function JS(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function HS(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function kd(e){return e.anyOf??e.oneOf}function YS(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=kd(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 QS(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=kd(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function ZS(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function XS(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 su(e){return typeof e.handler=="function"}function eN(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=zS(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:WS(i,s),envVar:JS(i,s)})}return o}function tN(e,t){const n=new Map,{props:r}=XS(e);for(const[o,s]of Object.entries(r)){let i="string";QS(s)?i="boolean":YS(s)&&(i="json"),n.set(ZS(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 iu(e){const{op:t,schema:n,transport:r,projection:o}=e,s=GS(t,o),i=n?eN(n):[],a=n?tN(n,i):new Map,c=n?Od(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:su(t)};if(su(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function nN(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function rN(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function oN(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(oN(s))}return r.push(AS(e)),wS(r)}function sN(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const iN={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function au(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Sd};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:sN(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:iN}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const aN={"decimal.js":"Decimal"};function cN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(aN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${cN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function fs(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 cu(e){return{raw:e,words:fs(e)}}function uN(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:`${fs(e).join("-")}/${fs(t).join("-")}`,host:"ts",namespace:cu(e),path:[cu(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function lN(e){return`data: ${e}
165
165
 
166
- `}function CS(e){return`event: error
166
+ `}function fN(e){return`event: error
167
167
  data: ${e}
168
168
 
169
- `}async function RS(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(TS(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=Ii(i)?i:new jb("internal",i instanceof Error?i.message:String(i));if(s)o.write(CS(JSON.stringify(a.toJSON()))),o.end();else{const c=DS(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const MS={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function DS(e){return MS[e]??500}function Yf(e){return Ii(e)?kb[e.code]??500:500}function Zf(e){return Ii(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function LS(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 US=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?Jb(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(Zb(n)){await RS(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(Yf(n)).send(Zf(n))}};function BS(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 FS(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=OS(e.options),c=_S(e.options),u=e.logger??Gb(),l=Hp({logger:u});l.setErrorHandler((w,S,N)=>{N.status(Yf(w)).send(Zf(w))});const f=new US(l,s,e.signal),p=[],h={},d={};for(const w of e.packages){if(!w.fns)throw new Error(`Package "${w.id}" is missing fns`);const S=w.fns,N=Object.entries(w.schemas).map(([V,H])=>({fnName:V,fnSchema:H,op:PS(w.id,V,H,e.operations)})),I={},T={};for(const{fnName:V,fnSchema:H,op:Q}of N)I[Q.id]=H,T[Q.id]=S[V],h[Q.id]=H,d[Q.id]=S[V];const K=co(I,a),L={fns:T,createClient:w.createClient,schemas:I};for(const{fnSchema:V,op:H}of N){const Q=Hc({op:H,schema:V,transport:"http",projection:i});f.bindSchema(H.id,V),f.registerRoute(Q,Oe=>Jc(Q,K,Oe,L));const{params:ee,text:oe}=Jf(V);p.push({method:Q.http.verb,route:s+Q.http.route,text:oe,params:ee})}}const m=((t=e.packages[0])==null?void 0:t.id)??"ts",g=co(h,a),$={invoke:(w,S,N)=>g(w,{operation:{id:w},ctx:new Gf,domainArgs:S.domainArgs,envelope:S.envelope,signal:S.signal},N),invokeOptions:{fns:d,schemas:h,createClient:(n=e.packages[0])==null?void 0:n.createClient}},v=BS(a,c,m,e.operations??[],$);if(v.length>0){const w=co({},a),S={fns:{},schemas:{}};for(const N of v){const I=Hc({op:N,transport:"http",projection:i});f.registerRoute(I,T=>Jc(I,w,T,S)),p.push({method:I.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}`),LS(u,p),new Promise(w=>{e.signal&&e.signal.addEventListener("abort",async()=>{await l.close(),w()})})}const VS={id:"api-fastify",run(e){return FS(e)}};function Qc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function qS(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:Qc(i),path:s.map(Qc),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 KS={"decimal.js":"Decimal"};function zS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(KS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${zS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const Yc=new Set(["string","number","boolean","integer"]);function GS(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"?Yc.has(n):Array.isArray(n)?n.every(r=>Yc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function HS(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(GS)}const JS={"decimal.js":"Decimal"};function WS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(JS).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${WS(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Zc(e){return e.words.join("-")}function Xc(e){return e.words.map(YS).join("")}function eu(e){return e.words.join("_")}function QS(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||HS(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=>Zc(h)).join("/"),c=o.map(h=>eu(h)).join("_"),u=o.map(h=>eu(h)).slice(0,-1).join("."),l=Xc(o[o.length-2]??o[0]),f=Xc(o[o.length-1]),p=o.map(h=>Zc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function YS(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ZS(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const s of e){const i=QS(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:XS(s.output)}};if(a==="GET")l.parameters=eE(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 XS(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function eE(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 tE(e,t={}){return[{...qS("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>ZS(e.operations,{title:t.title,version:t.version})}]}const nE={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 tE(e,t)}}}},ts="$apigen";let tu=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function rE(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new tu(`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 tu("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 Ui="x-apigen-logical",Bi="x-apigen-codec",ns="x-apigen-ctor",rs="x-apigen-tojson",oE="0.1.0";function nu(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 Vt(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 Vt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Xf(e,s,t);return Vt(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):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 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]=Vt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?uo(e,t,n):_t(e)}function qt(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 qt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Xf(e,s,t);return qt(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: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 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]=qt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?sE(e,n):e}function Xf(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{[ts]:r,v:s}}catch{}}return _t(e)}function sE(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 _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 iE(e){return{encode(t,n,r){const o=nu(e,r);return Vt(t,n,o)},decode(t,n,r){const o=nu(e,r);return qt(t,n,o)}}}const Fi={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)}},Vi={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)}},qi={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}},Ki={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"))}},aE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,zi={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"&&!aE.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",cE=new Set([os,ss,is]),Gi={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 ${[...cE].join(", ")}.`);return NaN}},uE=[Fi,Vi,qi,Ki,zi,Gi];function lE(e,t={}){for(const n of uE)e.register(n,{override:t.override??!1})}Fi.id,Vi.id,qi.id,Ki.id,zi.id,Gi.id;const ed=rE();lE(ed);const td=iE(ed.freeze());function fE(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function dE(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 pE(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 hE(e,t){return t===void 0||e===void 0?e:td.decode(e,t)}function lo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:td.encode(e,n)}async function mE(e,t,n,r,o,s){const i=dE(n).map(c=>hE(s[c],pE(n,c)));if(fE(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return lo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return lo(u,n)}const a=await e[r](...i);return lo(a,n)}let nd=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 gE(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=()=>mE(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const yE={"decimal.js":"Decimal"};function $E(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(yE).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${$E(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function vE(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}}},Pe(s);const i=n?Pe.destination({dest:e.destination,mkdir:!0,sync:!0}):Pe.destination(2);return Pe(s,i)}function rd(e){return e?e.type==="array"?`${rd(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function wE(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:rd(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const bE=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let od=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 SE(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&bE.includes(e.code)&&typeof e.toJSON=="function"}function ru(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Ur=new br({allErrors:!0});Sr(Ur);for(const e of[Ui,Bi,ns,rs,"discriminator"])Ur.addKeyword({keyword:e,valid:!0});Ur.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function EE(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function NE(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=Ur.compile(o.input);if(!i(s)){const a=i.errors??[];throw new od("invalid_argument",`Validation failed: ${EE(a)}`,a)}return n()}}async function OE(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=SE(n)?n:new od("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:ru("before-first-chunk",r)}:{ok:!1,carrier:ru("after-first-chunk",r,t.length)}}}function _E(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let gt=class 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 sd(e,t){const n=e[Bi];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function AE(e,t,n){const r=sd(t,n);return r?r.encode(e,t,n):e}function kE(e,t,n){const r=sd(t,n);return r?r.decode(e,t,n):e}function jE(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Ui]==="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 gt("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 gt("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 gt("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 AE(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 gt("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 gt("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 gt("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 gt("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 kE(r,h,{...s,path:`${s.path}[${f}]`})}}}const IE="x-apigen-instances";class Wn extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function ou(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function xE(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function su(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function PE(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function TE(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Ui]==="nominal"?!0:o[Bi]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Wn("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=ou(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[g,$]of Object.entries(d))m[g]=su($,a[g],{...i,path:`${i.path}/${g}`});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]=su(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 Wn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of xE(s))if(!(l in a))throw new Wn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[IE]===!1)throw new Wn("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=ou(s),u={};for(const[l,f]of Object.entries(a))u[l]=PE(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 CE=[Fi,Vi,qi,Ki,zi,Gi],RE={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},iu=TE({id:"ts.NominalSentinel",schema:RE}),ME={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},au=jE({id:"ts.UnionSentinel",schema:ME});function DE(){const e=[...CE.map(t=>[t.id,t]),[iu.id,iu],[au.id,au]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:oE,codecs:DE()});function cu(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=[n,o].filter(i=>typeof i=="string"&&i.length>0);return s.length>0?s.join(" — "):e}function id(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 LE(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const uu=new Set(["string","number","boolean","integer"]);function UE(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"?uu.has(n):Array.isArray(n)?n.every(r=>uu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function BE(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(UE)}const FE={"decimal.js":"Decimal"};function VE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(FE).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${VE(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function lu(e){return e.words.join("-")}function fu(e){return e.words.map(HE).join("")}function du(e){return e.words.join("_")}function qE(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||BE(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=>lu(h)).join("/"),c=o.map(h=>du(h)).join("_"),u=o.map(h=>du(h)).slice(0,-1).join("."),l=fu(o[o.length-2]??o[0]),f=fu(o[o.length-1]),p=o.map(h=>lu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function KE(e,t){return`x-${e}-${t}`}function zE(e,t){return`--${e}-${t}`}function GE(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function HE(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ad(e){return e.anyOf??e.oneOf}function JE(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=ad(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 WE(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=ad(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function QE(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function YE(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 pu(e){return typeof e.handler=="function"}function ZE(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=KE(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:zE(i,s),envVar:GE(i,s)})}return o}function XE(e,t){const n=new Map,{props:r}=YE(e);for(const[o,s]of Object.entries(r)){let i="string";WE(s)?i="boolean":JE(s)&&(i="json"),n.set(QE(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=qE(t,o),i=n?ZE(n):[],a=n?XE(n,i):new Map,c=n?wE(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:pu(t)};if(pu(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function eN(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function tN(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function nN(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function po(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(nN(s))}return r.push(NE(e)),gE(r)}function rN(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const oN={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function mu(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new nd};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:rN(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:oN}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const sN={"decimal.js":"Decimal"};function iN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(sN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${iN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function aN(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 cN={"decimal.js":"Decimal"};function uN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(cN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${uN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function lN(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function as(e){return{raw:e,words:aN(e)}}function fN(e){return as(lN($o.basename(e)))}function dN(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=as(t);return{id:`${e.id}/${t}`,host:"ts",namespace:as(e.id),path:e.dropFileSegment?[r]:[fN(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}const pN=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function hN(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&pN.includes(e.code)&&typeof e.toJSON=="function"}async function mN(e){const t=await OE(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 gN{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(_E(n)){t.output=await mN(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=id(o==null?void 0:o.output),i=LE(s,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(t,n,r){throw hN(n)&&n.code,n}}function yN(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 $N(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 vN(e,t){var n,r;const o=e.options.projection??{},s=e.options.toolDescriptions??{},i=eN(e.options),a=tN(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,g=Object.entries(d.schemas).map(([N,I])=>({fnName:N,fnSchema:I,op:dN({id:d.id,importPath:d.importPath},N,e.operations)})),$={},v={};for(const{fnName:N,fnSchema:I,op:T}of g)$[T.id]=I,v[T.id]=m[N],c[T.id]=I,u[T.id]=m[N];const w=po($,i),S={fns:v,createClient:d.createClient,schemas:$};for(const{fnName:N,fnSchema:I,op:T}of g){const K=hu({op:T,schema:I,transport:"mcp",projection:o});t.bindSchema(T.id,I);const{outputSchema:L}=id(I.output),V=cu(K.mcp.name,I,s[K.mcp.name]??s[N]);t.bindToolMeta(K.mcp.name,{description:V,inputSchema:I.input,outputSchema:L}),t.registerRoute(K,H=>mu(K,w,H,S))}}const l=((n=e.packages[0])==null?void 0:n.id)??"ts",f=po(c,i),p={invoke:(d,m,g)=>f(d,{operation:{id:d},ctx:new nd,domainArgs:m.domainArgs,envelope:m.envelope,signal:m.signal},g),invokeOptions:{fns:u,schemas:c,createClient:(r=e.packages[0])==null?void 0:r.createClient}},h=$N(i,a,l,e.operations??[],p);if(h.length>0){const d=po({},i),m={fns:{},schemas:{}};for(const g of h){const $=hu({op:g,transport:"mcp",projection:o}),v=cu($.mcp.name,void 0,s[$.mcp.name]),w=yN(g.input);t.bindToolMeta($.mcp.name,{description:v,inputSchema:w}),t.registerRoute($,S=>mu($,d,S,m))}}}function ho(e,t){const n=new Jp.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(ma.ListToolsRequestSchema,async()=>({tools:e.listTools()})),n.setRequestHandler(ma.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 gu(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 wN(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??vE();o.info(`mcp server starting (${t})`);const s=new gN;vN(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=ho(s,o),u=new Wp.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=ha.createServer(gu(o,async(l,f)=>{const p=l.url??"";if(l.method==="GET"&&p==="/sse"){const h=ho(s,o),d=new Qp.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=ha.createServer(gu(o,async(c,u)=>{const l=ho(s,o),f=new Yp.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 bN={id:"mcp",run(e){return wN(e)}};class ot 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 cs="$apigen";class yu extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function SN(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new yu(`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 yu("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 Hi="x-apigen-logical",Ji="x-apigen-codec",us="x-apigen-ctor",ls="x-apigen-tojson",EN="0.1.0";function $u(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=cd(e,s,t);return Kt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return mo(e,t,n);const a=t.items;if(!a)return e.map(u=>At(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?At(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 mo(e,t,n);const a=t.properties;if(!a)return At(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?mo(e,t,n):At(e)}function zt(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 zt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=cd(e,s,t);return zt(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:zt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>zt(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]=zt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?NN(e,n):e}function cd(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 mo(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{[cs]:r,v:s}}catch{}}return At(e)}function NN(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&cs in e){const n=e,r=n[cs],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function At(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(At);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=At(r));return t}return null}function ON(e){return{encode(t,n,r){const o=$u(e,r);return Kt(t,n,o)},decode(t,n,r){const o=$u(e,r);return zt(t,n,o)}}}const Wi={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)}},Qi={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)}},Yi={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}},Zi={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"))}},_N=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Xi={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"&&!_N.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},fs="NaN",ds="Infinity",ps="-Infinity",AN=new Set([fs,ds,ps]),ea={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?ds:e===-1/0?ps:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===fs)return NaN;if(e===ds)return 1/0;if(e===ps)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 ${[...AN].join(", ")}.`);return NaN}},kN=[Wi,Qi,Yi,Zi,Xi,ea];function jN(e,t={}){for(const n of kN)e.register(n,{override:t.override??!1})}Wi.id,Qi.id,Yi.id,Zi.id,Xi.id,ea.id;const ud=SN();jN(ud);ON(ud.freeze());class IN{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 xN={"decimal.js":"Decimal"};function PN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(xN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${PN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const TN=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class ld 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 fd(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&TN.includes(e.code)&&typeof e.toJSON=="function"}function vu(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const ta=new br({allErrors:!0});Sr(ta);for(const e of[Hi,Ji,us,ls,"discriminator"])ta.addKeyword({keyword:e,valid:!0});ta.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function CN(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=fd(n)?n:new ld("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:vu("before-first-chunk",r)}:{ok:!1,carrier:vu("after-first-chunk",r,t.length)}}}function RN(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class yt extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function go(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 dd(e,t){const n=e[Ji];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function MN(e,t,n){const r=dd(t,n);return r?r.encode(e,t,n):e}function DN(e,t,n){const r=dd(t,n);return r?r.decode(e,t,n):e}function LN(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Hi]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:go(r)!==void 0},encode(r,o,s){const i=go(o);if(!i)throw new yt("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 yt("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 yt("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 MN(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 yt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=go(o);if(!a)throw new yt("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 yt("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 yt("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 DN(r,h,{...s,path:`${s.path}[${f}]`})}}}const UN="x-apigen-instances";class Qn extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function wu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function BN(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function bu(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function FN(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function VN(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Hi]==="nominal"?!0:o[Ji]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Qn("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=wu(s),c=typeof s[ls]=="string"?s[ls]:"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[g,$]of Object.entries(d))m[g]=bu($,a[g],{...i,path:`${i.path}/${g}`});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]=bu(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 Qn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of BN(s))if(!(l in a))throw new Qn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[UN]===!1)throw new Qn("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=wu(s),u={};for(const[l,f]of Object.entries(a))u[l]=FN(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 qN=[Wi,Qi,Yi,Zi,Xi,ea],KN={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Su=VN({id:"ts.NominalSentinel",schema:KN}),zN={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Eu=LN({id:"ts.UnionSentinel",schema:zN});function GN(){const e=[...qN.map(t=>[t.id,t]),[Su.id,Su],[Eu.id,Eu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:EN,codecs:GN()});const HN=4,JN=32;function hs(e){return fd(e)?e:e instanceof Error?new ld("internal",e.message):e}function WN(e,t){if(e==="serial"||e==="chained")return 1;const n=t??HN;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),JN)}function QN(){}function YN(e,t){var n;if(!e&&!t)return{signal:void 0,dispose:QN};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 Nu(e,t,n,r,o,s){const i=YN(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await e(t,a,o);if(RN(c)){const u=await CN(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:hs(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:hs(a)}}finally{i.dispose()}}async function ZN(e,t,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=WN(s,o.concurrency),c=new Array(n.length),u=d=>({index:d,status:"rejected",reason:hs(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 g=await Nu(e,t,m,n[m],r,o.itemTimeoutMs);c[m]=g,g.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 Nu(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 XN={"decimal.js":"Decimal"};function eO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(XN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${eO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function tO(e,t){const n=e.operation;if(typeof n!="string"||n.length===0)throw new ot("invalid_argument",'@adhd/apigen-plugin-batch: "operation" must be a non-empty string naming the target operation id');if(!t.includes(n))throw new ot("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 ot("invalid_argument",'@adhd/apigen-plugin-batch: "items" must be an array');const o=e.concurrency;if(o!==void 0&&typeof o!="number")throw new ot("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 ot("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 ot("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 ot("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 nO(e,t){return async n=>{if(!t)throw new ot("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=tO(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 IN,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return ZN(t.invoke,r.operation,s,t.invokeOptions,o)}}function rO(e,t={},n){return Nb(e,t).map(o=>({...o,handler:nO(o.operationIds,n)}))}const Ou={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 rO(e,t,n)}}}},pd=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED"]),hd=new Set(["MITIGATED"]),md=new Set(["SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]),na=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Ke(e){return na.has(e)}function $r(e){return pd.has(e)||hd.has(e)}function vr(e){return md.has(e)}class gd 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 yd 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 $d extends Error{constructor(t){super(`transition to terminal-dismissed status "${t}" requires a reason string`),this.name="ReasonRequiredError"}}class vd 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 oO extends Error{constructor(t){super(`dependency cycle detected: ${t.join(" -> ")}`),this.cycle=t,this.name="DependencyCycleError"}}function sO(e,t){const n=t??q.join(Qt.homedir(),`.${e.orgNamespace}`);return q.join(n,e.project,e.namespace,"config.yaml")}function iO(e,t,n){const r=sO(e,n);let o={};if(Y.existsSync(r))try{const a=ga.parse(Y.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 Y.mkdirSync(q.dirname(r),{recursive:!0}),Y.writeFileSync(r,ga.stringify(i),"utf8"),r}const _e="backlog-item",_u="backlog-plan",Au="backlog-assignee",aO="adhd-backlog:";function cO(e){return Cu.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function wd(e){return e.replace(/[^\p{L}\p{N}_\s]/gu," ").trim().replace(/\s+/g," ")}function Br(e){return e.split("-")[0]??e}function Fr(e){return e.replace(/-\d+$/,"")}function ra(e,t,n,r){return`${n}
169
+ `}async function dN(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(lN(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=zi(i)?i:new iS("internal",i instanceof Error?i.message:String(i));if(s)o.write(fN(JSON.stringify(a.toJSON()))),o.end();else{const c=hN(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const pN={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function hN(e){return pN[e]??500}function Ad(e){return zi(e)?sS[e.code]??500:500}function jd(e){return zi(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function mN(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 gN=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?OS(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(jS(n)){await dN(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(Ad(n)).send(jd(n))}};function yN(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 $N(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=nN(e.options),c=rN(e.options),u=e.logger??SS(),l=kh({logger:u});l.setErrorHandler((b,S,O)=>{O.status(Ad(b)).send(jd(b))});const f=new gN(l,s,e.signal),p=[],h={},d={};for(const b of e.packages){if(!b.fns)throw new Error(`Package "${b.id}" is missing fns`);const S=b.fns,O=Object.entries(b.schemas).map(([q,Z])=>({fnName:q,fnSchema:Z,op:uN(b.id,q,Z,e.operations)})),j={},C={};for(const{fnName:q,fnSchema:Z,op:Q}of O)j[Q.id]=Z,C[Q.id]=S[q],h[Q.id]=Z,d[Q.id]=S[q];const W=bo(j,a),B={fns:C,createClient:b.createClient,schemas:j};for(const{fnSchema:q,op:Z}of O){const Q=iu({op:Z,schema:q,transport:"http",projection:i});f.bindSchema(Z.id,q),f.registerRoute(Q,Ue=>au(Q,W,Ue,B));const{params:ve,text:Ne}=Od(q);p.push({method:Q.http.verb,route:s+Q.http.route,text:Ne,params:ve})}}const g=((t=e.packages[0])==null?void 0:t.id)??"ts",y=bo(h,a),$={invoke:(b,S,O)=>y(b,{operation:{id:b},ctx:new Sd,domainArgs:S.domainArgs,envelope:S.envelope,signal:S.signal},O),invokeOptions:{fns:d,schemas:h,createClient:(n=e.packages[0])==null?void 0:n.createClient}},v=yN(a,c,g,e.operations??[],$);if(v.length>0){const b=bo({},a),S={fns:{},schemas:{}};for(const O of v){const j=iu({op:O,transport:"http",projection:i});f.registerRoute(j,C=>au(j,b,C,S)),p.push({method:j.http.verb,route:`${s}/${O.id}`,text:"",params:[]})}}return await l.listen({port:r,host:o}),u.info({host:o,port:r},`listening on http://${o}:${r}`),mN(u,p),new Promise(b=>{e.signal&&e.signal.addEventListener("abort",async()=>{await l.close(),b()})})}const vN={id:"api-fastify",run(e){return $N(e)}};function uu(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function wN(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:uu(i),path:s.map(uu),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 bN={"decimal.js":"Decimal"};function EN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(bN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${EN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const lu=new Set(["string","number","boolean","integer"]);function SN(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"?lu.has(n):Array.isArray(n)?n.every(r=>lu.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(SN)}const ON={"decimal.js":"Decimal"};function _N(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ON).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${_N(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function fu(e){return e.words.join("-")}function du(e){return e.words.map(AN).join("")}function pu(e){return e.words.join("_")}function kN(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||NN(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=>fu(h)).join("/"),c=o.map(h=>pu(h)).join("_"),u=o.map(h=>pu(h)).slice(0,-1).join("."),l=du(o[o.length-2]??o[0]),f=du(o[o.length-1]),p=o.map(h=>fu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function AN(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function jN(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const s of e){const i=kN(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:IN(s.output)}};if(a==="GET")l.parameters=PN(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 IN(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function PN(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 xN(e,t={}){return[{...wN("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>jN(e.operations,{title:t.title,version:t.version})}]}const TN={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 xN(e,t)}}}},ds="$apigen";let hu=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function CN(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new hu(`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 hu("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",na="x-apigen-codec",ps="x-apigen-ctor",hs="x-apigen-tojson",RN="0.1.0";function mu(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 Lt(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 Lt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Id(e,s,t);return Lt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Eo(e,t,n);const a=t.items;if(!a)return e.map(u=>Et(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Et(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 Eo(e,t,n);const a=t.properties;if(!a)return Et(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?Eo(e,t,n):Et(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=Id(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?MN(e,n):e}function Id(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 Eo(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{[ds]:r,v:s}}catch{}}return Et(e)}function MN(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&ds in e){const n=e,r=n[ds],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Et(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Et);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Et(r));return t}return null}function DN(e){return{encode(t,n,r){const o=mu(e,r);return Lt(t,n,o)},decode(t,n,r){const o=mu(e,r);return Bt(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)}},oa={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)}},sa={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}},ia={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"))}},LN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,aa={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"&&!LN.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},ms="NaN",gs="Infinity",ys="-Infinity",BN=new Set([ms,gs,ys]),ca={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)?ms:e===1/0?gs:e===-1/0?ys:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===ms)return NaN;if(e===gs)return 1/0;if(e===ys)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 ${[...BN].join(", ")}.`);return NaN}},UN=[ra,oa,sa,ia,aa,ca];function FN(e,t={}){for(const n of UN)e.register(n,{override:t.override??!1})}ra.id,oa.id,sa.id,ia.id,aa.id,ca.id;const Pd=CN();FN(Pd);const xd=DN(Pd.freeze());function VN(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function qN(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 KN(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 GN(e,t){return t===void 0||e===void 0?e:xd.decode(e,t)}function So(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:xd.encode(e,n)}async function zN(e,t,n,r,o,s){const i=qN(n).map(c=>GN(s[c],KN(n,c)));if(VN(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return So(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return So(u,n)}const a=await e[r](...i);return So(a,n)}let Td=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 WN(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=()=>zN(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const JN={"decimal.js":"Decimal"};function HN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(JN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${HN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function YN(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}}},_e(s);const i=n?_e.destination({dest:e.destination,mkdir:!0,sync:!0}):_e.destination(2);return _e(s,i)}function Cd(e){return e?e.type==="array"?`${Cd(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function QN(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:Cd(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const ZN=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let Rd=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 XN(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&ZN.includes(e.code)&&typeof e.toJSON=="function"}function gu(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Lr=new wr({allErrors:!0});br(Lr);for(const e of[ta,na,ps,hs,"discriminator"])Lr.addKeyword({keyword:e,valid:!0});Lr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function eO(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function tO(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=Lr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Rd("invalid_argument",`Validation failed: ${eO(a)}`,a)}return n()}}async function nO(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=XN(n)?n:new Rd("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:gu("before-first-chunk",r)}:{ok:!1,carrier:gu("after-first-chunk",r,t.length)}}}function rO(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 Md(e,t){const n=e[na];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function oO(e,t,n){const r=Md(t,n);return r?r.encode(e,t,n):e}function sO(e,t,n){const r=Md(t,n);return r?r.decode(e,t,n):e}function iO(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: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 oO(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 sO(r,h,{...s,path:`${s.path}[${f}]`})}}}const aO="x-apigen-instances";class Wn extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function yu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function cO(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function $u(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function uO(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function lO(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[ta]==="nominal"?!0:o[na]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Wn("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=yu(s),c=typeof s[hs]=="string"?s[hs]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const g={};for(const[y,$]of Object.entries(d))g[y]=$u($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=$u(g,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 Wn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of cO(s))if(!(l in a))throw new Wn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[aO]===!1)throw new Wn("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=yu(s),u={};for(const[l,f]of Object.entries(a))u[l]=uO(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 fO=[ra,oa,sa,ia,aa,ca],dO={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},vu=lO({id:"ts.NominalSentinel",schema:dO}),pO={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},wu=iO({id:"ts.UnionSentinel",schema:pO});function hO(){const e=[...fO.map(t=>[t.id,t]),[vu.id,vu],[wu.id,wu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:RN,codecs:hO()});function bu(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=[n,o].filter(i=>typeof i=="string"&&i.length>0);return s.length>0?s.join(" — "):e}function Dd(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 mO(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const Eu=new Set(["string","number","boolean","integer"]);function gO(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"?Eu.has(n):Array.isArray(n)?n.every(r=>Eu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function yO(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(gO)}const $O={"decimal.js":"Decimal"};function vO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries($O).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${vO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Su(e){return e.words.join("-")}function Nu(e){return e.words.map(NO).join("")}function Ou(e){return e.words.join("_")}function wO(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||yO(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=>Su(h)).join("/"),c=o.map(h=>Ou(h)).join("_"),u=o.map(h=>Ou(h)).slice(0,-1).join("."),l=Nu(o[o.length-2]??o[0]),f=Nu(o[o.length-1]),p=o.map(h=>Su(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function bO(e,t){return`x-${e}-${t}`}function EO(e,t){return`--${e}-${t}`}function SO(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function NO(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ld(e){return e.anyOf??e.oneOf}function OO(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Ld(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 _O(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Ld(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function kO(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function AO(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 _u(e){return typeof e.handler=="function"}function jO(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=bO(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:EO(i,s),envVar:SO(i,s)})}return o}function IO(e,t){const n=new Map,{props:r}=AO(e);for(const[o,s]of Object.entries(r)){let i="string";_O(s)?i="boolean":OO(s)&&(i="json"),n.set(kO(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 ku(e){const{op:t,schema:n,transport:r,projection:o}=e,s=wO(t,o),i=n?jO(n):[],a=n?IO(n,i):new Map,c=n?QN(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:_u(t)};if(_u(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function PO(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function xO(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function TO(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Oo(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(TO(s))}return r.push(tO(e)),WN(r)}function CO(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const RO={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Au(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Td};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:CO(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:RO}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const MO={"decimal.js":"Decimal"};function DO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(MO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${DO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function LO(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 BO={"decimal.js":"Decimal"};function UO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(BO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${UO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function FO(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function $s(e){return{raw:e,words:LO(e)}}function VO(e){return $s(FO(jo.basename(e)))}function qO(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=$s(t);return{id:`${e.id}/${t}`,host:"ts",namespace:$s(e.id),path:e.dropFileSegment?[r]:[VO(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}const KO=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function GO(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&KO.includes(e.code)&&typeof e.toJSON=="function"}async function zO(e){const t=await nO(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 WO{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(rO(n)){t.output=await zO(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=Dd(o==null?void 0:o.output),i=mO(s,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(t,n,r){throw GO(n)&&n.code,n}}function JO(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 HO(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 YO(e,t){var n,r;const o=e.options.projection??{},s=e.options.toolDescriptions??{},i=PO(e.options),a=xO(e.options),c={},u={};for(const d of e.packages){if(!d.fns)throw new Error(`Package "${d.id}" is missing fns`);const g=d.fns,y=Object.entries(d.schemas).map(([O,j])=>({fnName:O,fnSchema:j,op:qO({id:d.id,importPath:d.importPath},O,e.operations)})),$={},v={};for(const{fnName:O,fnSchema:j,op:C}of y)$[C.id]=j,v[C.id]=g[O],c[C.id]=j,u[C.id]=g[O];const b=Oo($,i),S={fns:v,createClient:d.createClient,schemas:$};for(const{fnName:O,fnSchema:j,op:C}of y){const W=ku({op:C,schema:j,transport:"mcp",projection:o});t.bindSchema(C.id,j);const{outputSchema:B}=Dd(j.output),q=bu(W.mcp.name,j,s[W.mcp.name]??s[O]);t.bindToolMeta(W.mcp.name,{description:q,inputSchema:j.input,outputSchema:B}),t.registerRoute(W,Z=>Au(W,b,Z,S))}}const l=((n=e.packages[0])==null?void 0:n.id)??"ts",f=Oo(c,i),p={invoke:(d,g,y)=>f(d,{operation:{id:d},ctx:new Td,domainArgs:g.domainArgs,envelope:g.envelope,signal:g.signal},y),invokeOptions:{fns:u,schemas:c,createClient:(r=e.packages[0])==null?void 0:r.createClient}},h=HO(i,a,l,e.operations??[],p);if(h.length>0){const d=Oo({},i),g={fns:{},schemas:{}};for(const y of h){const $=ku({op:y,transport:"mcp",projection:o}),v=bu($.mcp.name,void 0,s[$.mcp.name]),b=JO(y.input);t.bindToolMeta($.mcp.name,{description:v,inputSchema:b}),t.registerRoute($,S=>Au($,d,S,g))}}}function _o(e,t){const n=new Ah.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(xa.ListToolsRequestSchema,async()=>({tools:e.listTools()})),n.setRequestHandler(xa.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 ju(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 QO(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??YN();o.info(`mcp server starting (${t})`);const s=new WO;YO(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=_o(s,o),u=new jh.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=Pa.createServer(ju(o,async(l,f)=>{const p=l.url??"";if(l.method==="GET"&&p==="/sse"){const h=_o(s,o),d=new Ih.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=Pa.createServer(ju(o,async(c,u)=>{const l=_o(s,o),f=new Ph.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 ZO={id:"mcp",run(e){return QO(e)}};class et 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 vs="$apigen";class Iu extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function XO(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Iu(`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 Iu("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 ua="x-apigen-logical",la="x-apigen-codec",ws="x-apigen-ctor",bs="x-apigen-tojson",e_="0.1.0";function Pu(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=Bd(e,s,t);return Ut(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return ko(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):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 ko(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]=Ut(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?ko(e,t,n):St(e)}function Ft(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 Ft(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Bd(e,s,t);return Ft(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:Ft(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ft(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]=Ft(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?t_(e,n):e}function Bd(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 ko(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{[vs]:r,v:s}}catch{}}return St(e)}function t_(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&vs in e){const n=e,r=n[vs],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 n_(e){return{encode(t,n,r){const o=Pu(e,r);return Ut(t,n,o)},decode(t,n,r){const o=Pu(e,r);return Ft(t,n,o)}}}const fa={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)}},da={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)}},pa={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}},ha={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"))}},r_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ma={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"&&!r_.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Es="NaN",Ss="Infinity",Ns="-Infinity",o_=new Set([Es,Ss,Ns]),ga={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)?Es:e===1/0?Ss:e===-1/0?Ns:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Es)return NaN;if(e===Ss)return 1/0;if(e===Ns)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 ${[...o_].join(", ")}.`);return NaN}},s_=[fa,da,pa,ha,ma,ga];function i_(e,t={}){for(const n of s_)e.register(n,{override:t.override??!1})}fa.id,da.id,pa.id,ha.id,ma.id,ga.id;const Ud=XO();i_(Ud);n_(Ud.freeze());class a_{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 c_={"decimal.js":"Decimal"};function u_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(c_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${u_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const l_=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class Fd 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 Vd(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&l_.includes(e.code)&&typeof e.toJSON=="function"}function xu(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const ya=new wr({allErrors:!0});br(ya);for(const e of[ua,la,ws,bs,"discriminator"])ya.addKeyword({keyword:e,valid:!0});ya.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function f_(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=Vd(n)?n:new Fd("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:xu("before-first-chunk",r)}:{ok:!1,carrier:xu("after-first-chunk",r,t.length)}}}function d_(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class dt extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Ao(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 qd(e,t){const n=e[la];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function p_(e,t,n){const r=qd(t,n);return r?r.encode(e,t,n):e}function h_(e,t,n){const r=qd(t,n);return r?r.decode(e,t,n):e}function m_(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[ua]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Ao(r)!==void 0},encode(r,o,s){const i=Ao(o);if(!i)throw new dt("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 dt("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 dt("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 p_(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 dt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Ao(o);if(!a)throw new dt("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 dt("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 dt("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 h_(r,h,{...s,path:`${s.path}[${f}]`})}}}const g_="x-apigen-instances";class Jn extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function Tu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function y_(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Cu(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function $_(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function v_(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[ua]==="nominal"?!0:o[la]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Jn("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=Tu(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 g={};for(const[y,$]of Object.entries(d))g[y]=Cu($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=Cu(g,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 Jn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of y_(s))if(!(l in a))throw new Jn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[g_]===!1)throw new Jn("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=Tu(s),u={};for(const[l,f]of Object.entries(a))u[l]=$_(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[ws]=="string"?s[ws]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const w_=[fa,da,pa,ha,ma,ga],b_={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Ru=v_({id:"ts.NominalSentinel",schema:b_}),E_={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Mu=m_({id:"ts.UnionSentinel",schema:E_});function S_(){const e=[...w_.map(t=>[t.id,t]),[Ru.id,Ru],[Mu.id,Mu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:e_,codecs:S_()});const N_=4,O_=32;function Os(e){return Vd(e)?e:e instanceof Error?new Fd("internal",e.message):e}function __(e,t){if(e==="serial"||e==="chained")return 1;const n=t??N_;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),O_)}function k_(){}function A_(e,t){var n;if(!e&&!t)return{signal:void 0,dispose:k_};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 Du(e,t,n,r,o,s){const i=A_(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await e(t,a,o);if(d_(c)){const u=await f_(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:Os(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:Os(a)}}finally{i.dispose()}}async function j_(e,t,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=__(s,o.concurrency),c=new Array(n.length),u=d=>({index:d,status:"rejected",reason:Os(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 g=0;g<n.length;g++){if(d){c[g]=u(g);continue}const y=await Du(e,t,g,n[g],r,o.itemTimeoutMs);c[g]=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 g=await Du(e,t,d,n[d],r,o.itemTimeoutMs);c[d]=g,g.status==="rejected"&&i==="abort"&&(f=!0)}});return await Promise.all(h),c}const I_={"decimal.js":"Decimal"};function P_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(I_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${P_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function x_(e,t){const n=e.operation;if(typeof n!="string"||n.length===0)throw new et("invalid_argument",'@adhd/apigen-plugin-batch: "operation" must be a non-empty string naming the target operation id');if(!t.includes(n))throw new et("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 et("invalid_argument",'@adhd/apigen-plugin-batch: "items" must be an array');const o=e.concurrency;if(o!==void 0&&typeof o!="number")throw new et("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 et("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 et("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 et("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 T_(e,t){return async n=>{if(!t)throw new et("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=x_(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 a_,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return j_(t.invoke,r.operation,s,t.invokeOptions,o)}}function C_(e,t={},n){return tS(e,t).map(o=>({...o,handler:T_(o.operationIds,n)}))}const Lu={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 C_(e,t,n)}}}},Kd=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED"]),Gd=new Set(["MITIGATED"]),zd=new Set(["SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]),$a=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Le(e){return $a.has(e)}function yr(e){return Kd.has(e)||Gd.has(e)}function $r(e){return zd.has(e)}class Wd 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 Jd 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 Hd extends Error{constructor(t){super(`transition to terminal-dismissed status "${t}" requires a reason string`),this.name="ReasonRequiredError"}}class Yd 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 R_ extends Error{constructor(t){super(`dependency cycle detected: ${t.join(" -> ")}`),this.cycle=t,this.name="DependencyCycleError"}}function M_(e,t){const n=t??T.join(We.homedir(),`.${e.orgNamespace}`);return T.join(n,e.project,e.namespace,"config.yaml")}function D_(e,t,n){const r=M_(e,n);let o={};if(U.existsSync(r))try{const a=Ta.parse(U.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 U.mkdirSync(T.dirname(r),{recursive:!0}),U.writeFileSync(r,Ta.stringify(i),"utf8"),r}const we="backlog-item",Bu="backlog-plan",Uu="backlog-assignee",L_="adhd-backlog:";function B_(e){return Wu.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Qd(e){return e.replace(/[^\p{L}\p{N}_\s]/gu," ").trim().replace(/\s+/g," ")}function Br(e){return e.split("-")[0]??e}function Ur(e){return e.replace(/-\d+$/,"")}function va(e,t,n,r){return`${n}
170
170
 
171
171
  ${r}
172
172
 
173
- <!-- ${aO}${e}::${t} -->`}function oa(e,t){return`${e}::${t}`}function sa(e){switch(e){case"CRITICAL":return 10;case"HIGH":return 8;case"MEDIUM":return 5;case"LOW":return 2;default:return 1}}function bd(e,t,n=[]){return[...new Set([_e,e,t,...n])]}function Ve(e){return e.tags.includes(_e)&&!e.isSuperseded}function fe(e){const t=e.metadata??{},n=t.humanId??"",r=t.kind??Br(n),o=t.family??Fr(n),s=new Set([_e,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 uO=5,lO=20,fO=500;function dO(e){const t=e==null?void 0:e.code;return t==="SQLITE_BUSY"||t==="SQLITE_BUSY_TIMEOUT"||t==="SQLITE_BUSY_SNAPSHOT"}function pO(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.max(0,Math.round(e)))}function Sd(e,t={}){const n=t.maxAttempts??uO;for(let r=0;;r++)try{return e()}catch(o){if(!dO(o)||r>=n-1)throw o;const s=Math.min(fO,lO*2**r);pO(s*(.5+Math.random()*.5))}}function hO(e,t,n){const r=e.graph.queryNodes({kind:"generic",tags:[_e],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")}`}function mO(e,t,n){return e.graph.queryNodes({kind:"generic",tags:[_e],namespace:t,metadata:{humanId:n}}).find(o=>{var s;return Ve(o)&&((s=o.metadata)==null?void 0:s.humanId)===n})??null}function Ed(e,t,n,r,o){return Sd(()=>e.db.transaction(()=>{if(r){const i=mO(e,t,r);return o(r,i)}const s=hO(e,t,n);return o(s,null)}).immediate())}const Nd="backlog-audit-event";function Od(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=e.graph.writeNode(c,{kind:"generic",name:`audit-event::${n}::${r}::${i}`,tags:[Nd],namespace:n,metadata:a});e.graph.writeEdge(u,t,"DERIVED_FROM")}function gO(e,t){return e.graph.queryNodes({kind:"generic",tags:[Nd],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 ku={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3};function ju(e){const t=[_e];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 yO(e,t){return t.status==="open"?e.filter(n=>!Ke(n.status)):t.status==="closed"?e.filter(n=>Ke(n.status)):e}function Iu(e,t){return t.rootLevel?e.filter(n=>{const r=n.metadata;return!(r!=null&&r.projectPath)&&!(r!=null&&r.plan)}):e}function xu(e,t){return t.excludeArchived?e.filter(n=>{var r;return!((r=n.metadata)!=null&&r.archivedAt)}):e}function _d(e,t={}){if(t.grep){const o=ju({...t}),s=wd(t.grep);if(!s)return[];const i=e.graph.searchNodes(s,{limit:t.limit??1e3,filter:o});let a=xu(Iu(i.filter(Ve),t),t);return t.offset&&(a=a.slice(t.offset)),a}const n=ju(t);t.limit!==void 0&&(n.limit=t.limit),t.offset!==void 0&&(n.offset=t.offset);const r=e.graph.queryNodes(n);return xu(Iu(r.filter(Ve),t),t)}function ft(e,t={}){const r=_d(e,t).map(fe);return yO(r,t)}function et(e,t,n){const r=oa(t,n),s=e.graph.queryNodes({kind:"generic",tags:[_e],namespace:t,metadata:{humanId:n}}).filter(Ve);return s.find(i=>i.name===r)??s[0]??null}function ms(e){var t;return((t=e.metadata)==null?void 0:t.repo)??e.namespace??""}function $O(e,t){return e.graph.queryNodes({kind:"generic",tags:[_e],metadata:{humanId:t}}).filter(Ve)}function Ad(e){const t=e.graph.queryNodes({kind:"generic",tags:[_e]}),n=new Set;for(const r of t){if(!Ve(r))continue;const o=ms(r);o&&n.add(o)}return n}function ke(e,t,n){const r=$O(e,n).filter(s=>ms(s)!==t),o=[...new Set(r.map(ms).filter(s=>s.length>0))];return new gd(t,n,o)}function fn(e,t){const n={};for(const r of e){const o=t(r);o&&(n[o]=(n[o]??0)+1)}return n}function vO(e,t={}){const n=ft(e,{repo:t.repo,projectPath:t.projectPath}),r=n.filter(s=>!Ke(s.status)),o=n.filter(s=>Ke(s.status));return{total:n.length,open:r.length,closed:o.length,byStatus:fn(n,s=>s.status),byKind:fn(n,s=>s.kind),byFamily:fn(n,s=>s.family),byPriority:fn(n,s=>s.priority),byRepo:t.repo===void 0?fn(n,s=>s.repo):{}}}function wO(e,t={},n=20){const o=ft(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(s=>s.priority!==void 0);return o.sort((s,i)=>{const a=ku[s.priority??""]??4,c=ku[i.priority??""]??4;return a-c||s.humanId.localeCompare(i.humanId)}),o.slice(0,n)}function kd(e,t){const n=e.graph.getEdges({src:t,rel:"DEPENDS_ON"}),r=[];for(const o of n){const s=e.graph.getNode(o.dst);s&&r.push(s)}return r}function bO(e,t,n){const r=et(e,t,n);return r?kd(e,r.id).filter(o=>!o.tInvalid).map(fe).filter(o=>!Ke(o.status)):[]}function SO(e,t={}){return ft(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(r=>{if(r.claimedBy)return!1;const o=et(e,r.repo,r.humanId);return o?kd(e,o.id).filter(i=>!i.tInvalid).every(i=>Ke(fe(i).status)):!1})}function jd(e,t={}){const n=ft(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=et(e,s.repo,s.humanId);if(i)for(const a of["DEPENDS_ON","RELATES_TO","PART_OF"])for(const c of e.graph.getEdges({src:i.id,rel:a})){const u=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}}function EO(e,t={}){var c;const n=jd(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:NO([...s],o)}:{ok:!0,order:i}}function NO(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}function OO(e,t,n={}){const r=ft(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)}function _O(e,t,n){var u,l,f,p;const r=et(e,t,n);if(!r)throw ke(e,t,n);const o=fe(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(...gO(e,r.id)),s.sort((h,d)=>h.at.localeCompare(d.at));const i=e.graph.getSupersessionChain(r.id);let a;if(i.length>1){const h=i.findIndex(g=>g.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 AO extends Error{constructor(t){super(`backlog item not found or invalidated: node ${t}`),this.nodeId=t,this.name="NotFoundError"}}function je(e,t,n){return Sd(()=>e.db.transaction(()=>{const r=e.graph.getNode(t);if(!r||r.tInvalid)throw new AO(t);const o=r.metadata??{},s=n(o);return e.graph.touch(t,{metadata:s}),s}).immediate())}function kO(e,t,n){const r=new Map,o=wd(n.title);if(o)for(const i of e.graph.searchNodes(o,{limit:10,filter:{tags:[_e],namespace:t}}))Ve(i)&&r.set(i.id,i);const s=n.dedupeScan;if(s!=null&&s.symbol)for(const i of e.graph.queryNodes({kind:"generic",tags:[_e],namespace:t,metadata:{dedupeSymbol:s.symbol}}))Ve(i)&&r.set(i.id,i);if(s!=null&&s.path)for(const i of e.graph.queryNodes({kind:"generic",tags:[_e],namespace:t,metadata:{dedupePath:s.path}}))Ve(i)&&r.set(i.id,i);if(s!=null&&s.errorText)for(const i of e.graph.queryNodes({kind:"generic",tags:[_e],namespace:t,metadata:{dedupeErrorText:s.errorText}}))Ve(i)&&r.set(i.id,i);return[...r.values()].map(fe)}function ia(e,t){if(t.idOverride){const s=et(e,t.repo,t.idOverride);if(s){const i=fe(s);return{item:i,created:!1,duplicateCandidates:[i]}}}const n=t.force?[]:kO(e,t.repo,t);if(n.length>0&&!t.force)return{item:n[0],created:!1,duplicateCandidates:n};const r=Ad(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 Ed(e,t.repo,t.family,t.idOverride,(s,i)=>{var h,d,m;if(i){const g=fe(i);return{item:g,created:!1,duplicateCandidates:[g]}}const a=Br(s),c=Fr(s),u=new Date().toISOString(),l={humanId:s,kind:a,family:c,title:t.title,body:t.body,status:"OPEN",repo:t.repo,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=e.graph.writeNode(ra(t.repo,s,t.title,t.body),{kind:"generic",name:oa(t.repo,s),summary:t.title,tags:bd(a,c,t.tags),namespace:t.repo,importance:sa(t.priority),confidence:"confirmed",...t.projectPath!==void 0?{projectPath:t.projectPath}:{},metadata:l}),p=e.graph.getNode(f);if(!p)throw new Error(`backlog: writeNode returned an id that does not resolve: ${f}`);return{item:fe(p),created:!0,duplicateCandidates:[],...o!==void 0?{repoWarning:o}:{}}})}function Id(e,t,n){const r=et(e,t,n);return r?fe(r):null}function xd(e,t,n){const r=et(e,t,n);if(!r)throw ke(e,t,n);return r}function Pd(e,t,n,r){const o=xd(e,t,n);let s="",i="";if(je(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=Br(n),l=Fr(n);c.tags=bd(u,l,r.tags)}r.projectPath!==void 0&&(c.projectPath=r.projectPath),e.graph.touch(o.id,c)}if(r.title!==void 0||r.body!==void 0){const c=ra(t,n,s,i);e.db.prepare("UPDATE node SET content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL").run(c,cO(c),o.id)}const a=e.graph.getNode(o.id);if(!a)throw ke(e,t,n);return fe(a)}function jO(e,t,n,r){const o=xd(e,t,n);e.graph.invalidate(o.id,r)}function aa(e,t,n){const r=e.graph.getNode(t),o=r==null?void 0:r.metadata;o!=null&&o.repo&&(o!=null&&o.humanId)&&Od(e,t,o.repo,o.humanId,"claim",n)}const IO=30;class xO extends Error{constructor(t,n){super(`cannot release claim held by "${t}" as "${n}" without force`),this.heldBy=t,this.name="ClaimContentionError"}}function Td(e,t,n,r={}){const o=(r.staleAfterMin??IO)*6e4;let s;return je(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"&&aa(e,t,{status:s.status,by:n}),s}function PO(e,t,n){let r;return je(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}}),aa(e,t,{status:r.status,by:n}),r}function TO(e,t,n,r={}){let o;return je(e,t,s=>{if(!s.claimedBy)return o={status:"release-noop"},s;if(s.claimedBy!==n&&!r.force)throw new xO(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"&&aa(e,t,{status:o.status,by:n,wasClaimedBy:o.wasClaimedBy}),o}function Vr(e,t,n){const r=et(e,t,n);if(!r)throw ke(e,t,n);return r}function jn(e,t,n,r,o){const s=Vr(e,t,n);let i;je(e,s.id,c=>{i=c.status;const u=o.citations&&o.citations.length>0?[...c.citations,...o.citations]:c.citations;if($r(r)&&u.length===0)throw new yd(r);if(vr(r)&&!o.reason)throw new $d(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 na.has(r)&&(delete p.claimedBy,delete p.claimedAt),p}),Od(e,s.id,t,n,"transition",{from:i,to:r,by:o.by,...o.reason?{reason:o.reason}:{}});const a=e.graph.getNode(s.id);if(!a)throw ke(e,t,n);return fe(a)}function CO(e,t,n,r,o){return jn(e,t,n,r,o)}function RO(e,t,n,r){const o=Vr(e,t,n),s=Td(e,o.id,r);if(s.status==="held")throw new vd(s.heldBy??"unknown",s.heldSince??"unknown");return jn(e,t,n,"IN_PROGRESS",{by:r})}function MO(e,t,n,r){const o=Vr(e,t,n);je(e,o.id,i=>({...i,citations:[...i.citations,r],updatedAt:new Date().toISOString()}));const s=e.graph.getNode(o.id);if(!s)throw ke(e,t,n);return fe(s)}function DO(e,t,n,r,o){const s=Vr(e,t,n);je(e,s.id,a=>{const c=new Date().toISOString();return{...a,notes:[...a.notes,{by:r,at:c,text:o}],updatedAt:c}});const i=e.graph.getNode(s.id);if(!i)throw ke(e,t,n);return fe(i)}function LO(e,t,n={}){const r=new Set((n.exclude??[]).map(i=>i.toUpperCase())),o=ft(e,{repo:t.repo,projectPath:t.projectPath,status:"closed"}),s=[];for(const i of o){if(r.has(i.humanId.toUpperCase())||!Ke(i.status))continue;const a=new Date().toISOString();je(e,i.nodeId,u=>({...u,archivedAt:a,updatedAt:a}));const c=e.graph.getNode(i.nodeId);c&&s.push(fe(c))}return s}function Ae(e,t,n){const r=et(e,t,n);if(!r)throw ke(e,t,n);return r}function UO(e,t,n,r){const o=Ae(e,t,n),s=Ae(e,t,r);e.graph.writeEdge(o.id,s.id,"DEPENDS_ON")}function BO(e,t,n,r){const o=Ae(e,t,n),s=Ae(e,t,r);e.db.prepare("DELETE FROM edge WHERE src = ? AND dst = ? AND rel = 'DEPENDS_ON'").run(o.id,s.id)}function FO(e,t,n,r){const o=Ae(e,t,n),s=Ae(e,t,r);e.graph.writeEdge(o.id,s.id,"RELATES_TO")}function VO(e,t,n,r,o){const s=Ae(e,t,n),i=new Date().toISOString();let a="";const c=Ed(e,t,r.family,r.idOverride,l=>{a=l;const f=Br(a),p=Fr(a),h={humanId:a,kind:f,family:p,title:r.title,body:r.body,status:"OPEN",repo:t,citations:[],notes:[],createdAt:i,updatedAt:i};return r.priority!==void 0&&(h.priority=r.priority),r.projectPath!==void 0&&(h.projectPath=r.projectPath),r.plan!==void 0&&(h.plan=r.plan),e.graph.supersede(s.id,ra(t,a,r.title,r.body),{kind:"generic",name:oa(t,a),summary:r.title,tags:["backlog-item",f,p,...r.tags??[]],namespace:t,importance:sa(r.priority),confidence:"confirmed",...r.projectPath!==void 0?{projectPath:r.projectPath}:{},metadata:h})});je(e,s.id,l=>{const f=[...l.notes,{by:"system",at:i,text:`[superseded by ${a}] ${o}`}],p={...l,status:"SUPERSEDED",notes:f,updatedAt:i};return delete p.claimedBy,delete p.claimedAt,p}),e.graph.invalidate(s.id,o);const u=e.graph.getNode(c);if(!u)throw new Error(`backlog: supersede() returned an id that does not resolve: ${c}`);return fe(u)}function qO(e,t,n,r){const o=Ae(e,t,n),s=[];for(const i of r){const a=ia(e,{...i,repo:t});e.graph.writeEdge(a.item.nodeId,o.id,"PART_OF"),s.push(a.item)}return s}function KO(e,t,n,r,o){const s=Ae(e,t,n),i=Ae(e,t,r);je(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}),e.graph.writeEdge(i.id,s.id,"SAME_AS"),e.graph.invalidate(i.id,o);const a=e.graph.getNode(s.id);if(!a)throw ke(e,t,n);return fe(a)}function Cd(e,t,n,r){const o=Ae(e,t,n);je(e,o.id,i=>({...i,priority:r,updatedAt:new Date().toISOString()})),e.graph.touch(o.id,{importance:sa(r)});const s=e.graph.getNode(o.id);if(!s)throw ke(e,t,n);return fe(s)}function zO(e,t,n){const r=`${t}::plan:${n}`,s=e.graph.queryNodes({kind:"generic",tags:[_u],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:[_u],namespace:t,metadata:{planSlug:n}})}function gs(e,t,n,r){const o=Ae(e,t,n),s=zO(e,t,r);je(e,o.id,i=>({...i,plan:r,updatedAt:new Date().toISOString()})),e.graph.writeEdge(o.id,s,"MEMBER_OF")}function GO(e,t){const r=e.graph.queryNodes({kind:"entity",tags:[Au],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:[Au],metadata:{identity:t}})}function HO(e,t,n,r,o){const s=Ae(e,t,n),i=GO(e,r);je(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}}),e.graph.writeEdge(s.id,i,"ASSIGNED_TO");const a=e.graph.getNode(s.id);if(!a)throw ke(e,t,n);return fe(a)}const Pu=/^(#{2,3})\s+([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)/,JO=["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","CLOSED"],WO=["MITIGATED"],QO=["INVALID","SUPERSEDED","DUPLICATE","WONTFIX"],YO=new Set([...JO,...WO,...QO]),ZO=new Set(["OPEN","IN_PROGRESS","PARTIAL","OUTSTANDING","DEFERRED","BLOCKED","MIXED","UNKNOWN","FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Rd(e){const t=e.toUpperCase();return t==="IN-PROGRESS"?"IN_PROGRESS":t==="CLOSED"?"RESOLVED":ZO.has(t)?t:"UNKNOWN"}function Md(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 Dd(e,t){const n=t.match(/^\s*-?\s*\*\*Status:\*?\*?\s*([^\n]+)/im),r=n?Md(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 Ld(e,t){const r=`${e}
174
- ${t}`.match(/\*{0,2}priority:?\*{0,2}\s*[:-]?\s*(CRITICAL|HIGH|MEDIUM|LOW)/i);return r?r[1].toUpperCase():/—\s*CRITICAL\b/i.test(e)||/\bCRITICAL\b/.test(e)?"CRITICAL":""}const XO=/^[A-Z][A-Z0-9_-]*$/;function e_(e){const t=e.trim().split(/\s+/)[0]??"";return XO.test(t)&&/[0-9_]/.test(t)}function Ud(e){const t=e.split(`
173
+ <!-- ${L_}${e}::${t} -->`}function wa(e,t){return`${e}::${t}`}function ba(e){switch(e){case"CRITICAL":return 10;case"HIGH":return 8;case"MEDIUM":return 5;case"LOW":return 2;default:return 1}}function Zd(e,t,n=[]){return[...new Set([we,e,t,...n])]}function Me(e){return e.tags.includes(we)&&!e.isSuperseded}function se(e){const t=e.metadata??{},n=t.humanId??"",r=t.kind??Br(n),o=t.family??Ur(n),s=new Set([we,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 U_=5,F_=20,V_=500;function q_(e){const t=e==null?void 0:e.code;return t==="SQLITE_BUSY"||t==="SQLITE_BUSY_TIMEOUT"||t==="SQLITE_BUSY_SNAPSHOT"}function K_(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.max(0,Math.round(e)))}function Xd(e,t={}){const n=t.maxAttempts??U_;for(let r=0;;r++)try{return e()}catch(o){if(!q_(o)||r>=n-1)throw o;const s=Math.min(V_,F_*2**r);K_(s*(.5+Math.random()*.5))}}function G_(e,t,n){const r=e.graph.queryNodes({kind:"generic",tags:[we],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")}`}function z_(e,t,n){return e.graph.queryNodes({kind:"generic",tags:[we],namespace:t,metadata:{humanId:n}}).find(o=>{var s;return Me(o)&&((s=o.metadata)==null?void 0:s.humanId)===n})??null}function ep(e,t,n,r,o){return Xd(()=>e.db.transaction(()=>{if(r){const i=z_(e,t,r);return o(r,i)}const s=G_(e,t,n);return o(s,null)}).immediate())}const tp="backlog-audit-event";function np(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=e.graph.writeNode(c,{kind:"generic",name:`audit-event::${n}::${r}::${i}`,tags:[tp],namespace:n,metadata:a});e.graph.writeEdge(u,t,"DERIVED_FROM")}function W_(e,t){return e.graph.queryNodes({kind:"generic",tags:[tp],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 Fu={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3};function Vu(e){const t=[we];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 J_(e,t){return t.status==="open"?e.filter(n=>!Le(n.status)):t.status==="closed"?e.filter(n=>Le(n.status)):e}function qu(e,t){return t.rootLevel?e.filter(n=>{const r=n.metadata;return!(r!=null&&r.projectPath)&&!(r!=null&&r.plan)}):e}function Ku(e,t){return t.excludeArchived?e.filter(n=>{var r;return!((r=n.metadata)!=null&&r.archivedAt)}):e}function rp(e,t={}){if(t.grep){const o=Vu({...t}),s=Qd(t.grep);if(!s)return[];const i=e.graph.searchNodes(s,{limit:t.limit??1e3,filter:o});let a=Ku(qu(i.filter(Me),t),t);return t.offset&&(a=a.slice(t.offset)),a}const n=Vu(t);t.limit!==void 0&&(n.limit=t.limit),t.offset!==void 0&&(n.offset=t.offset);const r=e.graph.queryNodes(n);return Ku(qu(r.filter(Me),t),t)}function at(e,t={}){const r=rp(e,t).map(se);return J_(r,t)}function Ye(e,t,n){const r=wa(t,n),s=e.graph.queryNodes({kind:"generic",tags:[we],namespace:t,metadata:{humanId:n}}).filter(Me);return s.find(i=>i.name===r)??s[0]??null}function _s(e){var t;return((t=e.metadata)==null?void 0:t.repo)??e.namespace??""}function H_(e,t){return e.graph.queryNodes({kind:"generic",tags:[we],metadata:{humanId:t}}).filter(Me)}function op(e){const t=e.graph.queryNodes({kind:"generic",tags:[we]}),n=new Set;for(const r of t){if(!Me(r))continue;const o=_s(r);o&&n.add(o)}return n}function Ee(e,t,n){const r=H_(e,n).filter(s=>_s(s)!==t),o=[...new Set(r.map(_s).filter(s=>s.length>0))];return new Wd(t,n,o)}function an(e,t){const n={};for(const r of e){const o=t(r);o&&(n[o]=(n[o]??0)+1)}return n}function Y_(e,t={}){const n=at(e,{repo:t.repo,projectPath:t.projectPath}),r=n.filter(s=>!Le(s.status)),o=n.filter(s=>Le(s.status));return{total:n.length,open:r.length,closed:o.length,byStatus:an(n,s=>s.status),byKind:an(n,s=>s.kind),byFamily:an(n,s=>s.family),byPriority:an(n,s=>s.priority),byRepo:t.repo===void 0?an(n,s=>s.repo):{}}}function Q_(e,t={},n=20){const o=at(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(s=>s.priority!==void 0);return o.sort((s,i)=>{const a=Fu[s.priority??""]??4,c=Fu[i.priority??""]??4;return a-c||s.humanId.localeCompare(i.humanId)}),o.slice(0,n)}function sp(e,t){const n=e.graph.getEdges({src:t,rel:"DEPENDS_ON"}),r=[];for(const o of n){const s=e.graph.getNode(o.dst);s&&r.push(s)}return r}function Z_(e,t,n){const r=Ye(e,t,n);return r?sp(e,r.id).filter(o=>!o.tInvalid).map(se).filter(o=>!Le(o.status)):[]}function X_(e,t={}){return at(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(r=>{if(r.claimedBy)return!1;const o=Ye(e,r.repo,r.humanId);return o?sp(e,o.id).filter(i=>!i.tInvalid).every(i=>Le(se(i).status)):!1})}function ip(e,t={}){const n=at(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=Ye(e,s.repo,s.humanId);if(i)for(const a of["DEPENDS_ON","RELATES_TO","PART_OF"])for(const c of e.graph.getEdges({src:i.id,rel:a})){const u=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}}function ek(e,t={}){var c;const n=ip(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:tk([...s],o)}:{ok:!0,order:i}}function tk(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}function nk(e,t,n={}){const r=at(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)}function rk(e,t,n){var u,l,f,p;const r=Ye(e,t,n);if(!r)throw Ee(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(...W_(e,r.id)),s.sort((h,d)=>h.at.localeCompare(d.at));const i=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,g=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),g&&(a.supersededBy=g)}const c={humanId:o.humanId,history:s};return a&&(c.supersessionChain=a),c}class ok extends Error{constructor(t){super(`backlog item not found or invalidated: node ${t}`),this.nodeId=t,this.name="NotFoundError"}}function Se(e,t,n){return Xd(()=>e.db.transaction(()=>{const r=e.graph.getNode(t);if(!r||r.tInvalid)throw new ok(t);const o=r.metadata??{},s=n(o);return e.graph.touch(t,{metadata:s}),s}).immediate())}function sk(e,t,n){const r=new Map,o=Qd(n.title);if(o)for(const i of e.graph.searchNodes(o,{limit:10,filter:{tags:[we],namespace:t}}))Me(i)&&r.set(i.id,i);const s=n.dedupeScan;if(s!=null&&s.symbol)for(const i of e.graph.queryNodes({kind:"generic",tags:[we],namespace:t,metadata:{dedupeSymbol:s.symbol}}))Me(i)&&r.set(i.id,i);if(s!=null&&s.path)for(const i of e.graph.queryNodes({kind:"generic",tags:[we],namespace:t,metadata:{dedupePath:s.path}}))Me(i)&&r.set(i.id,i);if(s!=null&&s.errorText)for(const i of e.graph.queryNodes({kind:"generic",tags:[we],namespace:t,metadata:{dedupeErrorText:s.errorText}}))Me(i)&&r.set(i.id,i);return[...r.values()].map(se)}function Ea(e,t){if(t.idOverride){const s=Ye(e,t.repo,t.idOverride);if(s){const i=se(s);return{item:i,created:!1,duplicateCandidates:[i]}}}const n=t.force?[]:sk(e,t.repo,t);if(n.length>0&&!t.force)return{item:n[0],created:!1,duplicateCandidates:n};const r=op(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 ep(e,t.repo,t.family,t.idOverride,(s,i)=>{var h,d,g;if(i){const y=se(i);return{item:y,created:!1,duplicateCandidates:[y]}}const a=Br(s),c=Ur(s),u=new Date().toISOString(),l={humanId:s,kind:a,family:c,title:t.title,body:t.body,status:"OPEN",repo:t.repo,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),((g=t.dedupeScan)==null?void 0:g.errorText)!==void 0&&(l.dedupeErrorText=t.dedupeScan.errorText);const f=e.graph.writeNode(va(t.repo,s,t.title,t.body),{kind:"generic",name:wa(t.repo,s),summary:t.title,tags:Zd(a,c,t.tags),namespace:t.repo,importance:ba(t.priority),confidence:"confirmed",...t.projectPath!==void 0?{projectPath:t.projectPath}:{},metadata:l}),p=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}:{}}})}function ap(e,t,n){const r=Ye(e,t,n);return r?se(r):null}function cp(e,t,n){const r=Ye(e,t,n);if(!r)throw Ee(e,t,n);return r}function up(e,t,n,r){const o=cp(e,t,n);let s="",i="";if(Se(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=Br(n),l=Ur(n);c.tags=Zd(u,l,r.tags)}r.projectPath!==void 0&&(c.projectPath=r.projectPath),e.graph.touch(o.id,c)}if(r.title!==void 0||r.body!==void 0){const c=va(t,n,s,i);e.db.prepare("UPDATE node SET content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL").run(c,B_(c),o.id)}const a=e.graph.getNode(o.id);if(!a)throw Ee(e,t,n);return se(a)}function ik(e,t,n,r){const o=cp(e,t,n);e.graph.invalidate(o.id,r)}function Sa(e,t,n){const r=e.graph.getNode(t),o=r==null?void 0:r.metadata;o!=null&&o.repo&&(o!=null&&o.humanId)&&np(e,t,o.repo,o.humanId,"claim",n)}const ak=30;class ck extends Error{constructor(t,n){super(`cannot release claim held by "${t}" as "${n}" without force`),this.heldBy=t,this.name="ClaimContentionError"}}function lp(e,t,n,r={}){const o=(r.staleAfterMin??ak)*6e4;let s;return Se(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"&&Sa(e,t,{status:s.status,by:n}),s}function uk(e,t,n){let r;return Se(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}}),Sa(e,t,{status:r.status,by:n}),r}function lk(e,t,n,r={}){let o;return Se(e,t,s=>{if(!s.claimedBy)return o={status:"release-noop"},s;if(s.claimedBy!==n&&!r.force)throw new ck(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"&&Sa(e,t,{status:o.status,by:n,wasClaimedBy:o.wasClaimedBy}),o}function Fr(e,t,n){const r=Ye(e,t,n);if(!r)throw Ee(e,t,n);return r}function _n(e,t,n,r,o){const s=Fr(e,t,n);let i;Se(e,s.id,c=>{i=c.status;const u=o.citations&&o.citations.length>0?[...c.citations,...o.citations]:c.citations;if(yr(r)&&u.length===0)throw new Jd(r);if($r(r)&&!o.reason)throw new Hd(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 $a.has(r)&&(delete p.claimedBy,delete p.claimedAt),p}),np(e,s.id,t,n,"transition",{from:i,to:r,by:o.by,...o.reason?{reason:o.reason}:{}});const a=e.graph.getNode(s.id);if(!a)throw Ee(e,t,n);return se(a)}function fk(e,t,n,r,o){return _n(e,t,n,r,o)}function dk(e,t,n,r){const o=Fr(e,t,n),s=lp(e,o.id,r);if(s.status==="held")throw new Yd(s.heldBy??"unknown",s.heldSince??"unknown");return _n(e,t,n,"IN_PROGRESS",{by:r})}function pk(e,t,n,r){const o=Fr(e,t,n);Se(e,o.id,i=>({...i,citations:[...i.citations,r],updatedAt:new Date().toISOString()}));const s=e.graph.getNode(o.id);if(!s)throw Ee(e,t,n);return se(s)}function hk(e,t,n,r,o){const s=Fr(e,t,n);Se(e,s.id,a=>{const c=new Date().toISOString();return{...a,notes:[...a.notes,{by:r,at:c,text:o}],updatedAt:c}});const i=e.graph.getNode(s.id);if(!i)throw Ee(e,t,n);return se(i)}function mk(e,t,n={}){const r=new Set((n.exclude??[]).map(i=>i.toUpperCase())),o=at(e,{repo:t.repo,projectPath:t.projectPath,status:"closed"}),s=[];for(const i of o){if(r.has(i.humanId.toUpperCase())||!Le(i.status))continue;const a=new Date().toISOString();Se(e,i.nodeId,u=>({...u,archivedAt:a,updatedAt:a}));const c=e.graph.getNode(i.nodeId);c&&s.push(se(c))}return s}function be(e,t,n){const r=Ye(e,t,n);if(!r)throw Ee(e,t,n);return r}function gk(e,t,n,r){const o=be(e,t,n),s=be(e,t,r);e.graph.writeEdge(o.id,s.id,"DEPENDS_ON")}function yk(e,t,n,r){const o=be(e,t,n),s=be(e,t,r);e.db.prepare("DELETE FROM edge WHERE src = ? AND dst = ? AND rel = 'DEPENDS_ON'").run(o.id,s.id)}function $k(e,t,n,r){const o=be(e,t,n),s=be(e,t,r);e.graph.writeEdge(o.id,s.id,"RELATES_TO")}function vk(e,t,n,r,o){const s=be(e,t,n),i=new Date().toISOString();let a="";const c=ep(e,t,r.family,r.idOverride,l=>{a=l;const f=Br(a),p=Ur(a),h={humanId:a,kind:f,family:p,title:r.title,body:r.body,status:"OPEN",repo:t,citations:[],notes:[],createdAt:i,updatedAt:i};return r.priority!==void 0&&(h.priority=r.priority),r.projectPath!==void 0&&(h.projectPath=r.projectPath),r.plan!==void 0&&(h.plan=r.plan),e.graph.supersede(s.id,va(t,a,r.title,r.body),{kind:"generic",name:wa(t,a),summary:r.title,tags:["backlog-item",f,p,...r.tags??[]],namespace:t,importance:ba(r.priority),confidence:"confirmed",...r.projectPath!==void 0?{projectPath:r.projectPath}:{},metadata:h})});Se(e,s.id,l=>{const f=[...l.notes,{by:"system",at:i,text:`[superseded by ${a}] ${o}`}],p={...l,status:"SUPERSEDED",notes:f,updatedAt:i};return delete p.claimedBy,delete p.claimedAt,p}),e.graph.invalidate(s.id,o);const u=e.graph.getNode(c);if(!u)throw new Error(`backlog: supersede() returned an id that does not resolve: ${c}`);return se(u)}function wk(e,t,n,r){const o=be(e,t,n),s=[];for(const i of r){const a=Ea(e,{...i,repo:t});e.graph.writeEdge(a.item.nodeId,o.id,"PART_OF"),s.push(a.item)}return s}function bk(e,t,n,r,o){const s=be(e,t,n),i=be(e,t,r);Se(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}),e.graph.writeEdge(i.id,s.id,"SAME_AS"),e.graph.invalidate(i.id,o);const a=e.graph.getNode(s.id);if(!a)throw Ee(e,t,n);return se(a)}function fp(e,t,n,r){const o=be(e,t,n);Se(e,o.id,i=>({...i,priority:r,updatedAt:new Date().toISOString()})),e.graph.touch(o.id,{importance:ba(r)});const s=e.graph.getNode(o.id);if(!s)throw Ee(e,t,n);return se(s)}function Ek(e,t,n){const r=`${t}::plan:${n}`,s=e.graph.queryNodes({kind:"generic",tags:[Bu],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:[Bu],namespace:t,metadata:{planSlug:n}})}function ks(e,t,n,r){const o=be(e,t,n),s=Ek(e,t,r);Se(e,o.id,i=>({...i,plan:r,updatedAt:new Date().toISOString()})),e.graph.writeEdge(o.id,s,"MEMBER_OF")}function Sk(e,t){const r=e.graph.queryNodes({kind:"entity",tags:[Uu],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:[Uu],metadata:{identity:t}})}function Nk(e,t,n,r,o){const s=be(e,t,n),i=Sk(e,r);Se(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}}),e.graph.writeEdge(s.id,i,"ASSIGNED_TO");const a=e.graph.getNode(s.id);if(!a)throw Ee(e,t,n);return se(a)}const Gu=/^(#{2,3})\s+([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)/,Ok=["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","CLOSED"],_k=["MITIGATED"],kk=["INVALID","SUPERSEDED","DUPLICATE","WONTFIX"],Ak=new Set([...Ok,..._k,...kk]),jk=new Set(["OPEN","IN_PROGRESS","PARTIAL","OUTSTANDING","DEFERRED","BLOCKED","MIXED","UNKNOWN","FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function dp(e){const t=e.toUpperCase();return t==="IN-PROGRESS"?"IN_PROGRESS":t==="CLOSED"?"RESOLVED":jk.has(t)?t:"UNKNOWN"}function pp(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 hp(e,t){const n=t.match(/^\s*-?\s*\*\*Status:\*?\*?\s*([^\n]+)/im),r=n?pp(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 mp(e,t){const r=`${e}
174
+ ${t}`.match(/\*{0,2}priority:?\*{0,2}\s*[:-]?\s*(CRITICAL|HIGH|MEDIUM|LOW)/i);return r?r[1].toUpperCase():/—\s*CRITICAL\b/i.test(e)||/\bCRITICAL\b/.test(e)?"CRITICAL":""}const Ik=/^[A-Z][A-Z0-9_-]*$/;function Pk(e){const t=e.trim().split(/\s+/)[0]??"";return Ik.test(t)&&/[0-9_]/.test(t)}function gp(e){const t=e.split(`
175
175
  `),n=[],r=[];let o=null;const s=()=>{if(!o)return;const i=o.bodyLines.join(`
176
- `),a=Dd(o.headerLine,i),c=Ld(o.headerLine,i),{bodyLines:u,...l}=o,f=!YO.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(Pu),u=/^#{2,3}\s/.test(i);if(c&&/\d/.test(c[2])){s();const l=c[2],f=i.replace(Pu,"").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+/,"");e_(l)&&r.push({line:a+1,headerLine:i}),s(),o=null}else o&&o.bodyLines.push(i)}),s(),{items:n,malformedHeaders:r}}function t_(e){return Ud(e).items}function Bd(e){return Ud(e)}function n_(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 r_(e){return e==="IN_PROGRESS"?"IN PROGRESS":e}function Fd(e){const t=[];t.push(`### ${e.humanId} — ${e.title}`),t.push(""),t.push(`**Status:** ${r_(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(n_(e.citations));for(const n of e.notes)t.push(`- Note (${n.by}, ${n.at}): ${n.text}`);return t.join(`
177
- `).trimEnd()}function Vd(e){return e.length===0?"":`${e.map(Fd).join(`
176
+ `),a=hp(o.headerLine,i),c=mp(o.headerLine,i),{bodyLines:u,...l}=o,f=!Ak.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(Gu),u=/^#{2,3}\s/.test(i);if(c&&/\d/.test(c[2])){s();const l=c[2],f=i.replace(Gu,"").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+/,"");Pk(l)&&r.push({line:a+1,headerLine:i}),s(),o=null}else o&&o.bodyLines.push(i)}),s(),{items:n,malformedHeaders:r}}function xk(e){return gp(e).items}function yp(e){return gp(e)}function Tk(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 Ck(e){return e==="IN_PROGRESS"?"IN PROGRESS":e}function $p(e){const t=[];t.push(`### ${e.humanId} — ${e.title}`),t.push(""),t.push(`**Status:** ${Ck(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(Tk(e.citations));for(const n of e.notes)t.push(`- Note (${n.by}, ${n.at}): ${n.text}`);return t.join(`
177
+ `).trimEnd()}function vp(e){return e.length===0?"":`${e.map($p).join(`
178
178
 
179
179
  `)}
180
- `}function o_(e){return e.split(`
181
- `).map(s_).join(`
182
- `)}function s_(e){return/^###\s/.test(e)?`##${e}`:/^##\s/.test(e)?`##${e}`:e}function qd(e,t){let n=`### Archived — resolved/terminal backlog items relocated in batch (${t})
180
+ `}function Rk(e){return e.split(`
181
+ `).map(Mk).join(`
182
+ `)}function Mk(e){return/^###\s/.test(e)?`##${e}`:/^##\s/.test(e)?`##${e}`:e}function wp(e,t){let n=`### Archived — resolved/terminal backlog items relocated in batch (${t})
183
183
 
184
184
  `;return n+="> Moved via `@adhd/backlog`'s `archiveResolved` (canonical terminal statuses: FIXED/RESOLVED/DONE/\n",n+=`> SHIPPED/VERIFIED/REMOVED/MITIGATED/SUPERSEDED/INVALID/DUPLICATE/WONTFIX). The graph node itself is
185
185
  `,n+=`> NEVER deleted — this is a rendered snapshot; full history remains queryable via auditTrail.
186
186
 
187
- `,n+=e.map(r=>o_(Fd(r))).join(`
187
+ `,n+=e.map(r=>Rk($p(r))).join(`
188
188
 
189
189
  `),n+=`
190
- `,n}function Kd(e){return e.map(t=>{const n={humanId:t.id,title:t.title,body:t.body,status:Rd(t.status)};return t.priority&&(t.priority==="CRITICAL"||t.priority==="HIGH"||t.priority==="MEDIUM"||t.priority==="LOW")&&(n.priority=t.priority),n})}function ca(e,t,n){const r=Id(e.store,t,n);if(!r)throw ke(e.store,t,n);return r}async function zd(e,t){return ia(e.store,t)}async function Gd(e,t,n){const r=Id(e.store,t,n);if(r)return r;const o=ke(e.store,t,n);if(o.foundInRepos.length>0)throw o;return null}async function Hd(e,t,n,r){return Pd(e.store,t,n,r)}async function Jd(e,t){return ft(e.store,t??{})}async function Wd(e,t,n,r){jO(e.store,t,n,r)}async function Qd(e,t){return vO(e.store,t??{})}async function Yd(e,t,n){return wO(e.store,t??{},n??20)}async function Zd(e,t){return SO(e.store,t??{})}async function Xd(e,t,n){return bO(e.store,t,n)}async function ep(e,t){return jd(e.store,t??{})}async function tp(e,t){return EO(e.store,t??{})}async function np(e,t,n){return OO(e.store,t,n??{})}async function rp(e,t,n,r,o){const s=ca(e,t,n);return Td(e.store,s.nodeId,r,o??{})}async function op(e,t,n,r){const o=ca(e,t,n);return PO(e.store,o.nodeId,r)}async function sp(e,t,n,r,o){const s=ca(e,t,n);return TO(e.store,s.nodeId,r,o??{})}async function ip(e,t,n,r,o){return HO(e.store,t,n,r,o)}async function ap(e,t,n,r){return RO(e.store,t,n,r)}async function cp(e,t,n,r,o){return jn(e.store,t,n,r,o)}async function up(e,t,n,r){return MO(e.store,t,n,r)}async function lp(e,t,n,r,o){return DO(e.store,t,n,r,o)}async function fp(e,t,n,r,o){return CO(e.store,t,n,r,o)}async function dp(e,t,n){const r=LO(e.store,t,n??{}),o=r.length>0?qd(r,new Date().toISOString().slice(0,10)):"";return{archivedCount:r.length,changelogMarkdown:o}}async function pp(e,t,n,r){UO(e.store,t,n,r)}async function hp(e,t,n,r){BO(e.store,t,n,r)}async function mp(e,t,n,r){FO(e.store,t,n,r)}async function gp(e,t,n,r,o){return VO(e.store,t,n,r,o)}async function yp(e,t,n,r){return qO(e.store,t,n,r)}async function $p(e,t,n,r,o){return KO(e.store,t,n,r,o)}async function vp(e,t,n,r){return Cd(e.store,t,n,r)}async function wp(e,t,n,r){gs(e.store,t,n,r)}async function bp(e,t){const n=Y.readFileSync(t.path,"utf8"),{items:r,malformedHeaders:o}=Bd(n),s=Kd(r),i=t.sourcePath??t.path,a=Ad(e.store),c=a.size>0&&!a.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...a].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0,u={parsed:s.length,created:0,skippedDuplicates:0,updated:0,errors:[],malformedHeaders:o,...c!==void 0?{repoWarning:c}:{}};if(t.dryRun)return u;for(const l of s)try{const f=ia(e.store,{family:l.humanId.replace(/-\d+$/,""),idOverride:l.humanId,title:l.title,body:l.body,repo:t.repo,...t.projectPath!==void 0?{projectPath:t.projectPath}:{},...t.plan!==void 0?{plan:t.plan}:{},importedFrom:i,...l.priority!==void 0?{priority:l.priority}:{},force:!0});if(f.created&&t.plan!==void 0&&gs(e.store,t.repo,l.humanId,t.plan),f.created&&l.status!=="OPEN"&&jn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...$r(l.status)?{citations:[{file:t.path}]}:{},...vr(l.status)?{reason:`imported from markdown at status ${l.status}`}:{}}),f.created){u.created+=1;continue}u.skippedDuplicates+=1;const p=f.duplicateCandidates[0]??f.item;let h=!1;if(p.importedFrom===void 0||p.importedFrom===i){const m={};p.title!==l.title&&(m.title=l.title),p.body!==l.body&&(m.body=l.body),p.importedFrom===void 0&&(m.importedFrom=i),t.projectPath!==void 0&&p.projectPath!==t.projectPath&&(m.projectPath=t.projectPath),Object.keys(m).length>0&&(Pd(e.store,t.repo,l.humanId,m),h=!0),l.priority!==void 0&&p.priority!==l.priority&&(Cd(e.store,t.repo,l.humanId,l.priority),h=!0),p.status!==l.status&&(jn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...$r(l.status)?{citations:[{file:t.path}]}:{},...vr(l.status)?{reason:`re-imported from markdown at status ${l.status}`}:{}}),h=!0)}t.plan!==void 0&&p.plan!==t.plan&&(gs(e.store,t.repo,l.humanId,t.plan),h=!0),h&&(u.updated+=1)}catch(f){u.errors.push({humanId:l.humanId,message:f instanceof Error?f.message:String(f)})}return u}async function Sp(e,t){let r=_d(e.store,{...t,excludeArchived:!0}).map(fe);return(t==null?void 0:t.status)==="open"?r=r.filter(o=>!Ke(o.status)):(t==null?void 0:t.status)==="closed"&&(r=r.filter(o=>Ke(o.status))),Vd(r)}async function Ep(e,t){return ft(e.store,t??{})}async function Np(e,t,n){return _O(e.store,t,n)}const i_={"not-started":"not-started: BACKLOG.md is authoritative everywhere; the tool has not been adopted for this repo yet.","phase-1":"phase-1: seed import complete (or in progress) — BACKLOG.md remains authoritative; the graph is a read-only shadow copy.","phase-2":"phase-2: BACKLOG.md is still authoritative; the tool is shadow-running in parity-check mode (render vs. hand-edited markdown, non-blocking).","phase-3":"phase-3: the graph is authoritative. File/claim/transition/resolve via the backlog CLI/MCP — every BACKLOG.md is a generated projection, never hand-edited.","phase-4":"phase-4: phase-3 write path is live; the backlog-usage skill is published and distributed for agent discovery.","phase-5":"phase-5: the legacy tools/util/backlog.mjs parser has been deprecated/removed.",complete:"complete: migration fully done, including cross-repo rollout (Phase 6) where applicable."};async function Op(e){const t=e.env.config.migration.phase;return _p(t)}function _p(e){const t=i_[e]??`unknown phase value: ${e}`;return{phase:e,description:t,toolIsAuthoritative:e==="phase-3"||e==="phase-4"||e==="phase-5"||e==="complete"}}async function Ap(e,t){const n=iO(e.env,t,e.adhdRoot);return{..._p(t),configPath:n}}const a_=Object.freeze(Object.defineProperty({__proto__:null,addCitation:up,addDependency:pp,appendNote:lp,archiveResolved:dp,assignItem:ip,attachToPlan:wp,auditTrail:Np,blockers:Xd,claimItem:rp,createItem:zd,dependencyGraph:ep,exportJson:Ep,getItem:Gd,importFromMarkdown:bp,linkRelated:mp,listItems:Jd,mergeItems:$p,migrationStatus:Op,readyItems:Zd,releaseClaim:sp,removeDependency:hp,renderToMarkdown:Sp,renewClaim:op,resolveItem:fp,setMigrationPhase:Ap,setPriority:vp,softDeleteItem:Wd,splitItem:yp,spotlight:Yd,staleClaims:np,startWork:ap,stats:Qd,supersedeItem:gp,topoOrder:tp,transitionStatus:cp,updateItem:Hd},Symbol.toStringTag,{value:"Module"}));function ys(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function kp(){if(!process.env.VITEST)return;const e=()=>{},t={info:e,error:e,debug:e,fatal:e,warn:e,trace:e};return t.child=()=>t,t}function jp(){const e=q.dirname(wr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Te&&Te.tagName.toUpperCase()==="SCRIPT"&&Te.src||new URL("index.js",document.baseURI).href));return Y.existsSync(q.join(e,"client.d.ts"))?e:q.join(e,"..","dist")}function Tu(e){if(!e||typeof e!="object")return e;const t={},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 t||(t[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;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 t)?{}:r(t[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(e,new Set)}async function c_(){const e=q.join(jp(),"client.d.ts");if(!Y.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 fb({sourceFile:e,namespace:"backlog",dropFileSegment:!0})}async function ua(e){const t=typeof e=="function"?e:()=>e,n=await c_(),r={schemas:Object.fromEntries(n.filter(s=>s.kind==="action").map(s=>{var i;return[((i=s.path[s.path.length-1])==null?void 0:i.raw)??"",{input:Tu(s.input),output:Tu(s.output),hasCtx:s.hasCtx,safe:s.safe}]}))};return{pkg:{id:"backlog",schemas:Lw(r,[]),importPath:q.join(jp(),"client.js"),fns:a_,createClient:async()=>t()},operations:n}}async function Ip(e){const t=ki({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd});t.ensureDirs();const n=As(t.files.db,t.config.db.busyTimeoutMs),r={store:n,env:t},{pkg:o,operations:s}=await ua(r),i=kp(),a=[];(e.transport==="http"||e.transport==="both")&&a.push(ys(VS)({packages:[o],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[nE,Ou]},signal:e.signal,operations:s,logger:i})),(e.transport==="mcp"||e.transport==="both")&&a.push(ys(bN)({packages:[o],outputDir:"",options:{transport:"stdio",usePlugins:[Ou]},signal:e.signal,operations:s,logger:i}));try{await Promise.all(a)}finally{ks(n)}}const yo=["claude","codex","opencode"],u_={claude:".claude",codex:".codex",opencode:".opencode"};function l_(e,t,n,r){if(t==="project")return q.join(n,u_[e],"skills");const o=r??Qt.homedir();if(e==="claude")return q.join(o,".claude","skills");if(e==="codex"){const s=r?q.join(o,".codex"):process.env.CODEX_HOME??q.join(o,".codex");return q.join(s,"skills")}return q.join(o,".config","opencode","skills")}function f_(){const e=q.dirname(wr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Te&&Te.tagName.toUpperCase()==="SCRIPT"&&Te.src||new URL("index.js",document.baseURI).href));return q.join(e,"..","skill","SKILL.md")}function d_(e){let t="all",n="user";for(let o=0;o<e.length;o++){const s=e[o];if(s==="--host")t=e[++o]??"all";else if(s==="--scope")n=e[++o]??"user";else throw new Error(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project")throw new Error(`backlog install-skill: --scope must be "user" or "project", got "${n}"`);const r=t==="all"?[...yo]:[t];for(const o of r)if(!yo.includes(o))throw new Error(`backlog install-skill: --host must be one of ${yo.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function xp(e,t=process.cwd(),n){const{hosts:r,scope:o}=d_(e),s=f_();if(!Y.existsSync(s))throw new Error(`backlog install-skill: packaged skill file not found at ${s} — was @adhd/backlog built/installed correctly?`);const i=Y.readFileSync(s,"utf8"),a=q.join(q.dirname(wr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:Te&&Te.tagName.toUpperCase()==="SCRIPT"&&Te.src||new URL("index.js",document.baseURI).href)),"..","package.json"),c=JSON.parse(Y.readFileSync(a,"utf8")),u=[];for(const l of r){const f=q.join(l_(l,o,t,n),"backlog");Y.mkdirSync(f,{recursive:!0});const p=q.join(f,"SKILL.md");Y.writeFileSync(p,i,"utf8"),Y.writeFileSync(q.join(f,"extension.json"),JSON.stringify({name:c.name,version:c.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
191
- `,"utf8"),u.push({host:l,scope:o,path:p})}return u}async function Pp(e){const t=xp(e);console.log(JSON.stringify({installed:t}))}function p_(e){let t="mcp",n,r;for(let s=0;s<e.length;s++){const i=e[s];if(i==="--transport")t=e[++s];else if(i==="--port")n=Number(e[++s]);else if(i==="--host")r=e[++s];else throw new Error(`backlog serve: unknown argument "${i}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new Error(`backlog serve: --transport must be mcp|http|both, got "${t}"`);const o={transport:t};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function Tp(e,t={}){const n=p_(e),r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort()),await Ip({...n,...t,signal:r.signal})}function Cp(e){const t=e.find(n=>n.kind==="action");if(!t)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return Em(t).cli.path.slice(0,-1)}function Rp(e,t){var r;return e.length===0?[...e]:(r=e[0])!=null&&r.startsWith("-")?[...e]:t.length>0&&t.every((o,s)=>e[s]===o)?[...e]:[...t,...e]}async function Mp(e,t={}){const n=e??process.argv.slice(2);if(n[0]==="install-skill"){await Pp(n.slice(1));return}if(n[0]==="serve"){await Tp(n.slice(1),t);return}let r;const o=()=>{if(!r){const s=ki({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd});s.ensureDirs();const i=As(s.files.db,s.config.db.busyTimeoutMs);r={store:i,ctx:{store:i,env:s}}}return r.ctx};try{const{pkg:s,operations:i}=await ua(o),a=n,c=Cp(i);await ys($m)({packages:[s],operations:i,outputDir:"",options:{argv:Rp(a,c)},signal:t.signal??new AbortController().signal,logger:kp()})}finally{r&&ks(r.store)}}process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:Te&&Te.tagName.toUpperCase()==="SCRIPT"&&Te.src||new URL("index.js",document.baseURI).href)===wr.pathToFileURL(Y.realpathSync(process.argv[1])).href&&Mp().catch(e=>{console.error(e instanceof Error?e.stack??e.message:String(e)),process.exitCode=1});exports.BacklogItemNotFoundError=gd;exports.CitationRequiredError=yd;exports.ClaimHeldError=vd;exports.DependencyCycleError=oO;exports.ReasonRequiredError=$d;exports.TERMINAL_DISMISSED_STATUSES=md;exports.TERMINAL_DONE_STATUSES=pd;exports.TERMINAL_STATUSES=na;exports.TERMINAL_WORKAROUND_STATUSES=hd;exports.addCitation=up;exports.addDependency=pp;exports.appendNote=lp;exports.archiveResolved=dp;exports.assignItem=ip;exports.attachToPlan=wp;exports.auditTrail=Np;exports.backlogEnvironmentSpec=Pf;exports.blockers=Xd;exports.buildBacklogApigenPackage=ua;exports.buildBacklogEnv=ki;exports.buildChangelogSection=qd;exports.claimItem=rp;exports.classifyStatus=Md;exports.closeGraphBacklogStore=ks;exports.createItem=zd;exports.dependencyGraph=ep;exports.detectPriority=Ld;exports.detectStatus=Dd;exports.exportJson=Ep;exports.getItem=Gd;exports.importFromMarkdown=bp;exports.installSkill=xp;exports.isTerminalStatus=Ke;exports.linkRelated=mp;exports.listItems=Jd;exports.mergeItems=$p;exports.migrationStatus=Op;exports.normalizeLegacyStatus=Rd;exports.openGraphBacklogStore=As;exports.parseBacklogMarkdown=t_;exports.parseBacklogMarkdownWithDiagnostics=Bd;exports.prefixCommand=Rp;exports.readyItems=Zd;exports.releaseClaim=sp;exports.removeDependency=hp;exports.renderItemsToMarkdown=Vd;exports.renderToMarkdown=Sp;exports.renewClaim=op;exports.requiresCitation=$r;exports.requiresReason=vr;exports.resolveBacklogScope=Tf;exports.resolveCommandPrefix=Cp;exports.resolveItem=fp;exports.runBacklogCli=Mp;exports.runInstallSkillCommand=Pp;exports.runServeCommand=Tp;exports.setMigrationPhase=Ap;exports.setPriority=vp;exports.softDeleteItem=Wd;exports.splitItem=yp;exports.spotlight=Yd;exports.staleClaims=np;exports.startBacklogServer=Ip;exports.startWork=ap;exports.stats=Qd;exports.suggestClaimantIdentity=jw;exports.supersedeItem=gp;exports.toImportItems=Kd;exports.topoOrder=tp;exports.transitionStatus=cp;exports.updateItem=Hd;
190
+ `,n}function bp(e){return e.map(t=>{const n={humanId:t.id,title:t.title,body:t.body,status:dp(t.status)};return t.priority&&(t.priority==="CRITICAL"||t.priority==="HIGH"||t.priority==="MEDIUM"||t.priority==="LOW")&&(n.priority=t.priority),n})}function Na(e,t,n){const r=ap(e.store,t,n);if(!r)throw Ee(e.store,t,n);return r}async function Ep(e,t){return Ea(e.store,t)}async function Sp(e,t,n){const r=ap(e.store,t,n);if(r)return r;const o=Ee(e.store,t,n);if(o.foundInRepos.length>0)throw o;return null}async function Np(e,t,n,r){return up(e.store,t,n,r)}async function Op(e,t){return at(e.store,t??{})}async function _p(e,t,n,r){ik(e.store,t,n,r)}async function kp(e,t){return Y_(e.store,t??{})}async function Ap(e,t,n){return Q_(e.store,t??{},n??20)}async function jp(e,t){return X_(e.store,t??{})}async function Ip(e,t,n){return Z_(e.store,t,n)}async function Pp(e,t){return ip(e.store,t??{})}async function xp(e,t){return ek(e.store,t??{})}async function Tp(e,t,n){return nk(e.store,t,n??{})}async function Cp(e,t,n,r,o){const s=Na(e,t,n);return lp(e.store,s.nodeId,r,o??{})}async function Rp(e,t,n,r){const o=Na(e,t,n);return uk(e.store,o.nodeId,r)}async function Mp(e,t,n,r,o){const s=Na(e,t,n);return lk(e.store,s.nodeId,r,o??{})}async function Dp(e,t,n,r,o){return Nk(e.store,t,n,r,o)}async function Lp(e,t,n,r){return dk(e.store,t,n,r)}async function Bp(e,t,n,r,o){return _n(e.store,t,n,r,o)}async function Up(e,t,n,r){return pk(e.store,t,n,r)}async function Fp(e,t,n,r,o){return hk(e.store,t,n,r,o)}async function Vp(e,t,n,r,o){return fk(e.store,t,n,r,o)}async function qp(e,t,n){const r=mk(e.store,t,n??{}),o=r.length>0?wp(r,new Date().toISOString().slice(0,10)):"";return{archivedCount:r.length,changelogMarkdown:o}}async function Kp(e,t,n,r){gk(e.store,t,n,r)}async function Gp(e,t,n,r){yk(e.store,t,n,r)}async function zp(e,t,n,r){$k(e.store,t,n,r)}async function Wp(e,t,n,r,o){return vk(e.store,t,n,r,o)}async function Jp(e,t,n,r){return wk(e.store,t,n,r)}async function Hp(e,t,n,r,o){return bk(e.store,t,n,r,o)}async function Yp(e,t,n,r){return fp(e.store,t,n,r)}async function Qp(e,t,n,r){ks(e.store,t,n,r)}async function Zp(e,t){const n=U.readFileSync(t.path,"utf8"),{items:r,malformedHeaders:o}=yp(n),s=bp(r),i=t.sourcePath??t.path,a=op(e.store),c=a.size>0&&!a.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...a].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0,u={parsed:s.length,created:0,skippedDuplicates:0,updated:0,errors:[],malformedHeaders:o,...c!==void 0?{repoWarning:c}:{}};if(t.dryRun)return u;for(const l of s)try{const f=Ea(e.store,{family:l.humanId.replace(/-\d+$/,""),idOverride:l.humanId,title:l.title,body:l.body,repo:t.repo,...t.projectPath!==void 0?{projectPath:t.projectPath}:{},...t.plan!==void 0?{plan:t.plan}:{},importedFrom:i,...l.priority!==void 0?{priority:l.priority}:{},force:!0});if(f.created&&t.plan!==void 0&&ks(e.store,t.repo,l.humanId,t.plan),f.created&&l.status!=="OPEN"&&_n(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...yr(l.status)?{citations:[{file:t.path}]}:{},...$r(l.status)?{reason:`imported from markdown at status ${l.status}`}:{}}),f.created){u.created+=1;continue}u.skippedDuplicates+=1;const p=f.duplicateCandidates[0]??f.item;let h=!1;if(p.importedFrom===void 0||p.importedFrom===i){const g={};p.title!==l.title&&(g.title=l.title),p.body!==l.body&&(g.body=l.body),p.importedFrom===void 0&&(g.importedFrom=i),t.projectPath!==void 0&&p.projectPath!==t.projectPath&&(g.projectPath=t.projectPath),Object.keys(g).length>0&&(up(e.store,t.repo,l.humanId,g),h=!0),l.priority!==void 0&&p.priority!==l.priority&&(fp(e.store,t.repo,l.humanId,l.priority),h=!0),p.status!==l.status&&(_n(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...yr(l.status)?{citations:[{file:t.path}]}:{},...$r(l.status)?{reason:`re-imported from markdown at status ${l.status}`}:{}}),h=!0)}t.plan!==void 0&&p.plan!==t.plan&&(ks(e.store,t.repo,l.humanId,t.plan),h=!0),h&&(u.updated+=1)}catch(f){u.errors.push({humanId:l.humanId,message:f instanceof Error?f.message:String(f)})}return u}async function Xp(e,t){let r=rp(e.store,{...t,excludeArchived:!0}).map(se);return(t==null?void 0:t.status)==="open"?r=r.filter(o=>!Le(o.status)):(t==null?void 0:t.status)==="closed"&&(r=r.filter(o=>Le(o.status))),vp(r)}async function eh(e,t){return at(e.store,t??{})}async function th(e,t,n){return rk(e.store,t,n)}const Dk={"not-started":"not-started: BACKLOG.md is authoritative everywhere; the tool has not been adopted for this repo yet.","phase-1":"phase-1: seed import complete (or in progress) — BACKLOG.md remains authoritative; the graph is a read-only shadow copy.","phase-2":"phase-2: BACKLOG.md is still authoritative; the tool is shadow-running in parity-check mode (render vs. hand-edited markdown, non-blocking).","phase-3":"phase-3: the graph is authoritative. File/claim/transition/resolve via the backlog CLI/MCP — every BACKLOG.md is a generated projection, never hand-edited.","phase-4":"phase-4: phase-3 write path is live; the backlog-usage skill is published and distributed for agent discovery.","phase-5":"phase-5: the legacy tools/util/backlog.mjs parser has been deprecated/removed.",complete:"complete: migration fully done, including cross-repo rollout (Phase 6) where applicable."};async function nh(e){const t=e.env.config.migration.phase;return rh(t)}function rh(e){const t=Dk[e]??`unknown phase value: ${e}`;return{phase:e,description:t,toolIsAuthoritative:e==="phase-3"||e==="phase-4"||e==="phase-5"||e==="complete"}}async function oh(e,t){const n=D_(e.env,t,e.adhdRoot);return{...rh(t),configPath:n}}const Lk=Object.freeze(Object.defineProperty({__proto__:null,addCitation:Up,addDependency:Kp,appendNote:Fp,archiveResolved:qp,assignItem:Dp,attachToPlan:Qp,auditTrail:th,blockers:Ip,claimItem:Cp,createItem:Ep,dependencyGraph:Pp,exportJson:eh,getItem:Sp,importFromMarkdown:Zp,linkRelated:zp,listItems:Op,mergeItems:Hp,migrationStatus:nh,readyItems:jp,releaseClaim:Mp,removeDependency:Gp,renderToMarkdown:Xp,renewClaim:Rp,resolveItem:Vp,setMigrationPhase:oh,setPriority:Yp,softDeleteItem:_p,splitItem:Jp,spotlight:Ap,staleClaims:Tp,startWork:Lp,stats:kp,supersedeItem:Wp,topoOrder:xp,transitionStatus:Bp,updateItem:Np},Symbol.toStringTag,{value:"Module"}));function As(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function sh(){if(!process.env.VITEST)return;const e=()=>{},t={info:e,error:e,debug:e,fatal:e,warn:e,trace:e};return t.child=()=>t,t}function ih(){const e=T.dirname(vr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:ke&&ke.tagName.toUpperCase()==="SCRIPT"&&ke.src||new URL("index.js",document.baseURI).href));return U.existsSync(T.join(e,"client.d.ts"))?e:T.join(e,"..","dist")}function zu(e){if(!e||typeof e!="object")return e;const t={},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 t||(t[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;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 t)?{}:r(t[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(e,new Set)}async function Bk(){const e=T.join(ih(),"client.d.ts");if(!U.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 VE({sourceFile:e,namespace:"backlog",dropFileSegment:!0})}async function Oa(e){const t=typeof e=="function"?e:()=>e,n=await Bk(),r={schemas:Object.fromEntries(n.filter(s=>s.kind==="action").map(s=>{var i;return[((i=s.path[s.path.length-1])==null?void 0:i.raw)??"",{input:zu(s.input),output:zu(s.output),hasCtx:s.hasCtx,safe:s.safe}]}))};return{pkg:{id:"backlog",schemas:mE(r,[]),importPath:T.join(ih(),"client.js"),fns:Lk,createClient:async()=>t()},operations:n}}async function ah(e){const t=Ki({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd});t.ensureDirs();const n=Ls(t.files.db,t.config.db.busyTimeoutMs),r={store:n,env:t},{pkg:o,operations:s}=await Oa(r),i=sh(),a=[];(e.transport==="http"||e.transport==="both")&&a.push(As(vN)({packages:[o],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[TN,Lu]},signal:e.signal,operations:s,logger:i})),(e.transport==="mcp"||e.transport==="both")&&a.push(As(ZO)({packages:[o],outputDir:"",options:{transport:"stdio",usePlugins:[Lu]},signal:e.signal,operations:s,logger:i}));try{await Promise.all(a)}finally{Bs(n)}}const zt=["claude","codex","opencode"],Uk={claude:".claude",codex:".codex",opencode:".opencode"};function ch(e,t){return t?T.join(e,".codex"):process.env.CODEX_HOME??T.join(e,".codex")}function Fk(e,t,n,r){if(t==="project")return T.join(n,Uk[e],"skills");const o=r??We.homedir();return e==="claude"?T.join(o,".claude","skills"):e==="codex"?T.join(ch(o,r),"skills"):T.join(o,".config","opencode","skills")}function Vk(){const e=T.dirname(vr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:ke&&ke.tagName.toUpperCase()==="SCRIPT"&&ke.src||new URL("index.js",document.baseURI).href)),t=T.join(e,"skill","SKILL.md");return U.existsSync(t)?t:T.join(e,"..","skill","SKILL.md")}function qk(e){let t="all",n="user";for(let o=0;o<e.length;o++){const s=e[o];if(s==="--host")t=e[++o]??"all";else if(s==="--scope")n=e[++o]??"user";else throw new Error(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project")throw new Error(`backlog install-skill: --scope must be "user" or "project", got "${n}"`);const r=t==="all"?[...zt]:[t];for(const o of r)if(!zt.includes(o))throw new Error(`backlog install-skill: --host must be one of ${zt.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function uh(e,t=process.cwd(),n){const{hosts:r,scope:o}=qk(e);return lh(r,o,t,n)}function lh(e,t,n,r){const o=Vk();if(!U.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const s=U.readFileSync(o,"utf8"),i=T.dirname(vr.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:ke&&ke.tagName.toUpperCase()==="SCRIPT"&&ke.src||new URL("index.js",document.baseURI).href)),a=T.join(i,"package.json"),c=U.existsSync(a)?a:T.join(i,"..","package.json"),u=JSON.parse(U.readFileSync(c,"utf8")),l=[];for(const f of e){const p=T.join(Fk(f,t,n,r),"backlog");U.mkdirSync(p,{recursive:!0});const h=T.join(p,"SKILL.md");U.writeFileSync(h,s,"utf8"),U.writeFileSync(T.join(p,"extension.json"),JSON.stringify({name:u.name,version:u.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
191
+ `,"utf8"),l.push({host:f,scope:t,path:h})}return l}async function fh(e){const t=uh(e);console.log(JSON.stringify({installed:t}))}const _a=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function Kk(e){if(!U.existsSync(e))return{};const t=U.readFileSync(e,"utf8").trim();if(t==="")return{};const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${e} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function dh(e,t,n,r){const o=Kk(e),s=o[t],i=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:{};i[n]=r,o[t]=i,U.mkdirSync(T.dirname(e),{recursive:!0}),U.writeFileSync(e,JSON.stringify(o,null,2)+`
192
+ `,"utf8")}function Gk(e,t,n){if(e==="project")return T.join(t,".mcp.json");const r=We.homedir();return T.join(r,".claude.json")}function zk(e,t,n){if(e==="project")return T.join(t,"opencode.json");const r=We.homedir();return T.join(r,".config","opencode","opencode.json")}function Wk(e,t,n){if(e==="project")return T.join(t,".codex","config.toml");const r=We.homedir();return T.join(ch(r,n),"config.toml")}function Jk(e,t,n){var u,l;const r=`[${t}]`,o=e.length>0?e.split(`
193
+ `):[],s=o.findIndex(f=>f.trim()===r),i=[r,...n];if(s===-1){if(o.length===0||o.every(f=>f.trim()===""))return i.join(`
194
+ `)+`
195
+ `;for(;o.length>0&&((u=o[o.length-1])==null?void 0:u.trim())==="";)o.pop();return[...o,"",...i].join(`
196
+ `)+`
197
+ `}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(`
198
+ `)+`
199
+ `}function Hk(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function Yk(e,t,n){const r=Gk(e,t);return dh(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[..._a]}),{host:"claude",scope:e,configPath:r,status:"written"}}function Qk(e,t,n){const r=zk(e,t);return dh(r,"mcp","backlog",{type:"local",command:["npx",..._a]}),{host:"opencode",scope:e,configPath:r,status:"written"}}function Zk(e,t,n){const r=Wk(e,t,n),o=U.existsSync(r)?U.readFileSync(r,"utf8"):"",s=Jk(o,"mcp_servers.backlog",['command = "npx"',`args = ${Hk(_a)}`]);return U.mkdirSync(T.dirname(r),{recursive:!0}),U.writeFileSync(r,s,"utf8"),{host:"codex",scope:e,configPath:r,status:"written"}}function Xk(e,t,n,r){return e==="claude"?Yk(t,n):e==="opencode"?Qk(t,n):Zk(t,n,r)}function eA(e,t){let n="all",r="user",o=!1,s=!1;for(let a=0;a<e.length;a++){const c=e[a];if(c==="--host")n=e[++a]??"all";else if(c==="--scope")r=e[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")s=!0;else throw new Error(`backlog ${t}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&s)throw new Error(`backlog ${t}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project")throw new Error(`backlog ${t}: --scope must be "user" or "project", got "${r}"`);const i=n==="all"?[...zt]:[n];for(const a of i)if(!zt.includes(a))throw new Error(`backlog ${t}: --host must be one of ${zt.join("|")}|all, got "${n}"`);return{hosts:i,scope:r,skillOnly:o,mcpOnly:s}}const tA=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
200
+
201
+ Installs the backlog skill AND registers the backlog MCP server into an agent
202
+ host's config, in one step.
203
+
204
+ --host <name> claude | opencode | codex | all (default: all)
205
+ --scope <name> user | project (default: user)
206
+ --skill-only only install the skill — never touch any MCP config
207
+ --mcp-only only register the MCP server — never touch any skill dir
208
+
209
+ Examples:
210
+ backlog install
211
+ backlog install --host claude --scope project
212
+ backlog install --mcp-only --host opencode
213
+
214
+ Back-compat: \`backlog install-skill\` remains available and behaves exactly
215
+ like \`backlog install --skill-only\` (original --host/--scope grammar only).
216
+ `;function nA(e,t=process.cwd(),n){const{hosts:r,scope:o,skillOnly:s,mcpOnly:i}=eA(e,"install"),a=i?[]:lh(r,o,t,n),c=s?[]:r.map(u=>Xk(u,o,t,n));return{skill:a,mcp:c}}async function rA(e){if(e[0]==="--help"||e[0]==="-h"){console.log(tA);return}const t=nA(e);for(const n of t.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of t.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(t))}function oA(e){let t="mcp",n,r;for(let s=0;s<e.length;s++){const i=e[s];if(i==="--transport")t=e[++s];else if(i==="--port")n=Number(e[++s]);else if(i==="--host")r=e[++s];else throw new Error(`backlog serve: unknown argument "${i}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new Error(`backlog serve: --transport must be mcp|http|both, got "${t}"`);const o={transport:t};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function ph(e,t={}){const n=oA(e),r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort()),await ah({...n,...t,signal:r.signal})}function hh(e){const t=e.find(n=>n.kind==="action");if(!t)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return rg(t).cli.path.slice(0,-1)}function mh(e,t){var r;return e.length===0?[...e]:(r=e[0])!=null&&r.startsWith("-")?[...e]:t.length>0&&t.every((o,s)=>e[s]===o)?[...e]:[...t,...e]}async function gh(e,t={}){const n=e??process.argv.slice(2);if(n[0]==="install-skill"){await fh(n.slice(1));return}if(n[0]==="install"){await rA(n.slice(1));return}if(n[0]==="serve"){await ph(n.slice(1),t);return}let r;const o=()=>{if(!r){const s=Ki({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd});s.ensureDirs();const i=Ls(s.files.db,s.config.db.busyTimeoutMs);r={store:i,ctx:{store:i,env:s}}}return r.ctx};try{const{pkg:s,operations:i}=await Oa(o),a=n,c=hh(i);await As(Zm)({packages:[s],operations:i,outputDir:"",options:{argv:mh(a,c)},signal:t.signal??new AbortController().signal,logger:sh()})}finally{r&&Bs(r.store)}}process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:ke&&ke.tagName.toUpperCase()==="SCRIPT"&&ke.src||new URL("index.js",document.baseURI).href)===vr.pathToFileURL(U.realpathSync(process.argv[1])).href&&gh().catch(e=>{console.error(e instanceof Error?e.stack??e.message:String(e)),process.exitCode=1});exports.BacklogItemNotFoundError=Wd;exports.CitationRequiredError=Jd;exports.ClaimHeldError=Yd;exports.DependencyCycleError=R_;exports.ReasonRequiredError=Hd;exports.TERMINAL_DISMISSED_STATUSES=zd;exports.TERMINAL_DONE_STATUSES=Kd;exports.TERMINAL_STATUSES=$a;exports.TERMINAL_WORKAROUND_STATUSES=Gd;exports.addCitation=Up;exports.addDependency=Kp;exports.appendNote=Fp;exports.archiveResolved=qp;exports.assignItem=Dp;exports.attachToPlan=Qp;exports.auditTrail=th;exports.backlogEnvironmentSpec=ud;exports.blockers=Ip;exports.buildBacklogApigenPackage=Oa;exports.buildBacklogEnv=Ki;exports.buildChangelogSection=wp;exports.claimItem=Cp;exports.classifyStatus=pp;exports.closeGraphBacklogStore=Bs;exports.createItem=Ep;exports.dependencyGraph=Pp;exports.detectPriority=mp;exports.detectStatus=hp;exports.exportJson=eh;exports.getItem=Sp;exports.importFromMarkdown=Zp;exports.installSkill=uh;exports.isTerminalStatus=Le;exports.linkRelated=zp;exports.listItems=Op;exports.mergeItems=Hp;exports.migrationStatus=nh;exports.normalizeLegacyStatus=dp;exports.openGraphBacklogStore=Ls;exports.parseBacklogMarkdown=xk;exports.parseBacklogMarkdownWithDiagnostics=yp;exports.prefixCommand=mh;exports.readyItems=jp;exports.releaseClaim=Mp;exports.removeDependency=Gp;exports.renderItemsToMarkdown=vp;exports.renderToMarkdown=Xp;exports.renewClaim=Rp;exports.requiresCitation=yr;exports.requiresReason=$r;exports.resolveBacklogScope=ld;exports.resolveCommandPrefix=hh;exports.resolveItem=Vp;exports.runBacklogCli=gh;exports.runInstallSkillCommand=fh;exports.runServeCommand=ph;exports.setMigrationPhase=oh;exports.setPriority=Yp;exports.softDeleteItem=_p;exports.splitItem=Jp;exports.spotlight=Ap;exports.staleClaims=Tp;exports.startBacklogServer=ah;exports.startWork=Lp;exports.stats=kp;exports.suggestClaimantIdentity=iE;exports.supersedeItem=Wp;exports.toImportItems=bp;exports.topoOrder=xp;exports.transitionStatus=Bp;exports.updateItem=Np;