@aviaratech/ai-delivery 0.3.24 → 0.3.25
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/CONTRIBUTING.md +157 -16
- package/README.md +20 -0
- package/dist/agentReadiness.test.d.ts +1 -0
- package/dist/agentReadiness.test.js +139 -0
- package/dist/agentReadiness.test.js.map +1 -0
- package/dist/cli.js +16 -5
- package/dist/cli.js.map +1 -1
- package/dist/contributorChecks.test.d.ts +1 -0
- package/dist/contributorChecks.test.js +1010 -0
- package/dist/contributorChecks.test.js.map +1 -0
- package/dist/currentConsumer.test.d.ts +1 -0
- package/dist/currentConsumer.test.js +832 -0
- package/dist/currentConsumer.test.js.map +1 -0
- package/dist/dependencyCompatibility.test.d.ts +1 -0
- package/dist/dependencyCompatibility.test.js +175 -0
- package/dist/dependencyCompatibility.test.js.map +1 -0
- package/dist/directoryIndependent.test.js +91 -1
- package/dist/directoryIndependent.test.js.map +1 -1
- package/dist/dispatch.js +6 -0
- package/dist/dispatch.js.map +1 -1
- package/dist/issue.d.ts +7 -0
- package/dist/issue.js +1 -1
- package/dist/issue.js.map +1 -1
- package/dist/issueJournal.test.js +88 -6
- package/dist/issueJournal.test.js.map +1 -1
- package/dist/mcp/tools.d.ts +7 -1
- package/dist/mcp/tools.js +20 -2
- package/dist/mcp/tools.js.map +1 -1
- package/dist/pluginInstaller.js +8 -2
- package/dist/pluginInstaller.js.map +1 -1
- package/dist/pluginInstaller.test.js +213 -2
- package/dist/pluginInstaller.test.js.map +1 -1
- package/dist/pluginPackaging.test.js +100 -6
- package/dist/pluginPackaging.test.js.map +1 -1
- package/dist/pr.d.ts +20 -13
- package/dist/pr.js +638 -66
- package/dist/pr.js.map +1 -1
- package/dist/pr.test.js +166 -7
- package/dist/pr.test.js.map +1 -1
- package/dist/prAssociation.test.d.ts +1 -0
- package/dist/prAssociation.test.js +1336 -0
- package/dist/prAssociation.test.js.map +1 -0
- package/dist/prDispatch.test.d.ts +1 -0
- package/dist/prDispatch.test.js +96 -0
- package/dist/prDispatch.test.js.map +1 -0
- package/dist/releaseReconciliation.test.js +6 -2
- package/dist/releaseReconciliation.test.js.map +1 -1
- package/dist/releaseWorkflow.test.d.ts +1 -0
- package/dist/releaseWorkflow.test.js +447 -0
- package/dist/releaseWorkflow.test.js.map +1 -0
- package/dist/services/agentReadinessService.js +2 -1
- package/dist/services/agentReadinessService.js.map +1 -1
- package/dist/stagedChecks.test.d.ts +1 -0
- package/dist/stagedChecks.test.js +228 -0
- package/dist/stagedChecks.test.js.map +1 -0
- package/package.json +9 -6
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +1 -1
- package/plugins/ai-delivery/runtime/dist/cli.js +40 -40
- package/plugins/ai-delivery/runtime/package.json +1 -1
|
@@ -71,16 +71,16 @@ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let
|
|
|
71
71
|
|
|
72
72
|
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=dt,c=!cn.jitless,l=c&&ft.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Gi([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Ji(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!jt(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>It(e,r,ln())))}),t)}var Yi=k(`$ZodUnion`,(e,t)=>{Wr.init(e,t),Zt(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),Zt(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Zt(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Zt(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Qe(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Ji(t,r,e,i)):Ji(o,r,e,i)}});function Xi(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}var Zi=k(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Yi.init(e,t);let n=e._zod.parse;Zt(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||et(t,e,new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=tt(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=Xe(()=>Xi(t));e._zod.parse=(i,a)=>{let o=i.value;if(!dt(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Qi=k(`$ZodIntersection`,(e,t)=>{Wr.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>ea(e,t,n)):ea(e,i,a)}});function $i(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(pt(e)&&pt(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=$i(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=$i(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ea(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=$i(t.value,n.value);if(!c.valid){if(jt(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var ta=k(`$ZodTuple`,(e,t)=>{Wr.init(e,t);let n=t.items,r=cn.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=na(n,`optin`),l=na(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=jt(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(jt(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>ra(t,i,e))):ra(r,i,e)}}return s.length?Promise.all(s).then(()=>ia(u,i,n,o,l)):ia(u,i,n,o,l)}});function na(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function ra(e,t,n){e.issues.length&&t.issues.push(...Nt(n,e.issues)),t.value[n]=e.value}function ia(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...Nt(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var aa=k(`$ZodRecord`,(e,t)=>{Wr.init(e,t);let n=cn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!pt(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>It(e,i,ln())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Nt(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Nt(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&yr.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>It(e,i,ln())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Nt(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Nt(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),oa=k(`$ZodEnum`,(e,t)=>{Wr.init(e,t);let n=Ke(t.entries),r=new Set(n);e._zod.values=r,Zt(e,`pattern`,e=>{let t=Ke(e.def.entries).filter(e=>ht.has(typeof e));return RegExp(t.length?`^(${t.map(e=>gt(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),sa=k(`$ZodLiteral`,(e,t)=>{Wr.init(e,t);let n=new Set(t.values);e._zod.values=n,Zt(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?gt(e):e?gt(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),ca=k(`$ZodTransform`,(e,t)=>{Wr.init(e,t),e._zod.optin=`optional`,cn.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new sn(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new on;return n.value=i,n}});function la(e,t){return e.value=t.issues.length?void 0:t.value,e}var ua=k(`$ZodOptional`,(e,t)=>{Wr.init(e,t),Zt(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,Zt(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Zt(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Qe(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>la(e,t)):la(e,r)}return t.innerType._zod.run(e,n)}}),da=k(`$ZodExactOptional`,(e,t)=>{ua.init(e,t),Zt(e,`values`,e=>e.def.innerType._zod.values),Zt(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),fa=k(`$ZodNullable`,(e,t)=>{Wr.init(e,t),Zt(e,`optin`,e=>e.def.innerType._zod.optin),Zt(e,`optout`,e=>e.def.innerType._zod.optout),Zt(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Qe(t.source)}|null)$`):void 0}),Zt(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),pa=k(`$ZodDefault`,(e,t)=>{Wr.init(e,t),e._zod.optin=`defaulted`,Zt(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ma(e,t)):ma(r,t)}});function ma(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ha=k(`$ZodPrefault`,(e,t)=>{Wr.init(e,t),e._zod.optin=`defaulted`,Zt(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ga=k(`$ZodNonOptional`,(e,t)=>{Wr.init(e,t),Zt(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>_a(t,e)):_a(i,e)}});function _a(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function va(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>It(e,r,ln()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var ya=k(`$ZodCatch`,(e,t)=>{Wr.init(e,t),Zt(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),Zt(e,`optout`,e=>e.def.innerType._zod.optout),Zt(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>va(e,r,t,n)):va(e,r,t,n)}}),ba=k(`$ZodPipe`,(e,t)=>{Wr.init(e,t),Zt(e,`values`,e=>e.def.in._zod.values),Zt(e,`optin`,e=>e.def.in._zod.optin),Zt(e,`optout`,e=>e.def.out._zod.optout),Zt(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>xa(e,t.in,n)):xa(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>xa(e,t.out,n)):xa(r,t.out,n)}});function xa(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var Sa=k(`$ZodPreprocess`,(e,t)=>{ba.init(e,t)}),Ca=k(`$ZodReadonly`,(e,t)=>{Wr.init(e,t),Zt(e,`propValues`,e=>e.def.innerType._zod.propValues),Zt(e,`values`,e=>e.def.innerType._zod.values),Zt(e,`optin`,e=>e.def.innerType?._zod?.optin),Zt(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(wa):wa(r)}});function wa(e){return e.memo||(e.value=Object.freeze(e.value)),e}var Ta=k(`$ZodCustom`,(e,t)=>{wr.init(e,t),Wr.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ea(t,n,r,e));Ea(i,n,r,e)}});function Ea(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Vt(e))}}var Da=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Oa=`~memo`,ka=[];function Aa(e){return typeof e==`object`&&!!e}function ja(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var Ma=new WeakMap,Na=0,Pa=1,Fa=2;function Ia(e,t,n){let r=Ma.get(e);if(r!==void 0)return r?Fa:Na;if(t.has(e))return Fa;t.add(e);let i=Na,a=e=>{if(i!==Fa&&e?._zod){let r=Ia(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=Na;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?Pa:o.value?._zod?Ia(o.value,t,n):Na;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=tt(c);s(e?o(e,!0):Pa),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Ia(r,t,!1):Pa);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),La(e,i)}function La(e,t){return t!==Pa&&Ma.set(e,t===Fa),t}function Ra(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var za,Ba=[],Va={alloc(e,t,n){let r=za;if(!r)return n;za=void 0;let i={value:n,issues:null};return r.set(t.value,i),Ba.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Ua(n,e.value))throw new Da;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Ia(e,new Set,!1);if(i===Na)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Fa||r?n=!0:r=!0}let l=s.value;if(!Aa(l))return t(s,c);let u=c[Oa];u||(u={buckets:new WeakMap,backEdges:void 0},c[Oa]=u);let d;i===c?d=a:(d=Ra(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...ja(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;za=d;let p=Ba.length,m=t(s,c);za=void 0;let h=Ba.length>p?Ba.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?ja(e.issues):ka),e)):(h&&(h.issues=m.issues.length?ja(m.issues):ka),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function Ha(){return Va}function Ua(e,t){let n=e[Oa]?.backEdges;return n!==void 0&&Aa(t)&&n.has(t)}var Wa=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(Bt(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${vt(e.values[0])}`:`Invalid option: expected one of ${qe(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${qe(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Ga(){return{localeError:Wa()}}var Ka,qa=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ja(){return new qa}(Ka=globalThis).__zod_globalRegistry??(Ka.__zod_globalRegistry=Ja());var Ya=globalThis.__zod_globalRegistry;function Xa(e){return e.checks&&=[...e.checks],e}function Za(e,t){return new e(Xa({type:`string`,...O(t)}))}function Qa(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...O(t)})}function $a(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...O(t)})}function eo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...O(t)})}function to(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...O(t)})}function no(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...O(t)})}function ro(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...O(t)})}function io(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...O(t)})}function ao(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...O(t)})}function oo(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...O(t)})}function so(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...O(t)})}function co(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...O(t)})}function lo(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...O(t)})}function uo(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...O(t)})}function fo(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...O(t)})}function po(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...O(t)})}function mo(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...O(t)})}function ho(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...O(t)})}function go(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...O(t)})}function _o(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...O(t)})}function vo(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...O(t)})}function yo(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...O(t)})}function bo(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...O(t)})}function xo(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...O(t)})}function So(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...O(t)})}function Co(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...O(t)})}function wo(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...O(t)})}function To(e,t){return new e(Xa({type:`number`,checks:[],...O(t)}))}function Eo(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...O(t)})}function Do(e,t){return new e({type:`boolean`,...O(t)})}function Oo(e,t){return new e({type:`null`,...O(t)})}function ko(e){return new e({type:`unknown`})}function Ao(e,t){return new e({type:`never`,...O(t)})}function jo(e,t){return new Dr({check:`less_than`,...O(t),value:e,inclusive:!1})}function Mo(e,t){return new Dr({check:`less_than`,...O(t),value:e,inclusive:!0})}function No(e,t){return new Or({check:`greater_than`,...O(t),value:e,inclusive:!1})}function Po(e,t){return new Or({check:`greater_than`,...O(t),value:e,inclusive:!0})}function Fo(e,t){return new kr({check:`multiple_of`,...O(t),value:e})}function Io(e,t){return new jr({check:`max_length`,...O(t),maximum:e})}function Lo(e,t){return new Mr({check:`min_length`,...O(t),minimum:e})}function Ro(e,t){return new Nr({check:`length_equals`,...O(t),length:e})}function zo(e,t){return new Fr({check:`string_format`,format:`regex`,...O(t),pattern:e})}function Bo(e){return new Ir({check:`string_format`,format:`lowercase`,...O(e)})}function Vo(e){return new Lr({check:`string_format`,format:`uppercase`,...O(e)})}function Ho(e,t){return new Rr({check:`string_format`,format:`includes`,...O(t),includes:e})}function Uo(e,t){return new zr({check:`string_format`,format:`starts_with`,...O(t),prefix:e})}function Wo(e,t){return new Br({check:`string_format`,format:`ends_with`,...O(t),suffix:e})}function Go(e){return new Vr({check:`overwrite`,tx:e})}function Ko(e){return Go(t=>t.normalize(e))}function qo(){return Go(e=>e.trim())}function Jo(){return Go(e=>e.toLowerCase())}function Yo(){return Go(e=>e.toUpperCase())}function Xo(){return Go(e=>lt(e))}function Zo(e,t,n){return new e({type:`array`,element:t,...O(n)})}function Qo(e,t,n){let r=O(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function $o(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...O(n)})}function es(e,t){let n=ts(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Vt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Vt(r))}},e(t.value,t)),t);return n}function ts(e,t){let n=new wr({check:`custom`,...O(t)});return n._zod.check=e,n}function ns(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&et(e,t,n[t]);return e}function rs(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Ya,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function is(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function as(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,as(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&ns(o.schema,c),t.io===`input`&&hs(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function os(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ss(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${os(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+os(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
73
73
|
|
|
74
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function cs(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;cs(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ls=new Set([`type`,`properties`,`required`,`additionalProperties`]),us=[`oneOf`,`anyOf`];function ds(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function fs(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ls.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??ds(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}et(n,r,e.length===1?e[0]:fs(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=ds(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ps(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ls)if(t in e)return;let n=t.filter(e=>us.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=fs(t);else{let e=n[0],i=us.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>fs([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,ns(e,r))}function ms(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):ns(i,s),ns(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())cs(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ps(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}ns(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,et(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:_s(t,`input`,e.processors),output:_s(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function hs(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return hs(r.element,n);if(r.type===`set`)return hs(r.valueType,n);if(r.type===`lazy`)return hs(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return hs(r.innerType,n);if(r.type===`intersection`)return hs(r.left,n)||hs(r.right,n);if(r.type===`record`||r.type===`map`)return hs(r.keyType,n)||hs(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:hs(r.in,n)||hs(r.out,n);if(r.type===`object`){for(let e in r.shape)if(hs(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(hs(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(hs(e,n))return!0;return!!(r.rest&&hs(r.rest,n))}return!1}var gs=(e,t={})=>n=>{let r=rs({...n,processors:t});return as(e,r),ss(r,e),ms(r,e)},_s=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=rs({...i??{},target:a,io:t,processors:n});return as(e,o),ss(o,e),ms(o,e)},vs=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},ys=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},bs=(e,t)=>{vs(e,`minimum`,t),ys(e,`maximum`,t)},xs=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Ss=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},Cs=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},ws=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Ts=(e,t)=>vs(e,`minimum`,t.minimum),Es=(e,t)=>ys(e,`maximum`,t.maximum),Ds=e=>(t,n)=>{ws(t,n.format);let[r,i]=e[n.format];vs(t,`minimum`,r),ys(t,`maximum`,i)},Os={greater_than:(e,t)=>vs(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>ys(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>xs(e,t.value),number_format:Ds(bt),bigint_format:Ds(xt),min_length:Ts,max_length:Es,length_equals:(e,t)=>bs(e,t.length),min_size:Ts,max_size:Es,size_equals:(e,t)=>bs(e,t.size),string_format:(e,t)=>{ws(e,t.format),t.pattern&&Ss(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Cs(e,t.mime)};function ks(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Os[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&vs(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&vs(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&ys(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&ys(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&xs(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Cs(t,i.mime);for(let e of i.patterns??[])Ss(t,e);return t}var As={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},js=new Map([[Ei,sr],[Oi,cr]]),Ms=e=>js.get(e)??e,Ns=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=ks(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=As[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Ms);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Ps=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ks(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):is(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Fs=(e,t,n,r)=>{n.type=`boolean`},Is=(e,t,n,r)=>{is(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},Ls=(e,t,n,r)=>{is(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},Rs=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},zs=(e,t,n,r)=>{is(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},Bs=(e,t,n,r)=>{is(e,t,n,r,`Void cannot be represented in JSON Schema`)},Vs=(e,t,n,r)=>{n.not={}},Hs=(e,t,n,r)=>{},Us=(e,t,n,r)=>{},Ws=(e,t,n,r)=>{is(e,t,n,r,`Date cannot be represented in JSON Schema`)},Gs=(e,t,n,r)=>{let i=e._zod.def,a=Ke(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ks=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(is(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(is(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},qs=(e,t,n,r)=>{is(e,t,n,r,`NaN cannot be represented in JSON Schema`)},Js=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ys=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=ks(e);a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),s&&(s.length===0?i.not={}:s.length===1?i.contentMediaType=s[0]:i.anyOf=s.map(e=>({contentMediaType:e})))},Xs=(e,t,n,r)=>{n.type=`boolean`},Zs=(e,t,n,r)=>{is(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Qs=(e,t,n,r)=>{is(e,t,n,r,`Function types cannot be represented in JSON Schema`)},$s=(e,t,n,r)=>{is(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ec=(e,t,n,r)=>{is(e,t,n,r,`Map cannot be represented in JSON Schema`)},tc=(e,t,n,r)=>{is(e,t,n,r,`Set cannot be represented in JSON Schema`)},nc=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=ks(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=as(a.element,t,{...r,path:[...r.path,`items`]})};function rc(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?rc(t.out):t.type===`catch`?rc(t.innerType):e._zod.optin}var ic=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&is(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)et(i.properties,e,as(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?rc(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=as(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ac=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>as(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},oc=(e,t,n,r)=>{let i=e._zod.def,a=as(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=as(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},sc=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>as(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?as(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?rc(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=ks(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function cc(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=cc(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>cc(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?yr:vr).source),p):p}var lc=new WeakMap;function uc(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of lc.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=cc(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var dc=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=ks(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=as(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)et(i.patternProperties,Ms(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=as(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=lc.get(t);n||(n=[],lc.set(t,n),t.deferred.push(()=>uc(t))),n.push(e)}i.additionalProperties=as(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&rc(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},fc=(e,t,n,r)=>{let i=e._zod.def,a=as(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},pc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},mc=Symbol();function hc(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(is(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),mc):JSON.parse(o)}var gc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=hc(i.defaultValue,e,t,n,r);o!==mc&&(n.default=o)},_c=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=hc(i.defaultValue,e,t,n,r);o!==mc&&(n._prefault=o)},vc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{is(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},yc=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;as(o,t,r);let s=t.seen.get(e);s.ref=o},bc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},xc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Sc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Cc={string:Ns,number:Ps,boolean:Fs,bigint:Is,symbol:Ls,null:Rs,undefined:zs,void:Bs,never:Vs,any:Hs,unknown:Us,date:Ws,enum:Gs,literal:Ks,nan:qs,template_literal:Js,file:Ys,success:Xs,custom:Zs,function:Qs,transform:$s,map:ec,set:tc,array:nc,object:ic,union:ac,intersection:oc,tuple:sc,record:dc,nullable:fc,nonoptional:pc,default:gc,prefault:_c,catch:vc,pipe:yc,readonly:bc,promise:xc,optional:Sc,lazy:(e,t,n,r)=>{let i=e._zod.innerType;as(i,t,r);let a=t.seen.get(e);a.ref=i}};function wc(e,t){if(`_idmap`in e){let n=e,r=rs({...t,processors:Cc}),i={};for(let e of n._idmap.entries()){let[t,n]=e;as(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;ss(r,n),et(a,t,ms(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=rs({...t,processors:Cc});return as(e,n),ss(n,e),ms(n,e)}var Tc=new WeakSet([Object.prototype,Error.prototype]);function Ec(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Dc=k(`ZodError`,(e,t)=>{gn.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Tc.has(n)||(Tc.add(n),Ec(n,`format`,e=>t=>bn(e,t)),Ec(n,`flatten`,e=>t=>yn(e,t)),Ec(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Je,2)}),Ec(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Je,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Oc=Sn(Dc),kc=wn(Dc),Ac=En(Dc),jc=kn(Dc),Mc=In(Dc),Nc=Ln(Dc),Pc=Rn(Dc),Fc=zn(Dc),Ic=Bn(Dc),Lc=Vn(Dc),Rc=Hn(Dc),zc=Un(Dc);function Bc(){cn.localeError||ln(Ga())}function Vc(){cn.memoizer||ln({memoizer:Ha()})}var Hc=k(`ZodType`,(e,t)=>(Bc(),Wr.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(st(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return _t(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(fu(e,t))},superRefine(e,t){return this.check(pu(e,t))},overwrite(e){return this.check(Go(e))},optional(){return Kl(this)},exactOptional(){return Jl(this)},nullable(){return Xl(this)},nullish(){return Kl(Xl(this))},nonoptional(e){return nu(this,e)},array(){return M(this)},or(e){return Ml([this,e])},and(e){return Il(this,e)},transform(e){return ou(this,Wl(e))},default(e){return Ql(this,e)},prefault(e){return eu(this,e)},catch(e){return iu(this,e)},pipe(e){return ou(this,e)},readonly(){return lu(this)},describe(e){let t=this.clone();return Ya.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ya.get(this);let t=this.clone();return Ya.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Wt(this,`~standard`,{...qr(this),jsonSchema:{input:_s(this,`input`),output:_s(this,`output`)}})},set"~standard"(e){Ut(this,`~standard`,e)},parse:function e(t,n){return Oc(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await kc(this,t,n,{callee:e})},safeParse(e,t){return Ac(this,e,t)},async safeParseAsync(e,t){return jc(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ut(this,`spa`,e)},validate(e,t){return Nn(this,e,t)},validateAsync(e,t){return Fn(this,e,t)},encode:function e(t,n){return Mc(this,t,n,{callee:e})},decode:function e(t,n){return Nc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Pc(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Fc(this,t,n,{callee:e})},safeEncode(e,t){return Ic(this,e,t)},safeDecode(e,t){return Lc(this,e,t)},async safeEncodeAsync(e,t){return Rc(this,e,t)},async safeDecodeAsync(e,t){return zc(this,e,t)},toJSONSchema(e){return gs(this,{})(e)},get description(){return Ya.get(this)?.description},get _def(){return this._zod.def}}),Uc=k(`_ZodString`,(e,t)=>{Jr.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ns(e,t,n,r)},Gt({format:e=>ks(e).format??null,minLength:e=>ks(e).minimum??null,maxLength:e=>ks(e).maximum??null},{regex(...e){return this.check(zo(...e))},includes(...e){return this.check(Ho(...e))},startsWith(...e){return this.check(Uo(...e))},endsWith(...e){return this.check(Wo(...e))},min(...e){return this.check(Lo(...e))},max(...e){return this.check(Io(...e))},length(...e){return this.check(Ro(...e))},nonempty(...e){return this.check(Lo(1,...e))},lowercase(e){return this.check(Bo(e))},uppercase(e){return this.check(Vo(e))},trim(){return this.check(qo())},normalize(...e){return this.check(Ko(...e))},toLowerCase(){return this.check(Jo())},toUpperCase(){return this.check(Yo())},slugify(){return this.check(Xo())}})),Wc=k(`ZodString`,(e,t)=>{Jr.init(e,t),Uc.init(e,t)},{email(e){return this.check(Qa(Xc,e))},url(e){return this.check(io(el,e))},jwt(e){return this.check(bo(gl,e))},emoji(e){return this.check(ao(nl,e))},guid(e){return this.check($a(Zc,e))},uuid(e){return this.check(eo(Qc,e))},uuidv4(e){return this.check(to(Qc,e))},uuidv6(e){return this.check(no(Qc,e))},uuidv7(e){return this.check(ro(Qc,e))},nanoid(e){return this.check(oo(rl,e))},cuid(e){return this.check(so(il,e))},cuid2(e){return this.check(co(al,e))},ulid(e){return this.check(lo(ol,e))},base64(e){return this.check(_o(pl,e))},base64url(e){return this.check(vo(ml,e))},xid(e){return this.check(uo(sl,e))},ksuid(e){return this.check(fo(cl,e))},ipv4(e){return this.check(po(ll,e))},ipv6(e){return this.check(mo(ul,e))},cidrv4(e){return this.check(ho(dl,e))},cidrv6(e){return this.check(go(fl,e))},e164(e){return this.check(yo(hl,e))},datetime(e){return this.check(xo(Kc,e))},date(e){return this.check(So(qc,e))},time(e){return this.check(Co(Jc,e))},duration(e){return this.check(wo(Yc,e))}});function A(e){return Za(Wc,e)}var Gc=k(`ZodStringFormat`,(e,t)=>{Yr.init(e,t),Uc.init(e,t)}),Kc=k(`ZodISODateTime`,(e,t)=>{mi.init(e,t),Gc.init(e,t)}),qc=k(`ZodISODate`,(e,t)=>{hi.init(e,t),Gc.init(e,t)}),Jc=k(`ZodISOTime`,(e,t)=>{gi.init(e,t),Gc.init(e,t)}),Yc=k(`ZodISODuration`,(e,t)=>{_i.init(e,t),Gc.init(e,t)}),Xc=k(`ZodEmail`,(e,t)=>{Qr.init(e,t),Gc.init(e,t)}),Zc=k(`ZodGUID`,(e,t)=>{Xr.init(e,t),Gc.init(e,t)}),Qc=k(`ZodUUID`,(e,t)=>{Zr.init(e,t),Gc.init(e,t)});function $c(e){return eo(Qc,e)}var el=k(`ZodURL`,(e,t)=>{oi.init(e,t),Gc.init(e,t)});function tl(e){return io(el,e)}var nl=k(`ZodEmoji`,(e,t)=>{si.init(e,t),Gc.init(e,t)}),rl=k(`ZodNanoID`,(e,t)=>{ci.init(e,t),Gc.init(e,t)}),il=k(`ZodCUID`,(e,t)=>{li.init(e,t),Gc.init(e,t)}),al=k(`ZodCUID2`,(e,t)=>{ui.init(e,t),Gc.init(e,t)}),ol=k(`ZodULID`,(e,t)=>{di.init(e,t),Gc.init(e,t)}),sl=k(`ZodXID`,(e,t)=>{fi.init(e,t),Gc.init(e,t)}),cl=k(`ZodKSUID`,(e,t)=>{pi.init(e,t),Gc.init(e,t)}),ll=k(`ZodIPv4`,(e,t)=>{vi.init(e,t),Gc.init(e,t)}),ul=k(`ZodIPv6`,(e,t)=>{xi.init(e,t),Gc.init(e,t)}),dl=k(`ZodCIDRv4`,(e,t)=>{Si.init(e,t),Gc.init(e,t)}),fl=k(`ZodCIDRv6`,(e,t)=>{wi.init(e,t),Gc.init(e,t)}),pl=k(`ZodBase64`,(e,t)=>{Di.init(e,t),Gc.init(e,t)}),ml=k(`ZodBase64URL`,(e,t)=>{Ai.init(e,t),Gc.init(e,t)}),hl=k(`ZodE164`,(e,t)=>{ji.init(e,t),Gc.init(e,t)}),gl=k(`ZodJWT`,(e,t)=>{Ni.init(e,t),Gc.init(e,t)}),_l=k(`ZodNumber`,(e,t)=>{Pi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ps(e,t,n,r),e.isFinite=!0},Gt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=ks(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=ks(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=ks(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>ks(e).format??null},{gt(e,t){return this.check(No(e,t))},gte(e,t){return this.check(Po(e,t))},min(e,t){return this.check(Po(e,t))},lt(e,t){return this.check(jo(e,t))},lte(e,t){return this.check(Mo(e,t))},max(e,t){return this.check(Mo(e,t))},int(e){return this.check(yl(e))},safe(e){return this.check(yl(e))},positive(e){return this.check(No(0,e))},nonnegative(e){return this.check(Po(0,e))},negative(e){return this.check(jo(0,e))},nonpositive(e){return this.check(Mo(0,e))},multipleOf(e,t){return this.check(Fo(e,t))},step(e,t){return this.check(Fo(e,t))},finite(){return this}}));function j(e){return To(_l,e)}var vl=k(`ZodNumberFormat`,(e,t)=>{Fi.init(e,t),_l.init(e,t)});function yl(e){return Eo(vl,e)}var bl=k(`ZodBoolean`,(e,t)=>{Ii.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fs(e,t,n,r)});function xl(e){return Do(bl,e)}var Sl=k(`ZodNull`,(e,t)=>{Li.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r)});function Cl(e){return Oo(Sl,e)}var wl=k(`ZodUnknown`,(e,t)=>{Ri.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Tl(){return ko(wl)}var El=k(`ZodNever`,(e,t)=>{zi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vs(e,t,n,r)});function Dl(e){return Ao(El,e)}var Ol=k(`ZodArray`,(e,t)=>{Vc(),Vi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nc(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Lo(e,t))},nonempty(e){return this.check(Lo(1,e))},max(e,t){return this.check(Io(e,t))},length(e,t){return this.check(Ro(e,t))},unwrap(){return this.element}});function M(e,t){return Zo(Ol,e,t)}var kl=k(`ZodObject`,(e,t)=>{Vc(),qi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ic(e,t,n,r),Qt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return F(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(st(this._zod.def,{catchall:e}))},passthrough(){return this.clone(st(this._zod.def,{catchall:Tl()}))},loose(){return this.clone(st(this._zod.def,{catchall:Tl()}))},strict(){return this.clone(st(this._zod.def,{catchall:Dl()}))},strip(){return this.clone(st(this._zod.def,{catchall:void 0}))},extend(e){return Tt(this,e)},safeExtend(e){return Dt(this,e)},merge(e){return Ot(this,e)},pick(e){return St(this,e)},omit(e){return wt(this,e)},partial(...e){return kt(Gl,this,e[0])},exactPartial(...e){return kt(ql,this,e[0],`exactPartial`)},required(...e){return At(tu,this,e[0])}});function N(e,t){return new kl({type:`object`,shape:e??{},...O(t)})}function P(e,t){return new kl({type:`object`,shape:e,catchall:Dl(),...O(t)})}function Al(e,t){return new kl({type:`object`,shape:e,catchall:Tl(),...O(t)})}var jl=k(`ZodUnion`,(e,t)=>{Yi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ac(e,t,n,r),e.options=t.options});function Ml(e,t){return new jl({type:`union`,options:e,...O(t)})}var Nl=k(`ZodDiscriminatedUnion`,(e,t)=>{jl.init(e,t),Zi.init(e,t)});function Pl(e,t,n){return new Nl({type:`union`,options:t,discriminator:e,...O(n)})}var Fl=k(`ZodIntersection`,(e,t)=>{Qi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oc(e,t,n,r)});function Il(e,t){return new Fl({type:`intersection`,left:e,right:t})}var Ll=k(`ZodTuple`,(e,t)=>{Vc(),ta.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sc(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Gl({type:`optional`,innerType:e}))})}});function Rl(e,t,n){let r=t instanceof Wr;return new Ll({type:`tuple`,items:e,rest:r?t:null,...O(r?n:t)})}var zl=k(`ZodRecord`,(e,t)=>{Vc(),aa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dc(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Bl(e,t,n){return!t||!t._zod?new zl({type:`record`,keyType:A(),valueType:e,...O(t)}):new zl({type:`record`,keyType:e,valueType:t,...O(n)})}var Vl=k(`ZodEnum`,(e,t)=>{oa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gs(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Vl({...t,checks:[],...O(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Vl({...t,checks:[],...O(r),entries:i})}});function F(e,t){return new Vl({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...O(t)})}var Hl=k(`ZodLiteral`,(e,t)=>{sa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ks(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function I(e,t){return new Hl({type:`literal`,values:Array.isArray(e)?e:[e],...O(t)})}var Ul=k(`ZodTransform`,(e,t)=>{Vc(),ca.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$s(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new sn(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Vt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Vt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Wl(e){return new Ul({type:`transform`,transform:e})}var Gl=k(`ZodOptional`,(e,t)=>{ua.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Kl(e){return new Gl({type:`optional`,innerType:e})}var ql=k(`ZodExactOptional`,(e,t)=>{da.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Jl(e){return new ql({type:`optional`,innerType:e})}var Yl=k(`ZodNullable`,(e,t)=>{fa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xl(e){return new Yl({type:`nullable`,innerType:e})}var Zl=k(`ZodDefault`,(e,t)=>{pa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ql(e,t){return new Zl({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():mt(t)}})}var $l=k(`ZodPrefault`,(e,t)=>{ha.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_c(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function eu(e,t){return new $l({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():mt(t)}})}var tu=k(`ZodNonOptional`,(e,t)=>{ga.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nu(e,t){return new tu({type:`nonoptional`,innerType:e,...O(t)})}var ru=k(`ZodCatch`,(e,t)=>{ya.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function iu(e,t){return new ru({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:en(t)})}var au=k(`ZodPipe`,(e,t)=>{ba.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yc(e,t,n,r),e.in=t.in,e.out=t.out});function ou(e,t){return new au({type:`pipe`,in:e,out:t})}var su=k(`ZodPreprocess`,(e,t)=>{au.init(e,t),Sa.init(e,t)}),cu=k(`ZodReadonly`,(e,t)=>{Ca.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function lu(e){return new cu({type:`readonly`,innerType:e})}var uu=k(`ZodCustom`,(e,t)=>{Ta.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zs(e,t,n,r)});function du(e,t){return Qo(uu,e??(()=>!0),t)}function fu(e,t={}){return $o(uu,e,t)}function pu(e,t){return es(e,t)}function mu(e,t){return new su({type:`pipe`,in:Wl(e),out:t})}function hu(e){return xo(Kc,e)}function gu(e){return So(qc,e)}var L=class extends Error{hint;constructor(e,t){super(e),this.name=`DeliveryError`,this.hint=t}},_u=`/usr/bin/git`,vu=[`--no-replace-objects`,`-c`,`core.hooksPath=/dev/null`,`-c`,`core.fsmonitor=false`,`-c`,`core.attributesFile=/dev/null`,`-c`,`diff.external=`];function yu(){let e={...process.env};for(let t of Object.keys(e))t.startsWith(`GIT_`)&&delete e[t];return{...e,GIT_CONFIG_NOSYSTEM:`1`,GIT_CONFIG_GLOBAL:`/dev/null`,GIT_ATTR_NOSYSTEM:`1`,GIT_TERMINAL_PROMPT:`0`}}function bu(e){let t=S(_u,[...vu,`config`,`--includes`,`--name-only`,`--get-regexp`,`^filter\\..*\\.(clean|smudge|process|required)$`],{cwd:e,env:yu(),encoding:`utf8`,maxBuffer:1048576,stdio:[`ignore`,`pipe`,`pipe`]});if(t.error||t.status!==0&&t.status!==1)throw new L(`Unable to inspect Git filters safely.`);let n=t.stdout.trim().split(`
|
|
75
|
-
`).filter(Boolean);if(n.length>4096||n.some(e=>!/^filter\.[^\r\n]+\.(clean|smudge|process|required)$/u.test(e)||e.length>1024))throw new
|
|
76
|
-
`).filter(Boolean);if(t!==void 0&&!r.includes(t))throw new L(`Selected Git remote does not exist in this checkout.`);if(t===void 0&&r.length!==1)throw new L(`Select a Git remote explicitly when the checkout has zero or multiple remotes.`);let i=t??r[0];if(!i)throw new L(`Git remote selection is missing.`);return i}function Cu(e,t){let n=Su(e,t),r=S(_u,[...bu(e),`config`,`--local`,`--no-includes`,`--get`,`remote.${n}.url`],{env:yu(),cwd:e,encoding:`utf8`});if(r.status!==0)throw new L(`Unable to determine repository identity from the selected Git remote.`);let i=r.stdout.trim(),a=/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/u.exec(i);if(!a?.[1]||!a[2])throw new L(`The selected Git remote must be a github.com repository URL.`);return{owner:a[1],repo:a[2]}}function wu(e){let t=t=>{try{if(xu(Cu(t,`origin`)).toLowerCase()!==e.repository.toLowerCase())return null;let n=S(_u,[...bu(t),`rev-parse`,`--show-toplevel`],{env:yu(),cwd:t,encoding:`utf8`,maxBuffer:1048576});return n.status===0?p(n.stdout.trim()):null}catch{return null}},n=t(e.launchDirectory);if(n)return n;let r=new Set;for(let n of e.checkoutRoots){let e=t(n);if(e){r.add(e);continue}let i;try{i=d(n,{withFileTypes:!0})}catch{throw new L(`Checkout root is unreadable: ${n}`)}for(let e of i){if(!e.isDirectory()&&!e.isSymbolicLink())continue;let i=t(T(n,e.name));i&&r.add(i)}}if(r.size!==1)throw new L(`Repository ${e.repository} has ${r.size===0?`no matching`:`ambiguous`} checkout; select its checkout with --repo-root or configure checkoutRoots.`);return[...r][0]}function Tu(e,...t){try{return b(_u,[...bu(e),...t],{env:yu(),cwd:e,encoding:`utf8`,maxBuffer:4194304,stdio:[`ignore`,`pipe`,`pipe`]}).trim()}catch(e){let n=String(e.stderr??``).trim();throw new L(`git ${t[0]??``} failed${n?`: ${n}`:``}`)}}function Eu(e,...t){let n=S(_u,[...bu(e),...t],{env:yu(),cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`]});if(n.error)throw n.error;return n.status??1}function Du(e){return p(E(e,Tu(e,`rev-parse`,`--show-toplevel`)))}function Ou(e){return p(E(e,Tu(e,`rev-parse`,`--git-common-dir`)))}function ku(e){let t=Ou(e);if(C(t)!==`.git`)throw new L(`Expected a conventional non-bare Git repository.`);return w(t)}function Au(e,t=`HEAD`){let n=Tu(e,`rev-parse`,`--verify`,t),r=Tu(e,`rev-parse`,`${n}^{tree}`);if(!/^[a-f0-9]{40}$/u.test(n)||!/^[a-f0-9]{40}$/u.test(r))throw new L(`Git coordinate is not a SHA-1 commit and tree.`);return{sha:n,tree:r}}function ju(e){if(Tu(e,`status`,`--porcelain`,`--untracked-files=all`)!==``)throw new L(`Delivery requires an exact clean worktree.`)}function Mu(e,t){let n=Su(e,t),r=`refs/remotes/${n}/`;if(Eu(e,`symbolic-ref`,`--quiet`,`${r}HEAD`)===0){let t=Tu(e,`symbolic-ref`,`--quiet`,`${r}HEAD`);if(!t.startsWith(r))throw new L(`Selected remote HEAD points outside its tracking refs.`);return t}if(Eu(e,`show-ref`,`--verify`,`--quiet`,`${r}main`)===0)return`${r}main`;throw new L(`Fetch the selected remote ${n} and set its default branch before delivery.`)}var R=A().regex(/^sha256:[a-f0-9]{64}$/u),Nu=A().regex(/^[a-f0-9]{40}$/u),Pu=A().regex(/^[^/\s]+\/[^/\s]+$/u),Fu=A().regex(/^[a-z][a-z0-9-]*$/u),Iu=N({sha:Nu,tree:Nu}).strict();function z(e){if(Array.isArray(e))return`[${e.map(z).join(`,`)}]`;if(typeof e==`object`&&e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${z(t[e])}`).join(`,`)}}`}let t=JSON.stringify(e);if(t===void 0)throw Error(`Delivery evidence contains an unsupported value.`);return t}function B(e){return V(Buffer.from(z(e),`utf8`))}function V(e){return`sha256:${se(`sha256`).update(e).digest(`hex`)}`}function Lu(e){return e.every((t,n)=>n===0||e[n-1]<t)}function H(e,n){let i=o(e);if(!i.isFile()||i.isSymbolicLink()||i.nlink!==1||(i.mode&511)!=384)throw Error(`Delivery evidence must be a private regular file.`);if(n===void 0)return l(e);if(n.maxBytes!==void 0&&i.size>n.maxBytes||n.expectedBytes!==void 0&&i.size!==n.expectedBytes)throw Error(`Delivery evidence size exceeds its bound or differs from retained evidence.`);let a=c(e,`r`);try{let t=r(a);if(t.dev!==i.dev||t.ino!==i.ino||t.size!==i.size||t.mode!==i.mode||t.nlink!==i.nlink||t.uid!==i.uid||t.mtimeMs!==i.mtimeMs||t.ctimeMs!==i.ctimeMs)throw Error(`Delivery evidence identity changed before its bounded read.`);let n=Buffer.alloc(i.size),s=0;for(;s<n.length;){let e=u(a,n,s,n.length-s,s);if(e===0)throw Error(`Delivery evidence was truncated during its bounded read.`);s+=e}let c=r(a),l=o(e);if(c.dev!==t.dev||c.ino!==t.ino||c.size!==t.size||c.mode!==t.mode||c.nlink!==t.nlink||c.uid!==t.uid||c.mtimeMs!==t.mtimeMs||c.ctimeMs!==t.ctimeMs||l.dev!==c.dev||l.ino!==c.ino||l.isSymbolicLink())throw Error(`Delivery evidence bytes are missing, corrupt or changed during its bounded read.`);return n}finally{t(a)}}function Ru(e){let n=c(w(e),`r`);try{i(n)}finally{t(n)}}function zu(e,n,r){if(r!==void 0&&(r!==V(n)||C(e)!==`${r.slice(7)}.bin`))throw Error(`Immutable output path does not bind its bytes.`);try{if(!H(e,{expectedBytes:n.length}).equals(n))throw Error(`Content addressed evidence path collision.`);return Ru(e),e}catch(e){if(e.code!==`ENOENT`)throw e}s(w(e),{recursive:!0,mode:448});let o=T(w(e),`.${C(e)}.${le()}.tmp`),l=c(o,`wx`,384),u=!1;try{try{y(l,n),i(l)}finally{t(l)}try{r===void 0?a(o,e):(m(o,e),u=!0)}catch(t){if(t.code!==`EEXIST`||!H(e,{expectedBytes:n.length}).equals(n))throw t}}finally{u||v(o)}if(Ru(e),!H(e,{expectedBytes:n.length}).equals(n))throw Error(`Content addressed evidence write failed.`);return e}function Bu(){return typeof navigator==`object`&&`userAgent`in navigator?navigator.userAgent:typeof process==`object`&&process.version!==void 0?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:`<environment undetectable>`}var Vu={method:`GET`,baseUrl:`https://api.github.com`,headers:{accept:`application/vnd.github.v3+json`,"user-agent":`octokit-endpoint.js/0.0.0-development ${Bu()}`},mediaType:{format:``}};function Hu(e){return e?Object.keys(e).reduce((t,n)=>(t[n.toLowerCase()]=e[n],t),{}):{}}function Uu(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let n=Object.prototype.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n instanceof n&&Function.prototype.call(n)===Function.prototype.call(e)}function Wu(e,t){let n=Object.assign({},e);return Object.keys(t).forEach(r=>{Uu(t[r])&&r in e?n[r]=Wu(e[r],t[r]):Object.assign(n,{[r]:t[r]})}),n}function Gu(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function Ku(e,t,n){if(typeof t==`string`){let[e,r]=t.split(` `);n=Object.assign(r?{method:e,url:r}:{url:e},n)}else n=Object.assign({},t);n.headers=Hu(n.headers),Gu(n),Gu(n.headers);let r=Wu(e||{},n);return n.url===`/graphql`&&(e&&e.mediaType.previews?.length&&(r.mediaType.previews=e.mediaType.previews.filter(e=>!r.mediaType.previews.includes(e)).concat(r.mediaType.previews)),r.mediaType.previews=(r.mediaType.previews||[]).map(e=>e.replace(/-preview/,``))),r}function qu(e,t){let n=/\?/.test(e)?`&`:`?`,r=Object.keys(t);return r.length===0?e:e+n+r.map(e=>e===`q`?`q=`+t.q.split(`+`).map(encodeURIComponent).join(`+`):`${e}=${encodeURIComponent(t[e])}`).join(`&`)}var Ju=/\{[^{}}]+\}/g;function Yu(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,``).split(/,/)}function Xu(e){let t=e.match(Ju);return t?t.map(Yu).reduce((e,t)=>e.concat(t),[]):[]}function Zu(e,t){let n={__proto__:null};for(let r of Object.keys(e))t.indexOf(r)===-1&&(n[r]=e[r]);return n}function Qu(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(e){return/%[0-9A-Fa-f]/.test(e)||(e=encodeURI(e).replace(/%5B/g,`[`).replace(/%5D/g,`]`)),e}).join(``)}function $u(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return`%`+e.charCodeAt(0).toString(16).toUpperCase()})}function ed(e,t,n){return t=e===`+`||e===`#`?Qu(t):$u(t),n?$u(n)+`=`+t:t}function td(e){return e!=null}function nd(e){return e===`;`||e===`&`||e===`?`}function rd(e,t,n,r){var i=e[n],a=[];if(td(i)&&i!==``){if(typeof i==`string`||typeof i==`number`||typeof i==`bigint`||typeof i==`boolean`)i=i.toString(),r&&r!==`*`&&(i=i.substring(0,parseInt(r,10))),a.push(ed(t,i,nd(t)?n:``));else if(r===`*`)Array.isArray(i)?i.filter(td).forEach(function(e){a.push(ed(t,e,nd(t)?n:``))}):Object.keys(i).forEach(function(e){td(i[e])&&a.push(ed(t,i[e],e))});else{let e=[];Array.isArray(i)?i.filter(td).forEach(function(n){e.push(ed(t,n))}):Object.keys(i).forEach(function(n){td(i[n])&&(e.push($u(n)),e.push(ed(t,i[n].toString())))}),nd(t)?a.push($u(n)+`=`+e.join(`,`)):e.length!==0&&a.push(e.join(`,`))}}else t===`;`?td(i)&&a.push($u(n)):i===``&&(t===`&`||t===`?`)?a.push($u(n)+`=`):i===``&&a.push(``);return a}function id(e){return{expand:ad.bind(null,e)}}function ad(e,t){var n=[`+`,`#`,`.`,`/`,`;`,`?`,`&`];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(e,r,i){if(r){let e=``,i=[];if(n.indexOf(r.charAt(0))!==-1&&(e=r.charAt(0),r=r.substr(1)),r.split(/,/g).forEach(function(n){var r=/([^:\*]*)(?::(\d+)|(\*))?/.exec(n);i.push(rd(t,e,r[1],r[2]||r[3]))}),e&&e!==`+`){var a=`,`;return e===`?`?a=`&`:e!==`#`&&(a=e),(i.length===0?``:e)+i.join(a)}return i.join(`,`)}return Qu(i)}),e===`/`?e:e.replace(/\/$/,``)}function od(e){let t=e.method.toUpperCase(),n=(e.url||`/`).replace(/:([a-z]\w+)/g,`{$1}`),r=Object.assign({},e.headers),i,a=Zu(e,[`method`,`baseUrl`,`url`,`headers`,`request`,`mediaType`]),o=Xu(n);n=id(n).expand(a),/^http/.test(n)||(n=e.baseUrl+n);let s=Zu(a,Object.keys(e).filter(e=>o.includes(e)).concat(`baseUrl`));return/application\/octet-stream/i.test(r.accept)||(e.mediaType.format&&(r.accept=r.accept.split(/,/).map(t=>t.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(`,`)),n.endsWith(`/graphql`)&&e.mediaType.previews?.length&&(r.accept=(r.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[]).concat(e.mediaType.previews).map(t=>`application/vnd.github.${t}-preview${e.mediaType.format?`.${e.mediaType.format}`:`+json`}`).join(`,`))),[`GET`,`HEAD`].includes(t)?n=qu(n,s):`data`in s?i=s.data:Object.keys(s).length&&(i=s),!r[`content-type`]&&i!==void 0&&(r[`content-type`]=`application/json; charset=utf-8`),[`PATCH`,`PUT`].includes(t)&&i===void 0&&(i=``),Object.assign({method:t,url:n,headers:r},i===void 0?null:{body:i},e.request?{request:e.request}:null)}function sd(e,t,n){return od(Ku(e,t,n))}function cd(e,t){let n=Ku(e,t),r=sd.bind(null,n);return Object.assign(r,{DEFAULTS:n,defaults:cd.bind(null,n),merge:Ku.bind(null,n),parse:od})}var ld=cd(null,Vu),ud=32,dd=9,fd=59,pd=61,md=34,hd=92,gd=44,_d=1,vd=2,yd=4,bd=8,xd=16,Sd=65280,Cd=65281,wd=new Uint8Array(256);wd[dd]|=vd,wd[ud]|=vd,wd[fd]|=yd,wd[gd]|=bd;for(let e=128;e<=255;e++)wd[e]|=_d;for(let e of"!#$%&'*+-.^_`|~")wd[e.charCodeAt(0)]|=xd;for(let e=48;e<=57;e++)wd[e]|=xd;for(let e=65;e<=90;e++)wd[e]|=17;for(let e=97;e<=122;e++)wd[e]|=xd;var Td=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function Ed(e,t){let n=yd|(t?.comma===!0?bd:0),r=e.length,i=t?.start??0;for(;(wd[e.charCodeAt(i)]&vd)!==0;)i++;let a=i,o=0,s=-1,c=t?.parameters===!1?bd:0;for(;a<r;){let t=e.charCodeAt(a),r=wd[t];if((r&n)!==0){c|=r&bd;break}(r&vd)===0?s=-1:s===-1&&(s=a),o|=t&Sd|r,a++}let l=s===-1?a:s,u=e.slice(i,l),d=(o&Cd)===0?u:u.toLowerCase();return a===r||c!==0?{type:d,index:a,parameters:new Td}:Dd(e,d,a,r,n)}function Dd(e,t,n,r,i){let a=new Td;parameter:for(;n<r;){for(n++;(wd[e.charCodeAt(n)]&vd)!==0;)n++;let t=n,o=0,s=-1;for(;n<r;){let c=e.charCodeAt(n),l=wd[c];if((l&i)!==0){if((l&bd)!==0)break parameter;continue parameter}if(c===pd){let c=s===-1?n:s,l=e.slice(t,c),u=(o&Cd)===0?l:l.toLowerCase();for(n++;(wd[e.charCodeAt(n)]&vd)!==0;)n++;if(n<r&&e.charCodeAt(n)===md){let t=++n,o=!1;for(;n<r;){let s=e.charCodeAt(n);if(s===md){a[u]===void 0&&(a[u]=o?Od(e,t,n):e.slice(t,n)),n++;let s=0;for(;n<r;){let t=wd[e.charCodeAt(n)];if((t&i)!==0){s=t&bd;break}n++}if(s!==0)break parameter;continue parameter}if(s===hd&&n+1<r){o=!0,n+=2;continue}n++}continue parameter}let d=n,f=0,p=-1;for(;n<r;){let t=wd[e.charCodeAt(n)];if((t&i)!==0){f=t&bd;break}(t&vd)===0?p=-1:p===-1&&(p=n),n++}if(a[u]===void 0){let t=p===-1?n:p;a[u]=e.slice(d,t)}if(f!==0)break parameter;continue parameter}(l&vd)===0?s=-1:s===-1&&(s=n),o|=c&Sd|l,n++}}return{type:t,index:n,parameters:a}}function Od(e,t,n){let r=``;for(let i=t;i<n;i++)e.charCodeAt(i)===hd&&(r+=e.slice(t,i),t=++i);return r+e.slice(t,n)}var kd=/^-?\d+$/,Ad=/^-?\d+n+$/,jd=JSON.stringify,Md=JSON.parse,Nd=/^-?\d+n$/,Pd=/([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g,Fd=/([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g,Id=e=>e===void 0||typeof e==`function`||typeof e==`symbol`,Ld=e=>typeof e==`object`&&!!e&&e.constructor&&e.constructor.name===`RawJSON`,Rd=(e,t,n)=>{let r=``;typeof n==`number`?r=` `.repeat(Math.min(10,Math.max(0,Math.floor(n)))):typeof n==`string`&&(r=n.slice(0,10));let i=typeof t==`function`,a=Array.isArray(t)?new Set(t.map(String)):null,o=(e,n,r)=>(typeof r==`object`&&r&&typeof r.toJSON==`function`&&(r=r.toJSON(n)),typeof r==`string`&&Ad.test(r)?r+`n`:typeof r==`bigint`?`rawJSON`in JSON?JSON.rawJSON(r.toString()):r.toString()+`n`:(i&&(r=t.call(e,n,r)),typeof r==`object`&&r&&(r instanceof Number||r instanceof String||r instanceof Boolean)&&(r=r.valueOf()),r)),s=o({"":e},``,e);if(Id(s))return;let c=typeof s!=`object`||!s,l=Ld(s);if(c||l)return jd(s);let u=[],d=0,f=[{parent:{"":s},key:``,val:s,isArray:Array.isArray(s),keys:Array.isArray(s)?null:Object.keys(s),index:0,first:!0}],p=new WeakSet([s]);for(;f.length>0;){let e=f[f.length-1];e.index===0&&(u.push(e.isArray?`[`:`{`),d++);let t=!1;if(e.isArray){if(e.index<e.val.length){e.first||u.push(`,`),r&&u.push(`
|
|
77
|
-
`+r.repeat(d));let t=e.val[e.index],n=o(e.val,String(e.index),t);if(
|
|
78
|
-
`+r.repeat(d)+
|
|
79
|
-
`+r.repeat(d)),u.push(e.isArray?`]`:`}`),p.delete(e.val),f.pop())}return u.join(``)},zd=(e,t,n)=>{try{return`rawJSON`in JSON?jd(e,(e,n)=>typeof n==`bigint`?JSON.rawJSON(n.toString()):typeof t==`function`?t(e,n):(Array.isArray(t)&&t.includes(e),n),n):e?jd(e,(e,n)=>typeof n==`string`&&Ad.test(n)||typeof n==`bigint`?n.toString()+`n`:typeof t==`function`?t(e,n):(Array.isArray(t)&&t.includes(e),n),n).replace(Pd,`$1$2$3`).replace(Fd,`$1$2$3`):jd(e,t,n)}catch(r){if(r instanceof RangeError){let r=Rd(e,t,n);return r===void 0?void 0:`rawJSON`in JSON?r:r.replace(Pd,`$1$2$3`).replace(Fd,`$1$2$3`)}throw r}},Bd=new Map,Vd=()=>{let e=JSON.parse.toString();if(Bd.has(e))return Bd.get(e);try{let t=JSON.parse(`1`,(e,t,n)=>!!n?.source&&n.source===`1`);return Bd.set(e,t),t}catch{return Bd.set(e,!1),!1}},Hd=(e,t,n,r)=>typeof t==`string`&&Nd.test(t)?BigInt(t.slice(0,-1)):typeof t==`string`&&Ad.test(t)?t.slice(0,-1):typeof r==`function`?r(e,t,n):t,Ud=(e,t)=>JSON.parse(e,(e,n,r)=>{let i=typeof n==`number`&&(n>2**53-1||n<-(2**53-1)),a=r&&kd.test(r.source);return i&&a?BigInt(r.source):typeof t==`function`?t(e,n,r):n}),Wd=(2**53-1).toString(),Gd=Wd.length,Kd=/"(?:[^"\\]|\\.)*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,qd=/^"-?\d+n+"$/,Jd=(e,t)=>{let n={"":e},r=[{parent:n,key:``,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){let{parent:n,key:i}=e,a=n[i];typeof a==`string`&&(Nd.test(a)?a=BigInt(a.slice(0,-1)):Ad.test(a)&&(a=a.slice(0,-1))),typeof t==`function`&&(a=t.call(n,i,a)),a===void 0?delete n[i]:n[i]=a,r.pop()}else{e.visited=!0;let t=e.parent[e.key];if(typeof t==`object`&&t){let e=Object.keys(t);for(let n=e.length-1;n>=0;n--)r.push({parent:t,key:e[n],visited:!1})}}}return n[``]},Yd=e=>e.replace(Kd,(e,t,n,r)=>{let i=e[0]===`"`;if(i&&qd.test(e))return e.substring(0,e.length-1)+`n"`;let a=n||r,o=t&&(t.length<Gd||t.length===Gd&&t<=Wd);return i||a||o?e:`"`+e+`n"`}),Xd=(e,t)=>{if(!e)return Md(e,t);try{return Vd()?Ud(e,t):Md(Yd(e),(e,n,r)=>Hd(e,n,r,t))}catch(n){if(n instanceof RangeError)return Jd(Md(Yd(e)),t);throw n}},Zd=class extends Error{name;status;request;response;constructor(e,t,n){super(e,{cause:n.cause}),this.name=`HttpError`,this.status=Number.parseInt(t),Number.isNaN(this.status)&&(this.status=0),`response`in n&&(this.response=n.response);let r=Object.assign({},n.request);n.request.headers.authorization&&(r.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/,` [REDACTED]`)})),r.url=r.url.replace(/\bclient_secret=\w+/g,`client_secret=[REDACTED]`).replace(/\baccess_token=\w+/g,`access_token=[REDACTED]`),this.request=r}},Qd={headers:{"user-agent":`octokit-request.js/10.0.16 ${Bu()}`}};function $d(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let n=Object.prototype.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n instanceof n&&Function.prototype.call(n)===Function.prototype.call(e)}var ef=()=>``;async function tf(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw Error(`fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing`);let n=e.request?.log||console,r=e.request?.parseSuccessResponseBody!==!1,i=$d(e.body)||Array.isArray(e.body)?zd(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,String(t)])),o;try{o=await t(e.url,{method:e.method,body:i,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:`half`}})}catch(t){let n=`Unknown Error`;if(t instanceof Error){if(t.name===`AbortError`)throw t.status=500,t;n=t.message,t.name===`TypeError`&&`cause`in t&&(t.cause instanceof Error?n=t.cause.message:typeof t.cause==`string`&&(n=t.cause))}let r=new Zd(n,500,{request:e});throw r.cause=t,r}let s=o.status,c=o.url,l={};for(let[e,t]of o.headers)l[e]=t;let u={url:c,status:s,headers:l,data:``};if(`deprecation`in l){let t=l.link&&l.link.match(/<([^<>]+)>; rel="deprecation"/),r=t&&t.pop();n.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${l.sunset}${r?`. See ${r}`:``}`)}if(s===204||s===205)return u;if(e.method===`HEAD`){if(s<400)return u;throw new Zd(o.statusText,s,{response:u,request:e})}if(s===304)throw u.data=await nf(o),new Zd(`Not modified`,s,{response:u,request:e});if(s>=400)throw u.data=await nf(o),new Zd(af(u.data),s,{response:u,request:e});return u.data=r?await nf(o):o.body,u}async function nf(e){let t=e.headers.get(`content-type`);if(!t)return e.text().catch(ef);let n=Ed(t);if(rf(n)){let t=``;try{return t=await e.text(),Xd(t)}catch{return t}}return n.type.startsWith(`text/`)||n.parameters.charset?.toLowerCase()===`utf-8`&&n.type!==`application/octet-stream`?e.text().catch(ef):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function rf(e){return e.type===`application/json`||e.type===`application/scim+json`}function af(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return`Unknown error`;if(typeof e==`object`&&e&&`message`in e){let t=e,n=`documentation_url`in t?` - ${t.documentation_url}`:``;return Array.isArray(t.errors)?`${t.message}: ${t.errors.map(e=>JSON.stringify(e)).join(`, `)}${n}`:`${t.message}${n}`}return`Unknown error: ${JSON.stringify(e)}`}function of(e,t){let n=e.defaults(t);return Object.assign(function(e,t){let r=n.merge(e,t);if(!r.request||!r.request.hook)return tf(n.parse(r));let i=(e,t)=>tf(n.parse(n.merge(e,t)));return Object.assign(i,{endpoint:n,defaults:of.bind(null,n)}),r.request.hook(i,r)},{endpoint:n,defaults:of.bind(null,n)})}var sf=of(ld,Qd);function cf(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:/^https:\/\/api\..*\.ghe\.com$/.test(t.baseUrl)?t.baseUrl.replace(`api.`,``):t.baseUrl.replace(`/api/v3`,``)}async function lf(e,t,n){let r={baseUrl:cf(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new Zd(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function uf(e){let t=await lf(e.request||sf,`POST /login/oauth/access_token`,{client_id:e.clientId,client_secret:e.clientSecret,code:e.code,redirect_uri:e.redirectUrl}),n={clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=df(e,t.data.expires_in),n.refreshTokenExpiresAt=df(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function df(e,t){return new Date(e+t*1e3).toISOString()}async function ff(e){let t=e.request||sf,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),lf(t,`POST /login/device/code`,n)}async function pf(e){let t=await lf(e.request||sf,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=mf(e,t.data.expires_in),n.refreshTokenExpiresAt=mf(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function mf(e,t){return new Date(e+t*1e3).toISOString()}async function hf(e){let t=await(e.request||sf)(`POST /applications/{client_id}/token`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token}),n={clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:e.token,scopes:t.data.scopes};return t.data.expires_at&&(n.expiresAt=t.data.expires_at),e.clientType===`github-app`&&delete n.scopes,{...t,authentication:n}}async function gf(e){let t=await lf(e.request||sf,`POST /login/oauth/access_token`,{client_id:e.clientId,client_secret:e.clientSecret,grant_type:`refresh_token`,refresh_token:e.refreshToken}),n=new Date(t.headers.date).getTime(),r={clientType:`github-app`,clientId:e.clientId,clientSecret:e.clientSecret,token:t.data.access_token,refreshToken:t.data.refresh_token,expiresAt:_f(n,t.data.expires_in),refreshTokenExpiresAt:_f(n,t.data.refresh_token_expires_in)};return{...t,authentication:r}}function _f(e,t){return new Date(e+t*1e3).toISOString()}async function vf(e){let t=await(e.request||sf)(`PATCH /applications/{client_id}/token`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token}),n={clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:t.data.token,scopes:t.data.scopes};return t.data.expires_at&&(n.expiresAt=t.data.expires_at),e.clientType===`github-app`&&delete n.scopes,{...t,authentication:n}}async function yf(e){return(e.request||sf)(`DELETE /applications/{client_id}/token`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token})}async function bf(e){return(e.request||sf)(`DELETE /applications/{client_id}/grant`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token})}async function xf(e,t){let n=Sf(e,t.auth);if(n)return n;let{data:r}=await ff({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await wf(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Sf(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)&&n}async function Cf(e){await new Promise(t=>setTimeout(t,e*1e3))}async function wf(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await pf({...i,clientType:`oauth-app`}):await pf({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Cf(r.interval),wf(e,t,n,r);if(a===`slow_down`)return await Cf(r.interval+7),wf(e,t,n,r);throw i}}async function Tf(e,t){return xf(e,{auth:t})}async function Ef(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await xf(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Df=`0.0.0-development`;function Of(e){let t=e.request||sf.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Df} ${Bu()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Tf.bind(null,i),{hook:Ef.bind(null,i)})}var kf=`0.0.0-development`;async function Af(e){if(`code`in e.strategyOptions){let{authentication:t}=await uf({clientId:e.clientId,clientSecret:e.clientSecret,clientType:e.clientType,onTokenCreated:e.onTokenCreated,...e.strategyOptions,request:e.request});return{type:`token`,tokenType:`oauth`,...t}}if(`onVerification`in e.strategyOptions){let t=await Of({clientType:e.clientType,clientId:e.clientId,onTokenCreated:e.onTokenCreated,...e.strategyOptions,request:e.request})({type:`oauth`});return{clientSecret:e.clientSecret,...t}}if(`token`in e.strategyOptions)return{type:`token`,tokenType:`oauth`,clientId:e.clientId,clientSecret:e.clientSecret,clientType:e.clientType,onTokenCreated:e.onTokenCreated,...e.strategyOptions};throw Error(`[@octokit/auth-oauth-user] Invalid strategy options`)}async function jf(e,t={}){if(e.authentication||=(e.clientType,await Af(e)),e.authentication.invalid)throw Error(`[@octokit/auth-oauth-user] Token is invalid`);let n=e.authentication;if(`expiresAt`in n&&(t.type===`refresh`||new Date(n.expiresAt)<new Date)){let{authentication:t}=await gf({clientType:`github-app`,clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:n.refreshToken,request:e.request});e.authentication={tokenType:`oauth`,type:`token`,...t}}if(t.type===`refresh`){if(e.clientType===`oauth-app`)throw Error(`[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens`);if(!n.hasOwnProperty(`expiresAt`))throw Error(`[@octokit/auth-oauth-user] Refresh token missing`);await e.onTokenCreated?.(e.authentication,{type:t.type})}if(t.type===`check`||t.type===`reset`){let n=t.type===`check`?hf:vf;try{let{authentication:r}=await n({clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:e.authentication.token,request:e.request});return e.authentication={tokenType:`oauth`,type:`token`,...r},t.type===`reset`&&await e.onTokenCreated?.(e.authentication,{type:t.type}),e.authentication}catch(t){throw t.status===404&&(t.message=`[@octokit/auth-oauth-user] Token is invalid`,e.authentication.invalid=!0),t}}if(t.type===`delete`||t.type===`deleteAuthorization`){let n=t.type===`delete`?yf:bf;try{await n({clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:e.authentication.token,request:e.request})}catch(e){if(e.status!==404)throw e}return e.authentication.invalid=!0,e.authentication}return e.authentication}var Mf=/\/applications\/[^/]+\/(token|grant)s?/;function Nf(e){return e&&Mf.test(e)}async function Pf(e,t,n,r={}){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);if(Nf(i.url)){let n=btoa(`${e.clientId}:${e.clientSecret}`);return i.headers.authorization=`basic ${n}`,t(i)}let{token:a}=(e.clientType,await jf({...e,request:t}));return i.headers.authorization=`token `+a,t(i)}function Ff({clientId:e,clientSecret:t,clientType:n=`oauth-app`,request:r=sf.defaults({headers:{"user-agent":`octokit-auth-oauth-app.js/${kf} ${Bu()}`}}),onTokenCreated:i,...a}){let o=Object.assign({clientType:n,clientId:e,clientSecret:t,onTokenCreated:i,strategyOptions:a,request:r});return Object.assign(jf.bind(null,o),{hook:Pf.bind(null,o)})}Ff.VERSION=kf;async function If(e,t){if(t.type===`oauth-app`)return{type:`oauth-app`,clientId:e.clientId,clientSecret:e.clientSecret,clientType:e.clientType,headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`}};if(`factory`in t){let{type:n,...r}={...t,...e};return t.factory(r)}let n={clientId:e.clientId,clientSecret:e.clientSecret,request:e.request,...t};return(e.clientType,await Ff({...n,clientType:e.clientType}))()}async function Lf(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);if(e.clientType===`github-app`&&!Nf(i.url))throw Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${i.method} ${i.url}" is not supported.`);let a=btoa(`${e.clientId}:${e.clientSecret}`);i.headers.authorization=`basic ${a}`;try{return await t(i)}catch(e){throw e.status===401&&(e.message=`[@octokit/auth-oauth-app] "${i.method} ${i.url}" does not support clientId/clientSecret basic authentication.`),e}}var Rf=`0.0.0-development`;function zf(e){let t=Object.assign({request:sf.defaults({headers:{"user-agent":`octokit-auth-oauth-app.js/${Rf} ${Bu()}`}}),clientType:`oauth-app`},e);return Object.assign(If.bind(null,t),{hook:Lf.bind(null,t)})}function Bf(e){return e.includes(`-----BEGIN RSA PRIVATE KEY-----`)}function Vf(e){return e.includes(`-----BEGIN OPENSSH PRIVATE KEY-----`)}function Hf(e){let t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t++)n[t]=e.charCodeAt(t);return t}function Uf(e){let t=e.trim().split(`
|
|
80
|
-
`).slice(1,-1).join(``);return
|
|
81
|
-
`),i=n-30,a=i+600;return{appId:e,expiration:a,token:await
|
|
74
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function cs(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;cs(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ls=new Set([`type`,`properties`,`required`,`additionalProperties`]),us=[`oneOf`,`anyOf`];function ds(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function fs(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ls.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??ds(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}et(n,r,e.length===1?e[0]:fs(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=ds(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ps(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ls)if(t in e)return;let n=t.filter(e=>us.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=fs(t);else{let e=n[0],i=us.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>fs([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,ns(e,r))}function ms(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):ns(i,s),ns(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())cs(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ps(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}ns(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,et(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:_s(t,`input`,e.processors),output:_s(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function hs(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return hs(r.element,n);if(r.type===`set`)return hs(r.valueType,n);if(r.type===`lazy`)return hs(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return hs(r.innerType,n);if(r.type===`intersection`)return hs(r.left,n)||hs(r.right,n);if(r.type===`record`||r.type===`map`)return hs(r.keyType,n)||hs(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:hs(r.in,n)||hs(r.out,n);if(r.type===`object`){for(let e in r.shape)if(hs(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(hs(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(hs(e,n))return!0;return!!(r.rest&&hs(r.rest,n))}return!1}var gs=(e,t={})=>n=>{let r=rs({...n,processors:t});return as(e,r),ss(r,e),ms(r,e)},_s=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=rs({...i??{},target:a,io:t,processors:n});return as(e,o),ss(o,e),ms(o,e)},vs=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},ys=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},bs=(e,t)=>{vs(e,`minimum`,t),ys(e,`maximum`,t)},xs=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Ss=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},Cs=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},ws=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Ts=(e,t)=>vs(e,`minimum`,t.minimum),Es=(e,t)=>ys(e,`maximum`,t.maximum),Ds=e=>(t,n)=>{ws(t,n.format);let[r,i]=e[n.format];vs(t,`minimum`,r),ys(t,`maximum`,i)},Os={greater_than:(e,t)=>vs(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>ys(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>xs(e,t.value),number_format:Ds(bt),bigint_format:Ds(xt),min_length:Ts,max_length:Es,length_equals:(e,t)=>bs(e,t.length),min_size:Ts,max_size:Es,size_equals:(e,t)=>bs(e,t.size),string_format:(e,t)=>{ws(e,t.format),t.pattern&&Ss(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Cs(e,t.mime)};function ks(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Os[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&vs(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&vs(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&ys(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&ys(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&xs(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Cs(t,i.mime);for(let e of i.patterns??[])Ss(t,e);return t}var As={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},js=new Map([[Ei,sr],[Oi,cr]]),Ms=e=>js.get(e)??e,Ns=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=ks(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=As[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Ms);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Ps=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ks(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):is(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Fs=(e,t,n,r)=>{n.type=`boolean`},Is=(e,t,n,r)=>{is(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},Ls=(e,t,n,r)=>{is(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},Rs=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},zs=(e,t,n,r)=>{is(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},Bs=(e,t,n,r)=>{is(e,t,n,r,`Void cannot be represented in JSON Schema`)},Vs=(e,t,n,r)=>{n.not={}},Hs=(e,t,n,r)=>{},Us=(e,t,n,r)=>{},Ws=(e,t,n,r)=>{is(e,t,n,r,`Date cannot be represented in JSON Schema`)},Gs=(e,t,n,r)=>{let i=e._zod.def,a=Ke(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ks=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(is(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(is(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},qs=(e,t,n,r)=>{is(e,t,n,r,`NaN cannot be represented in JSON Schema`)},Js=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ys=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=ks(e);a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),s&&(s.length===0?i.not={}:s.length===1?i.contentMediaType=s[0]:i.anyOf=s.map(e=>({contentMediaType:e})))},Xs=(e,t,n,r)=>{n.type=`boolean`},Zs=(e,t,n,r)=>{is(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Qs=(e,t,n,r)=>{is(e,t,n,r,`Function types cannot be represented in JSON Schema`)},$s=(e,t,n,r)=>{is(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ec=(e,t,n,r)=>{is(e,t,n,r,`Map cannot be represented in JSON Schema`)},tc=(e,t,n,r)=>{is(e,t,n,r,`Set cannot be represented in JSON Schema`)},nc=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=ks(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=as(a.element,t,{...r,path:[...r.path,`items`]})};function rc(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?rc(t.out):t.type===`catch`?rc(t.innerType):e._zod.optin}var ic=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&is(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)et(i.properties,e,as(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?rc(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=as(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ac=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>as(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},oc=(e,t,n,r)=>{let i=e._zod.def,a=as(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=as(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},sc=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>as(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?as(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?rc(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=ks(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function cc(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=cc(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>cc(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?yr:vr).source),p):p}var lc=new WeakMap;function uc(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of lc.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=cc(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var dc=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=ks(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=as(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)et(i.patternProperties,Ms(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=as(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=lc.get(t);n||(n=[],lc.set(t,n),t.deferred.push(()=>uc(t))),n.push(e)}i.additionalProperties=as(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&rc(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},fc=(e,t,n,r)=>{let i=e._zod.def,a=as(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},pc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},mc=Symbol();function hc(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(is(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),mc):JSON.parse(o)}var gc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=hc(i.defaultValue,e,t,n,r);o!==mc&&(n.default=o)},_c=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=hc(i.defaultValue,e,t,n,r);o!==mc&&(n._prefault=o)},vc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{is(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},yc=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;as(o,t,r);let s=t.seen.get(e);s.ref=o},bc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},xc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Sc=(e,t,n,r)=>{let i=e._zod.def;as(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Cc={string:Ns,number:Ps,boolean:Fs,bigint:Is,symbol:Ls,null:Rs,undefined:zs,void:Bs,never:Vs,any:Hs,unknown:Us,date:Ws,enum:Gs,literal:Ks,nan:qs,template_literal:Js,file:Ys,success:Xs,custom:Zs,function:Qs,transform:$s,map:ec,set:tc,array:nc,object:ic,union:ac,intersection:oc,tuple:sc,record:dc,nullable:fc,nonoptional:pc,default:gc,prefault:_c,catch:vc,pipe:yc,readonly:bc,promise:xc,optional:Sc,lazy:(e,t,n,r)=>{let i=e._zod.innerType;as(i,t,r);let a=t.seen.get(e);a.ref=i}};function wc(e,t){if(`_idmap`in e){let n=e,r=rs({...t,processors:Cc}),i={};for(let e of n._idmap.entries()){let[t,n]=e;as(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;ss(r,n),et(a,t,ms(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=rs({...t,processors:Cc});return as(e,n),ss(n,e),ms(n,e)}var Tc=new WeakSet([Object.prototype,Error.prototype]);function Ec(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Dc=k(`ZodError`,(e,t)=>{gn.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Tc.has(n)||(Tc.add(n),Ec(n,`format`,e=>t=>bn(e,t)),Ec(n,`flatten`,e=>t=>yn(e,t)),Ec(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Je,2)}),Ec(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Je,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Oc=Sn(Dc),kc=wn(Dc),Ac=En(Dc),jc=kn(Dc),Mc=In(Dc),Nc=Ln(Dc),Pc=Rn(Dc),Fc=zn(Dc),Ic=Bn(Dc),Lc=Vn(Dc),Rc=Hn(Dc),zc=Un(Dc);function Bc(){cn.localeError||ln(Ga())}function Vc(){cn.memoizer||ln({memoizer:Ha()})}var Hc=k(`ZodType`,(e,t)=>(Bc(),Wr.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(st(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return _t(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(du(e,t))},superRefine(e,t){return this.check(fu(e,t))},overwrite(e){return this.check(Go(e))},optional(){return Gl(this)},exactOptional(){return ql(this)},nullable(){return Yl(this)},nullish(){return Gl(Yl(this))},nonoptional(e){return tu(this,e)},array(){return N(this)},or(e){return jl([this,e])},and(e){return Fl(this,e)},transform(e){return au(this,Ul(e))},default(e){return Zl(this,e)},prefault(e){return $l(this,e)},catch(e){return ru(this,e)},pipe(e){return au(this,e)},readonly(){return cu(this)},describe(e){let t=this.clone();return Ya.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ya.get(this);let t=this.clone();return Ya.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Wt(this,`~standard`,{...qr(this),jsonSchema:{input:_s(this,`input`),output:_s(this,`output`)}})},set"~standard"(e){Ut(this,`~standard`,e)},parse:function e(t,n){return Oc(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await kc(this,t,n,{callee:e})},safeParse(e,t){return Ac(this,e,t)},async safeParseAsync(e,t){return jc(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ut(this,`spa`,e)},validate(e,t){return Nn(this,e,t)},validateAsync(e,t){return Fn(this,e,t)},encode:function e(t,n){return Mc(this,t,n,{callee:e})},decode:function e(t,n){return Nc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Pc(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Fc(this,t,n,{callee:e})},safeEncode(e,t){return Ic(this,e,t)},safeDecode(e,t){return Lc(this,e,t)},async safeEncodeAsync(e,t){return Rc(this,e,t)},async safeDecodeAsync(e,t){return zc(this,e,t)},toJSONSchema(e){return gs(this,{})(e)},get description(){return Ya.get(this)?.description},get _def(){return this._zod.def}}),Uc=k(`_ZodString`,(e,t)=>{Jr.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ns(e,t,n,r)},Gt({format:e=>ks(e).format??null,minLength:e=>ks(e).minimum??null,maxLength:e=>ks(e).maximum??null},{regex(...e){return this.check(zo(...e))},includes(...e){return this.check(Ho(...e))},startsWith(...e){return this.check(Uo(...e))},endsWith(...e){return this.check(Wo(...e))},min(...e){return this.check(Lo(...e))},max(...e){return this.check(Io(...e))},length(...e){return this.check(Ro(...e))},nonempty(...e){return this.check(Lo(1,...e))},lowercase(e){return this.check(Bo(e))},uppercase(e){return this.check(Vo(e))},trim(){return this.check(qo())},normalize(...e){return this.check(Ko(...e))},toLowerCase(){return this.check(Jo())},toUpperCase(){return this.check(Yo())},slugify(){return this.check(Xo())}})),Wc=k(`ZodString`,(e,t)=>{Jr.init(e,t),Uc.init(e,t)},{email(e){return this.check(Qa(Xc,e))},url(e){return this.check(io(el,e))},jwt(e){return this.check(bo(gl,e))},emoji(e){return this.check(ao(nl,e))},guid(e){return this.check($a(Zc,e))},uuid(e){return this.check(eo(Qc,e))},uuidv4(e){return this.check(to(Qc,e))},uuidv6(e){return this.check(no(Qc,e))},uuidv7(e){return this.check(ro(Qc,e))},nanoid(e){return this.check(oo(rl,e))},cuid(e){return this.check(so(il,e))},cuid2(e){return this.check(co(al,e))},ulid(e){return this.check(lo(ol,e))},base64(e){return this.check(_o(pl,e))},base64url(e){return this.check(vo(ml,e))},xid(e){return this.check(uo(sl,e))},ksuid(e){return this.check(fo(cl,e))},ipv4(e){return this.check(po(ll,e))},ipv6(e){return this.check(mo(ul,e))},cidrv4(e){return this.check(ho(dl,e))},cidrv6(e){return this.check(go(fl,e))},e164(e){return this.check(yo(hl,e))},datetime(e){return this.check(xo(Kc,e))},date(e){return this.check(So(qc,e))},time(e){return this.check(Co(Jc,e))},duration(e){return this.check(wo(Yc,e))}});function A(e){return Za(Wc,e)}var Gc=k(`ZodStringFormat`,(e,t)=>{Yr.init(e,t),Uc.init(e,t)}),Kc=k(`ZodISODateTime`,(e,t)=>{mi.init(e,t),Gc.init(e,t)}),qc=k(`ZodISODate`,(e,t)=>{hi.init(e,t),Gc.init(e,t)}),Jc=k(`ZodISOTime`,(e,t)=>{gi.init(e,t),Gc.init(e,t)}),Yc=k(`ZodISODuration`,(e,t)=>{_i.init(e,t),Gc.init(e,t)}),Xc=k(`ZodEmail`,(e,t)=>{Qr.init(e,t),Gc.init(e,t)}),Zc=k(`ZodGUID`,(e,t)=>{Xr.init(e,t),Gc.init(e,t)}),Qc=k(`ZodUUID`,(e,t)=>{Zr.init(e,t),Gc.init(e,t)});function $c(e){return eo(Qc,e)}var el=k(`ZodURL`,(e,t)=>{oi.init(e,t),Gc.init(e,t)});function tl(e){return io(el,e)}var nl=k(`ZodEmoji`,(e,t)=>{si.init(e,t),Gc.init(e,t)}),rl=k(`ZodNanoID`,(e,t)=>{ci.init(e,t),Gc.init(e,t)}),il=k(`ZodCUID`,(e,t)=>{li.init(e,t),Gc.init(e,t)}),al=k(`ZodCUID2`,(e,t)=>{ui.init(e,t),Gc.init(e,t)}),ol=k(`ZodULID`,(e,t)=>{di.init(e,t),Gc.init(e,t)}),sl=k(`ZodXID`,(e,t)=>{fi.init(e,t),Gc.init(e,t)}),cl=k(`ZodKSUID`,(e,t)=>{pi.init(e,t),Gc.init(e,t)}),ll=k(`ZodIPv4`,(e,t)=>{vi.init(e,t),Gc.init(e,t)}),ul=k(`ZodIPv6`,(e,t)=>{xi.init(e,t),Gc.init(e,t)}),dl=k(`ZodCIDRv4`,(e,t)=>{Si.init(e,t),Gc.init(e,t)}),fl=k(`ZodCIDRv6`,(e,t)=>{wi.init(e,t),Gc.init(e,t)}),pl=k(`ZodBase64`,(e,t)=>{Di.init(e,t),Gc.init(e,t)}),ml=k(`ZodBase64URL`,(e,t)=>{Ai.init(e,t),Gc.init(e,t)}),hl=k(`ZodE164`,(e,t)=>{ji.init(e,t),Gc.init(e,t)}),gl=k(`ZodJWT`,(e,t)=>{Ni.init(e,t),Gc.init(e,t)}),_l=k(`ZodNumber`,(e,t)=>{Pi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ps(e,t,n,r),e.isFinite=!0},Gt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=ks(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=ks(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=ks(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>ks(e).format??null},{gt(e,t){return this.check(No(e,t))},gte(e,t){return this.check(Po(e,t))},min(e,t){return this.check(Po(e,t))},lt(e,t){return this.check(jo(e,t))},lte(e,t){return this.check(Mo(e,t))},max(e,t){return this.check(Mo(e,t))},int(e){return this.check(yl(e))},safe(e){return this.check(yl(e))},positive(e){return this.check(No(0,e))},nonnegative(e){return this.check(Po(0,e))},negative(e){return this.check(jo(0,e))},nonpositive(e){return this.check(Mo(0,e))},multipleOf(e,t){return this.check(Fo(e,t))},step(e,t){return this.check(Fo(e,t))},finite(){return this}}));function j(e){return To(_l,e)}var vl=k(`ZodNumberFormat`,(e,t)=>{Fi.init(e,t),_l.init(e,t)});function yl(e){return Eo(vl,e)}var bl=k(`ZodBoolean`,(e,t)=>{Ii.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fs(e,t,n,r)});function M(e){return Do(bl,e)}var xl=k(`ZodNull`,(e,t)=>{Li.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rs(e,t,n,r)});function Sl(e){return Oo(xl,e)}var Cl=k(`ZodUnknown`,(e,t)=>{Ri.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function wl(){return ko(Cl)}var Tl=k(`ZodNever`,(e,t)=>{zi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vs(e,t,n,r)});function El(e){return Ao(Tl,e)}var Dl=k(`ZodArray`,(e,t)=>{Vc(),Vi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nc(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Lo(e,t))},nonempty(e){return this.check(Lo(1,e))},max(e,t){return this.check(Io(e,t))},length(e,t){return this.check(Ro(e,t))},unwrap(){return this.element}});function N(e,t){return Zo(Dl,e,t)}var Ol=k(`ZodObject`,(e,t)=>{Vc(),qi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ic(e,t,n,r),Qt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return I(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(st(this._zod.def,{catchall:e}))},passthrough(){return this.clone(st(this._zod.def,{catchall:wl()}))},loose(){return this.clone(st(this._zod.def,{catchall:wl()}))},strict(){return this.clone(st(this._zod.def,{catchall:El()}))},strip(){return this.clone(st(this._zod.def,{catchall:void 0}))},extend(e){return Tt(this,e)},safeExtend(e){return Dt(this,e)},merge(e){return Ot(this,e)},pick(e){return St(this,e)},omit(e){return wt(this,e)},partial(...e){return kt(Wl,this,e[0])},exactPartial(...e){return kt(Kl,this,e[0],`exactPartial`)},required(...e){return At(eu,this,e[0])}});function P(e,t){return new Ol({type:`object`,shape:e??{},...O(t)})}function F(e,t){return new Ol({type:`object`,shape:e,catchall:El(),...O(t)})}function kl(e,t){return new Ol({type:`object`,shape:e,catchall:wl(),...O(t)})}var Al=k(`ZodUnion`,(e,t)=>{Yi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ac(e,t,n,r),e.options=t.options});function jl(e,t){return new Al({type:`union`,options:e,...O(t)})}var Ml=k(`ZodDiscriminatedUnion`,(e,t)=>{Al.init(e,t),Zi.init(e,t)});function Nl(e,t,n){return new Ml({type:`union`,options:t,discriminator:e,...O(n)})}var Pl=k(`ZodIntersection`,(e,t)=>{Qi.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oc(e,t,n,r)});function Fl(e,t){return new Pl({type:`intersection`,left:e,right:t})}var Il=k(`ZodTuple`,(e,t)=>{Vc(),ta.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sc(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Wl({type:`optional`,innerType:e}))})}});function Ll(e,t,n){let r=t instanceof Wr;return new Il({type:`tuple`,items:e,rest:r?t:null,...O(r?n:t)})}var Rl=k(`ZodRecord`,(e,t)=>{Vc(),aa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dc(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function zl(e,t,n){return!t||!t._zod?new Rl({type:`record`,keyType:A(),valueType:e,...O(t)}):new Rl({type:`record`,keyType:e,valueType:t,...O(n)})}var Bl=k(`ZodEnum`,(e,t)=>{oa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gs(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Bl({...t,checks:[],...O(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Bl({...t,checks:[],...O(r),entries:i})}});function I(e,t){return new Bl({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...O(t)})}var Vl=k(`ZodLiteral`,(e,t)=>{sa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ks(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function L(e,t){return new Vl({type:`literal`,values:Array.isArray(e)?e:[e],...O(t)})}var Hl=k(`ZodTransform`,(e,t)=>{Vc(),ca.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$s(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new sn(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Vt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Vt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Ul(e){return new Hl({type:`transform`,transform:e})}var Wl=k(`ZodOptional`,(e,t)=>{ua.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Gl(e){return new Wl({type:`optional`,innerType:e})}var Kl=k(`ZodExactOptional`,(e,t)=>{da.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ql(e){return new Kl({type:`optional`,innerType:e})}var Jl=k(`ZodNullable`,(e,t)=>{fa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Yl(e){return new Jl({type:`nullable`,innerType:e})}var Xl=k(`ZodDefault`,(e,t)=>{pa.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Zl(e,t){return new Xl({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():mt(t)}})}var Ql=k(`ZodPrefault`,(e,t)=>{ha.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_c(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function $l(e,t){return new Ql({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():mt(t)}})}var eu=k(`ZodNonOptional`,(e,t)=>{ga.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function tu(e,t){return new eu({type:`nonoptional`,innerType:e,...O(t)})}var nu=k(`ZodCatch`,(e,t)=>{ya.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ru(e,t){return new nu({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:en(t)})}var iu=k(`ZodPipe`,(e,t)=>{ba.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yc(e,t,n,r),e.in=t.in,e.out=t.out});function au(e,t){return new iu({type:`pipe`,in:e,out:t})}var ou=k(`ZodPreprocess`,(e,t)=>{iu.init(e,t),Sa.init(e,t)}),su=k(`ZodReadonly`,(e,t)=>{Ca.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bc(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function cu(e){return new su({type:`readonly`,innerType:e})}var lu=k(`ZodCustom`,(e,t)=>{Ta.init(e,t),Hc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zs(e,t,n,r)});function uu(e,t){return Qo(lu,e??(()=>!0),t)}function du(e,t={}){return $o(lu,e,t)}function fu(e,t){return es(e,t)}function pu(e,t){return new ou({type:`pipe`,in:Ul(e),out:t})}function mu(e){return xo(Kc,e)}function hu(e){return So(qc,e)}var R=class extends Error{hint;constructor(e,t){super(e),this.name=`DeliveryError`,this.hint=t}},gu=`/usr/bin/git`,_u=[`--no-replace-objects`,`-c`,`core.hooksPath=/dev/null`,`-c`,`core.fsmonitor=false`,`-c`,`core.attributesFile=/dev/null`,`-c`,`diff.external=`];function vu(){let e={...process.env};for(let t of Object.keys(e))t.startsWith(`GIT_`)&&delete e[t];return{...e,GIT_CONFIG_NOSYSTEM:`1`,GIT_CONFIG_GLOBAL:`/dev/null`,GIT_ATTR_NOSYSTEM:`1`,GIT_TERMINAL_PROMPT:`0`}}function yu(e){let t=S(gu,[..._u,`config`,`--includes`,`--name-only`,`--get-regexp`,`^filter\\..*\\.(clean|smudge|process|required)$`],{cwd:e,env:vu(),encoding:`utf8`,maxBuffer:1048576,stdio:[`ignore`,`pipe`,`pipe`]});if(t.error||t.status!==0&&t.status!==1)throw new R(`Unable to inspect Git filters safely.`);let n=t.stdout.trim().split(`
|
|
75
|
+
`).filter(Boolean);if(n.length>4096||n.some(e=>!/^filter\.[^\r\n]+\.(clean|smudge|process|required)$/u.test(e)||e.length>1024))throw new R(`Git filter configuration exceeds the safe probe boundary.`);return[..._u,...n.flatMap(e=>[`-c`,`${e}=${e.endsWith(`.required`)?`false`:``}`])]}function bu(e){return`${e.owner}/${e.repo}`}function xu(e,t){let n=S(gu,[...yu(e),`remote`],{env:vu(),cwd:e,encoding:`utf8`});if(n.status!==0)throw new R(`Unable to list Git remotes.`);let r=n.stdout.trim().split(`
|
|
76
|
+
`).filter(Boolean);if(t!==void 0&&!r.includes(t))throw new R(`Selected Git remote does not exist in this checkout.`);if(t===void 0&&r.length!==1)throw new R(`Select a Git remote explicitly when the checkout has zero or multiple remotes.`);let i=t??r[0];if(!i)throw new R(`Git remote selection is missing.`);return i}function Su(e,t){let n=xu(e,t),r=S(gu,[...yu(e),`config`,`--local`,`--no-includes`,`--get`,`remote.${n}.url`],{env:vu(),cwd:e,encoding:`utf8`});if(r.status!==0)throw new R(`Unable to determine repository identity from the selected Git remote.`);let i=r.stdout.trim(),a=/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/u.exec(i);if(!a?.[1]||!a[2])throw new R(`The selected Git remote must be a github.com repository URL.`);return{owner:a[1],repo:a[2]}}function Cu(e){let t=t=>{try{if(bu(Su(t,`origin`)).toLowerCase()!==e.repository.toLowerCase())return null;let n=S(gu,[...yu(t),`rev-parse`,`--show-toplevel`],{env:vu(),cwd:t,encoding:`utf8`,maxBuffer:1048576});return n.status===0?p(n.stdout.trim()):null}catch{return null}},n=t(e.launchDirectory);if(n)return n;let r=new Set;for(let n of e.checkoutRoots){let e=t(n);if(e){r.add(e);continue}let i;try{i=d(n,{withFileTypes:!0})}catch{throw new R(`Checkout root is unreadable: ${n}`)}for(let e of i){if(!e.isDirectory()&&!e.isSymbolicLink())continue;let i=t(T(n,e.name));i&&r.add(i)}}if(r.size!==1)throw new R(`Repository ${e.repository} has ${r.size===0?`no matching`:`ambiguous`} checkout; select its checkout with --repo-root or configure checkoutRoots.`);return[...r][0]}function wu(e,...t){try{return b(gu,[...yu(e),...t],{env:vu(),cwd:e,encoding:`utf8`,maxBuffer:4194304,stdio:[`ignore`,`pipe`,`pipe`]}).trim()}catch(e){let n=String(e.stderr??``).trim();throw new R(`git ${t[0]??``} failed${n?`: ${n}`:``}`)}}function Tu(e,...t){let n=S(gu,[...yu(e),...t],{env:vu(),cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`]});if(n.error)throw n.error;return n.status??1}function Eu(e){return p(E(e,wu(e,`rev-parse`,`--show-toplevel`)))}function Du(e){return p(E(e,wu(e,`rev-parse`,`--git-common-dir`)))}function Ou(e){let t=Du(e);if(C(t)!==`.git`)throw new R(`Expected a conventional non-bare Git repository.`);return w(t)}function ku(e,t=`HEAD`){let n=wu(e,`rev-parse`,`--verify`,t),r=wu(e,`rev-parse`,`${n}^{tree}`);if(!/^[a-f0-9]{40}$/u.test(n)||!/^[a-f0-9]{40}$/u.test(r))throw new R(`Git coordinate is not a SHA-1 commit and tree.`);return{sha:n,tree:r}}function Au(e){if(wu(e,`status`,`--porcelain`,`--untracked-files=all`)!==``)throw new R(`Delivery requires an exact clean worktree.`)}function ju(e,t){let n=xu(e,t),r=`refs/remotes/${n}/`;if(Tu(e,`symbolic-ref`,`--quiet`,`${r}HEAD`)===0){let t=wu(e,`symbolic-ref`,`--quiet`,`${r}HEAD`);if(!t.startsWith(r))throw new R(`Selected remote HEAD points outside its tracking refs.`);return t}if(Tu(e,`show-ref`,`--verify`,`--quiet`,`${r}main`)===0)return`${r}main`;throw new R(`Fetch the selected remote ${n} and set its default branch before delivery.`)}var z=A().regex(/^sha256:[a-f0-9]{64}$/u),Mu=A().regex(/^[a-f0-9]{40}$/u),Nu=A().regex(/^[^/\s]+\/[^/\s]+$/u),Pu=A().regex(/^[a-z][a-z0-9-]*$/u),Fu=P({sha:Mu,tree:Mu}).strict();function B(e){if(Array.isArray(e))return`[${e.map(B).join(`,`)}]`;if(typeof e==`object`&&e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${B(t[e])}`).join(`,`)}}`}let t=JSON.stringify(e);if(t===void 0)throw Error(`Delivery evidence contains an unsupported value.`);return t}function V(e){return H(Buffer.from(B(e),`utf8`))}function H(e){return`sha256:${se(`sha256`).update(e).digest(`hex`)}`}function Iu(e){return e.every((t,n)=>n===0||e[n-1]<t)}function U(e,n){let i=o(e);if(!i.isFile()||i.isSymbolicLink()||i.nlink!==1||(i.mode&511)!=384)throw Error(`Delivery evidence must be a private regular file.`);if(n===void 0)return l(e);if(n.maxBytes!==void 0&&i.size>n.maxBytes||n.expectedBytes!==void 0&&i.size!==n.expectedBytes)throw Error(`Delivery evidence size exceeds its bound or differs from retained evidence.`);let a=c(e,`r`);try{let t=r(a);if(t.dev!==i.dev||t.ino!==i.ino||t.size!==i.size||t.mode!==i.mode||t.nlink!==i.nlink||t.uid!==i.uid||t.mtimeMs!==i.mtimeMs||t.ctimeMs!==i.ctimeMs)throw Error(`Delivery evidence identity changed before its bounded read.`);let n=Buffer.alloc(i.size),s=0;for(;s<n.length;){let e=u(a,n,s,n.length-s,s);if(e===0)throw Error(`Delivery evidence was truncated during its bounded read.`);s+=e}let c=r(a),l=o(e);if(c.dev!==t.dev||c.ino!==t.ino||c.size!==t.size||c.mode!==t.mode||c.nlink!==t.nlink||c.uid!==t.uid||c.mtimeMs!==t.mtimeMs||c.ctimeMs!==t.ctimeMs||l.dev!==c.dev||l.ino!==c.ino||l.isSymbolicLink())throw Error(`Delivery evidence bytes are missing, corrupt or changed during its bounded read.`);return n}finally{t(a)}}function Lu(e){let n=c(w(e),`r`);try{i(n)}finally{t(n)}}function Ru(e,n,r){if(r!==void 0&&(r!==H(n)||C(e)!==`${r.slice(7)}.bin`))throw Error(`Immutable output path does not bind its bytes.`);try{if(!U(e,{expectedBytes:n.length}).equals(n))throw Error(`Content addressed evidence path collision.`);return Lu(e),e}catch(e){if(e.code!==`ENOENT`)throw e}s(w(e),{recursive:!0,mode:448});let o=T(w(e),`.${C(e)}.${le()}.tmp`),l=c(o,`wx`,384),u=!1;try{try{y(l,n),i(l)}finally{t(l)}try{r===void 0?a(o,e):(m(o,e),u=!0)}catch(t){if(t.code!==`EEXIST`||!U(e,{expectedBytes:n.length}).equals(n))throw t}}finally{u||v(o)}if(Lu(e),!U(e,{expectedBytes:n.length}).equals(n))throw Error(`Content addressed evidence write failed.`);return e}function zu(){return typeof navigator==`object`&&`userAgent`in navigator?navigator.userAgent:typeof process==`object`&&process.version!==void 0?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:`<environment undetectable>`}var Bu={method:`GET`,baseUrl:`https://api.github.com`,headers:{accept:`application/vnd.github.v3+json`,"user-agent":`octokit-endpoint.js/0.0.0-development ${zu()}`},mediaType:{format:``}};function Vu(e){return e?Object.keys(e).reduce((t,n)=>(t[n.toLowerCase()]=e[n],t),{}):{}}function Hu(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let n=Object.prototype.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n instanceof n&&Function.prototype.call(n)===Function.prototype.call(e)}function Uu(e,t){let n=Object.assign({},e);return Object.keys(t).forEach(r=>{Hu(t[r])&&r in e?n[r]=Uu(e[r],t[r]):Object.assign(n,{[r]:t[r]})}),n}function Wu(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function Gu(e,t,n){if(typeof t==`string`){let[e,r]=t.split(` `);n=Object.assign(r?{method:e,url:r}:{url:e},n)}else n=Object.assign({},t);n.headers=Vu(n.headers),Wu(n),Wu(n.headers);let r=Uu(e||{},n);return n.url===`/graphql`&&(e&&e.mediaType.previews?.length&&(r.mediaType.previews=e.mediaType.previews.filter(e=>!r.mediaType.previews.includes(e)).concat(r.mediaType.previews)),r.mediaType.previews=(r.mediaType.previews||[]).map(e=>e.replace(/-preview/,``))),r}function Ku(e,t){let n=/\?/.test(e)?`&`:`?`,r=Object.keys(t);return r.length===0?e:e+n+r.map(e=>e===`q`?`q=`+t.q.split(`+`).map(encodeURIComponent).join(`+`):`${e}=${encodeURIComponent(t[e])}`).join(`&`)}var qu=/\{[^{}}]+\}/g;function Ju(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,``).split(/,/)}function Yu(e){let t=e.match(qu);return t?t.map(Ju).reduce((e,t)=>e.concat(t),[]):[]}function Xu(e,t){let n={__proto__:null};for(let r of Object.keys(e))t.indexOf(r)===-1&&(n[r]=e[r]);return n}function Zu(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(e){return/%[0-9A-Fa-f]/.test(e)||(e=encodeURI(e).replace(/%5B/g,`[`).replace(/%5D/g,`]`)),e}).join(``)}function Qu(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return`%`+e.charCodeAt(0).toString(16).toUpperCase()})}function $u(e,t,n){return t=e===`+`||e===`#`?Zu(t):Qu(t),n?Qu(n)+`=`+t:t}function ed(e){return e!=null}function td(e){return e===`;`||e===`&`||e===`?`}function nd(e,t,n,r){var i=e[n],a=[];if(ed(i)&&i!==``){if(typeof i==`string`||typeof i==`number`||typeof i==`bigint`||typeof i==`boolean`)i=i.toString(),r&&r!==`*`&&(i=i.substring(0,parseInt(r,10))),a.push($u(t,i,td(t)?n:``));else if(r===`*`)Array.isArray(i)?i.filter(ed).forEach(function(e){a.push($u(t,e,td(t)?n:``))}):Object.keys(i).forEach(function(e){ed(i[e])&&a.push($u(t,i[e],e))});else{let e=[];Array.isArray(i)?i.filter(ed).forEach(function(n){e.push($u(t,n))}):Object.keys(i).forEach(function(n){ed(i[n])&&(e.push(Qu(n)),e.push($u(t,i[n].toString())))}),td(t)?a.push(Qu(n)+`=`+e.join(`,`)):e.length!==0&&a.push(e.join(`,`))}}else t===`;`?ed(i)&&a.push(Qu(n)):i===``&&(t===`&`||t===`?`)?a.push(Qu(n)+`=`):i===``&&a.push(``);return a}function rd(e){return{expand:id.bind(null,e)}}function id(e,t){var n=[`+`,`#`,`.`,`/`,`;`,`?`,`&`];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(e,r,i){if(r){let e=``,i=[];if(n.indexOf(r.charAt(0))!==-1&&(e=r.charAt(0),r=r.substr(1)),r.split(/,/g).forEach(function(n){var r=/([^:\*]*)(?::(\d+)|(\*))?/.exec(n);i.push(nd(t,e,r[1],r[2]||r[3]))}),e&&e!==`+`){var a=`,`;return e===`?`?a=`&`:e!==`#`&&(a=e),(i.length===0?``:e)+i.join(a)}return i.join(`,`)}return Zu(i)}),e===`/`?e:e.replace(/\/$/,``)}function ad(e){let t=e.method.toUpperCase(),n=(e.url||`/`).replace(/:([a-z]\w+)/g,`{$1}`),r=Object.assign({},e.headers),i,a=Xu(e,[`method`,`baseUrl`,`url`,`headers`,`request`,`mediaType`]),o=Yu(n);n=rd(n).expand(a),/^http/.test(n)||(n=e.baseUrl+n);let s=Xu(a,Object.keys(e).filter(e=>o.includes(e)).concat(`baseUrl`));return/application\/octet-stream/i.test(r.accept)||(e.mediaType.format&&(r.accept=r.accept.split(/,/).map(t=>t.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(`,`)),n.endsWith(`/graphql`)&&e.mediaType.previews?.length&&(r.accept=(r.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[]).concat(e.mediaType.previews).map(t=>`application/vnd.github.${t}-preview${e.mediaType.format?`.${e.mediaType.format}`:`+json`}`).join(`,`))),[`GET`,`HEAD`].includes(t)?n=Ku(n,s):`data`in s?i=s.data:Object.keys(s).length&&(i=s),!r[`content-type`]&&i!==void 0&&(r[`content-type`]=`application/json; charset=utf-8`),[`PATCH`,`PUT`].includes(t)&&i===void 0&&(i=``),Object.assign({method:t,url:n,headers:r},i===void 0?null:{body:i},e.request?{request:e.request}:null)}function od(e,t,n){return ad(Gu(e,t,n))}function sd(e,t){let n=Gu(e,t),r=od.bind(null,n);return Object.assign(r,{DEFAULTS:n,defaults:sd.bind(null,n),merge:Gu.bind(null,n),parse:ad})}var cd=sd(null,Bu),ld=32,ud=9,dd=59,fd=61,pd=34,md=92,hd=44,gd=1,_d=2,vd=4,yd=8,bd=16,xd=65280,Sd=65281,Cd=new Uint8Array(256);Cd[ud]|=_d,Cd[ld]|=_d,Cd[dd]|=vd,Cd[hd]|=yd;for(let e=128;e<=255;e++)Cd[e]|=gd;for(let e of"!#$%&'*+-.^_`|~")Cd[e.charCodeAt(0)]|=bd;for(let e=48;e<=57;e++)Cd[e]|=bd;for(let e=65;e<=90;e++)Cd[e]|=17;for(let e=97;e<=122;e++)Cd[e]|=bd;var wd=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function Td(e,t){let n=vd|(t?.comma===!0?yd:0),r=e.length,i=t?.start??0;for(;(Cd[e.charCodeAt(i)]&_d)!==0;)i++;let a=i,o=0,s=-1,c=t?.parameters===!1?yd:0;for(;a<r;){let t=e.charCodeAt(a),r=Cd[t];if((r&n)!==0){c|=r&yd;break}(r&_d)===0?s=-1:s===-1&&(s=a),o|=t&xd|r,a++}let l=s===-1?a:s,u=e.slice(i,l),d=(o&Sd)===0?u:u.toLowerCase();return a===r||c!==0?{type:d,index:a,parameters:new wd}:Ed(e,d,a,r,n)}function Ed(e,t,n,r,i){let a=new wd;parameter:for(;n<r;){for(n++;(Cd[e.charCodeAt(n)]&_d)!==0;)n++;let t=n,o=0,s=-1;for(;n<r;){let c=e.charCodeAt(n),l=Cd[c];if((l&i)!==0){if((l&yd)!==0)break parameter;continue parameter}if(c===fd){let c=s===-1?n:s,l=e.slice(t,c),u=(o&Sd)===0?l:l.toLowerCase();for(n++;(Cd[e.charCodeAt(n)]&_d)!==0;)n++;if(n<r&&e.charCodeAt(n)===pd){let t=++n,o=!1;for(;n<r;){let s=e.charCodeAt(n);if(s===pd){a[u]===void 0&&(a[u]=o?Dd(e,t,n):e.slice(t,n)),n++;let s=0;for(;n<r;){let t=Cd[e.charCodeAt(n)];if((t&i)!==0){s=t&yd;break}n++}if(s!==0)break parameter;continue parameter}if(s===md&&n+1<r){o=!0,n+=2;continue}n++}continue parameter}let d=n,f=0,p=-1;for(;n<r;){let t=Cd[e.charCodeAt(n)];if((t&i)!==0){f=t&yd;break}(t&_d)===0?p=-1:p===-1&&(p=n),n++}if(a[u]===void 0){let t=p===-1?n:p;a[u]=e.slice(d,t)}if(f!==0)break parameter;continue parameter}(l&_d)===0?s=-1:s===-1&&(s=n),o|=c&xd|l,n++}}return{type:t,index:n,parameters:a}}function Dd(e,t,n){let r=``;for(let i=t;i<n;i++)e.charCodeAt(i)===md&&(r+=e.slice(t,i),t=++i);return r+e.slice(t,n)}var Od=/^-?\d+$/,kd=/^-?\d+n+$/,Ad=JSON.stringify,jd=JSON.parse,Md=/^-?\d+n$/,Nd=/([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g,Pd=/([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g,Fd=e=>e===void 0||typeof e==`function`||typeof e==`symbol`,Id=e=>typeof e==`object`&&!!e&&e.constructor&&e.constructor.name===`RawJSON`,Ld=(e,t,n)=>{let r=``;typeof n==`number`?r=` `.repeat(Math.min(10,Math.max(0,Math.floor(n)))):typeof n==`string`&&(r=n.slice(0,10));let i=typeof t==`function`,a=Array.isArray(t)?new Set(t.map(String)):null,o=(e,n,r)=>(typeof r==`object`&&r&&typeof r.toJSON==`function`&&(r=r.toJSON(n)),typeof r==`string`&&kd.test(r)?r+`n`:typeof r==`bigint`?`rawJSON`in JSON?JSON.rawJSON(r.toString()):r.toString()+`n`:(i&&(r=t.call(e,n,r)),typeof r==`object`&&r&&(r instanceof Number||r instanceof String||r instanceof Boolean)&&(r=r.valueOf()),r)),s=o({"":e},``,e);if(Fd(s))return;let c=typeof s!=`object`||!s,l=Id(s);if(c||l)return Ad(s);let u=[],d=0,f=[{parent:{"":s},key:``,val:s,isArray:Array.isArray(s),keys:Array.isArray(s)?null:Object.keys(s),index:0,first:!0}],p=new WeakSet([s]);for(;f.length>0;){let e=f[f.length-1];e.index===0&&(u.push(e.isArray?`[`:`{`),d++);let t=!1;if(e.isArray){if(e.index<e.val.length){e.first||u.push(`,`),r&&u.push(`
|
|
77
|
+
`+r.repeat(d));let t=e.val[e.index],n=o(e.val,String(e.index),t);if(Fd(n))u.push(`null`),e.first=!1,e.index++;else{let t=typeof n==`object`&&!!n,r=Id(n);if(t&&!r){if(p.has(n))throw TypeError(`Converting circular structure to JSON`);p.add(n),f.push({parent:e.val,key:String(e.index),val:n,isArray:Array.isArray(n),keys:Array.isArray(n)?null:Object.keys(n),index:0,first:!0}),e.first=!1,e.index++}else u.push(Ad(n)),e.first=!1,e.index++}}else t=!0}else{for(;e.index<e.keys.length;){let t=e.keys[e.index++];if(a&&!a.has(t))continue;let n=e.val[t],i=o(e.val,t,n);if(Fd(i))continue;e.first||u.push(`,`),r?u.push(`
|
|
78
|
+
`+r.repeat(d)+Ad(t)+`: `):u.push(Ad(t)+`:`);let s=typeof i==`object`&&!!i,c=Id(i);if(s&&!c){if(p.has(i))throw TypeError(`Converting circular structure to JSON`);p.add(i),f.push({parent:e.val,key:t,val:i,isArray:Array.isArray(i),keys:Array.isArray(i)?null:Object.keys(i),index:0,first:!0}),e.first=!1;break}u.push(Ad(i)),e.first=!1}e.index>=e.keys.length&&f[f.length-1]===e&&(t=!0)}t&&(d--,!e.first&&r&&u.push(`
|
|
79
|
+
`+r.repeat(d)),u.push(e.isArray?`]`:`}`),p.delete(e.val),f.pop())}return u.join(``)},Rd=(e,t,n)=>{try{return`rawJSON`in JSON?Ad(e,(e,n)=>typeof n==`bigint`?JSON.rawJSON(n.toString()):typeof t==`function`?t(e,n):(Array.isArray(t)&&t.includes(e),n),n):e?Ad(e,(e,n)=>typeof n==`string`&&kd.test(n)||typeof n==`bigint`?n.toString()+`n`:typeof t==`function`?t(e,n):(Array.isArray(t)&&t.includes(e),n),n).replace(Nd,`$1$2$3`).replace(Pd,`$1$2$3`):Ad(e,t,n)}catch(r){if(r instanceof RangeError){let r=Ld(e,t,n);return r===void 0?void 0:`rawJSON`in JSON?r:r.replace(Nd,`$1$2$3`).replace(Pd,`$1$2$3`)}throw r}},zd=new Map,Bd=()=>{let e=JSON.parse.toString();if(zd.has(e))return zd.get(e);try{let t=JSON.parse(`1`,(e,t,n)=>!!n?.source&&n.source===`1`);return zd.set(e,t),t}catch{return zd.set(e,!1),!1}},Vd=(e,t,n,r)=>typeof t==`string`&&Md.test(t)?BigInt(t.slice(0,-1)):typeof t==`string`&&kd.test(t)?t.slice(0,-1):typeof r==`function`?r(e,t,n):t,Hd=(e,t)=>JSON.parse(e,(e,n,r)=>{let i=typeof n==`number`&&(n>2**53-1||n<-(2**53-1)),a=r&&Od.test(r.source);return i&&a?BigInt(r.source):typeof t==`function`?t(e,n,r):n}),Ud=(2**53-1).toString(),Wd=Ud.length,Gd=/"(?:[^"\\]|\\.)*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,Kd=/^"-?\d+n+"$/,qd=(e,t)=>{let n={"":e},r=[{parent:n,key:``,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){let{parent:n,key:i}=e,a=n[i];typeof a==`string`&&(Md.test(a)?a=BigInt(a.slice(0,-1)):kd.test(a)&&(a=a.slice(0,-1))),typeof t==`function`&&(a=t.call(n,i,a)),a===void 0?delete n[i]:n[i]=a,r.pop()}else{e.visited=!0;let t=e.parent[e.key];if(typeof t==`object`&&t){let e=Object.keys(t);for(let n=e.length-1;n>=0;n--)r.push({parent:t,key:e[n],visited:!1})}}}return n[``]},Jd=e=>e.replace(Gd,(e,t,n,r)=>{let i=e[0]===`"`;if(i&&Kd.test(e))return e.substring(0,e.length-1)+`n"`;let a=n||r,o=t&&(t.length<Wd||t.length===Wd&&t<=Ud);return i||a||o?e:`"`+e+`n"`}),Yd=(e,t)=>{if(!e)return jd(e,t);try{return Bd()?Hd(e,t):jd(Jd(e),(e,n,r)=>Vd(e,n,r,t))}catch(n){if(n instanceof RangeError)return qd(jd(Jd(e)),t);throw n}},Xd=class extends Error{name;status;request;response;constructor(e,t,n){super(e,{cause:n.cause}),this.name=`HttpError`,this.status=Number.parseInt(t),Number.isNaN(this.status)&&(this.status=0),`response`in n&&(this.response=n.response);let r=Object.assign({},n.request);n.request.headers.authorization&&(r.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/,` [REDACTED]`)})),r.url=r.url.replace(/\bclient_secret=\w+/g,`client_secret=[REDACTED]`).replace(/\baccess_token=\w+/g,`access_token=[REDACTED]`),this.request=r}},Zd={headers:{"user-agent":`octokit-request.js/10.0.16 ${zu()}`}};function Qd(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let n=Object.prototype.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n instanceof n&&Function.prototype.call(n)===Function.prototype.call(e)}var $d=()=>``;async function ef(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw Error(`fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing`);let n=e.request?.log||console,r=e.request?.parseSuccessResponseBody!==!1,i=Qd(e.body)||Array.isArray(e.body)?Rd(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,String(t)])),o;try{o=await t(e.url,{method:e.method,body:i,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:`half`}})}catch(t){let n=`Unknown Error`;if(t instanceof Error){if(t.name===`AbortError`)throw t.status=500,t;n=t.message,t.name===`TypeError`&&`cause`in t&&(t.cause instanceof Error?n=t.cause.message:typeof t.cause==`string`&&(n=t.cause))}let r=new Xd(n,500,{request:e});throw r.cause=t,r}let s=o.status,c=o.url,l={};for(let[e,t]of o.headers)l[e]=t;let u={url:c,status:s,headers:l,data:``};if(`deprecation`in l){let t=l.link&&l.link.match(/<([^<>]+)>; rel="deprecation"/),r=t&&t.pop();n.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${l.sunset}${r?`. See ${r}`:``}`)}if(s===204||s===205)return u;if(e.method===`HEAD`){if(s<400)return u;throw new Xd(o.statusText,s,{response:u,request:e})}if(s===304)throw u.data=await tf(o),new Xd(`Not modified`,s,{response:u,request:e});if(s>=400)throw u.data=await tf(o),new Xd(rf(u.data),s,{response:u,request:e});return u.data=r?await tf(o):o.body,u}async function tf(e){let t=e.headers.get(`content-type`);if(!t)return e.text().catch($d);let n=Td(t);if(nf(n)){let t=``;try{return t=await e.text(),Yd(t)}catch{return t}}return n.type.startsWith(`text/`)||n.parameters.charset?.toLowerCase()===`utf-8`&&n.type!==`application/octet-stream`?e.text().catch($d):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function nf(e){return e.type===`application/json`||e.type===`application/scim+json`}function rf(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return`Unknown error`;if(typeof e==`object`&&e&&`message`in e){let t=e,n=`documentation_url`in t?` - ${t.documentation_url}`:``;return Array.isArray(t.errors)?`${t.message}: ${t.errors.map(e=>JSON.stringify(e)).join(`, `)}${n}`:`${t.message}${n}`}return`Unknown error: ${JSON.stringify(e)}`}function af(e,t){let n=e.defaults(t);return Object.assign(function(e,t){let r=n.merge(e,t);if(!r.request||!r.request.hook)return ef(n.parse(r));let i=(e,t)=>ef(n.parse(n.merge(e,t)));return Object.assign(i,{endpoint:n,defaults:af.bind(null,n)}),r.request.hook(i,r)},{endpoint:n,defaults:af.bind(null,n)})}var of=af(cd,Zd);function sf(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:/^https:\/\/api\..*\.ghe\.com$/.test(t.baseUrl)?t.baseUrl.replace(`api.`,``):t.baseUrl.replace(`/api/v3`,``)}async function cf(e,t,n){let r={baseUrl:sf(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new Xd(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function lf(e){let t=await cf(e.request||of,`POST /login/oauth/access_token`,{client_id:e.clientId,client_secret:e.clientSecret,code:e.code,redirect_uri:e.redirectUrl}),n={clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=uf(e,t.data.expires_in),n.refreshTokenExpiresAt=uf(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function uf(e,t){return new Date(e+t*1e3).toISOString()}async function df(e){let t=e.request||of,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),cf(t,`POST /login/device/code`,n)}async function ff(e){let t=await cf(e.request||of,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=pf(e,t.data.expires_in),n.refreshTokenExpiresAt=pf(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function pf(e,t){return new Date(e+t*1e3).toISOString()}async function mf(e){let t=await(e.request||of)(`POST /applications/{client_id}/token`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token}),n={clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:e.token,scopes:t.data.scopes};return t.data.expires_at&&(n.expiresAt=t.data.expires_at),e.clientType===`github-app`&&delete n.scopes,{...t,authentication:n}}async function hf(e){let t=await cf(e.request||of,`POST /login/oauth/access_token`,{client_id:e.clientId,client_secret:e.clientSecret,grant_type:`refresh_token`,refresh_token:e.refreshToken}),n=new Date(t.headers.date).getTime(),r={clientType:`github-app`,clientId:e.clientId,clientSecret:e.clientSecret,token:t.data.access_token,refreshToken:t.data.refresh_token,expiresAt:gf(n,t.data.expires_in),refreshTokenExpiresAt:gf(n,t.data.refresh_token_expires_in)};return{...t,authentication:r}}function gf(e,t){return new Date(e+t*1e3).toISOString()}async function _f(e){let t=await(e.request||of)(`PATCH /applications/{client_id}/token`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token}),n={clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:t.data.token,scopes:t.data.scopes};return t.data.expires_at&&(n.expiresAt=t.data.expires_at),e.clientType===`github-app`&&delete n.scopes,{...t,authentication:n}}async function vf(e){return(e.request||of)(`DELETE /applications/{client_id}/token`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token})}async function yf(e){return(e.request||of)(`DELETE /applications/{client_id}/grant`,{headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`},client_id:e.clientId,access_token:e.token})}async function bf(e,t){let n=xf(e,t.auth);if(n)return n;let{data:r}=await df({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Cf(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function xf(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)&&n}async function Sf(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Cf(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await ff({...i,clientType:`oauth-app`}):await ff({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Sf(r.interval),Cf(e,t,n,r);if(a===`slow_down`)return await Sf(r.interval+7),Cf(e,t,n,r);throw i}}async function wf(e,t){return bf(e,{auth:t})}async function Tf(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await bf(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Ef=`0.0.0-development`;function Df(e){let t=e.request||of.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Ef} ${zu()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(wf.bind(null,i),{hook:Tf.bind(null,i)})}var Of=`0.0.0-development`;async function kf(e){if(`code`in e.strategyOptions){let{authentication:t}=await lf({clientId:e.clientId,clientSecret:e.clientSecret,clientType:e.clientType,onTokenCreated:e.onTokenCreated,...e.strategyOptions,request:e.request});return{type:`token`,tokenType:`oauth`,...t}}if(`onVerification`in e.strategyOptions){let t=await Df({clientType:e.clientType,clientId:e.clientId,onTokenCreated:e.onTokenCreated,...e.strategyOptions,request:e.request})({type:`oauth`});return{clientSecret:e.clientSecret,...t}}if(`token`in e.strategyOptions)return{type:`token`,tokenType:`oauth`,clientId:e.clientId,clientSecret:e.clientSecret,clientType:e.clientType,onTokenCreated:e.onTokenCreated,...e.strategyOptions};throw Error(`[@octokit/auth-oauth-user] Invalid strategy options`)}async function Af(e,t={}){if(e.authentication||=(e.clientType,await kf(e)),e.authentication.invalid)throw Error(`[@octokit/auth-oauth-user] Token is invalid`);let n=e.authentication;if(`expiresAt`in n&&(t.type===`refresh`||new Date(n.expiresAt)<new Date)){let{authentication:t}=await hf({clientType:`github-app`,clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:n.refreshToken,request:e.request});e.authentication={tokenType:`oauth`,type:`token`,...t}}if(t.type===`refresh`){if(e.clientType===`oauth-app`)throw Error(`[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens`);if(!n.hasOwnProperty(`expiresAt`))throw Error(`[@octokit/auth-oauth-user] Refresh token missing`);await e.onTokenCreated?.(e.authentication,{type:t.type})}if(t.type===`check`||t.type===`reset`){let n=t.type===`check`?mf:_f;try{let{authentication:r}=await n({clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:e.authentication.token,request:e.request});return e.authentication={tokenType:`oauth`,type:`token`,...r},t.type===`reset`&&await e.onTokenCreated?.(e.authentication,{type:t.type}),e.authentication}catch(t){throw t.status===404&&(t.message=`[@octokit/auth-oauth-user] Token is invalid`,e.authentication.invalid=!0),t}}if(t.type===`delete`||t.type===`deleteAuthorization`){let n=t.type===`delete`?vf:yf;try{await n({clientType:e.clientType,clientId:e.clientId,clientSecret:e.clientSecret,token:e.authentication.token,request:e.request})}catch(e){if(e.status!==404)throw e}return e.authentication.invalid=!0,e.authentication}return e.authentication}var jf=/\/applications\/[^/]+\/(token|grant)s?/;function Mf(e){return e&&jf.test(e)}async function Nf(e,t,n,r={}){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);if(Mf(i.url)){let n=btoa(`${e.clientId}:${e.clientSecret}`);return i.headers.authorization=`basic ${n}`,t(i)}let{token:a}=(e.clientType,await Af({...e,request:t}));return i.headers.authorization=`token `+a,t(i)}function Pf({clientId:e,clientSecret:t,clientType:n=`oauth-app`,request:r=of.defaults({headers:{"user-agent":`octokit-auth-oauth-app.js/${Of} ${zu()}`}}),onTokenCreated:i,...a}){let o=Object.assign({clientType:n,clientId:e,clientSecret:t,onTokenCreated:i,strategyOptions:a,request:r});return Object.assign(Af.bind(null,o),{hook:Nf.bind(null,o)})}Pf.VERSION=Of;async function Ff(e,t){if(t.type===`oauth-app`)return{type:`oauth-app`,clientId:e.clientId,clientSecret:e.clientSecret,clientType:e.clientType,headers:{authorization:`basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`}};if(`factory`in t){let{type:n,...r}={...t,...e};return t.factory(r)}let n={clientId:e.clientId,clientSecret:e.clientSecret,request:e.request,...t};return(e.clientType,await Pf({...n,clientType:e.clientType}))()}async function If(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);if(e.clientType===`github-app`&&!Mf(i.url))throw Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${i.method} ${i.url}" is not supported.`);let a=btoa(`${e.clientId}:${e.clientSecret}`);i.headers.authorization=`basic ${a}`;try{return await t(i)}catch(e){throw e.status===401&&(e.message=`[@octokit/auth-oauth-app] "${i.method} ${i.url}" does not support clientId/clientSecret basic authentication.`),e}}var Lf=`0.0.0-development`;function Rf(e){let t=Object.assign({request:of.defaults({headers:{"user-agent":`octokit-auth-oauth-app.js/${Lf} ${zu()}`}}),clientType:`oauth-app`},e);return Object.assign(Ff.bind(null,t),{hook:If.bind(null,t)})}function zf(e){return e.includes(`-----BEGIN RSA PRIVATE KEY-----`)}function Bf(e){return e.includes(`-----BEGIN OPENSSH PRIVATE KEY-----`)}function Vf(e){let t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t++)n[t]=e.charCodeAt(t);return t}function Hf(e){let t=e.trim().split(`
|
|
80
|
+
`).slice(1,-1).join(``);return Vf(atob(t))}function Uf(e,t){return`${Kf(e)}.${Kf(t)}`}function Wf(e){for(var t=``,n=new Uint8Array(e),r=n.byteLength,i=0;i<r;i++)t+=String.fromCharCode(n[i]);return Gf(btoa(t))}function Gf(e){return e.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function Kf(e){return Gf(btoa(JSON.stringify(e)))}function qf(e){return zf(e)?ce(e).export({type:`pkcs8`,format:`pem`}):e}async function Jf({privateKey:e,payload:t}){let n=qf(e);if(zf(n))throw Error(`[universal-github-app-jwt] Private Key is in PKCS#1 format, but only PKCS#8 is supported. See https://github.com/gr2m/universal-github-app-jwt#private-key-formats`);if(Bf(n))throw Error(`[universal-github-app-jwt] Private Key is in OpenSSH format, but only PKCS#8 is supported. See https://github.com/gr2m/universal-github-app-jwt#private-key-formats`);let r={name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}},i={alg:`RS256`,typ:`JWT`},a=Hf(n),o=await ue.importKey(`pkcs8`,a,r,!1,[`sign`]),s=Uf(i,t),c=Vf(s);return`${s}.${Wf(await ue.sign(r.name,o,c))}`}async function Yf({id:e,privateKey:t,now:n=Math.floor(Date.now()/1e3)}){let r=t.replace(/\\n/g,`
|
|
81
|
+
`),i=n-30,a=i+600;return{appId:e,expiration:a,token:await Jf({privateKey:r,payload:{iat:i,exp:a,iss:e}})}}function Xf(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<0)throw Error(`Invalid max value`);if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`Invalid ttl value`)}var Zf=class{constructor(e=1e3,t=0){Xf(e,t),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=t}bumpLru(e){if(this.last===e)return;let t=this.last,n=e.next,r=e.prev;this.first===e&&(this.first=n),e.next=null,e.prev=t,t.next=e,r!==null&&(r.next=n),n!==null&&(n.prev=r),this.last=e}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let t=this.items[e];t!==void 0&&(delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev))}deleteMany(e){for(var t=0;t<e.length;t++)this.delete(e[t])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let t=this.items[e];if(t!==void 0)return t.expiry}get(e){let t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(t),t.value}}getMany(e){let t=Array(e.length);for(var n=0;n<e.length;n++)t[n]=this.get(e[n]);return t}keys(){return Object.keys(this.items)}set(e,t){let n=this.items[e];if(n!==void 0){n.value=t,n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(n);return}this.max>0&&this.size>=this.max&&this.evict();let r={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};this.items[e]=r,++this.size===1?this.first=r:this.last.next=r,this.last=r}};async function Qf({appId:e,privateKey:t,timeDifference:n,createJwt:r}){try{if(r){let{jwt:t,expiresAt:i}=await r(e,n);return{type:`app`,token:t,appId:e,expiresAt:i}}let i={id:e,privateKey:t};n&&Object.assign(i,{now:Math.floor(Date.now()/1e3)+n});let a=await Yf(i);return{type:`app`,token:a.token,appId:a.appId,expiresAt:new Date(a.expiration*1e3).toISOString()}}catch(e){throw t===`-----BEGIN RSA PRIVATE KEY-----`?Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"):e}}function $f(){return new Zf(15e3,354e4)}async function ep(e,t){let n=np(t),r=await e.get(n);if(!r)return;let[i,a,o,s,c,l]=r.split(`|`);return{token:i,createdAt:a,expiresAt:o,permissions:t.permissions||c.split(/,/).reduce((e,t)=>(/!$/.test(t)?e[t.slice(0,-1)]=`write`:e[t]=`read`,e),{}),repositoryIds:t.repositoryIds,repositoryNames:t.repositoryNames,singleFileName:l,repositorySelection:s}}async function tp(e,t,n){let r=np(t),i=t.permissions?``:Object.keys(n.permissions).map(e=>`${e}${n.permissions[e]===`write`?`!`:``}`).join(`,`),a=[n.token,n.createdAt,n.expiresAt,n.repositorySelection,i,n.singleFileName].join(`|`);await e.set(r,a)}function np({installationId:e,permissions:t={},repositoryIds:n=[],repositoryNames:r=[]}){let i=Object.keys(t).sort().map(e=>t[e]===`read`?e:`${e}!`).join(`,`);return[e,n.sort().join(`,`),r.join(`,`),i].filter(Boolean).join(`|`)}function rp({installationId:e,token:t,createdAt:n,expiresAt:r,repositorySelection:i,permissions:a,repositoryIds:o,repositoryNames:s,singleFileName:c}){return Object.assign({type:`token`,tokenType:`installation`,token:t,installationId:e,permissions:a,createdAt:n,expiresAt:r,repositorySelection:i},o?{repositoryIds:o}:null,s?{repositoryNames:s}:null,c?{singleFileName:c}:null)}async function ip(e,t,n){let r=Number(t.installationId||e.installationId);if(!r)throw Error(`[@octokit/auth-app] installationId option is required for installation authentication.`);if(t.factory){let{type:n,factory:r,oauthApp:i,...a}={...e,...t};return r(a)}let i=n||e.request;return op(e,{...t,installationId:r},i)}var ap=new Map;function op(e,t,n){let r=np(t);if(ap.has(r))return ap.get(r);let i=sp(e,t,n).finally(()=>ap.delete(r));return ap.set(r,i),i}async function sp(e,t,n){if(!t.refresh){let n=await ep(e.cache,t);if(n){let{token:e,createdAt:r,expiresAt:i,permissions:a,repositoryIds:o,repositoryNames:s,singleFileName:c,repositorySelection:l}=n;return rp({installationId:t.installationId,token:e,createdAt:r,expiresAt:i,permissions:a,repositorySelection:l,repositoryIds:o,repositoryNames:s,singleFileName:c})}}let r=await Qf(e),i={installation_id:t.installationId,mediaType:{previews:[`machine-man`]},headers:{authorization:`bearer ${r.token}`}};t.repositoryIds&&Object.assign(i,{repository_ids:t.repositoryIds}),t.repositoryNames&&Object.assign(i,{repositories:t.repositoryNames}),t.permissions&&Object.assign(i,{permissions:t.permissions});let{data:{token:a,expires_at:o,repositories:s,permissions:c,repository_selection:l,single_file:u}}=await n(`POST /app/installations/{installation_id}/access_tokens`,i),d=c||{},f=l||`all`,p=s?s.map(e=>e.id):void 0,m=s?s.map(e=>e.name):void 0,h=new Date().toISOString(),g={token:a,createdAt:h,expiresAt:o,repositorySelection:f,permissions:d,repositoryIds:p,repositoryNames:m};u&&Object.assign(i,{singleFileName:u}),await tp(e.cache,t,g);let _={installationId:t.installationId,token:a,createdAt:h,expiresAt:o,repositorySelection:f,permissions:d,repositoryIds:p,repositoryNames:m};return u&&Object.assign(_,{singleFileName:u}),rp(_)}async function cp(e,t){switch(t.type){case`app`:return Qf(e);case`oauth-app`:return e.oauthApp({type:`oauth-app`});case`installation`:return ip(e,{...t,type:`installation`});case`oauth-user`:return e.oauthApp(t);default:throw Error(`Invalid auth type: ${t.type}`)}}var lp=[`/app`,`/app/hook/config`,`/app/hook/deliveries`,`/app/hook/deliveries/{delivery_id}`,`/app/hook/deliveries/{delivery_id}/attempts`,`/app/installations`,`/app/installations/{installation_id}`,`/app/installations/{installation_id}/access_tokens`,`/app/installations/{installation_id}/suspended`,`/app/installation-requests`,`/marketplace_listing/accounts/{account_id}`,`/marketplace_listing/plan`,`/marketplace_listing/plans`,`/marketplace_listing/plans/{plan_id}/accounts`,`/marketplace_listing/stubbed/accounts/{account_id}`,`/marketplace_listing/stubbed/plan`,`/marketplace_listing/stubbed/plans`,`/marketplace_listing/stubbed/plans/{plan_id}/accounts`,`/orgs/{org}/installation`,`/repos/{owner}/{repo}/installation`,`/users/{username}/installation`,`/enterprises/{enterprise}/installation`];function up(e){let t=`^(?:${e.map(e=>e.split(`/`).map(e=>e.startsWith(`{`)?`(?:.+?)`:e).join(`/`)).map(e=>`(?:${e})`).join(`|`)})$`;return new RegExp(t,`i`)}var dp=up(lp);function fp(e){return!!e&&dp.test(e.split(`?`)[0])}var pp=5e3;function mp(e){return!(e.message.match(/'Expiration time' claim \('exp'\) is too far in the future/)||e.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/)||e.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/))}async function hp(e,t,n,r){let i=t.endpoint.merge(n,r),a=i.url;if(/\/login\/oauth\/access_token$/.test(a))return t(i);if(fp(a.replace(t.endpoint.DEFAULTS.baseUrl,``))){let{token:n}=await Qf(e);i.headers.authorization=`bearer ${n}`;let r;try{r=await t(i)}catch(n){if(mp(n)||n.response.headers.date===void 0)throw n;let r=Math.floor((Date.parse(n.response.headers.date)-Date.parse(new Date().toString()))/1e3);e.log.warn(n.message),e.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${r} seconds. Retrying request with the difference accounted for.`);let{token:a}=await Qf({...e,timeDifference:r});return i.headers.authorization=`bearer ${a}`,t(i)}return r}if(Mf(a)){let n=await e.oauthApp({type:`oauth-app`});return i.headers.authorization=n.headers.authorization,t(i)}let{token:o,createdAt:s}=await ip(e,{},t.defaults({baseUrl:i.baseUrl}));return i.headers.authorization=`token ${o}`,gp(e,t,i,s)}async function gp(e,t,n,r,i=0){let a=+new Date-new Date(r);try{return await t(n)}catch(o){if(o.status!==401)throw o;if(a>=pp)throw i>0&&(o.message=`After ${i} retries within ${a/1e3}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`),o;++i;let s=i*1e3;return e.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${i}, wait: ${s/1e3}s)`),await new Promise(e=>setTimeout(e,s)),gp(e,t,n,r,i)}}var _p=`8.3.1`;function vp(e){if(!e.appId)throw Error(`[@octokit/auth-app] appId option is required`);if(!e.privateKey&&!e.createJwt)throw Error(`[@octokit/auth-app] privateKey option is required`);if(e.privateKey&&e.createJwt)throw Error(`[@octokit/auth-app] privateKey and createJwt options are mutually exclusive`);if(`installationId`in e&&!e.installationId)throw Error(`[@octokit/auth-app] installationId is set to a falsy value`);let t=e.log||{};typeof t.warn!=`function`&&(t.warn=console.warn.bind(console));let n=e.request||of.defaults({headers:{"user-agent":`octokit-auth-app.js/${_p} ${zu()}`}}),r=Object.assign({request:n,cache:$f()},e,e.installationId?{installationId:Number(e.installationId)}:{},{log:t,oauthApp:Rf({clientType:`github-app`,clientId:e.clientId||``,clientSecret:e.clientSecret||``,request:n})});return Object.assign(cp.bind(null,r),{hook:hp.bind(null,r)})}var yp=`0.0.0-development`;function bp(e){return`Request failed due to following response errors:
|
|
82
82
|
`+e.errors.map(e=>` - ${e.message}`).join(`
|
|
83
|
-
`)}var Sp=class extends Error{constructor(e,t,n){super(xp(n)),this.request=e,this.headers=t,this.response=n,this.errors=n.errors,this.data=n.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}request;headers;response;name=`GraphqlResponseError`;errors;data},Cp=[`method`,`baseUrl`,`url`,`headers`,`request`,`query`,`mediaType`,`operationName`],wp=[`query`,`method`,`url`],Tp=/\/api\/v3\/?$/;function Ep(e,t,n){if(n){if(typeof t==`string`&&`query`in n)return Promise.reject(Error(`[@octokit/graphql] "query" cannot be used as variable name`));for(let e in n)if(wp.includes(e))return Promise.reject(Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}let r=typeof t==`string`?Object.assign({query:t},n):t,i=Object.keys(r).reduce((e,t)=>Cp.includes(t)?(e[t]=r[t],e):(e.variables||={},e.variables[t]=r[t],e),{}),a=r.baseUrl||e.endpoint.DEFAULTS.baseUrl;return Tp.test(a)&&(i.url=a.replace(Tp,`/api/graphql`)),e(i).then(e=>{if(e.data.errors){let t={};for(let n of Object.keys(e.headers))t[n]=e.headers[n];throw new Sp(i,t,e.data)}return e.data.data})}function Dp(e,t){let n=e.defaults(t);return Object.assign((e,t)=>Ep(n,e,t),{defaults:Dp.bind(null,n),endpoint:n.endpoint})}var Op=Dp(sf,{headers:{"user-agent":`octokit-graphql.js/${bp} ${Bu()}`},method:`POST`,url:`/graphql`});function kp(e){return Dp(e,{method:`POST`,url:`/graphql`})}function Ap(e,t,n,r){if(typeof n!=`function`)throw Error(`method for before hook must be a function`);return r||={},Array.isArray(t)?t.reverse().reduce((t,n)=>Ap.bind(null,e,n,t,r),n)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((e,t)=>t.hook.bind(null,e,r),n)():n(r))}function jp(e,t,n,r){let i=r;e.registry[n]||(e.registry[n]=[]),t===`before`&&(r=(e,t)=>Promise.resolve().then(i.bind(null,t)).then(e.bind(null,t))),t===`after`&&(r=(e,t)=>{let n;return Promise.resolve().then(e.bind(null,t)).then(e=>(n=e,i(n,t))).then(()=>n)}),t===`error`&&(r=(e,t)=>Promise.resolve().then(e.bind(null,t)).catch(e=>i(e,t))),e.registry[n].push({hook:r,orig:i})}function Mp(e,t,n){if(!e.registry[t])return;let r=e.registry[t].map(e=>e.orig).indexOf(n);r!==-1&&e.registry[t].splice(r,1)}var Np=Function.bind,Pp=Np.bind(Np);function Fp(e,t,n){let r=Pp(Mp,null).apply(null,n?[t,n]:[t]);e.api={remove:r},e.remove=r,[`before`,`error`,`after`,`wrap`].forEach(r=>{let i=n?[t,r,n]:[t,r];e[r]=e.api[r]=Pp(jp,null).apply(null,i)})}function Ip(){let e=Symbol(`Singular`),t={registry:{}},n=Ap.bind(null,t,e);return Fp(n,t,e),n}function Lp(){let e={registry:{}},t=Ap.bind(null,e);return Fp(t,e),t}var Rp={Singular:Ip,Collection:Lp},zp=`(?:[a-zA-Z0-9_-]+)`,Bp=`\\.`,Vp=RegExp(`^${zp}${Bp}${zp}${Bp}${zp}$`),Hp=Vp.test.bind(Vp);async function Up(e){let t=Hp(e),n=e.startsWith(`v1.`)||e.startsWith(`ghs_`),r=e.startsWith(`ghu_`);return{type:`token`,token:e,tokenType:t?`app`:n?`installation`:r?`user-to-server`:`oauth`}}function Wp(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function Gp(e,t,n,r){let i=t.endpoint.merge(n,r);return i.headers.authorization=Wp(e),t(i)}var Kp=function(e){if(!e)throw Error(`[@octokit/auth-token] No token passed to createTokenAuth`);if(typeof e!=`string`)throw Error(`[@octokit/auth-token] Token passed to createTokenAuth is not a string`);return e=e.replace(/^(token|bearer) +/i,``),Object.assign(Up.bind(null,e),{hook:Gp.bind(null,e)})},qp=`7.0.8`,Jp=()=>{},Yp=console.warn.bind(console),Xp=console.error.bind(console);function Zp(e={}){return typeof e.debug!=`function`&&(e.debug=Jp),typeof e.info!=`function`&&(e.info=Jp),typeof e.warn!=`function`&&(e.warn=Yp),typeof e.error!=`function`&&(e.error=Xp),e}var Qp=`octokit-core.js/${qp} ${Bu()}`,$p=class{static VERSION=qp;static defaults(e){return class extends this{constructor(...t){let n=t[0]||{};if(typeof e==`function`){super(e(n));return}super(Object.assign({},e,n,n.userAgent&&e.userAgent?{userAgent:`${n.userAgent} ${e.userAgent}`}:null))}}}static plugins=[];static plugin(...e){let t=this.plugins;return class extends this{static plugins=t.concat(e.filter(e=>!t.includes(e)))}}constructor(e={}){let t=new Rp.Collection,n={baseUrl:sf.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,`request`)}),mediaType:{previews:[],format:``}};if(n.headers[`user-agent`]=e.userAgent?`${e.userAgent} ${Qp}`:Qp,e.baseUrl&&(n.baseUrl=e.baseUrl),e.previews&&(n.mediaType.previews=e.previews),e.timeZone&&(n.headers[`time-zone`]=e.timeZone),this.request=sf.defaults(n),this.graphql=kp(this.request).defaults(n),this.log=Zp(e.log),this.hook=t,e.authStrategy){let{authStrategy:n,...r}=e,i=n(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:r},e.auth));t.wrap(`request`,i.hook),this.auth=i}else if(!e.auth)this.auth=async()=>({type:`unauthenticated`});else{let n=Kp(e.auth);t.wrap(`request`,n.hook),this.auth=n}let r=this.constructor;for(let t=0;t<r.plugins.length;++t)Object.assign(this,r.plugins[t](this,e))}request;graphql;log;hook;auth},em=`6.0.0`;function tm(e){e.hook.wrap(`request`,(t,n)=>{e.log.debug(`request`,n);let r=Date.now(),i=e.request.endpoint.parse(n),a=i.url.replace(n.baseUrl,``);return t(n).then(t=>{let n=t.headers[`x-github-request-id`];return e.log.info(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t}).catch(t=>{let n=t.response?.headers[`x-github-request-id`]||`UNKNOWN`;throw e.log.error(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t})})}tm.VERSION=em;var nm=`0.0.0-development`;function rm(e){if(!e.data)return{...e,data:[]};if(!((`total_count`in e.data||`total_commits`in e.data)&&!(`url`in e.data)))return e;let t=e.data.incomplete_results,n=e.data.repository_selection,r=e.data.total_count,i=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let a=Object.keys(e.data)[0];return e.data=e.data[a],t!==void 0&&(e.data.incomplete_results=t),n!==void 0&&(e.data.repository_selection=n),e.data.total_count=r,e.data.total_commits=i,e}function im(e,t,n){let r=typeof t==`function`?t.endpoint(n):e.request.endpoint(t,n),i=typeof t==`function`?t:e.request,a=r.method,o=r.headers,s=r.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!s)return{done:!0};try{let e=rm(await i({method:a,url:s,headers:o}));if(s=((e.headers.link||``).match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!s&&`total_commits`in e.data){let t=new URL(e.url),n=t.searchParams,r=parseInt(n.get(`page`)||`1`,10);r*parseInt(n.get(`per_page`)||`250`,10)<e.data.total_commits&&(n.set(`page`,String(r+1)),s=t.toString())}return{value:e}}catch(e){if(e.status!==409)throw e;return s=``,{value:{status:200,headers:{},data:[]}}}}})}}function am(e,t,n,r){return typeof n==`function`&&(r=n,n=void 0),om(e,[],im(e,t,n)[Symbol.asyncIterator](),r)}function om(e,t,n,r){return n.next().then(i=>{if(i.done)return t;let a=!1;function o(){a=!0}return t=t.concat(r?r(i.value,o):i.value.data),a?t:om(e,t,n,r)})}Object.assign(am,{iterator:im});function sm(e){return{paginate:Object.assign(am.bind(null,e),{iterator:im.bind(null,e)})}}sm.VERSION=nm;var cm=`17.0.0`,lm={actions:{addCustomLabelsToSelfHostedRunnerForOrg:[`POST /orgs/{org}/actions/runners/{runner_id}/labels`],addCustomLabelsToSelfHostedRunnerForRepo:[`POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],addRepoAccessToSelfHostedRunnerGroupInOrg:[`PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],approveWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve`],cancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel`],createEnvironmentVariable:[`POST /repos/{owner}/{repo}/environments/{environment_name}/variables`],createHostedRunnerForOrg:[`POST /orgs/{org}/actions/hosted-runners`],createOrUpdateEnvironmentSecret:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}`],createOrgVariable:[`POST /orgs/{org}/actions/variables`],createRegistrationTokenForOrg:[`POST /orgs/{org}/actions/runners/registration-token`],createRegistrationTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/registration-token`],createRemoveTokenForOrg:[`POST /orgs/{org}/actions/runners/remove-token`],createRemoveTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/remove-token`],createRepoVariable:[`POST /repos/{owner}/{repo}/actions/variables`],createWorkflowDispatch:[`POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches`],deleteActionsCacheById:[`DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}`],deleteActionsCacheByKey:[`DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}`],deleteArtifact:[`DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],deleteCustomImageFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],deleteCustomImageVersionFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],deleteEnvironmentSecret:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],deleteEnvironmentVariable:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],deleteHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],deleteOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}`],deleteOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}`],deleteRepoVariable:[`DELETE /repos/{owner}/{repo}/actions/variables/{name}`],deleteSelfHostedRunnerFromOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}`],deleteSelfHostedRunnerFromRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}`],deleteWorkflowRun:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}`],deleteWorkflowRunLogs:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],disableSelectedRepositoryGithubActionsOrganization:[`DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}`],disableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable`],downloadArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}`],downloadJobLogsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs`],downloadWorkflowRunAttemptLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs`],downloadWorkflowRunLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],enableSelectedRepositoryGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories/{repository_id}`],enableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable`],forceCancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel`],generateRunnerJitconfigForOrg:[`POST /orgs/{org}/actions/runners/generate-jitconfig`],generateRunnerJitconfigForRepo:[`POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig`],getActionsCacheList:[`GET /repos/{owner}/{repo}/actions/caches`],getActionsCacheUsage:[`GET /repos/{owner}/{repo}/actions/cache/usage`],getActionsCacheUsageByRepoForOrg:[`GET /orgs/{org}/actions/cache/usage-by-repository`],getActionsCacheUsageForOrg:[`GET /orgs/{org}/actions/cache/usage`],getAllowedActionsOrganization:[`GET /orgs/{org}/actions/permissions/selected-actions`],getAllowedActionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/selected-actions`],getArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],getCustomImageForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],getCustomImageVersionForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],getCustomOidcSubClaimForRepo:[`GET /repos/{owner}/{repo}/actions/oidc/customization/sub`],getEnvironmentPublicKey:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key`],getEnvironmentSecret:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],getEnvironmentVariable:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],getGithubActionsDefaultWorkflowPermissionsOrganization:[`GET /orgs/{org}/actions/permissions/workflow`],getGithubActionsDefaultWorkflowPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/workflow`],getGithubActionsPermissionsOrganization:[`GET /orgs/{org}/actions/permissions`],getGithubActionsPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions`],getHostedRunnerForOrg:[`GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],getHostedRunnersGithubOwnedImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/github-owned`],getHostedRunnersLimitsForOrg:[`GET /orgs/{org}/actions/hosted-runners/limits`],getHostedRunnersMachineSpecsForOrg:[`GET /orgs/{org}/actions/hosted-runners/machine-sizes`],getHostedRunnersPartnerImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/partner`],getHostedRunnersPlatformsForOrg:[`GET /orgs/{org}/actions/hosted-runners/platforms`],getJobForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}`],getOrgPublicKey:[`GET /orgs/{org}/actions/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}`],getOrgVariable:[`GET /orgs/{org}/actions/variables/{name}`],getPendingDeploymentsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],getRepoPermissions:[`GET /repos/{owner}/{repo}/actions/permissions`,{},{renamed:[`actions`,`getGithubActionsPermissionsRepository`]}],getRepoPublicKey:[`GET /repos/{owner}/{repo}/actions/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/actions/secrets/{secret_name}`],getRepoVariable:[`GET /repos/{owner}/{repo}/actions/variables/{name}`],getReviewsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals`],getSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}`],getSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}`],getWorkflow:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}`],getWorkflowAccessToRepository:[`GET /repos/{owner}/{repo}/actions/permissions/access`],getWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}`],getWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}`],getWorkflowRunUsage:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing`],getWorkflowUsage:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing`],listArtifactsForRepo:[`GET /repos/{owner}/{repo}/actions/artifacts`],listCustomImageVersionsForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions`],listCustomImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom`],listEnvironmentSecrets:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets`],listEnvironmentVariables:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables`],listGithubHostedRunnersInGroupForOrg:[`GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners`],listHostedRunnersForOrg:[`GET /orgs/{org}/actions/hosted-runners`],listJobsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs`],listJobsForWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs`],listLabelsForSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}/labels`],listLabelsForSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],listOrgSecrets:[`GET /orgs/{org}/actions/secrets`],listOrgVariables:[`GET /orgs/{org}/actions/variables`],listRepoOrganizationSecrets:[`GET /repos/{owner}/{repo}/actions/organization-secrets`],listRepoOrganizationVariables:[`GET /repos/{owner}/{repo}/actions/organization-variables`],listRepoSecrets:[`GET /repos/{owner}/{repo}/actions/secrets`],listRepoVariables:[`GET /repos/{owner}/{repo}/actions/variables`],listRepoWorkflows:[`GET /repos/{owner}/{repo}/actions/workflows`],listRunnerApplicationsForOrg:[`GET /orgs/{org}/actions/runners/downloads`],listRunnerApplicationsForRepo:[`GET /repos/{owner}/{repo}/actions/runners/downloads`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}/repositories`],listSelectedReposForOrgVariable:[`GET /orgs/{org}/actions/variables/{name}/repositories`],listSelectedRepositoriesEnabledGithubActionsOrganization:[`GET /orgs/{org}/actions/permissions/repositories`],listSelfHostedRunnersForOrg:[`GET /orgs/{org}/actions/runners`],listSelfHostedRunnersForRepo:[`GET /repos/{owner}/{repo}/actions/runners`],listWorkflowRunArtifacts:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts`],listWorkflowRuns:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs`],listWorkflowRunsForRepo:[`GET /repos/{owner}/{repo}/actions/runs`],reRunJobForWorkflowRun:[`POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun`],reRunWorkflow:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun`],reRunWorkflowFailedJobs:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs`],removeAllCustomLabelsFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels`],removeAllCustomLabelsFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],removeCustomLabelFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}`],removeCustomLabelFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],reviewCustomGatesForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule`],reviewPendingDeploymentsForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],setAllowedActionsOrganization:[`PUT /orgs/{org}/actions/permissions/selected-actions`],setAllowedActionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/selected-actions`],setCustomLabelsForSelfHostedRunnerForOrg:[`PUT /orgs/{org}/actions/runners/{runner_id}/labels`],setCustomLabelsForSelfHostedRunnerForRepo:[`PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],setCustomOidcSubClaimForRepo:[`PUT /repos/{owner}/{repo}/actions/oidc/customization/sub`],setGithubActionsDefaultWorkflowPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions/workflow`],setGithubActionsDefaultWorkflowPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/workflow`],setGithubActionsPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions`],setGithubActionsPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories`],setSelectedReposForOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories`],setSelectedRepositoriesEnabledGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories`],setWorkflowAccessToRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/access`],updateEnvironmentVariable:[`PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],updateHostedRunnerForOrg:[`PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],updateOrgVariable:[`PATCH /orgs/{org}/actions/variables/{name}`],updateRepoVariable:[`PATCH /repos/{owner}/{repo}/actions/variables/{name}`]},activity:{checkRepoIsStarredByAuthenticatedUser:[`GET /user/starred/{owner}/{repo}`],deleteRepoSubscription:[`DELETE /repos/{owner}/{repo}/subscription`],deleteThreadSubscription:[`DELETE /notifications/threads/{thread_id}/subscription`],getFeeds:[`GET /feeds`],getRepoSubscription:[`GET /repos/{owner}/{repo}/subscription`],getThread:[`GET /notifications/threads/{thread_id}`],getThreadSubscriptionForAuthenticatedUser:[`GET /notifications/threads/{thread_id}/subscription`],listEventsForAuthenticatedUser:[`GET /users/{username}/events`],listNotificationsForAuthenticatedUser:[`GET /notifications`],listOrgEventsForAuthenticatedUser:[`GET /users/{username}/events/orgs/{org}`],listPublicEvents:[`GET /events`],listPublicEventsForRepoNetwork:[`GET /networks/{owner}/{repo}/events`],listPublicEventsForUser:[`GET /users/{username}/events/public`],listPublicOrgEvents:[`GET /orgs/{org}/events`],listReceivedEventsForUser:[`GET /users/{username}/received_events`],listReceivedPublicEventsForUser:[`GET /users/{username}/received_events/public`],listRepoEvents:[`GET /repos/{owner}/{repo}/events`],listRepoNotificationsForAuthenticatedUser:[`GET /repos/{owner}/{repo}/notifications`],listReposStarredByAuthenticatedUser:[`GET /user/starred`],listReposStarredByUser:[`GET /users/{username}/starred`],listReposWatchedByUser:[`GET /users/{username}/subscriptions`],listStargazersForRepo:[`GET /repos/{owner}/{repo}/stargazers`],listWatchedReposForAuthenticatedUser:[`GET /user/subscriptions`],listWatchersForRepo:[`GET /repos/{owner}/{repo}/subscribers`],markNotificationsAsRead:[`PUT /notifications`],markRepoNotificationsAsRead:[`PUT /repos/{owner}/{repo}/notifications`],markThreadAsDone:[`DELETE /notifications/threads/{thread_id}`],markThreadAsRead:[`PATCH /notifications/threads/{thread_id}`],setRepoSubscription:[`PUT /repos/{owner}/{repo}/subscription`],setThreadSubscription:[`PUT /notifications/threads/{thread_id}/subscription`],starRepoForAuthenticatedUser:[`PUT /user/starred/{owner}/{repo}`],unstarRepoForAuthenticatedUser:[`DELETE /user/starred/{owner}/{repo}`]},apps:{addRepoToInstallation:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`addRepoToInstallationForAuthenticatedUser`]}],addRepoToInstallationForAuthenticatedUser:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`],checkToken:[`POST /applications/{client_id}/token`],createFromManifest:[`POST /app-manifests/{code}/conversions`],createInstallationAccessToken:[`POST /app/installations/{installation_id}/access_tokens`],deleteAuthorization:[`DELETE /applications/{client_id}/grant`],deleteInstallation:[`DELETE /app/installations/{installation_id}`],deleteToken:[`DELETE /applications/{client_id}/token`],getAuthenticated:[`GET /app`],getBySlug:[`GET /apps/{app_slug}`],getInstallation:[`GET /app/installations/{installation_id}`],getOrgInstallation:[`GET /orgs/{org}/installation`],getRepoInstallation:[`GET /repos/{owner}/{repo}/installation`],getSubscriptionPlanForAccount:[`GET /marketplace_listing/accounts/{account_id}`],getSubscriptionPlanForAccountStubbed:[`GET /marketplace_listing/stubbed/accounts/{account_id}`],getUserInstallation:[`GET /users/{username}/installation`],getWebhookConfigForApp:[`GET /app/hook/config`],getWebhookDelivery:[`GET /app/hook/deliveries/{delivery_id}`],listAccountsForPlan:[`GET /marketplace_listing/plans/{plan_id}/accounts`],listAccountsForPlanStubbed:[`GET /marketplace_listing/stubbed/plans/{plan_id}/accounts`],listInstallationReposForAuthenticatedUser:[`GET /user/installations/{installation_id}/repositories`],listInstallationRequestsForAuthenticatedApp:[`GET /app/installation-requests`],listInstallations:[`GET /app/installations`],listInstallationsForAuthenticatedUser:[`GET /user/installations`],listPlans:[`GET /marketplace_listing/plans`],listPlansStubbed:[`GET /marketplace_listing/stubbed/plans`],listReposAccessibleToInstallation:[`GET /installation/repositories`],listSubscriptionsForAuthenticatedUser:[`GET /user/marketplace_purchases`],listSubscriptionsForAuthenticatedUserStubbed:[`GET /user/marketplace_purchases/stubbed`],listWebhookDeliveries:[`GET /app/hook/deliveries`],redeliverWebhookDelivery:[`POST /app/hook/deliveries/{delivery_id}/attempts`],removeRepoFromInstallation:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`removeRepoFromInstallationForAuthenticatedUser`]}],removeRepoFromInstallationForAuthenticatedUser:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`],resetToken:[`PATCH /applications/{client_id}/token`],revokeInstallationAccessToken:[`DELETE /installation/token`],scopeToken:[`POST /applications/{client_id}/token/scoped`],suspendInstallation:[`PUT /app/installations/{installation_id}/suspended`],unsuspendInstallation:[`DELETE /app/installations/{installation_id}/suspended`],updateWebhookConfigForApp:[`PATCH /app/hook/config`]},billing:{getGithubActionsBillingOrg:[`GET /orgs/{org}/settings/billing/actions`],getGithubActionsBillingUser:[`GET /users/{username}/settings/billing/actions`],getGithubBillingPremiumRequestUsageReportOrg:[`GET /organizations/{org}/settings/billing/premium_request/usage`],getGithubBillingPremiumRequestUsageReportUser:[`GET /users/{username}/settings/billing/premium_request/usage`],getGithubBillingUsageReportOrg:[`GET /organizations/{org}/settings/billing/usage`],getGithubBillingUsageReportUser:[`GET /users/{username}/settings/billing/usage`],getGithubPackagesBillingOrg:[`GET /orgs/{org}/settings/billing/packages`],getGithubPackagesBillingUser:[`GET /users/{username}/settings/billing/packages`],getSharedStorageBillingOrg:[`GET /orgs/{org}/settings/billing/shared-storage`],getSharedStorageBillingUser:[`GET /users/{username}/settings/billing/shared-storage`]},campaigns:{createCampaign:[`POST /orgs/{org}/campaigns`],deleteCampaign:[`DELETE /orgs/{org}/campaigns/{campaign_number}`],getCampaignSummary:[`GET /orgs/{org}/campaigns/{campaign_number}`],listOrgCampaigns:[`GET /orgs/{org}/campaigns`],updateCampaign:[`PATCH /orgs/{org}/campaigns/{campaign_number}`]},checks:{create:[`POST /repos/{owner}/{repo}/check-runs`],createSuite:[`POST /repos/{owner}/{repo}/check-suites`],get:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}`],getSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}`],listAnnotations:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations`],listForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-runs`],listForSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs`],listSuitesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-suites`],rerequestRun:[`POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest`],rerequestSuite:[`POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest`],setSuitesPreferences:[`PATCH /repos/{owner}/{repo}/check-suites/preferences`],update:[`PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}`]},codeScanning:{commitAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits`],createAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],createVariantAnalysis:[`POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses`],deleteAnalysis:[`DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}`],deleteCodeqlDatabase:[`DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getAlert:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`,{},{renamedParameters:{alert_id:`alert_number`}}],getAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}`],getAutofix:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],getCodeqlDatabase:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getDefaultSetup:[`GET /repos/{owner}/{repo}/code-scanning/default-setup`],getSarif:[`GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}`],getVariantAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}`],getVariantAnalysisRepoTask:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}`],listAlertInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`],listAlertsForOrg:[`GET /orgs/{org}/code-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/code-scanning/alerts`],listAlertsInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`,{},{renamed:[`codeScanning`,`listAlertInstances`]}],listCodeqlDatabases:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases`],listRecentAnalyses:[`GET /repos/{owner}/{repo}/code-scanning/analyses`],updateAlert:[`PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`],updateDefaultSetup:[`PATCH /repos/{owner}/{repo}/code-scanning/default-setup`],uploadSarif:[`POST /repos/{owner}/{repo}/code-scanning/sarifs`]},codeSecurity:{attachConfiguration:[`POST /orgs/{org}/code-security/configurations/{configuration_id}/attach`],attachEnterpriseConfiguration:[`POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach`],createConfiguration:[`POST /orgs/{org}/code-security/configurations`],createConfigurationForEnterprise:[`POST /enterprises/{enterprise}/code-security/configurations`],deleteConfiguration:[`DELETE /orgs/{org}/code-security/configurations/{configuration_id}`],deleteConfigurationForEnterprise:[`DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],detachConfiguration:[`DELETE /orgs/{org}/code-security/configurations/detach`],getConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}`],getConfigurationForRepository:[`GET /repos/{owner}/{repo}/code-security-configuration`],getConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations`],getConfigurationsForOrg:[`GET /orgs/{org}/code-security/configurations`],getDefaultConfigurations:[`GET /orgs/{org}/code-security/configurations/defaults`],getDefaultConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/defaults`],getRepositoriesForConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories`],getRepositoriesForEnterpriseConfiguration:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories`],getSingleConfigurationForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],setConfigurationAsDefault:[`PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults`],setConfigurationAsDefaultForEnterprise:[`PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults`],updateConfiguration:[`PATCH /orgs/{org}/code-security/configurations/{configuration_id}`],updateEnterpriseConfiguration:[`PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}`]},codesOfConduct:{getAllCodesOfConduct:[`GET /codes_of_conduct`],getConductCode:[`GET /codes_of_conduct/{key}`]},codespaces:{addRepositoryForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],checkPermissionsForDevcontainer:[`GET /repos/{owner}/{repo}/codespaces/permissions_check`],codespaceMachinesForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/machines`],createForAuthenticatedUser:[`POST /user/codespaces`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],createOrUpdateSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}`],createWithPrForAuthenticatedUser:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces`],createWithRepoForAuthenticatedUser:[`POST /repos/{owner}/{repo}/codespaces`],deleteForAuthenticatedUser:[`DELETE /user/codespaces/{codespace_name}`],deleteFromOrganization:[`DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],deleteSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}`],exportForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/exports`],getCodespacesForUserInOrg:[`GET /orgs/{org}/members/{username}/codespaces`],getExportDetailsForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/exports/{export_id}`],getForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}`],getOrgPublicKey:[`GET /orgs/{org}/codespaces/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}`],getPublicKeyForAuthenticatedUser:[`GET /user/codespaces/secrets/public-key`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/codespaces/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],getSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}`],listDevcontainersInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/devcontainers`],listForAuthenticatedUser:[`GET /user/codespaces`],listInOrganization:[`GET /orgs/{org}/codespaces`,{},{renamedParameters:{org_id:`org`}}],listInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces`],listOrgSecrets:[`GET /orgs/{org}/codespaces/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/codespaces/secrets`],listRepositoriesForSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}/repositories`],listSecretsForAuthenticatedUser:[`GET /user/codespaces/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],preFlightWithRepoForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/new`],publishForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/publish`],removeRepositoryForSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],repoMachinesForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/machines`],setRepositoriesForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],startForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/start`],stopForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/stop`],stopInOrganization:[`POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop`],updateForAuthenticatedUser:[`PATCH /user/codespaces/{codespace_name}`]},copilot:{addCopilotSeatsForTeams:[`POST /orgs/{org}/copilot/billing/selected_teams`],addCopilotSeatsForUsers:[`POST /orgs/{org}/copilot/billing/selected_users`],cancelCopilotSeatAssignmentForTeams:[`DELETE /orgs/{org}/copilot/billing/selected_teams`],cancelCopilotSeatAssignmentForUsers:[`DELETE /orgs/{org}/copilot/billing/selected_users`],copilotMetricsForOrganization:[`GET /orgs/{org}/copilot/metrics`],copilotMetricsForTeam:[`GET /orgs/{org}/team/{team_slug}/copilot/metrics`],getCopilotOrganizationDetails:[`GET /orgs/{org}/copilot/billing`],getCopilotSeatDetailsForUser:[`GET /orgs/{org}/members/{username}/copilot`],listCopilotSeats:[`GET /orgs/{org}/copilot/billing/seats`]},credentials:{revoke:[`POST /credentials/revoke`]},dependabot:{addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],getAlert:[`GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],getOrgPublicKey:[`GET /orgs/{org}/dependabot/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/dependabot/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],listAlertsForEnterprise:[`GET /enterprises/{enterprise}/dependabot/alerts`],listAlertsForOrg:[`GET /orgs/{org}/dependabot/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/dependabot/alerts`],listOrgSecrets:[`GET /orgs/{org}/dependabot/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/dependabot/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],repositoryAccessForOrg:[`GET /organizations/{org}/dependabot/repository-access`],setRepositoryAccessDefaultLevel:[`PUT /organizations/{org}/dependabot/repository-access/default-level`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],updateAlert:[`PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],updateRepositoryAccessForOrg:[`PATCH /organizations/{org}/dependabot/repository-access`]},dependencyGraph:{createRepositorySnapshot:[`POST /repos/{owner}/{repo}/dependency-graph/snapshots`],diffRange:[`GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}`],exportSbom:[`GET /repos/{owner}/{repo}/dependency-graph/sbom`]},emojis:{get:[`GET /emojis`]},enterpriseTeamMemberships:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove`],get:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],list:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships`],remove:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`]},enterpriseTeamOrganizations:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove`],delete:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignment:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignments:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations`]},enterpriseTeams:{create:[`POST /enterprises/{enterprise}/teams`],delete:[`DELETE /enterprises/{enterprise}/teams/{team_slug}`],get:[`GET /enterprises/{enterprise}/teams/{team_slug}`],list:[`GET /enterprises/{enterprise}/teams`],update:[`PATCH /enterprises/{enterprise}/teams/{team_slug}`]},gists:{checkIsStarred:[`GET /gists/{gist_id}/star`],create:[`POST /gists`],createComment:[`POST /gists/{gist_id}/comments`],delete:[`DELETE /gists/{gist_id}`],deleteComment:[`DELETE /gists/{gist_id}/comments/{comment_id}`],fork:[`POST /gists/{gist_id}/forks`],get:[`GET /gists/{gist_id}`],getComment:[`GET /gists/{gist_id}/comments/{comment_id}`],getRevision:[`GET /gists/{gist_id}/{sha}`],list:[`GET /gists`],listComments:[`GET /gists/{gist_id}/comments`],listCommits:[`GET /gists/{gist_id}/commits`],listForUser:[`GET /users/{username}/gists`],listForks:[`GET /gists/{gist_id}/forks`],listPublic:[`GET /gists/public`],listStarred:[`GET /gists/starred`],star:[`PUT /gists/{gist_id}/star`],unstar:[`DELETE /gists/{gist_id}/star`],update:[`PATCH /gists/{gist_id}`],updateComment:[`PATCH /gists/{gist_id}/comments/{comment_id}`]},git:{createBlob:[`POST /repos/{owner}/{repo}/git/blobs`],createCommit:[`POST /repos/{owner}/{repo}/git/commits`],createRef:[`POST /repos/{owner}/{repo}/git/refs`],createTag:[`POST /repos/{owner}/{repo}/git/tags`],createTree:[`POST /repos/{owner}/{repo}/git/trees`],deleteRef:[`DELETE /repos/{owner}/{repo}/git/refs/{ref}`],getBlob:[`GET /repos/{owner}/{repo}/git/blobs/{file_sha}`],getCommit:[`GET /repos/{owner}/{repo}/git/commits/{commit_sha}`],getRef:[`GET /repos/{owner}/{repo}/git/ref/{ref}`],getTag:[`GET /repos/{owner}/{repo}/git/tags/{tag_sha}`],getTree:[`GET /repos/{owner}/{repo}/git/trees/{tree_sha}`],listMatchingRefs:[`GET /repos/{owner}/{repo}/git/matching-refs/{ref}`],updateRef:[`PATCH /repos/{owner}/{repo}/git/refs/{ref}`]},gitignore:{getAllTemplates:[`GET /gitignore/templates`],getTemplate:[`GET /gitignore/templates/{name}`]},hostedCompute:{createNetworkConfigurationForOrg:[`POST /orgs/{org}/settings/network-configurations`],deleteNetworkConfigurationFromOrg:[`DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkConfigurationForOrg:[`GET /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkSettingsForOrg:[`GET /orgs/{org}/settings/network-settings/{network_settings_id}`],listNetworkConfigurationsForOrg:[`GET /orgs/{org}/settings/network-configurations`],updateNetworkConfigurationForOrg:[`PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}`]},interactions:{getRestrictionsForAuthenticatedUser:[`GET /user/interaction-limits`],getRestrictionsForOrg:[`GET /orgs/{org}/interaction-limits`],getRestrictionsForRepo:[`GET /repos/{owner}/{repo}/interaction-limits`],getRestrictionsForYourPublicRepos:[`GET /user/interaction-limits`,{},{renamed:[`interactions`,`getRestrictionsForAuthenticatedUser`]}],removeRestrictionsForAuthenticatedUser:[`DELETE /user/interaction-limits`],removeRestrictionsForOrg:[`DELETE /orgs/{org}/interaction-limits`],removeRestrictionsForRepo:[`DELETE /repos/{owner}/{repo}/interaction-limits`],removeRestrictionsForYourPublicRepos:[`DELETE /user/interaction-limits`,{},{renamed:[`interactions`,`removeRestrictionsForAuthenticatedUser`]}],setRestrictionsForAuthenticatedUser:[`PUT /user/interaction-limits`],setRestrictionsForOrg:[`PUT /orgs/{org}/interaction-limits`],setRestrictionsForRepo:[`PUT /repos/{owner}/{repo}/interaction-limits`],setRestrictionsForYourPublicRepos:[`PUT /user/interaction-limits`,{},{renamed:[`interactions`,`setRestrictionsForAuthenticatedUser`]}]},issues:{addAssignees:[`POST /repos/{owner}/{repo}/issues/{issue_number}/assignees`],addBlockedByDependency:[`POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],addLabels:[`POST /repos/{owner}/{repo}/issues/{issue_number}/labels`],addSubIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],checkUserCanBeAssigned:[`GET /repos/{owner}/{repo}/assignees/{assignee}`],checkUserCanBeAssignedToIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}`],create:[`POST /repos/{owner}/{repo}/issues`],createComment:[`POST /repos/{owner}/{repo}/issues/{issue_number}/comments`],createLabel:[`POST /repos/{owner}/{repo}/labels`],createMilestone:[`POST /repos/{owner}/{repo}/milestones`],deleteComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}`],deleteLabel:[`DELETE /repos/{owner}/{repo}/labels/{name}`],deleteMilestone:[`DELETE /repos/{owner}/{repo}/milestones/{milestone_number}`],get:[`GET /repos/{owner}/{repo}/issues/{issue_number}`],getComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}`],getEvent:[`GET /repos/{owner}/{repo}/issues/events/{event_id}`],getLabel:[`GET /repos/{owner}/{repo}/labels/{name}`],getMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}`],getParent:[`GET /repos/{owner}/{repo}/issues/{issue_number}/parent`],list:[`GET /issues`],listAssignees:[`GET /repos/{owner}/{repo}/assignees`],listComments:[`GET /repos/{owner}/{repo}/issues/{issue_number}/comments`],listCommentsForRepo:[`GET /repos/{owner}/{repo}/issues/comments`],listDependenciesBlockedBy:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],listDependenciesBlocking:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking`],listEvents:[`GET /repos/{owner}/{repo}/issues/{issue_number}/events`],listEventsForRepo:[`GET /repos/{owner}/{repo}/issues/events`],listEventsForTimeline:[`GET /repos/{owner}/{repo}/issues/{issue_number}/timeline`],listForAuthenticatedUser:[`GET /user/issues`],listForOrg:[`GET /orgs/{org}/issues`],listForRepo:[`GET /repos/{owner}/{repo}/issues`],listLabelsForMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels`],listLabelsForRepo:[`GET /repos/{owner}/{repo}/labels`],listLabelsOnIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/labels`],listMilestones:[`GET /repos/{owner}/{repo}/milestones`],listSubIssues:[`GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],lock:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/lock`],removeAllLabels:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels`],removeAssignees:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees`],removeDependencyBlockedBy:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}`],removeLabel:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}`],removeSubIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue`],reprioritizeSubIssue:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority`],setLabels:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/labels`],unlock:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock`],update:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}`],updateComment:[`PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}`],updateLabel:[`PATCH /repos/{owner}/{repo}/labels/{name}`],updateMilestone:[`PATCH /repos/{owner}/{repo}/milestones/{milestone_number}`]},licenses:{get:[`GET /licenses/{license}`],getAllCommonlyUsed:[`GET /licenses`],getForRepo:[`GET /repos/{owner}/{repo}/license`]},markdown:{render:[`POST /markdown`],renderRaw:[`POST /markdown/raw`,{headers:{"content-type":`text/plain; charset=utf-8`}}]},meta:{get:[`GET /meta`],getAllVersions:[`GET /versions`],getOctocat:[`GET /octocat`],getZen:[`GET /zen`],root:[`GET /`]},migrations:{deleteArchiveForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/archive`],deleteArchiveForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/archive`],downloadArchiveForOrg:[`GET /orgs/{org}/migrations/{migration_id}/archive`],getArchiveForAuthenticatedUser:[`GET /user/migrations/{migration_id}/archive`],getStatusForAuthenticatedUser:[`GET /user/migrations/{migration_id}`],getStatusForOrg:[`GET /orgs/{org}/migrations/{migration_id}`],listForAuthenticatedUser:[`GET /user/migrations`],listForOrg:[`GET /orgs/{org}/migrations`],listReposForAuthenticatedUser:[`GET /user/migrations/{migration_id}/repositories`],listReposForOrg:[`GET /orgs/{org}/migrations/{migration_id}/repositories`],listReposForUser:[`GET /user/migrations/{migration_id}/repositories`,{},{renamed:[`migrations`,`listReposForAuthenticatedUser`]}],startForAuthenticatedUser:[`POST /user/migrations`],startForOrg:[`POST /orgs/{org}/migrations`],unlockRepoForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock`],unlockRepoForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock`]},oidc:{getOidcCustomSubTemplateForOrg:[`GET /orgs/{org}/actions/oidc/customization/sub`],updateOidcCustomSubTemplateForOrg:[`PUT /orgs/{org}/actions/oidc/customization/sub`]},orgs:{addSecurityManagerTeam:[`PUT /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team`}],assignTeamToOrgRole:[`PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],assignUserToOrgRole:[`PUT /orgs/{org}/organization-roles/users/{username}/{role_id}`],blockUser:[`PUT /orgs/{org}/blocks/{username}`],cancelInvitation:[`DELETE /orgs/{org}/invitations/{invitation_id}`],checkBlockedUser:[`GET /orgs/{org}/blocks/{username}`],checkMembershipForUser:[`GET /orgs/{org}/members/{username}`],checkPublicMembershipForUser:[`GET /orgs/{org}/public_members/{username}`],convertMemberToOutsideCollaborator:[`PUT /orgs/{org}/outside_collaborators/{username}`],createArtifactStorageRecord:[`POST /orgs/{org}/artifacts/metadata/storage-record`],createInvitation:[`POST /orgs/{org}/invitations`],createIssueType:[`POST /orgs/{org}/issue-types`],createWebhook:[`POST /orgs/{org}/hooks`],customPropertiesForOrgsCreateOrUpdateOrganizationValues:[`PATCH /organizations/{org}/org-properties/values`],customPropertiesForOrgsGetOrganizationValues:[`GET /organizations/{org}/org-properties/values`],customPropertiesForReposCreateOrUpdateOrganizationDefinition:[`PUT /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:[`PATCH /orgs/{org}/properties/schema`],customPropertiesForReposCreateOrUpdateOrganizationValues:[`PATCH /orgs/{org}/properties/values`],customPropertiesForReposDeleteOrganizationDefinition:[`DELETE /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinition:[`GET /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinitions:[`GET /orgs/{org}/properties/schema`],customPropertiesForReposGetOrganizationValues:[`GET /orgs/{org}/properties/values`],delete:[`DELETE /orgs/{org}`],deleteAttestationsBulk:[`POST /orgs/{org}/attestations/delete-request`],deleteAttestationsById:[`DELETE /orgs/{org}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /orgs/{org}/attestations/digest/{subject_digest}`],deleteIssueType:[`DELETE /orgs/{org}/issue-types/{issue_type_id}`],deleteWebhook:[`DELETE /orgs/{org}/hooks/{hook_id}`],disableSelectedRepositoryImmutableReleasesOrganization:[`DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],enableSelectedRepositoryImmutableReleasesOrganization:[`PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],get:[`GET /orgs/{org}`],getImmutableReleasesSettings:[`GET /orgs/{org}/settings/immutable-releases`],getImmutableReleasesSettingsRepositories:[`GET /orgs/{org}/settings/immutable-releases/repositories`],getMembershipForAuthenticatedUser:[`GET /user/memberships/orgs/{org}`],getMembershipForUser:[`GET /orgs/{org}/memberships/{username}`],getOrgRole:[`GET /orgs/{org}/organization-roles/{role_id}`],getOrgRulesetHistory:[`GET /orgs/{org}/rulesets/{ruleset_id}/history`],getOrgRulesetVersion:[`GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}`],getWebhook:[`GET /orgs/{org}/hooks/{hook_id}`],getWebhookConfigForOrg:[`GET /orgs/{org}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}`],list:[`GET /organizations`],listAppInstallations:[`GET /orgs/{org}/installations`],listArtifactStorageRecords:[`GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records`],listAttestationRepositories:[`GET /orgs/{org}/attestations/repositories`],listAttestations:[`GET /orgs/{org}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}`],listBlockedUsers:[`GET /orgs/{org}/blocks`],listFailedInvitations:[`GET /orgs/{org}/failed_invitations`],listForAuthenticatedUser:[`GET /user/orgs`],listForUser:[`GET /users/{username}/orgs`],listInvitationTeams:[`GET /orgs/{org}/invitations/{invitation_id}/teams`],listIssueTypes:[`GET /orgs/{org}/issue-types`],listMembers:[`GET /orgs/{org}/members`],listMembershipsForAuthenticatedUser:[`GET /user/memberships/orgs`],listOrgRoleTeams:[`GET /orgs/{org}/organization-roles/{role_id}/teams`],listOrgRoleUsers:[`GET /orgs/{org}/organization-roles/{role_id}/users`],listOrgRoles:[`GET /orgs/{org}/organization-roles`],listOrganizationFineGrainedPermissions:[`GET /orgs/{org}/organization-fine-grained-permissions`],listOutsideCollaborators:[`GET /orgs/{org}/outside_collaborators`],listPatGrantRepositories:[`GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories`],listPatGrantRequestRepositories:[`GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories`],listPatGrantRequests:[`GET /orgs/{org}/personal-access-token-requests`],listPatGrants:[`GET /orgs/{org}/personal-access-tokens`],listPendingInvitations:[`GET /orgs/{org}/invitations`],listPublicMembers:[`GET /orgs/{org}/public_members`],listSecurityManagerTeams:[`GET /orgs/{org}/security-managers`,{},{deprecated:`octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams`}],listWebhookDeliveries:[`GET /orgs/{org}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /orgs/{org}/hooks`],pingWebhook:[`POST /orgs/{org}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeMember:[`DELETE /orgs/{org}/members/{username}`],removeMembershipForUser:[`DELETE /orgs/{org}/memberships/{username}`],removeOutsideCollaborator:[`DELETE /orgs/{org}/outside_collaborators/{username}`],removePublicMembershipForAuthenticatedUser:[`DELETE /orgs/{org}/public_members/{username}`],removeSecurityManagerTeam:[`DELETE /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team`}],reviewPatGrantRequest:[`POST /orgs/{org}/personal-access-token-requests/{pat_request_id}`],reviewPatGrantRequestsInBulk:[`POST /orgs/{org}/personal-access-token-requests`],revokeAllOrgRolesTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}`],revokeAllOrgRolesUser:[`DELETE /orgs/{org}/organization-roles/users/{username}`],revokeOrgRoleTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],revokeOrgRoleUser:[`DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}`],setImmutableReleasesSettings:[`PUT /orgs/{org}/settings/immutable-releases`],setImmutableReleasesSettingsRepositories:[`PUT /orgs/{org}/settings/immutable-releases/repositories`],setMembershipForUser:[`PUT /orgs/{org}/memberships/{username}`],setPublicMembershipForAuthenticatedUser:[`PUT /orgs/{org}/public_members/{username}`],unblockUser:[`DELETE /orgs/{org}/blocks/{username}`],update:[`PATCH /orgs/{org}`],updateIssueType:[`PUT /orgs/{org}/issue-types/{issue_type_id}`],updateMembershipForAuthenticatedUser:[`PATCH /user/memberships/orgs/{org}`],updatePatAccess:[`POST /orgs/{org}/personal-access-tokens/{pat_id}`],updatePatAccesses:[`POST /orgs/{org}/personal-access-tokens`],updateWebhook:[`PATCH /orgs/{org}/hooks/{hook_id}`],updateWebhookConfigForOrg:[`PATCH /orgs/{org}/hooks/{hook_id}/config`]},packages:{deletePackageForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}`],deletePackageForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}`],deletePackageForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}`],deletePackageVersionForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getAllPackageVersionsForAPackageOwnedByAnOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByOrg`]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByAuthenticatedUser`]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions`],getPackageForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}`],getPackageForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}`],getPackageForUser:[`GET /users/{username}/packages/{package_type}/{package_name}`],getPackageVersionForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],listDockerMigrationConflictingPackagesForAuthenticatedUser:[`GET /user/docker/conflicts`],listDockerMigrationConflictingPackagesForOrganization:[`GET /orgs/{org}/docker/conflicts`],listDockerMigrationConflictingPackagesForUser:[`GET /users/{username}/docker/conflicts`],listPackagesForAuthenticatedUser:[`GET /user/packages`],listPackagesForOrganization:[`GET /orgs/{org}/packages`],listPackagesForUser:[`GET /users/{username}/packages`],restorePackageForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageVersionForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`]},privateRegistries:{createOrgPrivateRegistry:[`POST /orgs/{org}/private-registries`],deleteOrgPrivateRegistry:[`DELETE /orgs/{org}/private-registries/{secret_name}`],getOrgPrivateRegistry:[`GET /orgs/{org}/private-registries/{secret_name}`],getOrgPublicKey:[`GET /orgs/{org}/private-registries/public-key`],listOrgPrivateRegistries:[`GET /orgs/{org}/private-registries`],updateOrgPrivateRegistry:[`PATCH /orgs/{org}/private-registries/{secret_name}`]},projects:{addItemForOrg:[`POST /orgs/{org}/projectsV2/{project_number}/items`],addItemForUser:[`POST /users/{username}/projectsV2/{project_number}/items`],deleteItemForOrg:[`DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],deleteItemForUser:[`DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}`],getFieldForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}`],getFieldForUser:[`GET /users/{username}/projectsV2/{project_number}/fields/{field_id}`],getForOrg:[`GET /orgs/{org}/projectsV2/{project_number}`],getForUser:[`GET /users/{username}/projectsV2/{project_number}`],getOrgItem:[`GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],getUserItem:[`GET /users/{username}/projectsV2/{project_number}/items/{item_id}`],listFieldsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields`],listFieldsForUser:[`GET /users/{username}/projectsV2/{project_number}/fields`],listForOrg:[`GET /orgs/{org}/projectsV2`],listForUser:[`GET /users/{username}/projectsV2`],listItemsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/items`],listItemsForUser:[`GET /users/{username}/projectsV2/{project_number}/items`],updateItemForOrg:[`PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],updateItemForUser:[`PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}`]},pulls:{checkIfMerged:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/merge`],create:[`POST /repos/{owner}/{repo}/pulls`],createReplyForReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies`],createReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],createReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments`],deletePendingReview:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],deleteReviewComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}`],dismissReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals`],get:[`GET /repos/{owner}/{repo}/pulls/{pull_number}`],getReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],getReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}`],list:[`GET /repos/{owner}/{repo}/pulls`],listCommentsForReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments`],listCommits:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/commits`],listFiles:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/files`],listRequestedReviewers:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],listReviewComments:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/comments`],listReviewCommentsForRepo:[`GET /repos/{owner}/{repo}/pulls/comments`],listReviews:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],merge:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge`],removeRequestedReviewers:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],requestReviewers:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],submitReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events`],update:[`PATCH /repos/{owner}/{repo}/pulls/{pull_number}`],updateBranch:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch`],updateReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],updateReviewComment:[`PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}`]},rateLimit:{get:[`GET /rate_limit`]},reactions:{createForCommitComment:[`POST /repos/{owner}/{repo}/comments/{comment_id}/reactions`],createForIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/reactions`],createForIssueComment:[`POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],createForPullRequestReviewComment:[`POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],createForRelease:[`POST /repos/{owner}/{repo}/releases/{release_id}/reactions`],createForTeamDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],createForTeamDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`],deleteForCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}`],deleteForIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}`],deleteForIssueComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}`],deleteForPullRequestComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}`],deleteForRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}`],deleteForTeamDiscussion:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}`],deleteForTeamDiscussionComment:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}`],listForCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}/reactions`],listForIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/reactions`],listForIssueComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],listForPullRequestReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],listForRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}/reactions`],listForTeamDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],listForTeamDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`]},repos:{acceptInvitation:[`PATCH /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`acceptInvitationForAuthenticatedUser`]}],acceptInvitationForAuthenticatedUser:[`PATCH /user/repository_invitations/{invitation_id}`],addAppAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],addCollaborator:[`PUT /repos/{owner}/{repo}/collaborators/{username}`],addStatusCheckContexts:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],addTeamAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],addUserAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],cancelPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel`],checkAutomatedSecurityFixes:[`GET /repos/{owner}/{repo}/automated-security-fixes`],checkCollaborator:[`GET /repos/{owner}/{repo}/collaborators/{username}`],checkImmutableReleases:[`GET /repos/{owner}/{repo}/immutable-releases`],checkPrivateVulnerabilityReporting:[`GET /repos/{owner}/{repo}/private-vulnerability-reporting`],checkVulnerabilityAlerts:[`GET /repos/{owner}/{repo}/vulnerability-alerts`],codeownersErrors:[`GET /repos/{owner}/{repo}/codeowners/errors`],compareCommits:[`GET /repos/{owner}/{repo}/compare/{base}...{head}`],compareCommitsWithBasehead:[`GET /repos/{owner}/{repo}/compare/{basehead}`],createAttestation:[`POST /repos/{owner}/{repo}/attestations`],createAutolink:[`POST /repos/{owner}/{repo}/autolinks`],createCommitComment:[`POST /repos/{owner}/{repo}/commits/{commit_sha}/comments`],createCommitSignatureProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],createCommitStatus:[`POST /repos/{owner}/{repo}/statuses/{sha}`],createDeployKey:[`POST /repos/{owner}/{repo}/keys`],createDeployment:[`POST /repos/{owner}/{repo}/deployments`],createDeploymentBranchPolicy:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],createDeploymentProtectionRule:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],createDeploymentStatus:[`POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],createDispatchEvent:[`POST /repos/{owner}/{repo}/dispatches`],createForAuthenticatedUser:[`POST /user/repos`],createFork:[`POST /repos/{owner}/{repo}/forks`],createInOrg:[`POST /orgs/{org}/repos`],createOrUpdateEnvironment:[`PUT /repos/{owner}/{repo}/environments/{environment_name}`],createOrUpdateFileContents:[`PUT /repos/{owner}/{repo}/contents/{path}`],createOrgRuleset:[`POST /orgs/{org}/rulesets`],createPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments`],createPagesSite:[`POST /repos/{owner}/{repo}/pages`],createRelease:[`POST /repos/{owner}/{repo}/releases`],createRepoRuleset:[`POST /repos/{owner}/{repo}/rulesets`],createUsingTemplate:[`POST /repos/{template_owner}/{template_repo}/generate`],createWebhook:[`POST /repos/{owner}/{repo}/hooks`],customPropertiesForReposCreateOrUpdateRepositoryValues:[`PATCH /repos/{owner}/{repo}/properties/values`],customPropertiesForReposGetRepositoryValues:[`GET /repos/{owner}/{repo}/properties/values`],declineInvitation:[`DELETE /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`declineInvitationForAuthenticatedUser`]}],declineInvitationForAuthenticatedUser:[`DELETE /user/repository_invitations/{invitation_id}`],delete:[`DELETE /repos/{owner}/{repo}`],deleteAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],deleteAdminBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],deleteAnEnvironment:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}`],deleteAutolink:[`DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}`],deleteBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection`],deleteCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}`],deleteCommitSignatureProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],deleteDeployKey:[`DELETE /repos/{owner}/{repo}/keys/{key_id}`],deleteDeployment:[`DELETE /repos/{owner}/{repo}/deployments/{deployment_id}`],deleteDeploymentBranchPolicy:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],deleteFile:[`DELETE /repos/{owner}/{repo}/contents/{path}`],deleteInvitation:[`DELETE /repos/{owner}/{repo}/invitations/{invitation_id}`],deleteOrgRuleset:[`DELETE /orgs/{org}/rulesets/{ruleset_id}`],deletePagesSite:[`DELETE /repos/{owner}/{repo}/pages`],deletePullRequestReviewProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],deleteRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}`],deleteReleaseAsset:[`DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}`],deleteRepoRuleset:[`DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}`],deleteWebhook:[`DELETE /repos/{owner}/{repo}/hooks/{hook_id}`],disableAutomatedSecurityFixes:[`DELETE /repos/{owner}/{repo}/automated-security-fixes`],disableDeploymentProtectionRule:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],disableImmutableReleases:[`DELETE /repos/{owner}/{repo}/immutable-releases`],disablePrivateVulnerabilityReporting:[`DELETE /repos/{owner}/{repo}/private-vulnerability-reporting`],disableVulnerabilityAlerts:[`DELETE /repos/{owner}/{repo}/vulnerability-alerts`],downloadArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`,{},{renamed:[`repos`,`downloadZipballArchive`]}],downloadTarballArchive:[`GET /repos/{owner}/{repo}/tarball/{ref}`],downloadZipballArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`],enableAutomatedSecurityFixes:[`PUT /repos/{owner}/{repo}/automated-security-fixes`],enableImmutableReleases:[`PUT /repos/{owner}/{repo}/immutable-releases`],enablePrivateVulnerabilityReporting:[`PUT /repos/{owner}/{repo}/private-vulnerability-reporting`],enableVulnerabilityAlerts:[`PUT /repos/{owner}/{repo}/vulnerability-alerts`],generateReleaseNotes:[`POST /repos/{owner}/{repo}/releases/generate-notes`],get:[`GET /repos/{owner}/{repo}`],getAccessRestrictions:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],getAdminBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],getAllDeploymentProtectionRules:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],getAllEnvironments:[`GET /repos/{owner}/{repo}/environments`],getAllStatusCheckContexts:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`],getAllTopics:[`GET /repos/{owner}/{repo}/topics`],getAppsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`],getAutolink:[`GET /repos/{owner}/{repo}/autolinks/{autolink_id}`],getBranch:[`GET /repos/{owner}/{repo}/branches/{branch}`],getBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection`],getBranchRules:[`GET /repos/{owner}/{repo}/rules/branches/{branch}`],getClones:[`GET /repos/{owner}/{repo}/traffic/clones`],getCodeFrequencyStats:[`GET /repos/{owner}/{repo}/stats/code_frequency`],getCollaboratorPermissionLevel:[`GET /repos/{owner}/{repo}/collaborators/{username}/permission`],getCombinedStatusForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/status`],getCommit:[`GET /repos/{owner}/{repo}/commits/{ref}`],getCommitActivityStats:[`GET /repos/{owner}/{repo}/stats/commit_activity`],getCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}`],getCommitSignatureProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],getCommunityProfileMetrics:[`GET /repos/{owner}/{repo}/community/profile`],getContent:[`GET /repos/{owner}/{repo}/contents/{path}`],getContributorsStats:[`GET /repos/{owner}/{repo}/stats/contributors`],getCustomDeploymentProtectionRule:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],getDeployKey:[`GET /repos/{owner}/{repo}/keys/{key_id}`],getDeployment:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}`],getDeploymentBranchPolicy:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],getDeploymentStatus:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}`],getEnvironment:[`GET /repos/{owner}/{repo}/environments/{environment_name}`],getLatestPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/latest`],getLatestRelease:[`GET /repos/{owner}/{repo}/releases/latest`],getOrgRuleSuite:[`GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}`],getOrgRuleSuites:[`GET /orgs/{org}/rulesets/rule-suites`],getOrgRuleset:[`GET /orgs/{org}/rulesets/{ruleset_id}`],getOrgRulesets:[`GET /orgs/{org}/rulesets`],getPages:[`GET /repos/{owner}/{repo}/pages`],getPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/{build_id}`],getPagesDeployment:[`GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}`],getPagesHealthCheck:[`GET /repos/{owner}/{repo}/pages/health`],getParticipationStats:[`GET /repos/{owner}/{repo}/stats/participation`],getPullRequestReviewProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],getPunchCardStats:[`GET /repos/{owner}/{repo}/stats/punch_card`],getReadme:[`GET /repos/{owner}/{repo}/readme`],getReadmeInDirectory:[`GET /repos/{owner}/{repo}/readme/{dir}`],getRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}`],getReleaseAsset:[`GET /repos/{owner}/{repo}/releases/assets/{asset_id}`],getReleaseByTag:[`GET /repos/{owner}/{repo}/releases/tags/{tag}`],getRepoRuleSuite:[`GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}`],getRepoRuleSuites:[`GET /repos/{owner}/{repo}/rulesets/rule-suites`],getRepoRuleset:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}`],getRepoRulesetHistory:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history`],getRepoRulesetVersion:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}`],getRepoRulesets:[`GET /repos/{owner}/{repo}/rulesets`],getStatusChecksProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],getTeamsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`],getTopPaths:[`GET /repos/{owner}/{repo}/traffic/popular/paths`],getTopReferrers:[`GET /repos/{owner}/{repo}/traffic/popular/referrers`],getUsersWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`],getViews:[`GET /repos/{owner}/{repo}/traffic/views`],getWebhook:[`GET /repos/{owner}/{repo}/hooks/{hook_id}`],getWebhookConfigForRepo:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}`],listActivities:[`GET /repos/{owner}/{repo}/activity`],listAttestations:[`GET /repos/{owner}/{repo}/attestations/{subject_digest}`],listAutolinks:[`GET /repos/{owner}/{repo}/autolinks`],listBranches:[`GET /repos/{owner}/{repo}/branches`],listBranchesForHeadCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head`],listCollaborators:[`GET /repos/{owner}/{repo}/collaborators`],listCommentsForCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/comments`],listCommitCommentsForRepo:[`GET /repos/{owner}/{repo}/comments`],listCommitStatusesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/statuses`],listCommits:[`GET /repos/{owner}/{repo}/commits`],listContributors:[`GET /repos/{owner}/{repo}/contributors`],listCustomDeploymentRuleIntegrations:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps`],listDeployKeys:[`GET /repos/{owner}/{repo}/keys`],listDeploymentBranchPolicies:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],listDeploymentStatuses:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],listDeployments:[`GET /repos/{owner}/{repo}/deployments`],listForAuthenticatedUser:[`GET /user/repos`],listForOrg:[`GET /orgs/{org}/repos`],listForUser:[`GET /users/{username}/repos`],listForks:[`GET /repos/{owner}/{repo}/forks`],listInvitations:[`GET /repos/{owner}/{repo}/invitations`],listInvitationsForAuthenticatedUser:[`GET /user/repository_invitations`],listLanguages:[`GET /repos/{owner}/{repo}/languages`],listPagesBuilds:[`GET /repos/{owner}/{repo}/pages/builds`],listPublic:[`GET /repositories`],listPullRequestsAssociatedWithCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls`],listReleaseAssets:[`GET /repos/{owner}/{repo}/releases/{release_id}/assets`],listReleases:[`GET /repos/{owner}/{repo}/releases`],listTags:[`GET /repos/{owner}/{repo}/tags`],listTeams:[`GET /repos/{owner}/{repo}/teams`],listWebhookDeliveries:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /repos/{owner}/{repo}/hooks`],merge:[`POST /repos/{owner}/{repo}/merges`],mergeUpstream:[`POST /repos/{owner}/{repo}/merge-upstream`],pingWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeAppAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],removeCollaborator:[`DELETE /repos/{owner}/{repo}/collaborators/{username}`],removeStatusCheckContexts:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],removeStatusCheckProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],removeTeamAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],removeUserAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],renameBranch:[`POST /repos/{owner}/{repo}/branches/{branch}/rename`],replaceAllTopics:[`PUT /repos/{owner}/{repo}/topics`],requestPagesBuild:[`POST /repos/{owner}/{repo}/pages/builds`],setAdminBranchProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],setAppAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],setStatusCheckContexts:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],setTeamAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],setUserAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],testPushWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/tests`],transfer:[`POST /repos/{owner}/{repo}/transfer`],update:[`PATCH /repos/{owner}/{repo}`],updateBranchProtection:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection`],updateCommitComment:[`PATCH /repos/{owner}/{repo}/comments/{comment_id}`],updateDeploymentBranchPolicy:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],updateInformationAboutPagesSite:[`PUT /repos/{owner}/{repo}/pages`],updateInvitation:[`PATCH /repos/{owner}/{repo}/invitations/{invitation_id}`],updateOrgRuleset:[`PUT /orgs/{org}/rulesets/{ruleset_id}`],updatePullRequestReviewProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],updateRelease:[`PATCH /repos/{owner}/{repo}/releases/{release_id}`],updateReleaseAsset:[`PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}`],updateRepoRuleset:[`PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}`],updateStatusCheckPotection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`,{},{renamed:[`repos`,`updateStatusCheckProtection`]}],updateStatusCheckProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],updateWebhook:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}`],updateWebhookConfigForRepo:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config`],uploadReleaseAsset:[`POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}`,{baseUrl:`https://uploads.github.com`}]},search:{code:[`GET /search/code`],commits:[`GET /search/commits`],issuesAndPullRequests:[`GET /search/issues`],labels:[`GET /search/labels`],repos:[`GET /search/repositories`],topics:[`GET /search/topics`],users:[`GET /search/users`]},secretScanning:{createPushProtectionBypass:[`POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses`],getAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],getScanHistory:[`GET /repos/{owner}/{repo}/secret-scanning/scan-history`],listAlertsForOrg:[`GET /orgs/{org}/secret-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/secret-scanning/alerts`],listLocationsForAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations`],listOrgPatternConfigs:[`GET /orgs/{org}/secret-scanning/pattern-configurations`],updateAlert:[`PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],updateOrgPatternConfigs:[`PATCH /orgs/{org}/secret-scanning/pattern-configurations`]},securityAdvisories:{createFork:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks`],createPrivateVulnerabilityReport:[`POST /repos/{owner}/{repo}/security-advisories/reports`],createRepositoryAdvisory:[`POST /repos/{owner}/{repo}/security-advisories`],createRepositoryAdvisoryCveRequest:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve`],getGlobalAdvisory:[`GET /advisories/{ghsa_id}`],getRepositoryAdvisory:[`GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}`],listGlobalAdvisories:[`GET /advisories`],listOrgRepositoryAdvisories:[`GET /orgs/{org}/security-advisories`],listRepositoryAdvisories:[`GET /repos/{owner}/{repo}/security-advisories`],updateRepositoryAdvisory:[`PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}`]},teams:{addOrUpdateMembershipForUserInOrg:[`PUT /orgs/{org}/teams/{team_slug}/memberships/{username}`],addOrUpdateRepoPermissionsInOrg:[`PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],checkPermissionsForRepoInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],create:[`POST /orgs/{org}/teams`],createDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],createDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions`],deleteDiscussionCommentInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],deleteDiscussionInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],deleteInOrg:[`DELETE /orgs/{org}/teams/{team_slug}`],getByName:[`GET /orgs/{org}/teams/{team_slug}`],getDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],getDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],getMembershipForUserInOrg:[`GET /orgs/{org}/teams/{team_slug}/memberships/{username}`],list:[`GET /orgs/{org}/teams`],listChildInOrg:[`GET /orgs/{org}/teams/{team_slug}/teams`],listDiscussionCommentsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],listDiscussionsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions`],listForAuthenticatedUser:[`GET /user/teams`],listMembersInOrg:[`GET /orgs/{org}/teams/{team_slug}/members`],listPendingInvitationsInOrg:[`GET /orgs/{org}/teams/{team_slug}/invitations`],listReposInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos`],removeMembershipForUserInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}`],removeRepoInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],updateDiscussionCommentInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],updateDiscussionInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],updateInOrg:[`PATCH /orgs/{org}/teams/{team_slug}`]},users:{addEmailForAuthenticated:[`POST /user/emails`,{},{renamed:[`users`,`addEmailForAuthenticatedUser`]}],addEmailForAuthenticatedUser:[`POST /user/emails`],addSocialAccountForAuthenticatedUser:[`POST /user/social_accounts`],block:[`PUT /user/blocks/{username}`],checkBlocked:[`GET /user/blocks/{username}`],checkFollowingForUser:[`GET /users/{username}/following/{target_user}`],checkPersonIsFollowedByAuthenticated:[`GET /user/following/{username}`],createGpgKeyForAuthenticated:[`POST /user/gpg_keys`,{},{renamed:[`users`,`createGpgKeyForAuthenticatedUser`]}],createGpgKeyForAuthenticatedUser:[`POST /user/gpg_keys`],createPublicSshKeyForAuthenticated:[`POST /user/keys`,{},{renamed:[`users`,`createPublicSshKeyForAuthenticatedUser`]}],createPublicSshKeyForAuthenticatedUser:[`POST /user/keys`],createSshSigningKeyForAuthenticatedUser:[`POST /user/ssh_signing_keys`],deleteAttestationsBulk:[`POST /users/{username}/attestations/delete-request`],deleteAttestationsById:[`DELETE /users/{username}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /users/{username}/attestations/digest/{subject_digest}`],deleteEmailForAuthenticated:[`DELETE /user/emails`,{},{renamed:[`users`,`deleteEmailForAuthenticatedUser`]}],deleteEmailForAuthenticatedUser:[`DELETE /user/emails`],deleteGpgKeyForAuthenticated:[`DELETE /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`deleteGpgKeyForAuthenticatedUser`]}],deleteGpgKeyForAuthenticatedUser:[`DELETE /user/gpg_keys/{gpg_key_id}`],deletePublicSshKeyForAuthenticated:[`DELETE /user/keys/{key_id}`,{},{renamed:[`users`,`deletePublicSshKeyForAuthenticatedUser`]}],deletePublicSshKeyForAuthenticatedUser:[`DELETE /user/keys/{key_id}`],deleteSocialAccountForAuthenticatedUser:[`DELETE /user/social_accounts`],deleteSshSigningKeyForAuthenticatedUser:[`DELETE /user/ssh_signing_keys/{ssh_signing_key_id}`],follow:[`PUT /user/following/{username}`],getAuthenticated:[`GET /user`],getById:[`GET /user/{account_id}`],getByUsername:[`GET /users/{username}`],getContextForUser:[`GET /users/{username}/hovercard`],getGpgKeyForAuthenticated:[`GET /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`getGpgKeyForAuthenticatedUser`]}],getGpgKeyForAuthenticatedUser:[`GET /user/gpg_keys/{gpg_key_id}`],getPublicSshKeyForAuthenticated:[`GET /user/keys/{key_id}`,{},{renamed:[`users`,`getPublicSshKeyForAuthenticatedUser`]}],getPublicSshKeyForAuthenticatedUser:[`GET /user/keys/{key_id}`],getSshSigningKeyForAuthenticatedUser:[`GET /user/ssh_signing_keys/{ssh_signing_key_id}`],list:[`GET /users`],listAttestations:[`GET /users/{username}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /users/{username}/attestations/bulk-list{?per_page,before,after}`],listBlockedByAuthenticated:[`GET /user/blocks`,{},{renamed:[`users`,`listBlockedByAuthenticatedUser`]}],listBlockedByAuthenticatedUser:[`GET /user/blocks`],listEmailsForAuthenticated:[`GET /user/emails`,{},{renamed:[`users`,`listEmailsForAuthenticatedUser`]}],listEmailsForAuthenticatedUser:[`GET /user/emails`],listFollowedByAuthenticated:[`GET /user/following`,{},{renamed:[`users`,`listFollowedByAuthenticatedUser`]}],listFollowedByAuthenticatedUser:[`GET /user/following`],listFollowersForAuthenticatedUser:[`GET /user/followers`],listFollowersForUser:[`GET /users/{username}/followers`],listFollowingForUser:[`GET /users/{username}/following`],listGpgKeysForAuthenticated:[`GET /user/gpg_keys`,{},{renamed:[`users`,`listGpgKeysForAuthenticatedUser`]}],listGpgKeysForAuthenticatedUser:[`GET /user/gpg_keys`],listGpgKeysForUser:[`GET /users/{username}/gpg_keys`],listPublicEmailsForAuthenticated:[`GET /user/public_emails`,{},{renamed:[`users`,`listPublicEmailsForAuthenticatedUser`]}],listPublicEmailsForAuthenticatedUser:[`GET /user/public_emails`],listPublicKeysForUser:[`GET /users/{username}/keys`],listPublicSshKeysForAuthenticated:[`GET /user/keys`,{},{renamed:[`users`,`listPublicSshKeysForAuthenticatedUser`]}],listPublicSshKeysForAuthenticatedUser:[`GET /user/keys`],listSocialAccountsForAuthenticatedUser:[`GET /user/social_accounts`],listSocialAccountsForUser:[`GET /users/{username}/social_accounts`],listSshSigningKeysForAuthenticatedUser:[`GET /user/ssh_signing_keys`],listSshSigningKeysForUser:[`GET /users/{username}/ssh_signing_keys`],setPrimaryEmailVisibilityForAuthenticated:[`PATCH /user/email/visibility`,{},{renamed:[`users`,`setPrimaryEmailVisibilityForAuthenticatedUser`]}],setPrimaryEmailVisibilityForAuthenticatedUser:[`PATCH /user/email/visibility`],unblock:[`DELETE /user/blocks/{username}`],unfollow:[`DELETE /user/following/{username}`],updateAuthenticated:[`PATCH /user`]}},um=new Map;for(let[e,t]of Object.entries(lm))for(let[n,r]of Object.entries(t)){let[t,i,a]=r,[o,s]=t.split(/ /),c=Object.assign({method:o,url:s},i);um.has(e)||um.set(e,new Map),um.get(e).set(n,{scope:e,methodName:n,endpointDefaults:c,decorations:a})}var dm={has({scope:e},t){return um.get(e).has(t)},getOwnPropertyDescriptor(e,t){return{value:this.get(e,t),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,t,n){return Object.defineProperty(e.cache,t,n),!0},deleteProperty(e,t){return delete e.cache[t],!0},ownKeys({scope:e}){return[...um.get(e).keys()]},set(e,t,n){return e.cache[t]=n},get({octokit:e,scope:t,cache:n},r){if(n[r])return n[r];let i=um.get(t).get(r);if(!i)return;let{endpointDefaults:a,decorations:o}=i;return n[r]=o?pm(e,t,r,a,o):e.request.defaults(a),n[r]}};function fm(e){let t={};for(let n of um.keys())t[n]=new Proxy({octokit:e,scope:n,cache:{}},dm);return t}function pm(e,t,n,r,i){let a=e.request.defaults(r);function o(...r){let o=a.endpoint.merge(...r);if(i.mapToData)return o=Object.assign({},o,{data:o[i.mapToData],[i.mapToData]:void 0}),a(o);if(i.renamed){let[r,a]=i.renamed;e.log.warn(`octokit.${t}.${n}() has been renamed to octokit.${r}.${a}()`)}if(i.deprecated&&e.log.warn(i.deprecated),i.renamedParameters){let o=a.endpoint.merge(...r);for(let[r,a]of Object.entries(i.renamedParameters))r in o&&(e.log.warn(`"${r}" parameter is deprecated for "octokit.${t}.${n}()". Use "${a}" instead`),a in o||(o[a]=o[r]),delete o[r]);return a(o)}return a(...r)}return Object.assign(o,a)}function mm(e){let t=fm(e);return{...t,rest:t}}mm.VERSION=cm;var hm=$p.plugin(tm,mm,sm).defaults({userAgent:`octokit-rest.js/22.0.1`}),gm=new WeakMap;function _m(e){if(typeof e.permissions!=`object`||e.permissions===null||Array.isArray(e.permissions))throw new L(`GitHub App ${e.role} role did not return installation permissions.`);let t=e.permissions,n=e.role===`author`?{contents:`write`,issues:`write`,organization_projects:`write`,pull_requests:`write`}:{contents:`read`,pull_requests:`write`};for(let[r,i]of[...Object.entries(n),...Object.entries(e.additional??{})]){let n=t[r];if(n!==`admin`&&n!==`write`&&(i===`write`||n!==`read`))throw new L(`GitHub App ${e.role} role lacks required ${r}:${i} permission.`)}}async function vm(e){e.signal?.throwIfAborted();let t=e.env??process.env,n=e.config.roles[e.role];if(n.authSource===`personal`){if(e.role!==`author`||e.identity.trim().toLowerCase()!==n.identity.toLowerCase())throw new L(`Personal author operation requires the configured author identity.`);let r=t[n.credentialEnv.token]?.trim();if(!r)throw new L(`Missing personal author token in ${n.credentialEnv.token}.`);return ym(r,`env:${n.credentialEnv.token}`,e.signal)}if(e.personalAuth!==void 0){if(e.personalAuth.enabled!==!0||e.role!==`author`||e.identity.trim().toLowerCase()!==`personal`)throw new L(`Personal-token auth requires the explicit personal author identity.`);let n=e.personalAuth.token?.trim()||t.GH_TOKEN?.trim()||t.GITHUB_TOKEN?.trim();if(!n)throw new L(`Explicit personal-token auth requested but no token was supplied.`);return ym(n,e.personalAuth.token?.trim()?`explicit-personal-token`:t.GH_TOKEN?.trim()?`env:GH_TOKEN`:`env:GITHUB_TOKEN`,e.signal)}if(e.identity.trim().toLowerCase()!==n.identity.toLowerCase())throw new L(`GitHub ${e.role} operation requires the configured ${e.role} identity.`);let r=lh({config:e.config,env:t,role:e.role}),i=e.role===`author`?`reviewer`:`author`;if((e.role!==`reviewer`||e.selectedAuthor?.role!==`author`||e.selectedAuthor.authSource!==`personal`)&&e.config.roles[i].authSource!==`personal`){let n=lh({config:e.config,env:t,role:i});if(r.appId===n.appId||r.installationId===n.installationId||r.privateKeyPath===n.privateKeyPath)throw new L(`Author and reviewer must use distinct GitHub App credentials.`)}let a;try{a=l(r.privateKeyPath,`utf8`)}catch{throw new L(`GitHub App private key for ${e.role} role is unavailable.`)}try{let t=yp({appId:r.appId,privateKey:a,...e.signal===void 0?{}:{request:new hm({request:{signal:e.signal}}).request}}),n=await t({installationId:r.installationId,type:`installation`});if(typeof n.token!=`string`||!n.token.startsWith(`ghs_`))throw new L(`GitHub ${e.role} role did not receive an App installation token.`);_m({...e.additionalPermissions===void 0?{}:{additional:e.additionalPermissions},permissions:n.permissions,role:e.role});let i=e.role===`reviewer`?async n=>{let i=n??e.signal;try{let e=await new hm({auth:(await t({type:`app`})).token,...i===void 0?{}:{request:{signal:i}}}).rest.apps.getAuthenticated();if(!e.data||e.data.id!==Number(r.appId)||!e.data.slug)throw new L(`Reviewer GitHub App identity did not match its configured App ID.`);return`${e.data.slug}[bot]`}catch(e){throw e instanceof L?e:new L(`Reviewer GitHub App actor lookup failed.`)}}:void 0,o=e.role===`author`?async n=>{let i=n??e.signal;try{let e=await new hm({auth:(await t({type:`app`})).token,...i===void 0?{}:{request:{signal:i}}}).rest.apps.getAuthenticated();if(!e.data||e.data.id!==Number(r.appId)||!e.data.slug)throw new L(`Author GitHub App identity did not match its configured App ID.`);return{actorLogin:`${e.data.slug}[bot]`,credentialIdentity:`app:${String(e.data.id)}:installation:${r.installationId}`}}catch(e){throw e instanceof L?e:new L(`Author GitHub App actor lookup failed.`)}}:void 0;return bm(n.token,`app`,e.role,`app:${r.appId}:installation:${r.installationId}`,i,o,n.permissions.contents,e.signal)}catch(t){throw t instanceof L?t:new L(`GitHub App authentication failed for ${e.role} role.`)}}function ym(e,t,n){return bm(e,`personal`,`author`,t,void 0,async t=>{let r=t??n;try{let t=(await new hm({auth:e,...r===void 0?{}:{request:{signal:r}}}).rest.users.getAuthenticated()).data;if(!Number.isSafeInteger(t.id)||t.id<=0||!t.login)throw new L(`Personal author identity readback is incomplete.`);return{actorLogin:t.login,credentialIdentity:`user:${String(t.id)}`}}catch(e){throw e instanceof L?e:e.status===401?new L(`Configured personal author token is invalid or expired; refresh the selected token.`):new L(`Personal author identity readback failed.`)}},void 0,n)}function bm(e,t,n,r,i,a,o,s){let c={authSource:t,credentialSource:r,...o?{effectiveContentsPermission:o}:{},role:n,...i?{appActorLogin:i}:{},...a?{authenticatedAuthor:a}:{},graphql:Op.defaults({headers:{authorization:`token ${e}`},...s===void 0?{}:{request:{signal:s}}}),rest:new hm({auth:e,...s===void 0?{}:{request:{signal:s}}})};return n===`author`&&gm.set(c,e),c}var xm=[`Todo`,`In Progress`,`Blocked`,`Done`];async function Sm(e){let t=e.configuration??await Cm({...e,settings:Vm(e.settings)}),n=await jm({...e,configuration:t});if(n===null||n.archived||n.status===null&&n.statusOptionId===null)return null;let r=Rm(n,t);return{itemId:n.id,status:r}}async function Cm(e){let t=Vm(e.settings);return Em(await wm({graphql:e.graphql,org:e.org,number:t.number}),{requireWritable:e.requireWritable===!0,settings:t})}async function wm(e){let t=[],n=null,r=!0,i=new Set,a=new Set,o=null;for(;r;){let s=zm(await e.graphql(`
|
|
83
|
+
`)}var xp=class extends Error{constructor(e,t,n){super(bp(n)),this.request=e,this.headers=t,this.response=n,this.errors=n.errors,this.data=n.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}request;headers;response;name=`GraphqlResponseError`;errors;data},Sp=[`method`,`baseUrl`,`url`,`headers`,`request`,`query`,`mediaType`,`operationName`],Cp=[`query`,`method`,`url`],wp=/\/api\/v3\/?$/;function Tp(e,t,n){if(n){if(typeof t==`string`&&`query`in n)return Promise.reject(Error(`[@octokit/graphql] "query" cannot be used as variable name`));for(let e in n)if(Cp.includes(e))return Promise.reject(Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}let r=typeof t==`string`?Object.assign({query:t},n):t,i=Object.keys(r).reduce((e,t)=>Sp.includes(t)?(e[t]=r[t],e):(e.variables||={},e.variables[t]=r[t],e),{}),a=r.baseUrl||e.endpoint.DEFAULTS.baseUrl;return wp.test(a)&&(i.url=a.replace(wp,`/api/graphql`)),e(i).then(e=>{if(e.data.errors){let t={};for(let n of Object.keys(e.headers))t[n]=e.headers[n];throw new xp(i,t,e.data)}return e.data.data})}function Ep(e,t){let n=e.defaults(t);return Object.assign((e,t)=>Tp(n,e,t),{defaults:Ep.bind(null,n),endpoint:n.endpoint})}var Dp=Ep(of,{headers:{"user-agent":`octokit-graphql.js/${yp} ${zu()}`},method:`POST`,url:`/graphql`});function Op(e){return Ep(e,{method:`POST`,url:`/graphql`})}function kp(e,t,n,r){if(typeof n!=`function`)throw Error(`method for before hook must be a function`);return r||={},Array.isArray(t)?t.reverse().reduce((t,n)=>kp.bind(null,e,n,t,r),n)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((e,t)=>t.hook.bind(null,e,r),n)():n(r))}function Ap(e,t,n,r){let i=r;e.registry[n]||(e.registry[n]=[]),t===`before`&&(r=(e,t)=>Promise.resolve().then(i.bind(null,t)).then(e.bind(null,t))),t===`after`&&(r=(e,t)=>{let n;return Promise.resolve().then(e.bind(null,t)).then(e=>(n=e,i(n,t))).then(()=>n)}),t===`error`&&(r=(e,t)=>Promise.resolve().then(e.bind(null,t)).catch(e=>i(e,t))),e.registry[n].push({hook:r,orig:i})}function jp(e,t,n){if(!e.registry[t])return;let r=e.registry[t].map(e=>e.orig).indexOf(n);r!==-1&&e.registry[t].splice(r,1)}var Mp=Function.bind,Np=Mp.bind(Mp);function Pp(e,t,n){let r=Np(jp,null).apply(null,n?[t,n]:[t]);e.api={remove:r},e.remove=r,[`before`,`error`,`after`,`wrap`].forEach(r=>{let i=n?[t,r,n]:[t,r];e[r]=e.api[r]=Np(Ap,null).apply(null,i)})}function Fp(){let e=Symbol(`Singular`),t={registry:{}},n=kp.bind(null,t,e);return Pp(n,t,e),n}function Ip(){let e={registry:{}},t=kp.bind(null,e);return Pp(t,e),t}var Lp={Singular:Fp,Collection:Ip},Rp=`(?:[a-zA-Z0-9_-]+)`,zp=`\\.`,Bp=RegExp(`^${Rp}${zp}${Rp}${zp}${Rp}$`),Vp=Bp.test.bind(Bp);async function Hp(e){let t=Vp(e),n=e.startsWith(`v1.`)||e.startsWith(`ghs_`),r=e.startsWith(`ghu_`);return{type:`token`,token:e,tokenType:t?`app`:n?`installation`:r?`user-to-server`:`oauth`}}function Up(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function Wp(e,t,n,r){let i=t.endpoint.merge(n,r);return i.headers.authorization=Up(e),t(i)}var Gp=function(e){if(!e)throw Error(`[@octokit/auth-token] No token passed to createTokenAuth`);if(typeof e!=`string`)throw Error(`[@octokit/auth-token] Token passed to createTokenAuth is not a string`);return e=e.replace(/^(token|bearer) +/i,``),Object.assign(Hp.bind(null,e),{hook:Wp.bind(null,e)})},Kp=`7.0.8`,qp=()=>{},Jp=console.warn.bind(console),Yp=console.error.bind(console);function Xp(e={}){return typeof e.debug!=`function`&&(e.debug=qp),typeof e.info!=`function`&&(e.info=qp),typeof e.warn!=`function`&&(e.warn=Jp),typeof e.error!=`function`&&(e.error=Yp),e}var Zp=`octokit-core.js/${Kp} ${zu()}`,Qp=class{static VERSION=Kp;static defaults(e){return class extends this{constructor(...t){let n=t[0]||{};if(typeof e==`function`){super(e(n));return}super(Object.assign({},e,n,n.userAgent&&e.userAgent?{userAgent:`${n.userAgent} ${e.userAgent}`}:null))}}}static plugins=[];static plugin(...e){let t=this.plugins;return class extends this{static plugins=t.concat(e.filter(e=>!t.includes(e)))}}constructor(e={}){let t=new Lp.Collection,n={baseUrl:of.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,`request`)}),mediaType:{previews:[],format:``}};if(n.headers[`user-agent`]=e.userAgent?`${e.userAgent} ${Zp}`:Zp,e.baseUrl&&(n.baseUrl=e.baseUrl),e.previews&&(n.mediaType.previews=e.previews),e.timeZone&&(n.headers[`time-zone`]=e.timeZone),this.request=of.defaults(n),this.graphql=Op(this.request).defaults(n),this.log=Xp(e.log),this.hook=t,e.authStrategy){let{authStrategy:n,...r}=e,i=n(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:r},e.auth));t.wrap(`request`,i.hook),this.auth=i}else if(!e.auth)this.auth=async()=>({type:`unauthenticated`});else{let n=Gp(e.auth);t.wrap(`request`,n.hook),this.auth=n}let r=this.constructor;for(let t=0;t<r.plugins.length;++t)Object.assign(this,r.plugins[t](this,e))}request;graphql;log;hook;auth},$p=`6.0.0`;function em(e){e.hook.wrap(`request`,(t,n)=>{e.log.debug(`request`,n);let r=Date.now(),i=e.request.endpoint.parse(n),a=i.url.replace(n.baseUrl,``);return t(n).then(t=>{let n=t.headers[`x-github-request-id`];return e.log.info(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t}).catch(t=>{let n=t.response?.headers[`x-github-request-id`]||`UNKNOWN`;throw e.log.error(`${i.method} ${a} - ${t.status} with id ${n} in ${Date.now()-r}ms`),t})})}em.VERSION=$p;var tm=`0.0.0-development`;function nm(e){if(!e.data)return{...e,data:[]};if(!((`total_count`in e.data||`total_commits`in e.data)&&!(`url`in e.data)))return e;let t=e.data.incomplete_results,n=e.data.repository_selection,r=e.data.total_count,i=e.data.total_commits;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count,delete e.data.total_commits;let a=Object.keys(e.data)[0];return e.data=e.data[a],t!==void 0&&(e.data.incomplete_results=t),n!==void 0&&(e.data.repository_selection=n),e.data.total_count=r,e.data.total_commits=i,e}function rm(e,t,n){let r=typeof t==`function`?t.endpoint(n):e.request.endpoint(t,n),i=typeof t==`function`?t:e.request,a=r.method,o=r.headers,s=r.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!s)return{done:!0};try{let e=nm(await i({method:a,url:s,headers:o}));if(s=((e.headers.link||``).match(/<([^<>]+)>;\s*rel="next"/)||[])[1],!s&&`total_commits`in e.data){let t=new URL(e.url),n=t.searchParams,r=parseInt(n.get(`page`)||`1`,10);r*parseInt(n.get(`per_page`)||`250`,10)<e.data.total_commits&&(n.set(`page`,String(r+1)),s=t.toString())}return{value:e}}catch(e){if(e.status!==409)throw e;return s=``,{value:{status:200,headers:{},data:[]}}}}})}}function im(e,t,n,r){return typeof n==`function`&&(r=n,n=void 0),am(e,[],rm(e,t,n)[Symbol.asyncIterator](),r)}function am(e,t,n,r){return n.next().then(i=>{if(i.done)return t;let a=!1;function o(){a=!0}return t=t.concat(r?r(i.value,o):i.value.data),a?t:am(e,t,n,r)})}Object.assign(im,{iterator:rm});function om(e){return{paginate:Object.assign(im.bind(null,e),{iterator:rm.bind(null,e)})}}om.VERSION=tm;var sm=`17.0.0`,cm={actions:{addCustomLabelsToSelfHostedRunnerForOrg:[`POST /orgs/{org}/actions/runners/{runner_id}/labels`],addCustomLabelsToSelfHostedRunnerForRepo:[`POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],addRepoAccessToSelfHostedRunnerGroupInOrg:[`PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],approveWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve`],cancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel`],createEnvironmentVariable:[`POST /repos/{owner}/{repo}/environments/{environment_name}/variables`],createHostedRunnerForOrg:[`POST /orgs/{org}/actions/hosted-runners`],createOrUpdateEnvironmentSecret:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}`],createOrgVariable:[`POST /orgs/{org}/actions/variables`],createRegistrationTokenForOrg:[`POST /orgs/{org}/actions/runners/registration-token`],createRegistrationTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/registration-token`],createRemoveTokenForOrg:[`POST /orgs/{org}/actions/runners/remove-token`],createRemoveTokenForRepo:[`POST /repos/{owner}/{repo}/actions/runners/remove-token`],createRepoVariable:[`POST /repos/{owner}/{repo}/actions/variables`],createWorkflowDispatch:[`POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches`],deleteActionsCacheById:[`DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}`],deleteActionsCacheByKey:[`DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}`],deleteArtifact:[`DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],deleteCustomImageFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],deleteCustomImageVersionFromOrg:[`DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],deleteEnvironmentSecret:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],deleteEnvironmentVariable:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],deleteHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],deleteOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}`],deleteOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}`],deleteRepoVariable:[`DELETE /repos/{owner}/{repo}/actions/variables/{name}`],deleteSelfHostedRunnerFromOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}`],deleteSelfHostedRunnerFromRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}`],deleteWorkflowRun:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}`],deleteWorkflowRunLogs:[`DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],disableSelectedRepositoryGithubActionsOrganization:[`DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}`],disableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable`],downloadArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}`],downloadJobLogsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs`],downloadWorkflowRunAttemptLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs`],downloadWorkflowRunLogs:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs`],enableSelectedRepositoryGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories/{repository_id}`],enableWorkflow:[`PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable`],forceCancelWorkflowRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel`],generateRunnerJitconfigForOrg:[`POST /orgs/{org}/actions/runners/generate-jitconfig`],generateRunnerJitconfigForRepo:[`POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig`],getActionsCacheList:[`GET /repos/{owner}/{repo}/actions/caches`],getActionsCacheUsage:[`GET /repos/{owner}/{repo}/actions/cache/usage`],getActionsCacheUsageByRepoForOrg:[`GET /orgs/{org}/actions/cache/usage-by-repository`],getActionsCacheUsageForOrg:[`GET /orgs/{org}/actions/cache/usage`],getAllowedActionsOrganization:[`GET /orgs/{org}/actions/permissions/selected-actions`],getAllowedActionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/selected-actions`],getArtifact:[`GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}`],getCustomImageForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}`],getCustomImageVersionForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}`],getCustomOidcSubClaimForRepo:[`GET /repos/{owner}/{repo}/actions/oidc/customization/sub`],getEnvironmentPublicKey:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key`],getEnvironmentSecret:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}`],getEnvironmentVariable:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],getGithubActionsDefaultWorkflowPermissionsOrganization:[`GET /orgs/{org}/actions/permissions/workflow`],getGithubActionsDefaultWorkflowPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions/workflow`],getGithubActionsPermissionsOrganization:[`GET /orgs/{org}/actions/permissions`],getGithubActionsPermissionsRepository:[`GET /repos/{owner}/{repo}/actions/permissions`],getHostedRunnerForOrg:[`GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],getHostedRunnersGithubOwnedImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/github-owned`],getHostedRunnersLimitsForOrg:[`GET /orgs/{org}/actions/hosted-runners/limits`],getHostedRunnersMachineSpecsForOrg:[`GET /orgs/{org}/actions/hosted-runners/machine-sizes`],getHostedRunnersPartnerImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/partner`],getHostedRunnersPlatformsForOrg:[`GET /orgs/{org}/actions/hosted-runners/platforms`],getJobForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/jobs/{job_id}`],getOrgPublicKey:[`GET /orgs/{org}/actions/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}`],getOrgVariable:[`GET /orgs/{org}/actions/variables/{name}`],getPendingDeploymentsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],getRepoPermissions:[`GET /repos/{owner}/{repo}/actions/permissions`,{},{renamed:[`actions`,`getGithubActionsPermissionsRepository`]}],getRepoPublicKey:[`GET /repos/{owner}/{repo}/actions/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/actions/secrets/{secret_name}`],getRepoVariable:[`GET /repos/{owner}/{repo}/actions/variables/{name}`],getReviewsForRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals`],getSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}`],getSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}`],getWorkflow:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}`],getWorkflowAccessToRepository:[`GET /repos/{owner}/{repo}/actions/permissions/access`],getWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}`],getWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}`],getWorkflowRunUsage:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing`],getWorkflowUsage:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing`],listArtifactsForRepo:[`GET /repos/{owner}/{repo}/actions/artifacts`],listCustomImageVersionsForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions`],listCustomImagesForOrg:[`GET /orgs/{org}/actions/hosted-runners/images/custom`],listEnvironmentSecrets:[`GET /repos/{owner}/{repo}/environments/{environment_name}/secrets`],listEnvironmentVariables:[`GET /repos/{owner}/{repo}/environments/{environment_name}/variables`],listGithubHostedRunnersInGroupForOrg:[`GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners`],listHostedRunnersForOrg:[`GET /orgs/{org}/actions/hosted-runners`],listJobsForWorkflowRun:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs`],listJobsForWorkflowRunAttempt:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs`],listLabelsForSelfHostedRunnerForOrg:[`GET /orgs/{org}/actions/runners/{runner_id}/labels`],listLabelsForSelfHostedRunnerForRepo:[`GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],listOrgSecrets:[`GET /orgs/{org}/actions/secrets`],listOrgVariables:[`GET /orgs/{org}/actions/variables`],listRepoOrganizationSecrets:[`GET /repos/{owner}/{repo}/actions/organization-secrets`],listRepoOrganizationVariables:[`GET /repos/{owner}/{repo}/actions/organization-variables`],listRepoSecrets:[`GET /repos/{owner}/{repo}/actions/secrets`],listRepoVariables:[`GET /repos/{owner}/{repo}/actions/variables`],listRepoWorkflows:[`GET /repos/{owner}/{repo}/actions/workflows`],listRunnerApplicationsForOrg:[`GET /orgs/{org}/actions/runners/downloads`],listRunnerApplicationsForRepo:[`GET /repos/{owner}/{repo}/actions/runners/downloads`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/actions/secrets/{secret_name}/repositories`],listSelectedReposForOrgVariable:[`GET /orgs/{org}/actions/variables/{name}/repositories`],listSelectedRepositoriesEnabledGithubActionsOrganization:[`GET /orgs/{org}/actions/permissions/repositories`],listSelfHostedRunnersForOrg:[`GET /orgs/{org}/actions/runners`],listSelfHostedRunnersForRepo:[`GET /repos/{owner}/{repo}/actions/runners`],listWorkflowRunArtifacts:[`GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts`],listWorkflowRuns:[`GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs`],listWorkflowRunsForRepo:[`GET /repos/{owner}/{repo}/actions/runs`],reRunJobForWorkflowRun:[`POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun`],reRunWorkflow:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun`],reRunWorkflowFailedJobs:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs`],removeAllCustomLabelsFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels`],removeAllCustomLabelsFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],removeCustomLabelFromSelfHostedRunnerForOrg:[`DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}`],removeCustomLabelFromSelfHostedRunnerForRepo:[`DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgVariable:[`DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}`],reviewCustomGatesForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule`],reviewPendingDeploymentsForRun:[`POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments`],setAllowedActionsOrganization:[`PUT /orgs/{org}/actions/permissions/selected-actions`],setAllowedActionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/selected-actions`],setCustomLabelsForSelfHostedRunnerForOrg:[`PUT /orgs/{org}/actions/runners/{runner_id}/labels`],setCustomLabelsForSelfHostedRunnerForRepo:[`PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels`],setCustomOidcSubClaimForRepo:[`PUT /repos/{owner}/{repo}/actions/oidc/customization/sub`],setGithubActionsDefaultWorkflowPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions/workflow`],setGithubActionsDefaultWorkflowPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/workflow`],setGithubActionsPermissionsOrganization:[`PUT /orgs/{org}/actions/permissions`],setGithubActionsPermissionsRepository:[`PUT /repos/{owner}/{repo}/actions/permissions`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/actions/secrets/{secret_name}/repositories`],setSelectedReposForOrgVariable:[`PUT /orgs/{org}/actions/variables/{name}/repositories`],setSelectedRepositoriesEnabledGithubActionsOrganization:[`PUT /orgs/{org}/actions/permissions/repositories`],setWorkflowAccessToRepository:[`PUT /repos/{owner}/{repo}/actions/permissions/access`],updateEnvironmentVariable:[`PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}`],updateHostedRunnerForOrg:[`PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}`],updateOrgVariable:[`PATCH /orgs/{org}/actions/variables/{name}`],updateRepoVariable:[`PATCH /repos/{owner}/{repo}/actions/variables/{name}`]},activity:{checkRepoIsStarredByAuthenticatedUser:[`GET /user/starred/{owner}/{repo}`],deleteRepoSubscription:[`DELETE /repos/{owner}/{repo}/subscription`],deleteThreadSubscription:[`DELETE /notifications/threads/{thread_id}/subscription`],getFeeds:[`GET /feeds`],getRepoSubscription:[`GET /repos/{owner}/{repo}/subscription`],getThread:[`GET /notifications/threads/{thread_id}`],getThreadSubscriptionForAuthenticatedUser:[`GET /notifications/threads/{thread_id}/subscription`],listEventsForAuthenticatedUser:[`GET /users/{username}/events`],listNotificationsForAuthenticatedUser:[`GET /notifications`],listOrgEventsForAuthenticatedUser:[`GET /users/{username}/events/orgs/{org}`],listPublicEvents:[`GET /events`],listPublicEventsForRepoNetwork:[`GET /networks/{owner}/{repo}/events`],listPublicEventsForUser:[`GET /users/{username}/events/public`],listPublicOrgEvents:[`GET /orgs/{org}/events`],listReceivedEventsForUser:[`GET /users/{username}/received_events`],listReceivedPublicEventsForUser:[`GET /users/{username}/received_events/public`],listRepoEvents:[`GET /repos/{owner}/{repo}/events`],listRepoNotificationsForAuthenticatedUser:[`GET /repos/{owner}/{repo}/notifications`],listReposStarredByAuthenticatedUser:[`GET /user/starred`],listReposStarredByUser:[`GET /users/{username}/starred`],listReposWatchedByUser:[`GET /users/{username}/subscriptions`],listStargazersForRepo:[`GET /repos/{owner}/{repo}/stargazers`],listWatchedReposForAuthenticatedUser:[`GET /user/subscriptions`],listWatchersForRepo:[`GET /repos/{owner}/{repo}/subscribers`],markNotificationsAsRead:[`PUT /notifications`],markRepoNotificationsAsRead:[`PUT /repos/{owner}/{repo}/notifications`],markThreadAsDone:[`DELETE /notifications/threads/{thread_id}`],markThreadAsRead:[`PATCH /notifications/threads/{thread_id}`],setRepoSubscription:[`PUT /repos/{owner}/{repo}/subscription`],setThreadSubscription:[`PUT /notifications/threads/{thread_id}/subscription`],starRepoForAuthenticatedUser:[`PUT /user/starred/{owner}/{repo}`],unstarRepoForAuthenticatedUser:[`DELETE /user/starred/{owner}/{repo}`]},apps:{addRepoToInstallation:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`addRepoToInstallationForAuthenticatedUser`]}],addRepoToInstallationForAuthenticatedUser:[`PUT /user/installations/{installation_id}/repositories/{repository_id}`],checkToken:[`POST /applications/{client_id}/token`],createFromManifest:[`POST /app-manifests/{code}/conversions`],createInstallationAccessToken:[`POST /app/installations/{installation_id}/access_tokens`],deleteAuthorization:[`DELETE /applications/{client_id}/grant`],deleteInstallation:[`DELETE /app/installations/{installation_id}`],deleteToken:[`DELETE /applications/{client_id}/token`],getAuthenticated:[`GET /app`],getBySlug:[`GET /apps/{app_slug}`],getInstallation:[`GET /app/installations/{installation_id}`],getOrgInstallation:[`GET /orgs/{org}/installation`],getRepoInstallation:[`GET /repos/{owner}/{repo}/installation`],getSubscriptionPlanForAccount:[`GET /marketplace_listing/accounts/{account_id}`],getSubscriptionPlanForAccountStubbed:[`GET /marketplace_listing/stubbed/accounts/{account_id}`],getUserInstallation:[`GET /users/{username}/installation`],getWebhookConfigForApp:[`GET /app/hook/config`],getWebhookDelivery:[`GET /app/hook/deliveries/{delivery_id}`],listAccountsForPlan:[`GET /marketplace_listing/plans/{plan_id}/accounts`],listAccountsForPlanStubbed:[`GET /marketplace_listing/stubbed/plans/{plan_id}/accounts`],listInstallationReposForAuthenticatedUser:[`GET /user/installations/{installation_id}/repositories`],listInstallationRequestsForAuthenticatedApp:[`GET /app/installation-requests`],listInstallations:[`GET /app/installations`],listInstallationsForAuthenticatedUser:[`GET /user/installations`],listPlans:[`GET /marketplace_listing/plans`],listPlansStubbed:[`GET /marketplace_listing/stubbed/plans`],listReposAccessibleToInstallation:[`GET /installation/repositories`],listSubscriptionsForAuthenticatedUser:[`GET /user/marketplace_purchases`],listSubscriptionsForAuthenticatedUserStubbed:[`GET /user/marketplace_purchases/stubbed`],listWebhookDeliveries:[`GET /app/hook/deliveries`],redeliverWebhookDelivery:[`POST /app/hook/deliveries/{delivery_id}/attempts`],removeRepoFromInstallation:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`,{},{renamed:[`apps`,`removeRepoFromInstallationForAuthenticatedUser`]}],removeRepoFromInstallationForAuthenticatedUser:[`DELETE /user/installations/{installation_id}/repositories/{repository_id}`],resetToken:[`PATCH /applications/{client_id}/token`],revokeInstallationAccessToken:[`DELETE /installation/token`],scopeToken:[`POST /applications/{client_id}/token/scoped`],suspendInstallation:[`PUT /app/installations/{installation_id}/suspended`],unsuspendInstallation:[`DELETE /app/installations/{installation_id}/suspended`],updateWebhookConfigForApp:[`PATCH /app/hook/config`]},billing:{getGithubActionsBillingOrg:[`GET /orgs/{org}/settings/billing/actions`],getGithubActionsBillingUser:[`GET /users/{username}/settings/billing/actions`],getGithubBillingPremiumRequestUsageReportOrg:[`GET /organizations/{org}/settings/billing/premium_request/usage`],getGithubBillingPremiumRequestUsageReportUser:[`GET /users/{username}/settings/billing/premium_request/usage`],getGithubBillingUsageReportOrg:[`GET /organizations/{org}/settings/billing/usage`],getGithubBillingUsageReportUser:[`GET /users/{username}/settings/billing/usage`],getGithubPackagesBillingOrg:[`GET /orgs/{org}/settings/billing/packages`],getGithubPackagesBillingUser:[`GET /users/{username}/settings/billing/packages`],getSharedStorageBillingOrg:[`GET /orgs/{org}/settings/billing/shared-storage`],getSharedStorageBillingUser:[`GET /users/{username}/settings/billing/shared-storage`]},campaigns:{createCampaign:[`POST /orgs/{org}/campaigns`],deleteCampaign:[`DELETE /orgs/{org}/campaigns/{campaign_number}`],getCampaignSummary:[`GET /orgs/{org}/campaigns/{campaign_number}`],listOrgCampaigns:[`GET /orgs/{org}/campaigns`],updateCampaign:[`PATCH /orgs/{org}/campaigns/{campaign_number}`]},checks:{create:[`POST /repos/{owner}/{repo}/check-runs`],createSuite:[`POST /repos/{owner}/{repo}/check-suites`],get:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}`],getSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}`],listAnnotations:[`GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations`],listForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-runs`],listForSuite:[`GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs`],listSuitesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/check-suites`],rerequestRun:[`POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest`],rerequestSuite:[`POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest`],setSuitesPreferences:[`PATCH /repos/{owner}/{repo}/check-suites/preferences`],update:[`PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}`]},codeScanning:{commitAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits`],createAutofix:[`POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],createVariantAnalysis:[`POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses`],deleteAnalysis:[`DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}`],deleteCodeqlDatabase:[`DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getAlert:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`,{},{renamedParameters:{alert_id:`alert_number`}}],getAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}`],getAutofix:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix`],getCodeqlDatabase:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}`],getDefaultSetup:[`GET /repos/{owner}/{repo}/code-scanning/default-setup`],getSarif:[`GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}`],getVariantAnalysis:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}`],getVariantAnalysisRepoTask:[`GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}`],listAlertInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`],listAlertsForOrg:[`GET /orgs/{org}/code-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/code-scanning/alerts`],listAlertsInstances:[`GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances`,{},{renamed:[`codeScanning`,`listAlertInstances`]}],listCodeqlDatabases:[`GET /repos/{owner}/{repo}/code-scanning/codeql/databases`],listRecentAnalyses:[`GET /repos/{owner}/{repo}/code-scanning/analyses`],updateAlert:[`PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}`],updateDefaultSetup:[`PATCH /repos/{owner}/{repo}/code-scanning/default-setup`],uploadSarif:[`POST /repos/{owner}/{repo}/code-scanning/sarifs`]},codeSecurity:{attachConfiguration:[`POST /orgs/{org}/code-security/configurations/{configuration_id}/attach`],attachEnterpriseConfiguration:[`POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach`],createConfiguration:[`POST /orgs/{org}/code-security/configurations`],createConfigurationForEnterprise:[`POST /enterprises/{enterprise}/code-security/configurations`],deleteConfiguration:[`DELETE /orgs/{org}/code-security/configurations/{configuration_id}`],deleteConfigurationForEnterprise:[`DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],detachConfiguration:[`DELETE /orgs/{org}/code-security/configurations/detach`],getConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}`],getConfigurationForRepository:[`GET /repos/{owner}/{repo}/code-security-configuration`],getConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations`],getConfigurationsForOrg:[`GET /orgs/{org}/code-security/configurations`],getDefaultConfigurations:[`GET /orgs/{org}/code-security/configurations/defaults`],getDefaultConfigurationsForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/defaults`],getRepositoriesForConfiguration:[`GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories`],getRepositoriesForEnterpriseConfiguration:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories`],getSingleConfigurationForEnterprise:[`GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}`],setConfigurationAsDefault:[`PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults`],setConfigurationAsDefaultForEnterprise:[`PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults`],updateConfiguration:[`PATCH /orgs/{org}/code-security/configurations/{configuration_id}`],updateEnterpriseConfiguration:[`PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}`]},codesOfConduct:{getAllCodesOfConduct:[`GET /codes_of_conduct`],getConductCode:[`GET /codes_of_conduct/{key}`]},codespaces:{addRepositoryForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],checkPermissionsForDevcontainer:[`GET /repos/{owner}/{repo}/codespaces/permissions_check`],codespaceMachinesForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/machines`],createForAuthenticatedUser:[`POST /user/codespaces`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],createOrUpdateSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}`],createWithPrForAuthenticatedUser:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces`],createWithRepoForAuthenticatedUser:[`POST /repos/{owner}/{repo}/codespaces`],deleteForAuthenticatedUser:[`DELETE /user/codespaces/{codespace_name}`],deleteFromOrganization:[`DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],deleteSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}`],exportForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/exports`],getCodespacesForUserInOrg:[`GET /orgs/{org}/members/{username}/codespaces`],getExportDetailsForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}/exports/{export_id}`],getForAuthenticatedUser:[`GET /user/codespaces/{codespace_name}`],getOrgPublicKey:[`GET /orgs/{org}/codespaces/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}`],getPublicKeyForAuthenticatedUser:[`GET /user/codespaces/secrets/public-key`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/codespaces/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}`],getSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}`],listDevcontainersInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/devcontainers`],listForAuthenticatedUser:[`GET /user/codespaces`],listInOrganization:[`GET /orgs/{org}/codespaces`,{},{renamedParameters:{org_id:`org`}}],listInRepositoryForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces`],listOrgSecrets:[`GET /orgs/{org}/codespaces/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/codespaces/secrets`],listRepositoriesForSecretForAuthenticatedUser:[`GET /user/codespaces/secrets/{secret_name}/repositories`],listSecretsForAuthenticatedUser:[`GET /user/codespaces/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],preFlightWithRepoForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/new`],publishForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/publish`],removeRepositoryForSecretForAuthenticatedUser:[`DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}`],repoMachinesForAuthenticatedUser:[`GET /repos/{owner}/{repo}/codespaces/machines`],setRepositoriesForSecretForAuthenticatedUser:[`PUT /user/codespaces/secrets/{secret_name}/repositories`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories`],startForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/start`],stopForAuthenticatedUser:[`POST /user/codespaces/{codespace_name}/stop`],stopInOrganization:[`POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop`],updateForAuthenticatedUser:[`PATCH /user/codespaces/{codespace_name}`]},copilot:{addCopilotSeatsForTeams:[`POST /orgs/{org}/copilot/billing/selected_teams`],addCopilotSeatsForUsers:[`POST /orgs/{org}/copilot/billing/selected_users`],cancelCopilotSeatAssignmentForTeams:[`DELETE /orgs/{org}/copilot/billing/selected_teams`],cancelCopilotSeatAssignmentForUsers:[`DELETE /orgs/{org}/copilot/billing/selected_users`],copilotMetricsForOrganization:[`GET /orgs/{org}/copilot/metrics`],copilotMetricsForTeam:[`GET /orgs/{org}/team/{team_slug}/copilot/metrics`],getCopilotOrganizationDetails:[`GET /orgs/{org}/copilot/billing`],getCopilotSeatDetailsForUser:[`GET /orgs/{org}/members/{username}/copilot`],listCopilotSeats:[`GET /orgs/{org}/copilot/billing/seats`]},credentials:{revoke:[`POST /credentials/revoke`]},dependabot:{addSelectedRepoToOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],createOrUpdateOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}`],createOrUpdateRepoSecret:[`PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],deleteOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}`],deleteRepoSecret:[`DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],getAlert:[`GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],getOrgPublicKey:[`GET /orgs/{org}/dependabot/secrets/public-key`],getOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}`],getRepoPublicKey:[`GET /repos/{owner}/{repo}/dependabot/secrets/public-key`],getRepoSecret:[`GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}`],listAlertsForEnterprise:[`GET /enterprises/{enterprise}/dependabot/alerts`],listAlertsForOrg:[`GET /orgs/{org}/dependabot/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/dependabot/alerts`],listOrgSecrets:[`GET /orgs/{org}/dependabot/secrets`],listRepoSecrets:[`GET /repos/{owner}/{repo}/dependabot/secrets`],listSelectedReposForOrgSecret:[`GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],removeSelectedRepoFromOrgSecret:[`DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}`],repositoryAccessForOrg:[`GET /organizations/{org}/dependabot/repository-access`],setRepositoryAccessDefaultLevel:[`PUT /organizations/{org}/dependabot/repository-access/default-level`],setSelectedReposForOrgSecret:[`PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories`],updateAlert:[`PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}`],updateRepositoryAccessForOrg:[`PATCH /organizations/{org}/dependabot/repository-access`]},dependencyGraph:{createRepositorySnapshot:[`POST /repos/{owner}/{repo}/dependency-graph/snapshots`],diffRange:[`GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}`],exportSbom:[`GET /repos/{owner}/{repo}/dependency-graph/sbom`]},emojis:{get:[`GET /emojis`]},enterpriseTeamMemberships:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove`],get:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`],list:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships`],remove:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}`]},enterpriseTeamOrganizations:{add:[`PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],bulkAdd:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add`],bulkRemove:[`POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove`],delete:[`DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignment:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}`],getAssignments:[`GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations`]},enterpriseTeams:{create:[`POST /enterprises/{enterprise}/teams`],delete:[`DELETE /enterprises/{enterprise}/teams/{team_slug}`],get:[`GET /enterprises/{enterprise}/teams/{team_slug}`],list:[`GET /enterprises/{enterprise}/teams`],update:[`PATCH /enterprises/{enterprise}/teams/{team_slug}`]},gists:{checkIsStarred:[`GET /gists/{gist_id}/star`],create:[`POST /gists`],createComment:[`POST /gists/{gist_id}/comments`],delete:[`DELETE /gists/{gist_id}`],deleteComment:[`DELETE /gists/{gist_id}/comments/{comment_id}`],fork:[`POST /gists/{gist_id}/forks`],get:[`GET /gists/{gist_id}`],getComment:[`GET /gists/{gist_id}/comments/{comment_id}`],getRevision:[`GET /gists/{gist_id}/{sha}`],list:[`GET /gists`],listComments:[`GET /gists/{gist_id}/comments`],listCommits:[`GET /gists/{gist_id}/commits`],listForUser:[`GET /users/{username}/gists`],listForks:[`GET /gists/{gist_id}/forks`],listPublic:[`GET /gists/public`],listStarred:[`GET /gists/starred`],star:[`PUT /gists/{gist_id}/star`],unstar:[`DELETE /gists/{gist_id}/star`],update:[`PATCH /gists/{gist_id}`],updateComment:[`PATCH /gists/{gist_id}/comments/{comment_id}`]},git:{createBlob:[`POST /repos/{owner}/{repo}/git/blobs`],createCommit:[`POST /repos/{owner}/{repo}/git/commits`],createRef:[`POST /repos/{owner}/{repo}/git/refs`],createTag:[`POST /repos/{owner}/{repo}/git/tags`],createTree:[`POST /repos/{owner}/{repo}/git/trees`],deleteRef:[`DELETE /repos/{owner}/{repo}/git/refs/{ref}`],getBlob:[`GET /repos/{owner}/{repo}/git/blobs/{file_sha}`],getCommit:[`GET /repos/{owner}/{repo}/git/commits/{commit_sha}`],getRef:[`GET /repos/{owner}/{repo}/git/ref/{ref}`],getTag:[`GET /repos/{owner}/{repo}/git/tags/{tag_sha}`],getTree:[`GET /repos/{owner}/{repo}/git/trees/{tree_sha}`],listMatchingRefs:[`GET /repos/{owner}/{repo}/git/matching-refs/{ref}`],updateRef:[`PATCH /repos/{owner}/{repo}/git/refs/{ref}`]},gitignore:{getAllTemplates:[`GET /gitignore/templates`],getTemplate:[`GET /gitignore/templates/{name}`]},hostedCompute:{createNetworkConfigurationForOrg:[`POST /orgs/{org}/settings/network-configurations`],deleteNetworkConfigurationFromOrg:[`DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkConfigurationForOrg:[`GET /orgs/{org}/settings/network-configurations/{network_configuration_id}`],getNetworkSettingsForOrg:[`GET /orgs/{org}/settings/network-settings/{network_settings_id}`],listNetworkConfigurationsForOrg:[`GET /orgs/{org}/settings/network-configurations`],updateNetworkConfigurationForOrg:[`PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}`]},interactions:{getRestrictionsForAuthenticatedUser:[`GET /user/interaction-limits`],getRestrictionsForOrg:[`GET /orgs/{org}/interaction-limits`],getRestrictionsForRepo:[`GET /repos/{owner}/{repo}/interaction-limits`],getRestrictionsForYourPublicRepos:[`GET /user/interaction-limits`,{},{renamed:[`interactions`,`getRestrictionsForAuthenticatedUser`]}],removeRestrictionsForAuthenticatedUser:[`DELETE /user/interaction-limits`],removeRestrictionsForOrg:[`DELETE /orgs/{org}/interaction-limits`],removeRestrictionsForRepo:[`DELETE /repos/{owner}/{repo}/interaction-limits`],removeRestrictionsForYourPublicRepos:[`DELETE /user/interaction-limits`,{},{renamed:[`interactions`,`removeRestrictionsForAuthenticatedUser`]}],setRestrictionsForAuthenticatedUser:[`PUT /user/interaction-limits`],setRestrictionsForOrg:[`PUT /orgs/{org}/interaction-limits`],setRestrictionsForRepo:[`PUT /repos/{owner}/{repo}/interaction-limits`],setRestrictionsForYourPublicRepos:[`PUT /user/interaction-limits`,{},{renamed:[`interactions`,`setRestrictionsForAuthenticatedUser`]}]},issues:{addAssignees:[`POST /repos/{owner}/{repo}/issues/{issue_number}/assignees`],addBlockedByDependency:[`POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],addLabels:[`POST /repos/{owner}/{repo}/issues/{issue_number}/labels`],addSubIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],checkUserCanBeAssigned:[`GET /repos/{owner}/{repo}/assignees/{assignee}`],checkUserCanBeAssignedToIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}`],create:[`POST /repos/{owner}/{repo}/issues`],createComment:[`POST /repos/{owner}/{repo}/issues/{issue_number}/comments`],createLabel:[`POST /repos/{owner}/{repo}/labels`],createMilestone:[`POST /repos/{owner}/{repo}/milestones`],deleteComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}`],deleteLabel:[`DELETE /repos/{owner}/{repo}/labels/{name}`],deleteMilestone:[`DELETE /repos/{owner}/{repo}/milestones/{milestone_number}`],get:[`GET /repos/{owner}/{repo}/issues/{issue_number}`],getComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}`],getEvent:[`GET /repos/{owner}/{repo}/issues/events/{event_id}`],getLabel:[`GET /repos/{owner}/{repo}/labels/{name}`],getMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}`],getParent:[`GET /repos/{owner}/{repo}/issues/{issue_number}/parent`],list:[`GET /issues`],listAssignees:[`GET /repos/{owner}/{repo}/assignees`],listComments:[`GET /repos/{owner}/{repo}/issues/{issue_number}/comments`],listCommentsForRepo:[`GET /repos/{owner}/{repo}/issues/comments`],listDependenciesBlockedBy:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by`],listDependenciesBlocking:[`GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking`],listEvents:[`GET /repos/{owner}/{repo}/issues/{issue_number}/events`],listEventsForRepo:[`GET /repos/{owner}/{repo}/issues/events`],listEventsForTimeline:[`GET /repos/{owner}/{repo}/issues/{issue_number}/timeline`],listForAuthenticatedUser:[`GET /user/issues`],listForOrg:[`GET /orgs/{org}/issues`],listForRepo:[`GET /repos/{owner}/{repo}/issues`],listLabelsForMilestone:[`GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels`],listLabelsForRepo:[`GET /repos/{owner}/{repo}/labels`],listLabelsOnIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/labels`],listMilestones:[`GET /repos/{owner}/{repo}/milestones`],listSubIssues:[`GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues`],lock:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/lock`],removeAllLabels:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels`],removeAssignees:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees`],removeDependencyBlockedBy:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}`],removeLabel:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}`],removeSubIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue`],reprioritizeSubIssue:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority`],setLabels:[`PUT /repos/{owner}/{repo}/issues/{issue_number}/labels`],unlock:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock`],update:[`PATCH /repos/{owner}/{repo}/issues/{issue_number}`],updateComment:[`PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}`],updateLabel:[`PATCH /repos/{owner}/{repo}/labels/{name}`],updateMilestone:[`PATCH /repos/{owner}/{repo}/milestones/{milestone_number}`]},licenses:{get:[`GET /licenses/{license}`],getAllCommonlyUsed:[`GET /licenses`],getForRepo:[`GET /repos/{owner}/{repo}/license`]},markdown:{render:[`POST /markdown`],renderRaw:[`POST /markdown/raw`,{headers:{"content-type":`text/plain; charset=utf-8`}}]},meta:{get:[`GET /meta`],getAllVersions:[`GET /versions`],getOctocat:[`GET /octocat`],getZen:[`GET /zen`],root:[`GET /`]},migrations:{deleteArchiveForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/archive`],deleteArchiveForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/archive`],downloadArchiveForOrg:[`GET /orgs/{org}/migrations/{migration_id}/archive`],getArchiveForAuthenticatedUser:[`GET /user/migrations/{migration_id}/archive`],getStatusForAuthenticatedUser:[`GET /user/migrations/{migration_id}`],getStatusForOrg:[`GET /orgs/{org}/migrations/{migration_id}`],listForAuthenticatedUser:[`GET /user/migrations`],listForOrg:[`GET /orgs/{org}/migrations`],listReposForAuthenticatedUser:[`GET /user/migrations/{migration_id}/repositories`],listReposForOrg:[`GET /orgs/{org}/migrations/{migration_id}/repositories`],listReposForUser:[`GET /user/migrations/{migration_id}/repositories`,{},{renamed:[`migrations`,`listReposForAuthenticatedUser`]}],startForAuthenticatedUser:[`POST /user/migrations`],startForOrg:[`POST /orgs/{org}/migrations`],unlockRepoForAuthenticatedUser:[`DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock`],unlockRepoForOrg:[`DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock`]},oidc:{getOidcCustomSubTemplateForOrg:[`GET /orgs/{org}/actions/oidc/customization/sub`],updateOidcCustomSubTemplateForOrg:[`PUT /orgs/{org}/actions/oidc/customization/sub`]},orgs:{addSecurityManagerTeam:[`PUT /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team`}],assignTeamToOrgRole:[`PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],assignUserToOrgRole:[`PUT /orgs/{org}/organization-roles/users/{username}/{role_id}`],blockUser:[`PUT /orgs/{org}/blocks/{username}`],cancelInvitation:[`DELETE /orgs/{org}/invitations/{invitation_id}`],checkBlockedUser:[`GET /orgs/{org}/blocks/{username}`],checkMembershipForUser:[`GET /orgs/{org}/members/{username}`],checkPublicMembershipForUser:[`GET /orgs/{org}/public_members/{username}`],convertMemberToOutsideCollaborator:[`PUT /orgs/{org}/outside_collaborators/{username}`],createArtifactStorageRecord:[`POST /orgs/{org}/artifacts/metadata/storage-record`],createInvitation:[`POST /orgs/{org}/invitations`],createIssueType:[`POST /orgs/{org}/issue-types`],createWebhook:[`POST /orgs/{org}/hooks`],customPropertiesForOrgsCreateOrUpdateOrganizationValues:[`PATCH /organizations/{org}/org-properties/values`],customPropertiesForOrgsGetOrganizationValues:[`GET /organizations/{org}/org-properties/values`],customPropertiesForReposCreateOrUpdateOrganizationDefinition:[`PUT /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposCreateOrUpdateOrganizationDefinitions:[`PATCH /orgs/{org}/properties/schema`],customPropertiesForReposCreateOrUpdateOrganizationValues:[`PATCH /orgs/{org}/properties/values`],customPropertiesForReposDeleteOrganizationDefinition:[`DELETE /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinition:[`GET /orgs/{org}/properties/schema/{custom_property_name}`],customPropertiesForReposGetOrganizationDefinitions:[`GET /orgs/{org}/properties/schema`],customPropertiesForReposGetOrganizationValues:[`GET /orgs/{org}/properties/values`],delete:[`DELETE /orgs/{org}`],deleteAttestationsBulk:[`POST /orgs/{org}/attestations/delete-request`],deleteAttestationsById:[`DELETE /orgs/{org}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /orgs/{org}/attestations/digest/{subject_digest}`],deleteIssueType:[`DELETE /orgs/{org}/issue-types/{issue_type_id}`],deleteWebhook:[`DELETE /orgs/{org}/hooks/{hook_id}`],disableSelectedRepositoryImmutableReleasesOrganization:[`DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],enableSelectedRepositoryImmutableReleasesOrganization:[`PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}`],get:[`GET /orgs/{org}`],getImmutableReleasesSettings:[`GET /orgs/{org}/settings/immutable-releases`],getImmutableReleasesSettingsRepositories:[`GET /orgs/{org}/settings/immutable-releases/repositories`],getMembershipForAuthenticatedUser:[`GET /user/memberships/orgs/{org}`],getMembershipForUser:[`GET /orgs/{org}/memberships/{username}`],getOrgRole:[`GET /orgs/{org}/organization-roles/{role_id}`],getOrgRulesetHistory:[`GET /orgs/{org}/rulesets/{ruleset_id}/history`],getOrgRulesetVersion:[`GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}`],getWebhook:[`GET /orgs/{org}/hooks/{hook_id}`],getWebhookConfigForOrg:[`GET /orgs/{org}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}`],list:[`GET /organizations`],listAppInstallations:[`GET /orgs/{org}/installations`],listArtifactStorageRecords:[`GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records`],listAttestationRepositories:[`GET /orgs/{org}/attestations/repositories`],listAttestations:[`GET /orgs/{org}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}`],listBlockedUsers:[`GET /orgs/{org}/blocks`],listFailedInvitations:[`GET /orgs/{org}/failed_invitations`],listForAuthenticatedUser:[`GET /user/orgs`],listForUser:[`GET /users/{username}/orgs`],listInvitationTeams:[`GET /orgs/{org}/invitations/{invitation_id}/teams`],listIssueTypes:[`GET /orgs/{org}/issue-types`],listMembers:[`GET /orgs/{org}/members`],listMembershipsForAuthenticatedUser:[`GET /user/memberships/orgs`],listOrgRoleTeams:[`GET /orgs/{org}/organization-roles/{role_id}/teams`],listOrgRoleUsers:[`GET /orgs/{org}/organization-roles/{role_id}/users`],listOrgRoles:[`GET /orgs/{org}/organization-roles`],listOrganizationFineGrainedPermissions:[`GET /orgs/{org}/organization-fine-grained-permissions`],listOutsideCollaborators:[`GET /orgs/{org}/outside_collaborators`],listPatGrantRepositories:[`GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories`],listPatGrantRequestRepositories:[`GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories`],listPatGrantRequests:[`GET /orgs/{org}/personal-access-token-requests`],listPatGrants:[`GET /orgs/{org}/personal-access-tokens`],listPendingInvitations:[`GET /orgs/{org}/invitations`],listPublicMembers:[`GET /orgs/{org}/public_members`],listSecurityManagerTeams:[`GET /orgs/{org}/security-managers`,{},{deprecated:`octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams`}],listWebhookDeliveries:[`GET /orgs/{org}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /orgs/{org}/hooks`],pingWebhook:[`POST /orgs/{org}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeMember:[`DELETE /orgs/{org}/members/{username}`],removeMembershipForUser:[`DELETE /orgs/{org}/memberships/{username}`],removeOutsideCollaborator:[`DELETE /orgs/{org}/outside_collaborators/{username}`],removePublicMembershipForAuthenticatedUser:[`DELETE /orgs/{org}/public_members/{username}`],removeSecurityManagerTeam:[`DELETE /orgs/{org}/security-managers/teams/{team_slug}`,{},{deprecated:`octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team`}],reviewPatGrantRequest:[`POST /orgs/{org}/personal-access-token-requests/{pat_request_id}`],reviewPatGrantRequestsInBulk:[`POST /orgs/{org}/personal-access-token-requests`],revokeAllOrgRolesTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}`],revokeAllOrgRolesUser:[`DELETE /orgs/{org}/organization-roles/users/{username}`],revokeOrgRoleTeam:[`DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}`],revokeOrgRoleUser:[`DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}`],setImmutableReleasesSettings:[`PUT /orgs/{org}/settings/immutable-releases`],setImmutableReleasesSettingsRepositories:[`PUT /orgs/{org}/settings/immutable-releases/repositories`],setMembershipForUser:[`PUT /orgs/{org}/memberships/{username}`],setPublicMembershipForAuthenticatedUser:[`PUT /orgs/{org}/public_members/{username}`],unblockUser:[`DELETE /orgs/{org}/blocks/{username}`],update:[`PATCH /orgs/{org}`],updateIssueType:[`PUT /orgs/{org}/issue-types/{issue_type_id}`],updateMembershipForAuthenticatedUser:[`PATCH /user/memberships/orgs/{org}`],updatePatAccess:[`POST /orgs/{org}/personal-access-tokens/{pat_id}`],updatePatAccesses:[`POST /orgs/{org}/personal-access-tokens`],updateWebhook:[`PATCH /orgs/{org}/hooks/{hook_id}`],updateWebhookConfigForOrg:[`PATCH /orgs/{org}/hooks/{hook_id}/config`]},packages:{deletePackageForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}`],deletePackageForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}`],deletePackageForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}`],deletePackageVersionForAuthenticatedUser:[`DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForOrg:[`DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],deletePackageVersionForUser:[`DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getAllPackageVersionsForAPackageOwnedByAnOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByOrg`]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`,{},{renamed:[`packages`,`getAllPackageVersionsForPackageOwnedByAuthenticatedUser`]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByOrg:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions`],getAllPackageVersionsForPackageOwnedByUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions`],getPackageForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}`],getPackageForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}`],getPackageForUser:[`GET /users/{username}/packages/{package_type}/{package_name}`],getPackageVersionForAuthenticatedUser:[`GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForOrganization:[`GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}`],getPackageVersionForUser:[`GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}`],listDockerMigrationConflictingPackagesForAuthenticatedUser:[`GET /user/docker/conflicts`],listDockerMigrationConflictingPackagesForOrganization:[`GET /orgs/{org}/docker/conflicts`],listDockerMigrationConflictingPackagesForUser:[`GET /users/{username}/docker/conflicts`],listPackagesForAuthenticatedUser:[`GET /user/packages`],listPackagesForOrganization:[`GET /orgs/{org}/packages`],listPackagesForUser:[`GET /users/{username}/packages`],restorePackageForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}`],restorePackageVersionForAuthenticatedUser:[`POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForOrg:[`POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`],restorePackageVersionForUser:[`POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore`]},privateRegistries:{createOrgPrivateRegistry:[`POST /orgs/{org}/private-registries`],deleteOrgPrivateRegistry:[`DELETE /orgs/{org}/private-registries/{secret_name}`],getOrgPrivateRegistry:[`GET /orgs/{org}/private-registries/{secret_name}`],getOrgPublicKey:[`GET /orgs/{org}/private-registries/public-key`],listOrgPrivateRegistries:[`GET /orgs/{org}/private-registries`],updateOrgPrivateRegistry:[`PATCH /orgs/{org}/private-registries/{secret_name}`]},projects:{addItemForOrg:[`POST /orgs/{org}/projectsV2/{project_number}/items`],addItemForUser:[`POST /users/{username}/projectsV2/{project_number}/items`],deleteItemForOrg:[`DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],deleteItemForUser:[`DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}`],getFieldForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}`],getFieldForUser:[`GET /users/{username}/projectsV2/{project_number}/fields/{field_id}`],getForOrg:[`GET /orgs/{org}/projectsV2/{project_number}`],getForUser:[`GET /users/{username}/projectsV2/{project_number}`],getOrgItem:[`GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],getUserItem:[`GET /users/{username}/projectsV2/{project_number}/items/{item_id}`],listFieldsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/fields`],listFieldsForUser:[`GET /users/{username}/projectsV2/{project_number}/fields`],listForOrg:[`GET /orgs/{org}/projectsV2`],listForUser:[`GET /users/{username}/projectsV2`],listItemsForOrg:[`GET /orgs/{org}/projectsV2/{project_number}/items`],listItemsForUser:[`GET /users/{username}/projectsV2/{project_number}/items`],updateItemForOrg:[`PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}`],updateItemForUser:[`PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}`]},pulls:{checkIfMerged:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/merge`],create:[`POST /repos/{owner}/{repo}/pulls`],createReplyForReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies`],createReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],createReviewComment:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/comments`],deletePendingReview:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],deleteReviewComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}`],dismissReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals`],get:[`GET /repos/{owner}/{repo}/pulls/{pull_number}`],getReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],getReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}`],list:[`GET /repos/{owner}/{repo}/pulls`],listCommentsForReview:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments`],listCommits:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/commits`],listFiles:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/files`],listRequestedReviewers:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],listReviewComments:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/comments`],listReviewCommentsForRepo:[`GET /repos/{owner}/{repo}/pulls/comments`],listReviews:[`GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews`],merge:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge`],removeRequestedReviewers:[`DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],requestReviewers:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`],submitReview:[`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events`],update:[`PATCH /repos/{owner}/{repo}/pulls/{pull_number}`],updateBranch:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch`],updateReview:[`PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}`],updateReviewComment:[`PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}`]},rateLimit:{get:[`GET /rate_limit`]},reactions:{createForCommitComment:[`POST /repos/{owner}/{repo}/comments/{comment_id}/reactions`],createForIssue:[`POST /repos/{owner}/{repo}/issues/{issue_number}/reactions`],createForIssueComment:[`POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],createForPullRequestReviewComment:[`POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],createForRelease:[`POST /repos/{owner}/{repo}/releases/{release_id}/reactions`],createForTeamDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],createForTeamDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`],deleteForCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}`],deleteForIssue:[`DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}`],deleteForIssueComment:[`DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}`],deleteForPullRequestComment:[`DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}`],deleteForRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}`],deleteForTeamDiscussion:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}`],deleteForTeamDiscussionComment:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}`],listForCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}/reactions`],listForIssue:[`GET /repos/{owner}/{repo}/issues/{issue_number}/reactions`],listForIssueComment:[`GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions`],listForPullRequestReviewComment:[`GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions`],listForRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}/reactions`],listForTeamDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions`],listForTeamDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions`]},repos:{acceptInvitation:[`PATCH /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`acceptInvitationForAuthenticatedUser`]}],acceptInvitationForAuthenticatedUser:[`PATCH /user/repository_invitations/{invitation_id}`],addAppAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],addCollaborator:[`PUT /repos/{owner}/{repo}/collaborators/{username}`],addStatusCheckContexts:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],addTeamAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],addUserAccessRestrictions:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],cancelPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel`],checkAutomatedSecurityFixes:[`GET /repos/{owner}/{repo}/automated-security-fixes`],checkCollaborator:[`GET /repos/{owner}/{repo}/collaborators/{username}`],checkImmutableReleases:[`GET /repos/{owner}/{repo}/immutable-releases`],checkPrivateVulnerabilityReporting:[`GET /repos/{owner}/{repo}/private-vulnerability-reporting`],checkVulnerabilityAlerts:[`GET /repos/{owner}/{repo}/vulnerability-alerts`],codeownersErrors:[`GET /repos/{owner}/{repo}/codeowners/errors`],compareCommits:[`GET /repos/{owner}/{repo}/compare/{base}...{head}`],compareCommitsWithBasehead:[`GET /repos/{owner}/{repo}/compare/{basehead}`],createAttestation:[`POST /repos/{owner}/{repo}/attestations`],createAutolink:[`POST /repos/{owner}/{repo}/autolinks`],createCommitComment:[`POST /repos/{owner}/{repo}/commits/{commit_sha}/comments`],createCommitSignatureProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],createCommitStatus:[`POST /repos/{owner}/{repo}/statuses/{sha}`],createDeployKey:[`POST /repos/{owner}/{repo}/keys`],createDeployment:[`POST /repos/{owner}/{repo}/deployments`],createDeploymentBranchPolicy:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],createDeploymentProtectionRule:[`POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],createDeploymentStatus:[`POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],createDispatchEvent:[`POST /repos/{owner}/{repo}/dispatches`],createForAuthenticatedUser:[`POST /user/repos`],createFork:[`POST /repos/{owner}/{repo}/forks`],createInOrg:[`POST /orgs/{org}/repos`],createOrUpdateEnvironment:[`PUT /repos/{owner}/{repo}/environments/{environment_name}`],createOrUpdateFileContents:[`PUT /repos/{owner}/{repo}/contents/{path}`],createOrgRuleset:[`POST /orgs/{org}/rulesets`],createPagesDeployment:[`POST /repos/{owner}/{repo}/pages/deployments`],createPagesSite:[`POST /repos/{owner}/{repo}/pages`],createRelease:[`POST /repos/{owner}/{repo}/releases`],createRepoRuleset:[`POST /repos/{owner}/{repo}/rulesets`],createUsingTemplate:[`POST /repos/{template_owner}/{template_repo}/generate`],createWebhook:[`POST /repos/{owner}/{repo}/hooks`],customPropertiesForReposCreateOrUpdateRepositoryValues:[`PATCH /repos/{owner}/{repo}/properties/values`],customPropertiesForReposGetRepositoryValues:[`GET /repos/{owner}/{repo}/properties/values`],declineInvitation:[`DELETE /user/repository_invitations/{invitation_id}`,{},{renamed:[`repos`,`declineInvitationForAuthenticatedUser`]}],declineInvitationForAuthenticatedUser:[`DELETE /user/repository_invitations/{invitation_id}`],delete:[`DELETE /repos/{owner}/{repo}`],deleteAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],deleteAdminBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],deleteAnEnvironment:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}`],deleteAutolink:[`DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}`],deleteBranchProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection`],deleteCommitComment:[`DELETE /repos/{owner}/{repo}/comments/{comment_id}`],deleteCommitSignatureProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],deleteDeployKey:[`DELETE /repos/{owner}/{repo}/keys/{key_id}`],deleteDeployment:[`DELETE /repos/{owner}/{repo}/deployments/{deployment_id}`],deleteDeploymentBranchPolicy:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],deleteFile:[`DELETE /repos/{owner}/{repo}/contents/{path}`],deleteInvitation:[`DELETE /repos/{owner}/{repo}/invitations/{invitation_id}`],deleteOrgRuleset:[`DELETE /orgs/{org}/rulesets/{ruleset_id}`],deletePagesSite:[`DELETE /repos/{owner}/{repo}/pages`],deletePullRequestReviewProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],deleteRelease:[`DELETE /repos/{owner}/{repo}/releases/{release_id}`],deleteReleaseAsset:[`DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}`],deleteRepoRuleset:[`DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}`],deleteWebhook:[`DELETE /repos/{owner}/{repo}/hooks/{hook_id}`],disableAutomatedSecurityFixes:[`DELETE /repos/{owner}/{repo}/automated-security-fixes`],disableDeploymentProtectionRule:[`DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],disableImmutableReleases:[`DELETE /repos/{owner}/{repo}/immutable-releases`],disablePrivateVulnerabilityReporting:[`DELETE /repos/{owner}/{repo}/private-vulnerability-reporting`],disableVulnerabilityAlerts:[`DELETE /repos/{owner}/{repo}/vulnerability-alerts`],downloadArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`,{},{renamed:[`repos`,`downloadZipballArchive`]}],downloadTarballArchive:[`GET /repos/{owner}/{repo}/tarball/{ref}`],downloadZipballArchive:[`GET /repos/{owner}/{repo}/zipball/{ref}`],enableAutomatedSecurityFixes:[`PUT /repos/{owner}/{repo}/automated-security-fixes`],enableImmutableReleases:[`PUT /repos/{owner}/{repo}/immutable-releases`],enablePrivateVulnerabilityReporting:[`PUT /repos/{owner}/{repo}/private-vulnerability-reporting`],enableVulnerabilityAlerts:[`PUT /repos/{owner}/{repo}/vulnerability-alerts`],generateReleaseNotes:[`POST /repos/{owner}/{repo}/releases/generate-notes`],get:[`GET /repos/{owner}/{repo}`],getAccessRestrictions:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions`],getAdminBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],getAllDeploymentProtectionRules:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules`],getAllEnvironments:[`GET /repos/{owner}/{repo}/environments`],getAllStatusCheckContexts:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`],getAllTopics:[`GET /repos/{owner}/{repo}/topics`],getAppsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`],getAutolink:[`GET /repos/{owner}/{repo}/autolinks/{autolink_id}`],getBranch:[`GET /repos/{owner}/{repo}/branches/{branch}`],getBranchProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection`],getBranchRules:[`GET /repos/{owner}/{repo}/rules/branches/{branch}`],getClones:[`GET /repos/{owner}/{repo}/traffic/clones`],getCodeFrequencyStats:[`GET /repos/{owner}/{repo}/stats/code_frequency`],getCollaboratorPermissionLevel:[`GET /repos/{owner}/{repo}/collaborators/{username}/permission`],getCombinedStatusForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/status`],getCommit:[`GET /repos/{owner}/{repo}/commits/{ref}`],getCommitActivityStats:[`GET /repos/{owner}/{repo}/stats/commit_activity`],getCommitComment:[`GET /repos/{owner}/{repo}/comments/{comment_id}`],getCommitSignatureProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures`],getCommunityProfileMetrics:[`GET /repos/{owner}/{repo}/community/profile`],getContent:[`GET /repos/{owner}/{repo}/contents/{path}`],getContributorsStats:[`GET /repos/{owner}/{repo}/stats/contributors`],getCustomDeploymentProtectionRule:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}`],getDeployKey:[`GET /repos/{owner}/{repo}/keys/{key_id}`],getDeployment:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}`],getDeploymentBranchPolicy:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],getDeploymentStatus:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}`],getEnvironment:[`GET /repos/{owner}/{repo}/environments/{environment_name}`],getLatestPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/latest`],getLatestRelease:[`GET /repos/{owner}/{repo}/releases/latest`],getOrgRuleSuite:[`GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}`],getOrgRuleSuites:[`GET /orgs/{org}/rulesets/rule-suites`],getOrgRuleset:[`GET /orgs/{org}/rulesets/{ruleset_id}`],getOrgRulesets:[`GET /orgs/{org}/rulesets`],getPages:[`GET /repos/{owner}/{repo}/pages`],getPagesBuild:[`GET /repos/{owner}/{repo}/pages/builds/{build_id}`],getPagesDeployment:[`GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}`],getPagesHealthCheck:[`GET /repos/{owner}/{repo}/pages/health`],getParticipationStats:[`GET /repos/{owner}/{repo}/stats/participation`],getPullRequestReviewProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],getPunchCardStats:[`GET /repos/{owner}/{repo}/stats/punch_card`],getReadme:[`GET /repos/{owner}/{repo}/readme`],getReadmeInDirectory:[`GET /repos/{owner}/{repo}/readme/{dir}`],getRelease:[`GET /repos/{owner}/{repo}/releases/{release_id}`],getReleaseAsset:[`GET /repos/{owner}/{repo}/releases/assets/{asset_id}`],getReleaseByTag:[`GET /repos/{owner}/{repo}/releases/tags/{tag}`],getRepoRuleSuite:[`GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}`],getRepoRuleSuites:[`GET /repos/{owner}/{repo}/rulesets/rule-suites`],getRepoRuleset:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}`],getRepoRulesetHistory:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history`],getRepoRulesetVersion:[`GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}`],getRepoRulesets:[`GET /repos/{owner}/{repo}/rulesets`],getStatusChecksProtection:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],getTeamsWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`],getTopPaths:[`GET /repos/{owner}/{repo}/traffic/popular/paths`],getTopReferrers:[`GET /repos/{owner}/{repo}/traffic/popular/referrers`],getUsersWithAccessToProtectedBranch:[`GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`],getViews:[`GET /repos/{owner}/{repo}/traffic/views`],getWebhook:[`GET /repos/{owner}/{repo}/hooks/{hook_id}`],getWebhookConfigForRepo:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/config`],getWebhookDelivery:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}`],listActivities:[`GET /repos/{owner}/{repo}/activity`],listAttestations:[`GET /repos/{owner}/{repo}/attestations/{subject_digest}`],listAutolinks:[`GET /repos/{owner}/{repo}/autolinks`],listBranches:[`GET /repos/{owner}/{repo}/branches`],listBranchesForHeadCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head`],listCollaborators:[`GET /repos/{owner}/{repo}/collaborators`],listCommentsForCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/comments`],listCommitCommentsForRepo:[`GET /repos/{owner}/{repo}/comments`],listCommitStatusesForRef:[`GET /repos/{owner}/{repo}/commits/{ref}/statuses`],listCommits:[`GET /repos/{owner}/{repo}/commits`],listContributors:[`GET /repos/{owner}/{repo}/contributors`],listCustomDeploymentRuleIntegrations:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps`],listDeployKeys:[`GET /repos/{owner}/{repo}/keys`],listDeploymentBranchPolicies:[`GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`],listDeploymentStatuses:[`GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses`],listDeployments:[`GET /repos/{owner}/{repo}/deployments`],listForAuthenticatedUser:[`GET /user/repos`],listForOrg:[`GET /orgs/{org}/repos`],listForUser:[`GET /users/{username}/repos`],listForks:[`GET /repos/{owner}/{repo}/forks`],listInvitations:[`GET /repos/{owner}/{repo}/invitations`],listInvitationsForAuthenticatedUser:[`GET /user/repository_invitations`],listLanguages:[`GET /repos/{owner}/{repo}/languages`],listPagesBuilds:[`GET /repos/{owner}/{repo}/pages/builds`],listPublic:[`GET /repositories`],listPullRequestsAssociatedWithCommit:[`GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls`],listReleaseAssets:[`GET /repos/{owner}/{repo}/releases/{release_id}/assets`],listReleases:[`GET /repos/{owner}/{repo}/releases`],listTags:[`GET /repos/{owner}/{repo}/tags`],listTeams:[`GET /repos/{owner}/{repo}/teams`],listWebhookDeliveries:[`GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries`],listWebhooks:[`GET /repos/{owner}/{repo}/hooks`],merge:[`POST /repos/{owner}/{repo}/merges`],mergeUpstream:[`POST /repos/{owner}/{repo}/merge-upstream`],pingWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/pings`],redeliverWebhookDelivery:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts`],removeAppAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],removeCollaborator:[`DELETE /repos/{owner}/{repo}/collaborators/{username}`],removeStatusCheckContexts:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],removeStatusCheckProtection:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],removeTeamAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],removeUserAccessRestrictions:[`DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],renameBranch:[`POST /repos/{owner}/{repo}/branches/{branch}/rename`],replaceAllTopics:[`PUT /repos/{owner}/{repo}/topics`],requestPagesBuild:[`POST /repos/{owner}/{repo}/pages/builds`],setAdminBranchProtection:[`POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins`],setAppAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps`,{},{mapToData:`apps`}],setStatusCheckContexts:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts`,{},{mapToData:`contexts`}],setTeamAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams`,{},{mapToData:`teams`}],setUserAccessRestrictions:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users`,{},{mapToData:`users`}],testPushWebhook:[`POST /repos/{owner}/{repo}/hooks/{hook_id}/tests`],transfer:[`POST /repos/{owner}/{repo}/transfer`],update:[`PATCH /repos/{owner}/{repo}`],updateBranchProtection:[`PUT /repos/{owner}/{repo}/branches/{branch}/protection`],updateCommitComment:[`PATCH /repos/{owner}/{repo}/comments/{comment_id}`],updateDeploymentBranchPolicy:[`PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}`],updateInformationAboutPagesSite:[`PUT /repos/{owner}/{repo}/pages`],updateInvitation:[`PATCH /repos/{owner}/{repo}/invitations/{invitation_id}`],updateOrgRuleset:[`PUT /orgs/{org}/rulesets/{ruleset_id}`],updatePullRequestReviewProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews`],updateRelease:[`PATCH /repos/{owner}/{repo}/releases/{release_id}`],updateReleaseAsset:[`PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}`],updateRepoRuleset:[`PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}`],updateStatusCheckPotection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`,{},{renamed:[`repos`,`updateStatusCheckProtection`]}],updateStatusCheckProtection:[`PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks`],updateWebhook:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}`],updateWebhookConfigForRepo:[`PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config`],uploadReleaseAsset:[`POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}`,{baseUrl:`https://uploads.github.com`}]},search:{code:[`GET /search/code`],commits:[`GET /search/commits`],issuesAndPullRequests:[`GET /search/issues`],labels:[`GET /search/labels`],repos:[`GET /search/repositories`],topics:[`GET /search/topics`],users:[`GET /search/users`]},secretScanning:{createPushProtectionBypass:[`POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses`],getAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],getScanHistory:[`GET /repos/{owner}/{repo}/secret-scanning/scan-history`],listAlertsForOrg:[`GET /orgs/{org}/secret-scanning/alerts`],listAlertsForRepo:[`GET /repos/{owner}/{repo}/secret-scanning/alerts`],listLocationsForAlert:[`GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations`],listOrgPatternConfigs:[`GET /orgs/{org}/secret-scanning/pattern-configurations`],updateAlert:[`PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}`],updateOrgPatternConfigs:[`PATCH /orgs/{org}/secret-scanning/pattern-configurations`]},securityAdvisories:{createFork:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks`],createPrivateVulnerabilityReport:[`POST /repos/{owner}/{repo}/security-advisories/reports`],createRepositoryAdvisory:[`POST /repos/{owner}/{repo}/security-advisories`],createRepositoryAdvisoryCveRequest:[`POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve`],getGlobalAdvisory:[`GET /advisories/{ghsa_id}`],getRepositoryAdvisory:[`GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}`],listGlobalAdvisories:[`GET /advisories`],listOrgRepositoryAdvisories:[`GET /orgs/{org}/security-advisories`],listRepositoryAdvisories:[`GET /repos/{owner}/{repo}/security-advisories`],updateRepositoryAdvisory:[`PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}`]},teams:{addOrUpdateMembershipForUserInOrg:[`PUT /orgs/{org}/teams/{team_slug}/memberships/{username}`],addOrUpdateRepoPermissionsInOrg:[`PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],checkPermissionsForRepoInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],create:[`POST /orgs/{org}/teams`],createDiscussionCommentInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],createDiscussionInOrg:[`POST /orgs/{org}/teams/{team_slug}/discussions`],deleteDiscussionCommentInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],deleteDiscussionInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],deleteInOrg:[`DELETE /orgs/{org}/teams/{team_slug}`],getByName:[`GET /orgs/{org}/teams/{team_slug}`],getDiscussionCommentInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],getDiscussionInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],getMembershipForUserInOrg:[`GET /orgs/{org}/teams/{team_slug}/memberships/{username}`],list:[`GET /orgs/{org}/teams`],listChildInOrg:[`GET /orgs/{org}/teams/{team_slug}/teams`],listDiscussionCommentsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`],listDiscussionsInOrg:[`GET /orgs/{org}/teams/{team_slug}/discussions`],listForAuthenticatedUser:[`GET /user/teams`],listMembersInOrg:[`GET /orgs/{org}/teams/{team_slug}/members`],listPendingInvitationsInOrg:[`GET /orgs/{org}/teams/{team_slug}/invitations`],listReposInOrg:[`GET /orgs/{org}/teams/{team_slug}/repos`],removeMembershipForUserInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}`],removeRepoInOrg:[`DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}`],updateDiscussionCommentInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}`],updateDiscussionInOrg:[`PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}`],updateInOrg:[`PATCH /orgs/{org}/teams/{team_slug}`]},users:{addEmailForAuthenticated:[`POST /user/emails`,{},{renamed:[`users`,`addEmailForAuthenticatedUser`]}],addEmailForAuthenticatedUser:[`POST /user/emails`],addSocialAccountForAuthenticatedUser:[`POST /user/social_accounts`],block:[`PUT /user/blocks/{username}`],checkBlocked:[`GET /user/blocks/{username}`],checkFollowingForUser:[`GET /users/{username}/following/{target_user}`],checkPersonIsFollowedByAuthenticated:[`GET /user/following/{username}`],createGpgKeyForAuthenticated:[`POST /user/gpg_keys`,{},{renamed:[`users`,`createGpgKeyForAuthenticatedUser`]}],createGpgKeyForAuthenticatedUser:[`POST /user/gpg_keys`],createPublicSshKeyForAuthenticated:[`POST /user/keys`,{},{renamed:[`users`,`createPublicSshKeyForAuthenticatedUser`]}],createPublicSshKeyForAuthenticatedUser:[`POST /user/keys`],createSshSigningKeyForAuthenticatedUser:[`POST /user/ssh_signing_keys`],deleteAttestationsBulk:[`POST /users/{username}/attestations/delete-request`],deleteAttestationsById:[`DELETE /users/{username}/attestations/{attestation_id}`],deleteAttestationsBySubjectDigest:[`DELETE /users/{username}/attestations/digest/{subject_digest}`],deleteEmailForAuthenticated:[`DELETE /user/emails`,{},{renamed:[`users`,`deleteEmailForAuthenticatedUser`]}],deleteEmailForAuthenticatedUser:[`DELETE /user/emails`],deleteGpgKeyForAuthenticated:[`DELETE /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`deleteGpgKeyForAuthenticatedUser`]}],deleteGpgKeyForAuthenticatedUser:[`DELETE /user/gpg_keys/{gpg_key_id}`],deletePublicSshKeyForAuthenticated:[`DELETE /user/keys/{key_id}`,{},{renamed:[`users`,`deletePublicSshKeyForAuthenticatedUser`]}],deletePublicSshKeyForAuthenticatedUser:[`DELETE /user/keys/{key_id}`],deleteSocialAccountForAuthenticatedUser:[`DELETE /user/social_accounts`],deleteSshSigningKeyForAuthenticatedUser:[`DELETE /user/ssh_signing_keys/{ssh_signing_key_id}`],follow:[`PUT /user/following/{username}`],getAuthenticated:[`GET /user`],getById:[`GET /user/{account_id}`],getByUsername:[`GET /users/{username}`],getContextForUser:[`GET /users/{username}/hovercard`],getGpgKeyForAuthenticated:[`GET /user/gpg_keys/{gpg_key_id}`,{},{renamed:[`users`,`getGpgKeyForAuthenticatedUser`]}],getGpgKeyForAuthenticatedUser:[`GET /user/gpg_keys/{gpg_key_id}`],getPublicSshKeyForAuthenticated:[`GET /user/keys/{key_id}`,{},{renamed:[`users`,`getPublicSshKeyForAuthenticatedUser`]}],getPublicSshKeyForAuthenticatedUser:[`GET /user/keys/{key_id}`],getSshSigningKeyForAuthenticatedUser:[`GET /user/ssh_signing_keys/{ssh_signing_key_id}`],list:[`GET /users`],listAttestations:[`GET /users/{username}/attestations/{subject_digest}`],listAttestationsBulk:[`POST /users/{username}/attestations/bulk-list{?per_page,before,after}`],listBlockedByAuthenticated:[`GET /user/blocks`,{},{renamed:[`users`,`listBlockedByAuthenticatedUser`]}],listBlockedByAuthenticatedUser:[`GET /user/blocks`],listEmailsForAuthenticated:[`GET /user/emails`,{},{renamed:[`users`,`listEmailsForAuthenticatedUser`]}],listEmailsForAuthenticatedUser:[`GET /user/emails`],listFollowedByAuthenticated:[`GET /user/following`,{},{renamed:[`users`,`listFollowedByAuthenticatedUser`]}],listFollowedByAuthenticatedUser:[`GET /user/following`],listFollowersForAuthenticatedUser:[`GET /user/followers`],listFollowersForUser:[`GET /users/{username}/followers`],listFollowingForUser:[`GET /users/{username}/following`],listGpgKeysForAuthenticated:[`GET /user/gpg_keys`,{},{renamed:[`users`,`listGpgKeysForAuthenticatedUser`]}],listGpgKeysForAuthenticatedUser:[`GET /user/gpg_keys`],listGpgKeysForUser:[`GET /users/{username}/gpg_keys`],listPublicEmailsForAuthenticated:[`GET /user/public_emails`,{},{renamed:[`users`,`listPublicEmailsForAuthenticatedUser`]}],listPublicEmailsForAuthenticatedUser:[`GET /user/public_emails`],listPublicKeysForUser:[`GET /users/{username}/keys`],listPublicSshKeysForAuthenticated:[`GET /user/keys`,{},{renamed:[`users`,`listPublicSshKeysForAuthenticatedUser`]}],listPublicSshKeysForAuthenticatedUser:[`GET /user/keys`],listSocialAccountsForAuthenticatedUser:[`GET /user/social_accounts`],listSocialAccountsForUser:[`GET /users/{username}/social_accounts`],listSshSigningKeysForAuthenticatedUser:[`GET /user/ssh_signing_keys`],listSshSigningKeysForUser:[`GET /users/{username}/ssh_signing_keys`],setPrimaryEmailVisibilityForAuthenticated:[`PATCH /user/email/visibility`,{},{renamed:[`users`,`setPrimaryEmailVisibilityForAuthenticatedUser`]}],setPrimaryEmailVisibilityForAuthenticatedUser:[`PATCH /user/email/visibility`],unblock:[`DELETE /user/blocks/{username}`],unfollow:[`DELETE /user/following/{username}`],updateAuthenticated:[`PATCH /user`]}},lm=new Map;for(let[e,t]of Object.entries(cm))for(let[n,r]of Object.entries(t)){let[t,i,a]=r,[o,s]=t.split(/ /),c=Object.assign({method:o,url:s},i);lm.has(e)||lm.set(e,new Map),lm.get(e).set(n,{scope:e,methodName:n,endpointDefaults:c,decorations:a})}var um={has({scope:e},t){return lm.get(e).has(t)},getOwnPropertyDescriptor(e,t){return{value:this.get(e,t),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,t,n){return Object.defineProperty(e.cache,t,n),!0},deleteProperty(e,t){return delete e.cache[t],!0},ownKeys({scope:e}){return[...lm.get(e).keys()]},set(e,t,n){return e.cache[t]=n},get({octokit:e,scope:t,cache:n},r){if(n[r])return n[r];let i=lm.get(t).get(r);if(!i)return;let{endpointDefaults:a,decorations:o}=i;return n[r]=o?fm(e,t,r,a,o):e.request.defaults(a),n[r]}};function dm(e){let t={};for(let n of lm.keys())t[n]=new Proxy({octokit:e,scope:n,cache:{}},um);return t}function fm(e,t,n,r,i){let a=e.request.defaults(r);function o(...r){let o=a.endpoint.merge(...r);if(i.mapToData)return o=Object.assign({},o,{data:o[i.mapToData],[i.mapToData]:void 0}),a(o);if(i.renamed){let[r,a]=i.renamed;e.log.warn(`octokit.${t}.${n}() has been renamed to octokit.${r}.${a}()`)}if(i.deprecated&&e.log.warn(i.deprecated),i.renamedParameters){let o=a.endpoint.merge(...r);for(let[r,a]of Object.entries(i.renamedParameters))r in o&&(e.log.warn(`"${r}" parameter is deprecated for "octokit.${t}.${n}()". Use "${a}" instead`),a in o||(o[a]=o[r]),delete o[r]);return a(o)}return a(...r)}return Object.assign(o,a)}function pm(e){let t=dm(e);return{...t,rest:t}}pm.VERSION=sm;var mm=Qp.plugin(em,pm,om).defaults({userAgent:`octokit-rest.js/22.0.1`}),hm=new WeakMap;function gm(e){if(typeof e.permissions!=`object`||e.permissions===null||Array.isArray(e.permissions))throw new R(`GitHub App ${e.role} role did not return installation permissions.`);let t=e.permissions,n=e.role===`author`?{contents:`write`,issues:`write`,organization_projects:`write`,pull_requests:`write`}:{contents:`read`,pull_requests:`write`};for(let[r,i]of[...Object.entries(n),...Object.entries(e.additional??{})]){let n=t[r];if(n!==`admin`&&n!==`write`&&(i===`write`||n!==`read`))throw new R(`GitHub App ${e.role} role lacks required ${r}:${i} permission.`)}}async function _m(e){e.signal?.throwIfAborted();let t=e.env??process.env,n=e.config.roles[e.role];if(n.authSource===`personal`){if(e.role!==`author`||e.identity.trim().toLowerCase()!==n.identity.toLowerCase())throw new R(`Personal author operation requires the configured author identity.`);let r=t[n.credentialEnv.token]?.trim();if(!r)throw new R(`Missing personal author token in ${n.credentialEnv.token}.`);return vm(r,`env:${n.credentialEnv.token}`,e.signal)}if(e.personalAuth!==void 0){if(e.personalAuth.enabled!==!0||e.role!==`author`||e.identity.trim().toLowerCase()!==`personal`)throw new R(`Personal-token auth requires the explicit personal author identity.`);let n=e.personalAuth.token?.trim()||t.GH_TOKEN?.trim()||t.GITHUB_TOKEN?.trim();if(!n)throw new R(`Explicit personal-token auth requested but no token was supplied.`);return vm(n,e.personalAuth.token?.trim()?`explicit-personal-token`:t.GH_TOKEN?.trim()?`env:GH_TOKEN`:`env:GITHUB_TOKEN`,e.signal)}if(e.identity.trim().toLowerCase()!==n.identity.toLowerCase())throw new R(`GitHub ${e.role} operation requires the configured ${e.role} identity.`);let r=ch({config:e.config,env:t,role:e.role}),i=e.role===`author`?`reviewer`:`author`;if((e.role!==`reviewer`||e.selectedAuthor?.role!==`author`||e.selectedAuthor.authSource!==`personal`)&&e.config.roles[i].authSource!==`personal`){let n=ch({config:e.config,env:t,role:i});if(r.appId===n.appId||r.installationId===n.installationId||r.privateKeyPath===n.privateKeyPath)throw new R(`Author and reviewer must use distinct GitHub App credentials.`)}let a;try{a=l(r.privateKeyPath,`utf8`)}catch{throw new R(`GitHub App private key for ${e.role} role is unavailable.`)}try{let t=vp({appId:r.appId,privateKey:a,...e.signal===void 0?{}:{request:new mm({request:{signal:e.signal}}).request}}),n=await t({installationId:r.installationId,type:`installation`});if(typeof n.token!=`string`||!n.token.startsWith(`ghs_`))throw new R(`GitHub ${e.role} role did not receive an App installation token.`);gm({...e.additionalPermissions===void 0?{}:{additional:e.additionalPermissions},permissions:n.permissions,role:e.role});let i=e.role===`reviewer`?async n=>{let i=n??e.signal;try{let e=await new mm({auth:(await t({type:`app`})).token,...i===void 0?{}:{request:{signal:i}}}).rest.apps.getAuthenticated();if(!e.data||e.data.id!==Number(r.appId)||!e.data.slug)throw new R(`Reviewer GitHub App identity did not match its configured App ID.`);return`${e.data.slug}[bot]`}catch(e){throw e instanceof R?e:new R(`Reviewer GitHub App actor lookup failed.`)}}:void 0,o=e.role===`author`?async n=>{let i=n??e.signal;try{let e=await new mm({auth:(await t({type:`app`})).token,...i===void 0?{}:{request:{signal:i}}}).rest.apps.getAuthenticated();if(!e.data||e.data.id!==Number(r.appId)||!e.data.slug)throw new R(`Author GitHub App identity did not match its configured App ID.`);return{actorLogin:`${e.data.slug}[bot]`,credentialIdentity:`app:${String(e.data.id)}:installation:${r.installationId}`}}catch(e){throw e instanceof R?e:new R(`Author GitHub App actor lookup failed.`)}}:void 0;return ym(n.token,`app`,e.role,`app:${r.appId}:installation:${r.installationId}`,i,o,n.permissions.contents,e.signal)}catch(t){throw t instanceof R?t:new R(`GitHub App authentication failed for ${e.role} role.`)}}function vm(e,t,n){return ym(e,`personal`,`author`,t,void 0,async t=>{let r=t??n;try{let t=(await new mm({auth:e,...r===void 0?{}:{request:{signal:r}}}).rest.users.getAuthenticated()).data;if(!Number.isSafeInteger(t.id)||t.id<=0||!t.login)throw new R(`Personal author identity readback is incomplete.`);return{actorLogin:t.login,credentialIdentity:`user:${String(t.id)}`}}catch(e){throw e instanceof R?e:e.status===401?new R(`Configured personal author token is invalid or expired; refresh the selected token.`):new R(`Personal author identity readback failed.`)}},void 0,n)}function ym(e,t,n,r,i,a,o,s){let c={authSource:t,credentialSource:r,...o?{effectiveContentsPermission:o}:{},role:n,...i?{appActorLogin:i}:{},...a?{authenticatedAuthor:a}:{},graphql:Dp.defaults({headers:{authorization:`token ${e}`},...s===void 0?{}:{request:{signal:s}}}),rest:new mm({auth:e,...s===void 0?{}:{request:{signal:s}}})};return n===`author`&&hm.set(c,e),c}var bm=[`Todo`,`In Progress`,`Blocked`,`Done`];async function xm(e){let t=e.configuration??await Sm({...e,settings:Bm(e.settings)}),n=await Am({...e,configuration:t});if(n===null||n.archived||n.status===null&&n.statusOptionId===null)return null;let r=Lm(n,t);return{itemId:n.id,status:r}}async function Sm(e){let t=Bm(e.settings);return Tm(await Cm({graphql:e.graphql,org:e.org,number:t.number}),{requireWritable:e.requireWritable===!0,settings:t})}async function Cm(e){let t=[],n=null,r=!0,i=new Set,a=new Set,o=null;for(;r;){let s=Rm(await e.graphql(`
|
|
84
84
|
query ProjectDeliveryConfiguration($org: String!, $number: Int!, $cursor: String) {
|
|
85
85
|
organization(login: $org) {
|
|
86
86
|
projectV2(number: $number) {
|
|
@@ -126,13 +126,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
|
-
`,{cursor:n,number:e.number,org:e.org}),`GitHub returned invalid delivery Project configuration.`);if(`errors`in s)throw new
|
|
129
|
+
`,{cursor:n,number:e.number,org:e.org}),`GitHub returned invalid delivery Project configuration.`);if(`errors`in s)throw new R(`GitHub returned partial delivery Project evidence.`);let c=Rm(Rm(s.organization,`Organization ${e.org} is unavailable to the selected GitHub identity.`).projectV2,`Expected organization Project #${String(e.number)}.`),l=Rm(c.fields,`GitHub omitted delivery Project fields.`),u=o;if(u!==null&&[`id`,`number`,`title`,`closed`,`viewerCanUpdate`].some(e=>u[e]!==c[e]))throw new R(`Delivery Project identity changed while reading its field pages.`);if(!Array.isArray(l.nodes))throw new R(`GitHub returned invalid delivery Project field nodes.`);for(let e of l.nodes){let n=Rm(e,`GitHub returned an incomplete delivery Project field.`),r=zm(n.id,`GitHub omitted a delivery Project field ID.`);if(a.has(r))throw new R(`GitHub repeated a delivery Project field.`);if(a.add(r),zm(n.name,`GitHub omitted a delivery Project field name.`),zm(n.__typename,`GitHub omitted a delivery Project field type.`),n.__typename===`ProjectV2SingleSelectField`){if(typeof n.isIssueField!=`boolean`)throw new R(`GitHub omitted the Project field binding kind.`);if(Pm(n.options,`Project field`),n.isIssueField){let e=Rm(n.issueField,`GitHub omitted the bound organization field.`);if(zm(e.__typename,`GitHub omitted the bound organization field type.`),e.__typename===`IssueFieldSingleSelect`){if(zm(e.id,`GitHub omitted the bound organization field ID.`),zm(e.name,`GitHub omitted the bound organization field name.`),!/^[1-9]\d*$/u.test(String(e.fullDatabaseId)))throw new R(`GitHub omitted the bound organization field database ID.`);Pm(e.options,`organization field`)}}}t.push(e)}o={...c,fields:{nodes:t}};let d=Rm(l.pageInfo,`GitHub omitted delivery Project field pagination.`);if(typeof d.hasNextPage!=`boolean`)throw new R(`GitHub omitted delivery Project pagination state.`);r=d.hasNextPage===!0;let f=typeof d.endCursor==`string`?d.endCursor:null;Dm({cursor:n,hasNextPage:r,nextCursor:f,seenCursors:i,surface:`field`}),f!==null&&i.add(f),n=f}if(o===null)throw new R(`Expected organization Project #${String(e.number)}.`);return o}function wm(e){let t=e.native.project;return{number:t.number,points:e.native.points,priority:e.native.priority,statuses:{Blocked:t.statuses.blocked,Done:t.statuses.done,"In Progress":t.statuses.inProgress,Todo:t.statuses.todo},statusField:t.statusField,title:t.title}}function Tm(e,t){let n=Bm(t.settings),r=Rm(e,`GitHub returned invalid delivery Project configuration.`);if(r.number!==n.number||r.title!==n.title)throw new R(`Expected organization Project #${String(n.number)} titled ${n.title}.`);if(t.requireWritable===!0&&r.viewerCanUpdate!==!0)throw new R(`Organization Project #${String(n.number)} is not writable by this identity.`);let i=zm(r.id,`GitHub omitted the delivery Project node id.`),a=Rm(r.fields,`GitHub omitted delivery Project fields.`);if(!Array.isArray(a.nodes))throw new R(`GitHub returned invalid delivery Project field nodes.`);let o=Im(a.nodes,n.statusField),s=Fm({expectedDatabaseId:n.points.databaseId,expectedOptions:n.points.values,fields:a.nodes,name:n.points.name}),c=Fm({expectedDatabaseId:n.priority.databaseId,expectedOptions:n.priority.values,fields:a.nodes,name:n.priority.name});if(o.__typename!==`ProjectV2SingleSelectField`||o.isIssueField!==!1)throw new R(`Project Status must be the sole Project-owned single-select workflow field.`);let l=Pm(o.options,`Project ${n.statusField}`);Om({expected:bm.map(e=>n.statuses[e]),fieldName:`Project ${n.statusField}`,options:l});let u=Object.fromEntries(bm.map(e=>[e,l.find(t=>t.name===n.statuses[e])?.id]));return{pointsFieldId:zm(s.id,`GitHub omitted the Project Points field id.`),priorityFieldId:zm(c.id,`GitHub omitted the Project Priority field id.`),projectId:i,projectNumber:n.number,settings:n,statusFieldId:zm(o.id,`GitHub omitted the Project Status field id.`),statusOptionIds:u,title:n.title,writable:r.viewerCanUpdate===!0}}async function Em(e){let t=e.configuration??await Sm({...e,settings:Bm(e.settings),requireWritable:!0});km(t);let n=await Am({...e,configuration:t});if(n?.archived===!0)throw new R(`The issue delivery Project item is archived and cannot be updated.`);if(n!==null&&n.status!==null&&n.statusOptionId!==null&&Lm(n,t)===e.status)return{itemId:n.id,status:e.status};if(n===null){let r=Rm(Rm(Rm(await e.graphql(`
|
|
130
130
|
mutation AddProjectDeliveryItem($projectId: ID!, $contentId: ID!) {
|
|
131
131
|
addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) {
|
|
132
132
|
item { id }
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
|
-
`,{contentId:e.issueNodeId,projectId:t.projectId}),`GitHub returned invalid Project item creation evidence.`).addProjectV2ItemById,`GitHub omitted Project item creation payload.`).item,`GitHub omitted the created Project item.`);n={archived:!1,contentId:e.issueNodeId,id:
|
|
135
|
+
`,{contentId:e.issueNodeId,projectId:t.projectId}),`GitHub returned invalid Project item creation evidence.`).addProjectV2ItemById,`GitHub omitted Project item creation payload.`).item,`GitHub omitted the created Project item.`);n={archived:!1,contentId:e.issueNodeId,id:zm(r.id,`GitHub omitted the created Project item id.`),status:null,statusOptionId:null}}let r=t.statusOptionIds[e.status];if(Rm(Rm(Rm(await e.graphql(`
|
|
136
136
|
mutation UpdateProjectDeliveryStatus($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
|
|
137
137
|
updateProjectV2ItemFieldValue(
|
|
138
138
|
input: {
|
|
@@ -145,7 +145,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
145
145
|
projectV2Item { id }
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
-
`,{fieldId:t.statusFieldId,itemId:n.id,optionId:r,projectId:t.projectId}),`GitHub returned invalid Project Status mutation evidence.`).updateProjectV2ItemFieldValue,`GitHub omitted Project Status mutation payload.`).projectV2Item,`GitHub omitted the updated Project item.`).id!==n.id)throw new
|
|
148
|
+
`,{fieldId:t.statusFieldId,itemId:n.id,optionId:r,projectId:t.projectId}),`GitHub returned invalid Project Status mutation evidence.`).updateProjectV2ItemFieldValue,`GitHub omitted Project Status mutation payload.`).projectV2Item,`GitHub omitted the updated Project item.`).id!==n.id)throw new R(`Project Status mutation returned a different item identity.`);return await Nm({configuration:t,graphql:e.graphql,issueNodeId:e.issueNodeId,itemId:n.id,status:e.status})}function Dm(e){if(e.hasNextPage&&e.nextCursor===null)throw new R(`Delivery Project ${e.surface} pagination omitted its next cursor.`);if(e.hasNextPage&&e.nextCursor!==null&&(e.nextCursor===e.cursor||e.seenCursors.has(e.nextCursor)))throw new R(`Delivery Project ${e.surface} pagination repeated a non-advancing cursor.`)}function Om(e){let t=e.options.map(e=>e.name),n=new Set(t),r=new Set(e.expected);if(n.size!==t.length||n.size!==r.size||t.some(e=>!r.has(e)))throw new R(`${e.fieldName} options must be exactly ${e.expected.join(`, `)} (order is provider-owned).`)}function km(e){if(!e.writable)throw new R(`Organization Project #${String(e.projectNumber)} is not writable by this identity.`)}async function Am(e){let t=[],n=null,r=!0,i=new Set;for(;r;){let a=Rm(Rm(Rm(Rm(await e.graphql(`
|
|
149
149
|
query ProjectDeliveryItems($org: String!, $number: Int!, $cursor: String, $statusField: String!) {
|
|
150
150
|
organization(login: $org) {
|
|
151
151
|
projectV2(number: $number) {
|
|
@@ -163,7 +163,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
163
163
|
}
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
|
-
`,{cursor:n,number:e.configuration.projectNumber,org:e.org,statusField:e.configuration.settings.statusField}),`GitHub returned invalid delivery Project item evidence.`).organization,`GitHub omitted the delivery Project organization.`).projectV2,`GitHub omitted the delivery Project.`).items,`GitHub omitted delivery Project items.`);if(!Array.isArray(a.nodes))throw new
|
|
166
|
+
`,{cursor:n,number:e.configuration.projectNumber,org:e.org,statusField:e.configuration.settings.statusField}),`GitHub returned invalid delivery Project item evidence.`).organization,`GitHub omitted the delivery Project organization.`).projectV2,`GitHub omitted the delivery Project.`).items,`GitHub omitted delivery Project items.`);if(!Array.isArray(a.nodes))throw new R(`GitHub returned invalid delivery Project items.`);for(let n of a.nodes){let r=Mm(n,e.configuration);r!==null&&r.contentId===e.issueNodeId&&t.push(r)}let o=Rm(a.pageInfo,`GitHub omitted delivery Project item pagination.`);r=o.hasNextPage===!0;let s=typeof o.endCursor==`string`?o.endCursor:null;Dm({cursor:n,hasNextPage:r,nextCursor:s,seenCursors:i,surface:`item`}),s!==null&&i.add(s),n=s}if(t.length>1)throw new R(`Issue has ${String(t.length)} duplicate Project items in ${e.configuration.title}.`);return t[0]??null}function jm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mm(e,t){let n=Rm(e,`GitHub returned an invalid delivery Project item.`),r=n.content;if(r==null)return null;let i=zm(Rm(r,`GitHub returned an invalid delivery Project item content node.`).id,`GitHub omitted a delivery Project item content id.`),a=n.fieldValueByName,o=null,s=null;if(a!=null){let e=Rm(a,`GitHub returned invalid Project Status readback.`),n=zm(e.name,`GitHub omitted Project Status name.`),r=zm(e.optionId,`GitHub omitted Project Status option id.`),i=t.settings.statuses,c=bm.find(e=>i[e]===n);if(c===void 0||t.statusOptionIds[c]!==r)throw new R(`GitHub returned unsupported Project Status ${n}.`);o=c,s=r}return{archived:n.isArchived===!0,contentId:i,id:zm(n.id,`GitHub omitted the delivery Project item id.`),status:o,statusOptionId:s}}async function Nm(e){let t=Rm(Rm(await e.graphql(`
|
|
167
167
|
query ProjectDeliveryItemReadback($itemId: ID!, $statusField: String!) {
|
|
168
168
|
node(id: $itemId) {
|
|
169
169
|
... on ProjectV2Item {
|
|
@@ -177,22 +177,22 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
177
177
|
}
|
|
178
178
|
}
|
|
179
179
|
}
|
|
180
|
-
`,{itemId:e.itemId,statusField:e.configuration.settings.statusField}),`GitHub returned invalid Project item readback.`).node,`GitHub omitted Project item readback.`),n=
|
|
180
|
+
`,{itemId:e.itemId,statusField:e.configuration.settings.statusField}),`GitHub returned invalid Project item readback.`).node,`GitHub omitted Project item readback.`),n=Rm(t.project,`GitHub omitted Project identity readback.`),r=Rm(t.content,`GitHub omitted Project item content readback.`),i=Rm(t.fieldValueByName,`GitHub omitted Project Status readback.`),a=zm(i.name,`GitHub omitted Project Status name readback.`),o=zm(i.optionId,`GitHub omitted Project Status option readback.`);if(t.id!==e.itemId||t.isArchived===!0||n.id!==e.configuration.projectId||n.number!==e.configuration.projectNumber||r.id!==e.issueNodeId||a!==e.configuration.settings.statuses[e.status]||o!==e.configuration.statusOptionIds[e.status])throw new R(`Project Status readback did not report ${e.status} for the exact issue item.`);return{itemId:e.itemId,status:e.status}}function Pm(e,t){if(!Array.isArray(e))throw new R(`${t} options are malformed.`);return e.map(e=>{let n=Rm(e,`${t} option is malformed.`);return{id:zm(n.id,`${t} option id is missing.`),name:zm(n.name,`${t} option name is missing.`)}})}function Fm(e){let t=Im(e.fields,e.name);if(t.__typename!==`ProjectV2SingleSelectField`||t.isIssueField!==!0)throw new R(`Project ${e.name} must bind the organization issue field.`);if(Array.isArray(t.options)&&t.options.length!==0)throw new R(`Project ${e.name} must not define Project-owned duplicate options.`);let n=Rm(t.issueField,`Project ${e.name} omitted its bound organization issue field.`),r=typeof n.fullDatabaseId==`string`?n.fullDatabaseId:String(n.fullDatabaseId);if(n.__typename!==`IssueFieldSingleSelect`||n.name!==e.name||r!==e.expectedDatabaseId)throw new R(`Project ${e.name} must bind organization issue field ${e.expectedDatabaseId}.`);return Om({expected:e.expectedOptions,fieldName:e.name,options:Pm(n.options,`organization ${e.name}`)}),t}function Im(e,t){let n=e.filter(e=>jm(e)&&e.name===t);if(n.length!==1)throw new R(`Expected exactly one Project ${t} field, found ${String(n.length)}.`);return n[0]}function Lm(e,t){if(e.status===null||e.statusOptionId===null||t.statusOptionIds[e.status]!==e.statusOptionId)throw new R(`The issue delivery Project item has no canonical Project Status.`);return e.status}function Rm(e,t){if(!jm(e))throw new R(t);return e}function zm(e,t){if(typeof e!=`string`||e.length===0)throw new R(t);return e}function Bm(e){if(e===void 0)throw new R(`Project delivery settings are required.`);return e}function Vm(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new R(`Incomplete GitHub ${t} discovery.`);return e}function Hm(e,t){if(typeof e!=`string`||!e.trim())throw new R(`Invalid GitHub ${t}.`);return e}function Um(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw new R(`Invalid GitHub ${t}.`);return e}function Wm(e){let t=Vm(e,`repository`);if(`errors`in t)throw new R(`Partial GitHub discovery cannot select a delivery destination.`);return Vm(t.repository,`repository`)}async function Gm(e){let t=[],n=new Set,r=new Set,i=null;for(;;){let a=Vm(Wm(await e.clients.graphql(`query DeliveryDiscovery($owner: String!, $repo: String!, $cursor: String) {
|
|
181
181
|
repository(owner: $owner, name: $repo) {
|
|
182
182
|
${e.field}(first: 100, after: $cursor) { nodes { ${e.selection} } pageInfo { hasNextPage endCursor } }
|
|
183
183
|
}
|
|
184
|
-
}`,{owner:e.owner,repo:e.repo,cursor:i}))[e.field],e.field);if(!Array.isArray(a.nodes))throw new
|
|
184
|
+
}`,{owner:e.owner,repo:e.repo,cursor:i}))[e.field],e.field);if(!Array.isArray(a.nodes))throw new R(`Incomplete GitHub ${e.field} nodes.`);for(let r of a.nodes){let i=Vm(r,e.field),a=Hm(i.id,`${e.field} node ID`);if(n.has(a))throw new R(`Repeated ${e.field} node during discovery.`);n.add(a),t.push(i)}let o=Vm(a.pageInfo,`${e.field} pagination`);if(typeof o.hasNextPage!=`boolean`)throw new R(`Incomplete GitHub discovery pagination.`);if(!o.hasNextPage)return t;let s=Hm(o.endCursor,`discovery cursor`);if(s===i||r.has(s))throw new R(`GitHub discovery cursor did not advance.`);r.add(s),i=s}}function Km(e,t){let n=e.filter(e=>e.name===t);if(n.length!==1)throw new R(`Select an unambiguous native single-select field for ${t}.`);let r=n[0];if(!r||r.__typename!==`IssueFieldSingleSelect`||!Array.isArray(r.options))throw new R(`Native ${t} must be an organization single-select issue field.`);let i=String(r.fullDatabaseId);if(!/^[1-9]\d*$/u.test(i)||!Number.isSafeInteger(Number(i)))throw new R(`Invalid native ${t} field ID.`);let a=r.options.map(e=>Hm(Vm(e,`${t} option`).name,`${t} option name`)).sort();if(!a.length||new Set(a).size!==a.length)throw new R(`Ambiguous native ${t} options.`);return{databaseId:i,name:t,values:a}}async function qm(e){let[t,n]=e.repository.split(`/`);if(!t||!n)throw new R(`Invalid delivery repository.`);let r=Wm(await e.clients.graphql(`query DeliveryRepository($owner: String!, $repo: String!) {
|
|
185
185
|
repository(owner: $owner, name: $repo) { id nameWithOwner isFork owner { __typename login } }
|
|
186
|
-
}`,{owner:t,repo:n})),i=
|
|
186
|
+
}`,{owner:t,repo:n})),i=Hm(r.nameWithOwner,`repository name`);if(i.toLowerCase()!==e.repository.toLowerCase())throw new R(`GitHub repository does not match the selected Git remote.`);if(typeof r.isFork!=`boolean`)throw new R(`GitHub omitted repository fork identity.`);if(r.isFork&&e.overrides.remote===void 0&&e.repositorySelected!==!0)throw new R(`A fork requires an explicit remote selection before delivery.`);let a=Vm(r.owner,`repository owner`);if(a.__typename!==`Organization`||Hm(a.login,`organization`).toLowerCase()!==t.toLowerCase())throw new R(`Native delivery requires a repository owned by its selected GitHub organization.`);let o=await Gm({...e,owner:t,repo:n,field:`issueFields`,selection:`__typename
|
|
187
187
|
... on IssueFieldSingleSelect { id fullDatabaseId name options { id name } }
|
|
188
188
|
... on IssueFieldDate { id }
|
|
189
189
|
... on IssueFieldNumber { id }
|
|
190
190
|
... on IssueFieldText { id }
|
|
191
|
-
`}),s=qm(o,e.overrides.pointsField??`Points`),c=qm(o,e.overrides.priorityField??`Priority`),l=(await Km({...e,owner:t,repo:n,field:`issueTypes`,selection:`id name isEnabled`})).filter(e=>{if(typeof e.isEnabled!=`boolean`)throw new L(`GitHub omitted issue type availability.`);return e.isEnabled}).map(e=>Um(e.name,`issue type`)).sort();if(!l.length||new Set(l).size!==l.length)throw new L(`No unambiguous enabled native issue types were discovered.`);let u=e.overrides.issueTypes?.slice().sort()??l;if(u.some(e=>!l.includes(e)))throw new L(`Configured issue type is unavailable in the selected repository.`);let d=e.overrides.project===void 0?`linked`:`explicit`,f=e.overrides.project===void 0?await Km({...e,owner:t,repo:n,field:`projectsV2`,selection:`id number title closed viewerCanUpdate owner { __typename ... on Organization { login } ... on User { login } }`}):[{number:e.overrides.project}],p=[];for(let n of f){if(d===`linked`){if(typeof n.closed!=`boolean`||typeof n.viewerCanUpdate!=`boolean`)throw new L(`Incomplete linked Project metadata.`);let e=Hm(n.owner,`Project owner`);if(e.__typename!==`Organization`||Um(e.login,`Project owner`).toLowerCase()!==t.toLowerCase())throw new L(`Linked Project owner does not match the selected repository organization.`);if(n.closed)continue}let r=Wm(n.number,`Project number`),i=await wm({graphql:e.clients.graphql,org:t,number:r});if(typeof i.viewerCanUpdate!=`boolean`||i.number!==r)throw new L(`Incomplete or drifting Project identity.`);if(typeof i.closed!=`boolean`)throw new L(`GitHub omitted Project closed state.`);if(i.closed){if(d===`explicit`)throw new L(`The explicitly selected Project is closed.`);continue}if(d===`linked`&&(i.id!==n.id||i.title!==n.title))throw new L(`Linked Project changed during discovery.`);let a={number:r,title:Um(i.title,`Project title`),points:s,priority:c,statusField:e.overrides.statusField??`Status`,statuses:{Todo:e.overrides.statuses?.todo??`Todo`,"In Progress":e.overrides.statuses?.inProgress??`In Progress`,Blocked:e.overrides.statuses?.blocked??`Blocked`,Done:e.overrides.statuses?.done??`Done`}},o;try{o=Em(i,{settings:a,requireWritable:!1})}catch(e){if(d===`explicit`||!(e instanceof L))throw e;continue}if(!o.writable)throw new L(`A compatible delivery Project is not writable; refusing destination fallback.`);p.push(o)}if(p.length!==1)throw new L(`Discovered ${p.length} compatible linked Projects. Select project explicitly in ai-delivery.config.json; no issue was created.`);let m=p[0];if(!m)throw new L(`Delivery Project selection is incomplete.`);return{repository:i,repositoryId:Um(r.id,`repository ID`),projectId:m.projectId,projectSource:d,statusFieldId:m.statusFieldId,statusOptionIds:m.statusOptionIds,pointsFieldId:m.pointsFieldId,priorityFieldId:m.priorityFieldId,native:{organization:Um(a.login,`organization`),issueTypes:u,points:s,priority:c,milestones:`repository`,relationships:{blockedBy:`native`,parent:`native`},project:{number:m.projectNumber,title:m.title,statusField:m.settings.statusField,statuses:{todo:m.settings.statuses.Todo,inProgress:m.settings.statuses[`In Progress`],blocked:m.settings.statuses.Blocked,done:m.settings.statuses.Done}}}}}var Ym=`RepositoryDeliveryPolicy@1`,Xm=A().trim().min(1),Zm=A().regex(/^[A-Z][A-Z0-9_]*$/u),Qm=j().int().positive(),$m=A().regex(/^[1-9]\d*$/u).refine(e=>Number.isSafeInteger(Number(e))),eh=M(Xm).min(1).superRefine((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:`custom`,message:`Values must be unique.`})}),th=N({databaseId:$m,name:Xm,values:eh}).strict(),nh=N({authSource:I(`app`).optional(),credentialEnv:N({appId:Zm,installationId:Zm,privateKeyPath:Zm}).strict(),identity:Xm}).strict(),rh=Ml([nh,N({authSource:I(`personal`),credentialEnv:N({token:Zm}).strict(),identity:Xm}).strict()]);N({commandPolicy:N({checks:N({format:F([`REQUIRED`,`OPTIONAL`,`SKIP`]),gitClean:F([`REQUIRED`,`OPTIONAL`,`SKIP`]),lint:F([`REQUIRED`,`OPTIONAL`,`SKIP`]),test:F([`REQUIRED`,`OPTIONAL`,`SKIP`]),typecheck:F([`REQUIRED`,`OPTIONAL`,`SKIP`])}).strict(),timeoutsMs:N({lint:Qm,test:Qm,typecheck:Qm}).strict()}).strict(),native:N({issueTypes:eh,milestones:I(`repository`),organization:Xm,points:th,priority:th,project:N({number:Qm,statuses:N({blocked:Xm,done:Xm,inProgress:Xm,todo:Xm}).strict(),statusField:Xm,title:Xm}).strict(),relationships:N({blockedBy:I(`native`),parent:I(`native`)}).strict()}).strict(),policy:N({contract:F([Ym,`RepositoryDeliveryPolicy@2`]),module:A().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u)}).strict(),repository:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u),roles:N({author:rh,reviewer:nh}).strict(),schemaVersion:I(`ai-delivery.config@2`)}).strict().superRefine((e,t)=>{e.repository.split(`/`)[0]?.toLowerCase()!==e.native.organization.toLowerCase()&&t.addIssue({code:`custom`,message:`Organization must match repository owner.`,path:[`native`,`organization`]}),e.roles.author.identity.toLowerCase()===e.roles.reviewer.identity.toLowerCase()&&t.addIssue({code:`custom`,message:`Author and reviewer identities must be distinct.`,path:[`roles`]}),[e.roles.author,e.roles.reviewer].some(e=>e.authSource!==`personal`&&/^personal(?:$|[-_])/iu.test(e.identity))&&t.addIssue({code:`custom`,message:`App role identities cannot be personal identities.`,path:[`roles`]});let n=Object.values(e.roles.author.credentialEnv),r=Object.values(e.roles.reviewer.credentialEnv);new Set([...n,...r]).size!==n.length+r.length&&t.addIssue({code:`custom`,message:`Author and reviewer credential environment names must be distinct.`,path:[`roles`]}),new Set(Object.values(e.native.project.statuses)).size!==4&&t.addIssue({code:`custom`,message:`Project statuses must be distinct.`,path:[`native`,`project`,`statuses`]}),e.native.points.values.some(e=>!/^[1-9]\d*$/u.test(e)||!Number.isSafeInteger(Number(e)))&&t.addIssue({code:`custom`,message:`Point values must be positive safe integers.`,path:[`native`,`points`,`values`]}),e.native.points.name===e.native.priority.name&&t.addIssue({code:`custom`,message:`Points and priority fields must be distinct.`,path:[`native`]}),e.native.points.databaseId===e.native.priority.databaseId&&t.addIssue({code:`custom`,message:`Points and priority field IDs must be distinct.`,path:[`native`]})});var ih=A().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u),ah=N({schemaVersion:I(`ai-delivery.config@2`).optional(),repository:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),remote:Xm.optional(),policy:N({module:ih}).strict().optional(),project:Qm.optional(),pointsField:Xm.optional(),priorityField:Xm.optional(),statusField:Xm.optional(),statuses:N({blocked:Xm,done:Xm,inProgress:Xm,todo:Xm}).strict().optional(),issueTypes:eh.optional()}).strict(),oh=P({schemaVersion:I(`ai-delivery.user@1`),roles:P({author:Pl(`authSource`,[nh,rh.options[1]]),reviewer:nh}),project:Qm,checkoutRoots:M(A().min(1).refine(ee,`Checkout roots must be absolute.`)),pointsField:Xm.optional(),priorityField:Xm.optional(),statusField:Xm.optional(),statuses:ah.shape.statuses,issueTypes:eh.optional()}).superRefine((e,t)=>{let n=e.roles;n.author.identity.toLowerCase()===n.reviewer.identity.toLowerCase()&&t.addIssue({code:`custom`,path:[`roles`],message:`Author and reviewer identities must be distinct.`}),[n.author,n.reviewer].some(e=>e.authSource!==`personal`&&/^personal(?:$|[-_])/iu.test(e.identity))&&t.addIssue({code:`custom`,path:[`roles`],message:`App role identities cannot be personal identities.`}),e.statuses&&new Set(Object.values(e.statuses)).size!==4&&t.addIssue({code:`custom`,path:[`statuses`],message:`Project statuses must be distinct.`});let r=[...Object.values(n.author.credentialEnv),...Object.values(n.reviewer.credentialEnv)];new Set(r).size!==r.length&&t.addIssue({code:`custom`,path:[`roles`],message:`Credential environment names must be distinct.`})});async function sh(e){let t=process.env.AI_DELIVERY_CONFIG??T(oe(),`.config`,`aviaratech-ai`,`ai-delivery.json`);if(!ee(t))throw new L(`AI_DELIVERY_CONFIG must be an absolute user configuration path.`);let n;try{n=l(t)}catch{throw new L(`Missing user configuration ${t}; configure roles.author, roles.reviewer, project and checkoutRoots.`)}let r;try{r=JSON.parse(n.toString(`utf8`))}catch{throw new L(`Invalid user configuration JSON at ${t}.`)}let i=oh.safeParse(r);if(!i.success)throw new L(`Invalid user configuration ${t}: ${i.error.issues.map(e=>`${e.path.join(`.`)||`configuration`}: ${e.message}`).join(`; `)}`);let{roles:a,checkoutRoots:o,schemaVersion:s,...c}=i.data;return{roles:a,checkoutRoots:o,configPath:t,overrides:c,sourceDigest:B(i.data)}}async function ch(e,t={}){t.signal?.throwIfAborted();let n=await sh(),r=t.repository??(()=>{let t=Cu(e,`origin`);return`${t.owner}/${t.repo}`})();if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(r))throw new L(`Repository must be owner/name.`);let i=t.clients??await vm({config:n,identity:t.personalAuth===!0&&n.roles.author.authSource!==`personal`?`personal`:n.roles.author.identity,role:`author`,...t.personalAuth===!0?{personalAuth:{enabled:!0}}:{},...t.signal===void 0?{}:{signal:t.signal}}),a;try{a=await Jm({clients:i,repository:r,overrides:n.overrides,repositorySelected:t.repository!==void 0})}catch(e){throw t.clients===void 0&&n.roles.author.authSource===`personal`&&e.status===401?new L(`Configured personal author token is invalid or expired; refresh the selected token.`):e}let o={schemaVersion:`ai-delivery.github@1`,repository:a.repository,roles:n.roles,native:a.native};return{config:o,configDigest:B({sourceDigest:n.sourceDigest,routing:a,roles:o.roles}),configPath:n.configPath,routing:a}}function lh(e){let{config:t,role:n}=e;if(t.roles[n].authSource===`personal`)throw new L(`Personal author credentials use the configured token environment variable.`);let r=e.env??process.env,i=t.roles[n].credentialEnv,a={appId:r[i.appId]?.trim(),installationId:r[i.installationId]?.trim(),privateKeyPath:r[i.privateKeyPath]?.trim()};if(!a.appId||!a.installationId||!a.privateKeyPath)throw new L(`Missing GitHub App credentials for ${n} role. Set ${i.appId}, ${i.installationId} and ${i.privateKeyPath}.`);if(!ee(a.privateKeyPath))throw new L(`GitHub App private-key path for ${n} role (${i.privateKeyPath}) must be absolute.`);let o=Number(a.installationId);if(!Number.isSafeInteger(o)||o<=0)throw new L(`Invalid GitHub App installation ID for ${n} role (${i.installationId}).`);let s=Number(a.appId);if(!Number.isSafeInteger(s)||s<=0)throw new L(`Invalid GitHub App ID for ${n} role (${i.appId}).`);return{appId:a.appId,installationId:o,privateKeyPath:a.privateKeyPath}}var uh=new Set([`runtime:stage`,`runtime:admit`,`cleanup`,`close`,`comment`,`create`,`develop`,`finish`,`start`,`update`,`pr:create`,`pr:merge`,`worktree`,`worktree:create`,`worktree:transition:apply`,`worktrees:cleanup`,`pr:checkout`]),dh=new Set([`pr:review`]);function fh(e){let t=e.commandName.trim().toLowerCase(),n=dh.has(t)?`reviewer`:uh.has(t)?`author`:null;if(n===null)return{error:null,normalizedCommandName:t,requiredRole:n,requiresExplicitIdentity:!1};let r=e.identity?.trim().toLowerCase()??``,i=null;return r?r===e.deliveryConfig.roles[n].identity.toLowerCase()?e.personalAuth===!0&&e.deliveryConfig.roles[n].authSource!==`personal`&&(i=`Personal-token override requires the explicit personal identity.`):r===`personal`?(n!==`author`||e.personalAuth!==!0)&&(i=`Command "${t}" requires its configured identity; personal-token override requires explicit author opt-in.`):i=e.personalAuth===!0?`Personal-token opt-in requires the explicit personal identity.`:`Command "${t}" requires configured ${n} identity "${e.deliveryConfig.roles[n].identity}".`:i=`Command "${t}" requires an explicit ${n} identity.`,{error:i,normalizedCommandName:t,requiredRole:n,requiresExplicitIdentity:!0}}var ph=N({digest:R,path:A().min(1),producer:A().min(1)}).strict(),mh=N({attestationKey:A().min(1).optional(),commands:M(N({argv:M(A().min(1)).min(1),label:A().min(1)}).strict()),dependsOn:M(Fu),id:Fu,resourceClass:F([`source_only`,`focused_node`,`canonical_verify`,`model`,`postgres_docker`]),semanticInputKeys:M(A().min(1)).min(1),semanticInputs:M(N({digest:R,key:A().min(1)}).strict()).min(1).optional()}).strict(),hh=N({artifacts:M(ph).min(1),base:Iu,configDigest:R,evidenceId:R,head:Iu,opaquePayload:A().min(1),policyDigest:R,producer:A().min(1),repository:Pu,schemaVersion:I(`ai-delivery.policy-evidence@1`)}).strict().superRefine((e,t)=>{let{evidenceId:n,...r}=e;(n!==B(r)||!Lu(e.artifacts.map(e=>e.path)))&&t.addIssue({code:`custom`,message:`Policy evidence identity or artifacts are invalid.`})}),gh=N({policyDigest:R,policyEvidence:hh,requiredStages:M(mh).min(1),risk:F([`standard`,`high`])}).strict().superRefine((e,t)=>{let n=new Set;for(let r of e.requiredStages)(n.has(r.id)||r.dependsOn.some(e=>!n.has(e))||new Set(r.dependsOn).size!==r.dependsOn.length||!Lu(r.semanticInputKeys)||r.semanticInputs!==void 0&&(!Lu(r.semanticInputs.map(e=>e.key))||z(r.semanticInputs.map(e=>e.key))!==z(r.semanticInputKeys))||r.commands.length===0!=(r.attestationKey!==void 0))&&t.addIssue({code:`custom`,message:`Policy stages must be unique, ordered and proof complete.`}),n.add(r.id)});N({additionalConstraints:N({exactBaseHeadLease:xl(),requiredAttestationIds:M(R)}).strict(),boundaryId:R,classificationReceiptId:R,configDigest:R,currentBase:Iu,currentHead:Iu,phase:F([`verify`,`publish`,`merge`]),policyEvidenceId:R,schemaVersion:I(`ai-delivery.policy-boundary@1`),stageReceiptSetHash:R}).strict().superRefine((e,t)=>{let{boundaryId:n,...r}=e;(n!==B(r)||!Lu(e.additionalConstraints.requiredAttestationIds))&&t.addIssue({code:`custom`,message:`Policy boundary identity or attestation inventory is invalid.`})});var _h=N({base:Iu,changedPaths:M(A().min(1)),configDigest:R,head:Iu,policyDigest:R,policyEvidence:hh,receiptId:R,repository:Pu,requiredStages:M(mh).min(1),risk:F([`standard`,`high`]),schemaVersion:F([`ai-delivery.classification@1`,`ai-delivery.classification@2`])}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==B(r)||!Lu(e.changedPaths)||e.base.sha!==e.head.sha&&e.changedPaths.length===0||e.policyEvidence.repository!==e.repository||z(e.policyEvidence.base)!==z(e.base)||z(e.policyEvidence.head)!==z(e.head)||e.policyEvidence.configDigest!==e.configDigest||e.policyEvidence.policyDigest!==e.policyDigest||e.requiredStages.some(t=>t.semanticInputs!==void 0!=(e.schemaVersion===`ai-delivery.classification@2`))||!gh.safeParse({policyDigest:e.policyDigest,policyEvidence:e.policyEvidence,requiredStages:e.requiredStages,risk:e.risk}).success)&&t.addIssue({code:`custom`,message:`Repository classification is unbound or invalid.`})}),vh=N({digest:R,key:A().min(1)}).strict(),yh=N({receiptId:R,stageId:Fu}).strict(),bh=(e,t)=>e<t?-1:+(e>t),xh={definitionHash:R,environmentDigest:R,inputId:R,policyDigest:R,semanticInputs:M(vh).min(1),stageId:Fu,upstream:M(yh)},Sh=Ml([P({...xh,classificationReceiptId:R,schemaVersion:I(`ai-delivery.stage-input@1`)}),P({...xh,configDigest:R,policyProducer:A().min(1),policyArtifacts:M(P({digest:R,path:A().min(1)})),schemaVersion:I(`ai-delivery.stage-input@2`)})]).superRefine((e,t)=>{let{inputId:n,...r}=e;(n!==B(r)||!Lu(e.semanticInputs.map(e=>e.key))||!Lu(e.upstream.map(e=>e.stageId))||e.schemaVersion===`ai-delivery.stage-input@2`&&!Lu(e.policyArtifacts.map(e=>e.path)))&&t.addIssue({code:`custom`,message:`Stage input identity or inventory is invalid.`})}),Ch=N({artifacts:M(N({digest:R,path:A().min(1)}).strict()),commands:M(N({exitCode:j().int().nonnegative(),label:A().min(1),outputDigest:R}).strict()),completedAt:hu(),input:Sh,receiptId:R,result:I(`passed`),schemaVersion:F([`ai-delivery.stage-receipt@1`,`ai-delivery.stage-receipt@2`]),startedAt:hu()}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==B(r)||e.schemaVersion===`ai-delivery.stage-receipt@2`!=(e.input.schemaVersion===`ai-delivery.stage-input@2`)||Date.parse(e.completedAt)<Date.parse(e.startedAt)||e.commands.some(e=>e.exitCode!==0)||!Lu(e.artifacts.map(e=>e.path)))&&t.addIssue({code:`custom`,message:`Stage receipt has incomplete or corrupt proof.`})}),wh=N({aggregateId:R,classificationReceiptId:R,policyDigest:R,result:I(`passed`),schemaVersion:F([`ai-delivery.stage-aggregate@1`,`ai-delivery.stage-aggregate@2`]),stages:M(N({inputId:R,receiptId:R,stageId:Fu}).strict()).min(1)}).strict().superRefine((e,t)=>{let{aggregateId:n,...r}=e;(n!==B(r)||new Set(e.stages.map(e=>e.stageId)).size!==e.stages.length)&&t.addIssue({code:`custom`,message:`Stage aggregate identity or inventory is invalid.`})});function Th(e){let t=_h.parse(e.classification),n=t.requiredStages.find(t=>t.id===e.stageId);if(n===void 0)throw Error(`Stage is absent from selected policy.`);let r=[...e.semanticInputs].sort((e,t)=>bh(e.key,t.key)).map(e=>vh.parse(e)),i=[...e.upstream].sort((e,t)=>bh(e.stageId,t.stageId)).map(e=>yh.parse(e));if(z(r.map(e=>e.key))!==z(n.semanticInputKeys)||t.schemaVersion===`ai-delivery.classification@2`&&z(r)!==z(n.semanticInputs)||z(i.map(e=>e.stageId))!==z([...n.dependsOn].sort()))throw Error(`Stage input lacks required semantic or upstream proof.`);let a={...t.schemaVersion===`ai-delivery.classification@1`?{classificationReceiptId:t.receiptId,schemaVersion:`ai-delivery.stage-input@1`}:{configDigest:t.configDigest,policyProducer:t.policyEvidence.producer,schemaVersion:`ai-delivery.stage-input@2`,policyArtifacts:t.policyEvidence.artifacts.filter(e=>e.path===n.attestationKey).map(({digest:e,path:t})=>({digest:e,path:t}))},definitionHash:B(n),environmentDigest:R.parse(e.environmentDigest),policyDigest:t.policyDigest,semanticInputs:r,stageId:n.id,upstream:i};return Sh.parse({...a,inputId:B(a)})}function Eh(e){let t=_h.parse(e.classification),n=Sh.parse(e.stageInput),r=t.requiredStages.find(e=>e.id===n.stageId);if(r===void 0||Th({classification:t,stageId:n.stageId,environmentDigest:n.environmentDigest,semanticInputs:n.semanticInputs,upstream:n.upstream}).inputId!==n.inputId||n.schemaVersion===`ai-delivery.stage-input@2`&&z(e.artifacts)!==z(n.policyArtifacts)||e.commands.length!==r.commands.length||e.commands.some((e,t)=>e.label!==r.commands[t]?.label||e.exitCode!==0)||r.attestationKey!==void 0&&e.artifacts.length===0)throw Error(`Stage receipt does not prove selected definition.`);let i={artifacts:[...e.artifacts].sort((e,t)=>bh(e.path,t.path)),commands:e.commands.map(e=>({...e})),completedAt:e.completedAt,input:n,result:`passed`,schemaVersion:n.schemaVersion===`ai-delivery.stage-input@2`?`ai-delivery.stage-receipt@2`:`ai-delivery.stage-receipt@1`,startedAt:e.startedAt};return Ch.parse({...i,receiptId:B(i)})}function Dh(e){let t=_h.parse(e.classification);if(e.receipts.length!==t.requiredStages.length)throw Error(`Aggregate requires every selected stage.`);let n=e.receipts.map(e=>Ch.parse(e)),r=new Map(n.map(e=>[e.input.stageId,e]));if(r.size!==n.length)throw Error(`Aggregate contains duplicate stages.`);for(let e of t.requiredStages){let n=r.get(e.id);if(n===void 0||z(n.input.upstream)!==z(e.dependsOn.map(e=>({stageId:e,receiptId:r.get(e)?.receiptId})).sort((e,t)=>bh(e.stageId,t.stageId)))||Eh({artifacts:n.artifacts,classification:t,commands:n.commands,completedAt:n.completedAt,stageInput:n.input,startedAt:n.startedAt}).receiptId!==n.receiptId)throw Error(`Aggregate contains missing, foreign or stale stage proof.`)}let i={classificationReceiptId:t.receiptId,policyDigest:t.policyDigest,result:`passed`,schemaVersion:t.schemaVersion===`ai-delivery.classification@2`?`ai-delivery.stage-aggregate@2`:`ai-delivery.stage-aggregate@1`,stages:t.requiredStages.map(e=>{let t=r.get(e.id);return{inputId:t.input.inputId,receiptId:t.receiptId,stageId:e.id}})};return wh.parse({...i,aggregateId:B(i)})}function Oh(e,t=1){return T(e,`ai-delivery`,`verification@${String(t)}`)}function kh(e,t){return T(Oh(e),`command-output`,`${R.parse(t).slice(7)}.bin`)}function Ah(e){if(e.bytes.length>8388608)throw Error(`Command output exceeds bounded evidence limit.`);let t=V(e.bytes);return zu(kh(e.gitCommonDir,t),e.bytes,t),t}function jh(e){let t=H(kh(e.gitCommonDir,e.digest),{maxBytes:8*1024**2,...e.expectedBytes===void 0?{}:{expectedBytes:e.expectedBytes}});if(V(t)!==e.digest)throw Error(`Command output bytes are corrupt.`);return t}var Mh=N({authorIdentity:A().min(1),diffScopeHash:R,head:Iu,result:I(`approved`),reviewerIdentity:A().min(1),reviewReceiptId:R}).strict().refine(e=>e.authorIdentity!==e.reviewerIdentity,`Approval requires a distinct reviewer identity.`);N({blockedBy:M(j().int().positive()),checksPassed:xl(),head:Iu,mergeable:xl(),observedAt:hu()}).strict(),N({aggregateId:R,approval:Mh.nullable(),base:Iu,boundaryId:R,classificationReceiptId:R,configDigest:R,evidenceId:R,head:Iu,phase:F([`verify`,`publish`,`merge`]),policyDigest:R,repository:Pu,result:I(`passed`),schemaVersion:I(`ai-delivery.delivery-evidence@1`)}).strict().superRefine((e,t)=>{let{evidenceId:n,...r}=e;(n!==B(r)||e.phase===`merge`&&e.approval===null)&&t.addIssue({code:`custom`,message:`Delivery evidence identity or approval is invalid.`})});var Nh=`2026-03-10`;function Ph(e){return{points:{databaseId:e.native.points.databaseId,name:e.native.points.name,values:e.native.points.values.map(e=>Number(e))},priority:{databaseId:e.native.priority.databaseId,name:e.native.priority.name,values:e.native.priority.values}}}var Fh={"X-GitHub-Api-Version":Nh};async function Ih(e){if((await Rh(e)).points===void 0)return;let t=e.catalog??await Lh(e);Hh(t,e.settings),await e.rest.request(`DELETE /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values/{issue_field_id}`,{headers:Fh,issue_field_id:t.points.id,issue_number:e.issueNumber,owner:e.owner,repo:e.repo});let n=await Rh(e);if(n.points!==void 0)throw new L(`Native issue metadata readback retained Points ${String(n.points)} after clearing issue #${String(e.issueNumber)}.`)}async function Lh(e){return Bh((await e.rest.request(`GET /orgs/{org}/issue-fields`,{headers:Fh,org:e.org})).data,e.settings)}async function Rh(e){return zh((await e.rest.request(`GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values`,{headers:Fh,issue_number:e.issueNumber,owner:e.owner,repo:e.repo})).data,e.settings)}function zh(e,t){if(!Array.isArray(e))throw new L(`GitHub returned an invalid issue-field value payload.`);let n={},r=new Set;for(let i of e){if(typeof i!=`object`||!i)continue;let e=i,a=e.issue_field_name;Uh({seen:r,settings:t,value:e}),a===t.points.name?n.points=Gh(e,t):a===t.priority.name&&(n.priority=Kh(e,t))}return n}function Bh(e,t){if(!Array.isArray(e))throw new L(`GitHub returned an invalid organization issue-field payload.`);let n=e.filter(e=>typeof e==`object`&&!!e);return{points:Jh({expectedId:t.points.databaseId,expectedValues:t.points.values.map(String),fields:n,name:t.points.name}),priority:Jh({expectedId:t.priority.databaseId,expectedValues:t.priority.values,fields:n,name:t.priority.name})}}async function Vh(e){if(e.metadata.points===void 0&&e.metadata.priority===void 0)return{};let t=e.catalog??await Lh(e);Hh(t,e.settings);let n=[];if(e.metadata.points!==void 0){if(!e.settings.points.values.includes(e.metadata.points))throw new L(`Unsupported ${e.settings.points.name} value.`);n.push({field_id:t.points.id,value:String(e.metadata.points)})}if(e.metadata.priority!==void 0){if(!e.settings.priority.values.includes(e.metadata.priority))throw new L(`Unsupported ${e.settings.priority.name} value.`);n.push({field_id:t.priority.id,value:e.metadata.priority})}if(n.length===0)return{};let r=zh((await e.rest.request(`POST /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values`,{headers:Fh,issue_field_values:n,issue_number:e.issueNumber,owner:e.owner,repo:e.repo})).data,e.settings);return Wh(e.metadata,r),r}function Hh(e,t){for(let n of[`points`,`priority`]){let r=e[n],i=t[n];if(!Number.isSafeInteger(r.id)||r.id<=0||r.name!==i.name||String(r.id)!==i.databaseId)throw new L(`Native ${i.name} catalog does not match configured issue field.`)}if(e.points.id===e.priority.id)throw new L(`Native Points and Priority catalogs must select distinct issue fields.`)}function Uh(e){let{seen:t,settings:n,value:r}=e,i=r.issue_field_name;if(i!==n.points.name&&i!==n.priority.name)return;if(t.has(i))throw new L(`GitHub returned duplicate native ${i} field values.`);if(t.add(i),r.data_type!==`single_select`)throw new L(`Native ${i} readback must be a constrained single-select field value.`);let a=i===n.points.name?n.points.databaseId:n.priority.databaseId;if(a!==void 0&&String(r.issue_field_id)!==a)throw new L(`Native ${i} readback does not match configured issue field.`)}function Wh(e,t){for(let n of[`points`,`priority`])if(e[n]!==void 0&&t[n]!==e[n])throw new L(`Native issue metadata readback mismatch for ${n}: expected ${String(e[n])}, found ${String(t[n])}.`)}function Gh(e,t){let n=qh(e),r=typeof n==`number`?n:Number(n);if(!Number.isSafeInteger(r)||!t.points.values.includes(r)||t.points.databaseId!==void 0&&String(n)!==String(r))throw new L(`GitHub returned unsupported ${t.points.name} value ${String(n)}.`);return r}function Kh(e,t){let n=qh(e);if(typeof n!=`string`||!t.priority.values.includes(n))throw new L(`GitHub returned unsupported ${t.priority.name} value ${String(n)}.`);return n}function qh(e){if(typeof e.single_select_option==`object`&&e.single_select_option!==null){let t=e.single_select_option;if(t.name!==void 0)return t.name}return e.value}function Jh({expectedId:e,expectedValues:t,fields:n,name:r}){let i=n.filter(e=>e.name===r);if(i.length!==1)throw new L(`Expected exactly one native ${r} issue field, found ${String(i.length)}.`);let[a]=i;if(a===void 0||a.data_type!==`single_select`||!Number.isSafeInteger(a.id))throw new L(`Native ${r} must be a constrained single-select issue field.`);if(e!==void 0&&String(a.id)!==e)throw new L(`Native ${r} does not match configured issue field ${e}.`);if(t!==void 0){let e=Array.isArray(a.options)?a.options.map(e=>typeof e==`object`&&e?e.name:null):[];if(e.length!==t.length||new Set(e).size!==t.length||e.some(e=>typeof e!=`string`||!t.includes(e)))throw new L(`Native ${r} options do not match configured values.`)}return{dataType:`single_select`,id:a.id,name:r}}var Yh=10,Xh=(e=0)=>t=>`\u001B[${t+e}m`,Zh=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,Qh=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,$h={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys($h.modifier);var eg=Object.keys($h.color),tg=Object.keys($h.bgColor);[...eg,...tg];function ng(){let e=new Map;for(let[t,n]of Object.entries($h)){for(let[t,r]of Object.entries(n))$h[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=$h[t],e.set(r[0],r[1]);Object.defineProperty($h,t,{value:n,enumerable:!1})}return Object.defineProperty($h,"codes",{value:e,enumerable:!1}),$h.color.close=`\x1B[39m`,$h.bgColor.close=`\x1B[49m`,$h.color.ansi=Xh(),$h.color.ansi256=Zh(),$h.color.ansi16m=Qh(),$h.bgColor.ansi=Xh(Yh),$h.bgColor.ansi256=Zh(Yh),$h.bgColor.ansi16m=Qh(Yh),Object.defineProperties($h,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>$h.rgbToAnsi256(...$h.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>$h.ansi256ToAnsi($h.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>$h.ansi256ToAnsi($h.hexToAnsi256(e)),enumerable:!1}}),$h}var rg=ng();function ig(e,t=globalThis.Deno?globalThis.Deno.args:ie.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}var{env:ag}=ie,og;ig(`no-color`)||ig(`no-colors`)||ig(`color=false`)||ig(`color=never`)?og=0:(ig(`color`)||ig(`colors`)||ig(`color=true`)||ig(`color=always`))&&(og=1);function sg(){if(`FORCE_COLOR`in ag)return ag.FORCE_COLOR===`true`?1:ag.FORCE_COLOR===`false`?0:ag.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(ag.FORCE_COLOR,10),3)}function cg(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function lg(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=sg();r!==void 0&&(og=r);let i=n?og:r;if(i===0)return 0;if(n){if(ig(`color=16m`)||ig(`color=full`)||ig(`color=truecolor`))return 3;if(ig(`color=256`))return 2}if(`TF_BUILD`in ag&&`AGENT_NAME`in ag)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(ag.TERM===`dumb`)return a;if(ie.platform===`win32`){let e=ae.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in ag)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in ag)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in ag)||ag.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in ag)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ag.TEAMCITY_VERSION);if(ag.COLORTERM===`truecolor`||ag.TERM===`xterm-kitty`||ag.TERM===`xterm-ghostty`||ag.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in ag){let e=Number.parseInt((ag.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(ag.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(ag.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ag.TERM)||`COLORTERM`in ag?1:a}function ug(e,t={}){return cg(lg(e,{streamIsTTY:e&&e.isTTY,...t}))}var dg={stdout:ug({isTTY:de.isatty(1)}),stderr:ug({isTTY:de.isatty(2)})};function fg(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function pg(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
191
|
+
`}),s=Km(o,e.overrides.pointsField??`Points`),c=Km(o,e.overrides.priorityField??`Priority`),l=(await Gm({...e,owner:t,repo:n,field:`issueTypes`,selection:`id name isEnabled`})).filter(e=>{if(typeof e.isEnabled!=`boolean`)throw new R(`GitHub omitted issue type availability.`);return e.isEnabled}).map(e=>Hm(e.name,`issue type`)).sort();if(!l.length||new Set(l).size!==l.length)throw new R(`No unambiguous enabled native issue types were discovered.`);let u=e.overrides.issueTypes?.slice().sort()??l;if(u.some(e=>!l.includes(e)))throw new R(`Configured issue type is unavailable in the selected repository.`);let d=e.overrides.project===void 0?`linked`:`explicit`,f=e.overrides.project===void 0?await Gm({...e,owner:t,repo:n,field:`projectsV2`,selection:`id number title closed viewerCanUpdate owner { __typename ... on Organization { login } ... on User { login } }`}):[{number:e.overrides.project}],p=[];for(let n of f){if(d===`linked`){if(typeof n.closed!=`boolean`||typeof n.viewerCanUpdate!=`boolean`)throw new R(`Incomplete linked Project metadata.`);let e=Vm(n.owner,`Project owner`);if(e.__typename!==`Organization`||Hm(e.login,`Project owner`).toLowerCase()!==t.toLowerCase())throw new R(`Linked Project owner does not match the selected repository organization.`);if(n.closed)continue}let r=Um(n.number,`Project number`),i=await Cm({graphql:e.clients.graphql,org:t,number:r});if(typeof i.viewerCanUpdate!=`boolean`||i.number!==r)throw new R(`Incomplete or drifting Project identity.`);if(typeof i.closed!=`boolean`)throw new R(`GitHub omitted Project closed state.`);if(i.closed){if(d===`explicit`)throw new R(`The explicitly selected Project is closed.`);continue}if(d===`linked`&&(i.id!==n.id||i.title!==n.title))throw new R(`Linked Project changed during discovery.`);let a={number:r,title:Hm(i.title,`Project title`),points:s,priority:c,statusField:e.overrides.statusField??`Status`,statuses:{Todo:e.overrides.statuses?.todo??`Todo`,"In Progress":e.overrides.statuses?.inProgress??`In Progress`,Blocked:e.overrides.statuses?.blocked??`Blocked`,Done:e.overrides.statuses?.done??`Done`}},o;try{o=Tm(i,{settings:a,requireWritable:!1})}catch(e){if(d===`explicit`||!(e instanceof R))throw e;continue}if(!o.writable)throw new R(`A compatible delivery Project is not writable; refusing destination fallback.`);p.push(o)}if(p.length!==1)throw new R(`Discovered ${p.length} compatible linked Projects. Select project explicitly in ai-delivery.config.json; no issue was created.`);let m=p[0];if(!m)throw new R(`Delivery Project selection is incomplete.`);return{repository:i,repositoryId:Hm(r.id,`repository ID`),projectId:m.projectId,projectSource:d,statusFieldId:m.statusFieldId,statusOptionIds:m.statusOptionIds,pointsFieldId:m.pointsFieldId,priorityFieldId:m.priorityFieldId,native:{organization:Hm(a.login,`organization`),issueTypes:u,points:s,priority:c,milestones:`repository`,relationships:{blockedBy:`native`,parent:`native`},project:{number:m.projectNumber,title:m.title,statusField:m.settings.statusField,statuses:{todo:m.settings.statuses.Todo,inProgress:m.settings.statuses[`In Progress`],blocked:m.settings.statuses.Blocked,done:m.settings.statuses.Done}}}}}var Jm=`RepositoryDeliveryPolicy@1`,Ym=A().trim().min(1),Xm=A().regex(/^[A-Z][A-Z0-9_]*$/u),Zm=j().int().positive(),Qm=A().regex(/^[1-9]\d*$/u).refine(e=>Number.isSafeInteger(Number(e))),$m=N(Ym).min(1).superRefine((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:`custom`,message:`Values must be unique.`})}),eh=P({databaseId:Qm,name:Ym,values:$m}).strict(),th=P({authSource:L(`app`).optional(),credentialEnv:P({appId:Xm,installationId:Xm,privateKeyPath:Xm}).strict(),identity:Ym}).strict(),nh=jl([th,P({authSource:L(`personal`),credentialEnv:P({token:Xm}).strict(),identity:Ym}).strict()]);P({commandPolicy:P({checks:P({format:I([`REQUIRED`,`OPTIONAL`,`SKIP`]),gitClean:I([`REQUIRED`,`OPTIONAL`,`SKIP`]),lint:I([`REQUIRED`,`OPTIONAL`,`SKIP`]),test:I([`REQUIRED`,`OPTIONAL`,`SKIP`]),typecheck:I([`REQUIRED`,`OPTIONAL`,`SKIP`])}).strict(),timeoutsMs:P({lint:Zm,test:Zm,typecheck:Zm}).strict()}).strict(),native:P({issueTypes:$m,milestones:L(`repository`),organization:Ym,points:eh,priority:eh,project:P({number:Zm,statuses:P({blocked:Ym,done:Ym,inProgress:Ym,todo:Ym}).strict(),statusField:Ym,title:Ym}).strict(),relationships:P({blockedBy:L(`native`),parent:L(`native`)}).strict()}).strict(),policy:P({contract:I([Jm,`RepositoryDeliveryPolicy@2`]),module:A().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u)}).strict(),repository:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u),roles:P({author:nh,reviewer:th}).strict(),schemaVersion:L(`ai-delivery.config@2`)}).strict().superRefine((e,t)=>{e.repository.split(`/`)[0]?.toLowerCase()!==e.native.organization.toLowerCase()&&t.addIssue({code:`custom`,message:`Organization must match repository owner.`,path:[`native`,`organization`]}),e.roles.author.identity.toLowerCase()===e.roles.reviewer.identity.toLowerCase()&&t.addIssue({code:`custom`,message:`Author and reviewer identities must be distinct.`,path:[`roles`]}),[e.roles.author,e.roles.reviewer].some(e=>e.authSource!==`personal`&&/^personal(?:$|[-_])/iu.test(e.identity))&&t.addIssue({code:`custom`,message:`App role identities cannot be personal identities.`,path:[`roles`]});let n=Object.values(e.roles.author.credentialEnv),r=Object.values(e.roles.reviewer.credentialEnv);new Set([...n,...r]).size!==n.length+r.length&&t.addIssue({code:`custom`,message:`Author and reviewer credential environment names must be distinct.`,path:[`roles`]}),new Set(Object.values(e.native.project.statuses)).size!==4&&t.addIssue({code:`custom`,message:`Project statuses must be distinct.`,path:[`native`,`project`,`statuses`]}),e.native.points.values.some(e=>!/^[1-9]\d*$/u.test(e)||!Number.isSafeInteger(Number(e)))&&t.addIssue({code:`custom`,message:`Point values must be positive safe integers.`,path:[`native`,`points`,`values`]}),e.native.points.name===e.native.priority.name&&t.addIssue({code:`custom`,message:`Points and priority fields must be distinct.`,path:[`native`]}),e.native.points.databaseId===e.native.priority.databaseId&&t.addIssue({code:`custom`,message:`Points and priority field IDs must be distinct.`,path:[`native`]})});var rh=A().regex(/^\.\/(?!.*(?:^|\/)\.\.(?:\/|$))[^\s]+\.(?:mjs|js)$/u),ih=P({schemaVersion:L(`ai-delivery.config@2`).optional(),repository:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),remote:Ym.optional(),policy:P({module:rh}).strict().optional(),project:Zm.optional(),pointsField:Ym.optional(),priorityField:Ym.optional(),statusField:Ym.optional(),statuses:P({blocked:Ym,done:Ym,inProgress:Ym,todo:Ym}).strict().optional(),issueTypes:$m.optional()}).strict(),ah=F({schemaVersion:L(`ai-delivery.user@1`),roles:F({author:Nl(`authSource`,[th,nh.options[1]]),reviewer:th}),project:Zm,checkoutRoots:N(A().min(1).refine(ee,`Checkout roots must be absolute.`)),pointsField:Ym.optional(),priorityField:Ym.optional(),statusField:Ym.optional(),statuses:ih.shape.statuses,issueTypes:$m.optional()}).superRefine((e,t)=>{let n=e.roles;n.author.identity.toLowerCase()===n.reviewer.identity.toLowerCase()&&t.addIssue({code:`custom`,path:[`roles`],message:`Author and reviewer identities must be distinct.`}),[n.author,n.reviewer].some(e=>e.authSource!==`personal`&&/^personal(?:$|[-_])/iu.test(e.identity))&&t.addIssue({code:`custom`,path:[`roles`],message:`App role identities cannot be personal identities.`}),e.statuses&&new Set(Object.values(e.statuses)).size!==4&&t.addIssue({code:`custom`,path:[`statuses`],message:`Project statuses must be distinct.`});let r=[...Object.values(n.author.credentialEnv),...Object.values(n.reviewer.credentialEnv)];new Set(r).size!==r.length&&t.addIssue({code:`custom`,path:[`roles`],message:`Credential environment names must be distinct.`})});async function oh(e){let t=process.env.AI_DELIVERY_CONFIG??T(oe(),`.config`,`aviaratech-ai`,`ai-delivery.json`);if(!ee(t))throw new R(`AI_DELIVERY_CONFIG must be an absolute user configuration path.`);let n;try{n=l(t)}catch{throw new R(`Missing user configuration ${t}; configure roles.author, roles.reviewer, project and checkoutRoots.`)}let r;try{r=JSON.parse(n.toString(`utf8`))}catch{throw new R(`Invalid user configuration JSON at ${t}.`)}let i=ah.safeParse(r);if(!i.success)throw new R(`Invalid user configuration ${t}: ${i.error.issues.map(e=>`${e.path.join(`.`)||`configuration`}: ${e.message}`).join(`; `)}`);let{roles:a,checkoutRoots:o,schemaVersion:s,...c}=i.data;return{roles:a,checkoutRoots:o,configPath:t,overrides:c,sourceDigest:V(i.data)}}async function sh(e,t={}){t.signal?.throwIfAborted();let n=await oh(),r=t.repository??(()=>{let t=Su(e,`origin`);return`${t.owner}/${t.repo}`})();if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(r))throw new R(`Repository must be owner/name.`);let i=t.clients??await _m({config:n,identity:t.personalAuth===!0&&n.roles.author.authSource!==`personal`?`personal`:n.roles.author.identity,role:`author`,...t.personalAuth===!0?{personalAuth:{enabled:!0}}:{},...t.signal===void 0?{}:{signal:t.signal}}),a;try{a=await qm({clients:i,repository:r,overrides:n.overrides,repositorySelected:t.repository!==void 0})}catch(e){throw t.clients===void 0&&n.roles.author.authSource===`personal`&&e.status===401?new R(`Configured personal author token is invalid or expired; refresh the selected token.`):e}let o={schemaVersion:`ai-delivery.github@1`,repository:a.repository,roles:n.roles,native:a.native};return{config:o,configDigest:V({sourceDigest:n.sourceDigest,routing:a,roles:o.roles}),configPath:n.configPath,routing:a}}function ch(e){let{config:t,role:n}=e;if(t.roles[n].authSource===`personal`)throw new R(`Personal author credentials use the configured token environment variable.`);let r=e.env??process.env,i=t.roles[n].credentialEnv,a={appId:r[i.appId]?.trim(),installationId:r[i.installationId]?.trim(),privateKeyPath:r[i.privateKeyPath]?.trim()};if(!a.appId||!a.installationId||!a.privateKeyPath)throw new R(`Missing GitHub App credentials for ${n} role. Set ${i.appId}, ${i.installationId} and ${i.privateKeyPath}.`);if(!ee(a.privateKeyPath))throw new R(`GitHub App private-key path for ${n} role (${i.privateKeyPath}) must be absolute.`);let o=Number(a.installationId);if(!Number.isSafeInteger(o)||o<=0)throw new R(`Invalid GitHub App installation ID for ${n} role (${i.installationId}).`);let s=Number(a.appId);if(!Number.isSafeInteger(s)||s<=0)throw new R(`Invalid GitHub App ID for ${n} role (${i.appId}).`);return{appId:a.appId,installationId:o,privateKeyPath:a.privateKeyPath}}var lh=new Set([`runtime:stage`,`runtime:admit`,`cleanup`,`close`,`comment`,`create`,`develop`,`finish`,`start`,`update`,`pr:create`,`pr:merge`,`worktree`,`worktree:create`,`worktree:transition:apply`,`worktrees:cleanup`,`pr:checkout`]),uh=new Set([`pr:review`]);function dh(e){let t=e.commandName.trim().toLowerCase(),n=uh.has(t)?`reviewer`:lh.has(t)?`author`:null;if(n===null)return{error:null,normalizedCommandName:t,requiredRole:n,requiresExplicitIdentity:!1};let r=e.identity?.trim().toLowerCase()??``,i=null;return r?r===e.deliveryConfig.roles[n].identity.toLowerCase()?e.personalAuth===!0&&e.deliveryConfig.roles[n].authSource!==`personal`&&(i=`Personal-token override requires the explicit personal identity.`):r===`personal`?(n!==`author`||e.personalAuth!==!0)&&(i=`Command "${t}" requires its configured identity; personal-token override requires explicit author opt-in.`):i=e.personalAuth===!0?`Personal-token opt-in requires the explicit personal identity.`:`Command "${t}" requires configured ${n} identity "${e.deliveryConfig.roles[n].identity}".`:i=`Command "${t}" requires an explicit ${n} identity.`,{error:i,normalizedCommandName:t,requiredRole:n,requiresExplicitIdentity:!0}}var fh=P({digest:z,path:A().min(1),producer:A().min(1)}).strict(),ph=P({attestationKey:A().min(1).optional(),commands:N(P({argv:N(A().min(1)).min(1),label:A().min(1)}).strict()),dependsOn:N(Pu),id:Pu,resourceClass:I([`source_only`,`focused_node`,`canonical_verify`,`model`,`postgres_docker`]),semanticInputKeys:N(A().min(1)).min(1),semanticInputs:N(P({digest:z,key:A().min(1)}).strict()).min(1).optional()}).strict(),mh=P({artifacts:N(fh).min(1),base:Fu,configDigest:z,evidenceId:z,head:Fu,opaquePayload:A().min(1),policyDigest:z,producer:A().min(1),repository:Nu,schemaVersion:L(`ai-delivery.policy-evidence@1`)}).strict().superRefine((e,t)=>{let{evidenceId:n,...r}=e;(n!==V(r)||!Iu(e.artifacts.map(e=>e.path)))&&t.addIssue({code:`custom`,message:`Policy evidence identity or artifacts are invalid.`})}),hh=P({policyDigest:z,policyEvidence:mh,requiredStages:N(ph).min(1),risk:I([`standard`,`high`])}).strict().superRefine((e,t)=>{let n=new Set;for(let r of e.requiredStages)(n.has(r.id)||r.dependsOn.some(e=>!n.has(e))||new Set(r.dependsOn).size!==r.dependsOn.length||!Iu(r.semanticInputKeys)||r.semanticInputs!==void 0&&(!Iu(r.semanticInputs.map(e=>e.key))||B(r.semanticInputs.map(e=>e.key))!==B(r.semanticInputKeys))||r.commands.length===0!=(r.attestationKey!==void 0))&&t.addIssue({code:`custom`,message:`Policy stages must be unique, ordered and proof complete.`}),n.add(r.id)});P({additionalConstraints:P({exactBaseHeadLease:M(),requiredAttestationIds:N(z)}).strict(),boundaryId:z,classificationReceiptId:z,configDigest:z,currentBase:Fu,currentHead:Fu,phase:I([`verify`,`publish`,`merge`]),policyEvidenceId:z,schemaVersion:L(`ai-delivery.policy-boundary@1`),stageReceiptSetHash:z}).strict().superRefine((e,t)=>{let{boundaryId:n,...r}=e;(n!==V(r)||!Iu(e.additionalConstraints.requiredAttestationIds))&&t.addIssue({code:`custom`,message:`Policy boundary identity or attestation inventory is invalid.`})});var gh=P({base:Fu,changedPaths:N(A().min(1)),configDigest:z,head:Fu,policyDigest:z,policyEvidence:mh,receiptId:z,repository:Nu,requiredStages:N(ph).min(1),risk:I([`standard`,`high`]),schemaVersion:I([`ai-delivery.classification@1`,`ai-delivery.classification@2`])}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==V(r)||!Iu(e.changedPaths)||e.base.sha!==e.head.sha&&e.changedPaths.length===0||e.policyEvidence.repository!==e.repository||B(e.policyEvidence.base)!==B(e.base)||B(e.policyEvidence.head)!==B(e.head)||e.policyEvidence.configDigest!==e.configDigest||e.policyEvidence.policyDigest!==e.policyDigest||e.requiredStages.some(t=>t.semanticInputs!==void 0!=(e.schemaVersion===`ai-delivery.classification@2`))||!hh.safeParse({policyDigest:e.policyDigest,policyEvidence:e.policyEvidence,requiredStages:e.requiredStages,risk:e.risk}).success)&&t.addIssue({code:`custom`,message:`Repository classification is unbound or invalid.`})}),_h=P({digest:z,key:A().min(1)}).strict(),vh=P({receiptId:z,stageId:Pu}).strict(),yh=(e,t)=>e<t?-1:+(e>t),bh={definitionHash:z,environmentDigest:z,inputId:z,policyDigest:z,semanticInputs:N(_h).min(1),stageId:Pu,upstream:N(vh)},xh=jl([F({...bh,classificationReceiptId:z,schemaVersion:L(`ai-delivery.stage-input@1`)}),F({...bh,configDigest:z,policyProducer:A().min(1),policyArtifacts:N(F({digest:z,path:A().min(1)})),schemaVersion:L(`ai-delivery.stage-input@2`)})]).superRefine((e,t)=>{let{inputId:n,...r}=e;(n!==V(r)||!Iu(e.semanticInputs.map(e=>e.key))||!Iu(e.upstream.map(e=>e.stageId))||e.schemaVersion===`ai-delivery.stage-input@2`&&!Iu(e.policyArtifacts.map(e=>e.path)))&&t.addIssue({code:`custom`,message:`Stage input identity or inventory is invalid.`})}),Sh=P({artifacts:N(P({digest:z,path:A().min(1)}).strict()),commands:N(P({exitCode:j().int().nonnegative(),label:A().min(1),outputDigest:z}).strict()),completedAt:mu(),input:xh,receiptId:z,result:L(`passed`),schemaVersion:I([`ai-delivery.stage-receipt@1`,`ai-delivery.stage-receipt@2`]),startedAt:mu()}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==V(r)||e.schemaVersion===`ai-delivery.stage-receipt@2`!=(e.input.schemaVersion===`ai-delivery.stage-input@2`)||Date.parse(e.completedAt)<Date.parse(e.startedAt)||e.commands.some(e=>e.exitCode!==0)||!Iu(e.artifacts.map(e=>e.path)))&&t.addIssue({code:`custom`,message:`Stage receipt has incomplete or corrupt proof.`})}),Ch=P({aggregateId:z,classificationReceiptId:z,policyDigest:z,result:L(`passed`),schemaVersion:I([`ai-delivery.stage-aggregate@1`,`ai-delivery.stage-aggregate@2`]),stages:N(P({inputId:z,receiptId:z,stageId:Pu}).strict()).min(1)}).strict().superRefine((e,t)=>{let{aggregateId:n,...r}=e;(n!==V(r)||new Set(e.stages.map(e=>e.stageId)).size!==e.stages.length)&&t.addIssue({code:`custom`,message:`Stage aggregate identity or inventory is invalid.`})});function wh(e){let t=gh.parse(e.classification),n=t.requiredStages.find(t=>t.id===e.stageId);if(n===void 0)throw Error(`Stage is absent from selected policy.`);let r=[...e.semanticInputs].sort((e,t)=>yh(e.key,t.key)).map(e=>_h.parse(e)),i=[...e.upstream].sort((e,t)=>yh(e.stageId,t.stageId)).map(e=>vh.parse(e));if(B(r.map(e=>e.key))!==B(n.semanticInputKeys)||t.schemaVersion===`ai-delivery.classification@2`&&B(r)!==B(n.semanticInputs)||B(i.map(e=>e.stageId))!==B([...n.dependsOn].sort()))throw Error(`Stage input lacks required semantic or upstream proof.`);let a={...t.schemaVersion===`ai-delivery.classification@1`?{classificationReceiptId:t.receiptId,schemaVersion:`ai-delivery.stage-input@1`}:{configDigest:t.configDigest,policyProducer:t.policyEvidence.producer,schemaVersion:`ai-delivery.stage-input@2`,policyArtifacts:t.policyEvidence.artifacts.filter(e=>e.path===n.attestationKey).map(({digest:e,path:t})=>({digest:e,path:t}))},definitionHash:V(n),environmentDigest:z.parse(e.environmentDigest),policyDigest:t.policyDigest,semanticInputs:r,stageId:n.id,upstream:i};return xh.parse({...a,inputId:V(a)})}function Th(e){let t=gh.parse(e.classification),n=xh.parse(e.stageInput),r=t.requiredStages.find(e=>e.id===n.stageId);if(r===void 0||wh({classification:t,stageId:n.stageId,environmentDigest:n.environmentDigest,semanticInputs:n.semanticInputs,upstream:n.upstream}).inputId!==n.inputId||n.schemaVersion===`ai-delivery.stage-input@2`&&B(e.artifacts)!==B(n.policyArtifacts)||e.commands.length!==r.commands.length||e.commands.some((e,t)=>e.label!==r.commands[t]?.label||e.exitCode!==0)||r.attestationKey!==void 0&&e.artifacts.length===0)throw Error(`Stage receipt does not prove selected definition.`);let i={artifacts:[...e.artifacts].sort((e,t)=>yh(e.path,t.path)),commands:e.commands.map(e=>({...e})),completedAt:e.completedAt,input:n,result:`passed`,schemaVersion:n.schemaVersion===`ai-delivery.stage-input@2`?`ai-delivery.stage-receipt@2`:`ai-delivery.stage-receipt@1`,startedAt:e.startedAt};return Sh.parse({...i,receiptId:V(i)})}function Eh(e){let t=gh.parse(e.classification);if(e.receipts.length!==t.requiredStages.length)throw Error(`Aggregate requires every selected stage.`);let n=e.receipts.map(e=>Sh.parse(e)),r=new Map(n.map(e=>[e.input.stageId,e]));if(r.size!==n.length)throw Error(`Aggregate contains duplicate stages.`);for(let e of t.requiredStages){let n=r.get(e.id);if(n===void 0||B(n.input.upstream)!==B(e.dependsOn.map(e=>({stageId:e,receiptId:r.get(e)?.receiptId})).sort((e,t)=>yh(e.stageId,t.stageId)))||Th({artifacts:n.artifacts,classification:t,commands:n.commands,completedAt:n.completedAt,stageInput:n.input,startedAt:n.startedAt}).receiptId!==n.receiptId)throw Error(`Aggregate contains missing, foreign or stale stage proof.`)}let i={classificationReceiptId:t.receiptId,policyDigest:t.policyDigest,result:`passed`,schemaVersion:t.schemaVersion===`ai-delivery.classification@2`?`ai-delivery.stage-aggregate@2`:`ai-delivery.stage-aggregate@1`,stages:t.requiredStages.map(e=>{let t=r.get(e.id);return{inputId:t.input.inputId,receiptId:t.receiptId,stageId:e.id}})};return Ch.parse({...i,aggregateId:V(i)})}function Dh(e,t=1){return T(e,`ai-delivery`,`verification@${String(t)}`)}function Oh(e,t){return T(Dh(e),`command-output`,`${z.parse(t).slice(7)}.bin`)}function kh(e){if(e.bytes.length>8388608)throw Error(`Command output exceeds bounded evidence limit.`);let t=H(e.bytes);return Ru(Oh(e.gitCommonDir,t),e.bytes,t),t}function Ah(e){let t=U(Oh(e.gitCommonDir,e.digest),{maxBytes:8*1024**2,...e.expectedBytes===void 0?{}:{expectedBytes:e.expectedBytes}});if(H(t)!==e.digest)throw Error(`Command output bytes are corrupt.`);return t}var jh=P({authorIdentity:A().min(1),diffScopeHash:z,head:Fu,result:L(`approved`),reviewerIdentity:A().min(1),reviewReceiptId:z}).strict().refine(e=>e.authorIdentity!==e.reviewerIdentity,`Approval requires a distinct reviewer identity.`);P({blockedBy:N(j().int().positive()),checksPassed:M(),head:Fu,mergeable:M(),observedAt:mu()}).strict(),P({aggregateId:z,approval:jh.nullable(),base:Fu,boundaryId:z,classificationReceiptId:z,configDigest:z,evidenceId:z,head:Fu,phase:I([`verify`,`publish`,`merge`]),policyDigest:z,repository:Nu,result:L(`passed`),schemaVersion:L(`ai-delivery.delivery-evidence@1`)}).strict().superRefine((e,t)=>{let{evidenceId:n,...r}=e;(n!==V(r)||e.phase===`merge`&&e.approval===null)&&t.addIssue({code:`custom`,message:`Delivery evidence identity or approval is invalid.`})});var Mh=`2026-03-10`;function Nh(e){return{points:{databaseId:e.native.points.databaseId,name:e.native.points.name,values:e.native.points.values.map(e=>Number(e))},priority:{databaseId:e.native.priority.databaseId,name:e.native.priority.name,values:e.native.priority.values}}}var Ph={"X-GitHub-Api-Version":Mh};async function Fh(e){if((await Lh(e)).points===void 0)return;let t=e.catalog??await Ih(e);Vh(t,e.settings),await e.rest.request(`DELETE /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values/{issue_field_id}`,{headers:Ph,issue_field_id:t.points.id,issue_number:e.issueNumber,owner:e.owner,repo:e.repo});let n=await Lh(e);if(n.points!==void 0)throw new R(`Native issue metadata readback retained Points ${String(n.points)} after clearing issue #${String(e.issueNumber)}.`)}async function Ih(e){return zh((await e.rest.request(`GET /orgs/{org}/issue-fields`,{headers:Ph,org:e.org})).data,e.settings)}async function Lh(e){return Rh((await e.rest.request(`GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values`,{headers:Ph,issue_number:e.issueNumber,owner:e.owner,repo:e.repo})).data,e.settings)}function Rh(e,t){if(!Array.isArray(e))throw new R(`GitHub returned an invalid issue-field value payload.`);let n={},r=new Set;for(let i of e){if(typeof i!=`object`||!i)continue;let e=i,a=e.issue_field_name;Hh({seen:r,settings:t,value:e}),a===t.points.name?n.points=Wh(e,t):a===t.priority.name&&(n.priority=Gh(e,t))}return n}function zh(e,t){if(!Array.isArray(e))throw new R(`GitHub returned an invalid organization issue-field payload.`);let n=e.filter(e=>typeof e==`object`&&!!e);return{points:qh({expectedId:t.points.databaseId,expectedValues:t.points.values.map(String),fields:n,name:t.points.name}),priority:qh({expectedId:t.priority.databaseId,expectedValues:t.priority.values,fields:n,name:t.priority.name})}}async function Bh(e){if(e.metadata.points===void 0&&e.metadata.priority===void 0)return{};let t=e.catalog??await Ih(e);Vh(t,e.settings);let n=[];if(e.metadata.points!==void 0){if(!e.settings.points.values.includes(e.metadata.points))throw new R(`Unsupported ${e.settings.points.name} value.`);n.push({field_id:t.points.id,value:String(e.metadata.points)})}if(e.metadata.priority!==void 0){if(!e.settings.priority.values.includes(e.metadata.priority))throw new R(`Unsupported ${e.settings.priority.name} value.`);n.push({field_id:t.priority.id,value:e.metadata.priority})}if(n.length===0)return{};let r=Rh((await e.rest.request(`POST /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values`,{headers:Ph,issue_field_values:n,issue_number:e.issueNumber,owner:e.owner,repo:e.repo})).data,e.settings);return Uh(e.metadata,r),r}function Vh(e,t){for(let n of[`points`,`priority`]){let r=e[n],i=t[n];if(!Number.isSafeInteger(r.id)||r.id<=0||r.name!==i.name||String(r.id)!==i.databaseId)throw new R(`Native ${i.name} catalog does not match configured issue field.`)}if(e.points.id===e.priority.id)throw new R(`Native Points and Priority catalogs must select distinct issue fields.`)}function Hh(e){let{seen:t,settings:n,value:r}=e,i=r.issue_field_name;if(i!==n.points.name&&i!==n.priority.name)return;if(t.has(i))throw new R(`GitHub returned duplicate native ${i} field values.`);if(t.add(i),r.data_type!==`single_select`)throw new R(`Native ${i} readback must be a constrained single-select field value.`);let a=i===n.points.name?n.points.databaseId:n.priority.databaseId;if(a!==void 0&&String(r.issue_field_id)!==a)throw new R(`Native ${i} readback does not match configured issue field.`)}function Uh(e,t){for(let n of[`points`,`priority`])if(e[n]!==void 0&&t[n]!==e[n])throw new R(`Native issue metadata readback mismatch for ${n}: expected ${String(e[n])}, found ${String(t[n])}.`)}function Wh(e,t){let n=Kh(e),r=typeof n==`number`?n:Number(n);if(!Number.isSafeInteger(r)||!t.points.values.includes(r)||t.points.databaseId!==void 0&&String(n)!==String(r))throw new R(`GitHub returned unsupported ${t.points.name} value ${String(n)}.`);return r}function Gh(e,t){let n=Kh(e);if(typeof n!=`string`||!t.priority.values.includes(n))throw new R(`GitHub returned unsupported ${t.priority.name} value ${String(n)}.`);return n}function Kh(e){if(typeof e.single_select_option==`object`&&e.single_select_option!==null){let t=e.single_select_option;if(t.name!==void 0)return t.name}return e.value}function qh({expectedId:e,expectedValues:t,fields:n,name:r}){let i=n.filter(e=>e.name===r);if(i.length!==1)throw new R(`Expected exactly one native ${r} issue field, found ${String(i.length)}.`);let[a]=i;if(a===void 0||a.data_type!==`single_select`||!Number.isSafeInteger(a.id))throw new R(`Native ${r} must be a constrained single-select issue field.`);if(e!==void 0&&String(a.id)!==e)throw new R(`Native ${r} does not match configured issue field ${e}.`);if(t!==void 0){let e=Array.isArray(a.options)?a.options.map(e=>typeof e==`object`&&e?e.name:null):[];if(e.length!==t.length||new Set(e).size!==t.length||e.some(e=>typeof e!=`string`||!t.includes(e)))throw new R(`Native ${r} options do not match configured values.`)}return{dataType:`single_select`,id:a.id,name:r}}var Jh=10,Yh=(e=0)=>t=>`\u001B[${t+e}m`,Xh=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,Zh=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,Qh={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Qh.modifier);var $h=Object.keys(Qh.color),eg=Object.keys(Qh.bgColor);[...$h,...eg];function tg(){let e=new Map;for(let[t,n]of Object.entries(Qh)){for(let[t,r]of Object.entries(n))Qh[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=Qh[t],e.set(r[0],r[1]);Object.defineProperty(Qh,t,{value:n,enumerable:!1})}return Object.defineProperty(Qh,"codes",{value:e,enumerable:!1}),Qh.color.close=`\x1B[39m`,Qh.bgColor.close=`\x1B[49m`,Qh.color.ansi=Yh(),Qh.color.ansi256=Xh(),Qh.color.ansi16m=Zh(),Qh.bgColor.ansi=Yh(Jh),Qh.bgColor.ansi256=Xh(Jh),Qh.bgColor.ansi16m=Zh(Jh),Object.defineProperties(Qh,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>Qh.rgbToAnsi256(...Qh.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>Qh.ansi256ToAnsi(Qh.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Qh.ansi256ToAnsi(Qh.hexToAnsi256(e)),enumerable:!1}}),Qh}var ng=tg();function rg(e,t=globalThis.Deno?globalThis.Deno.args:ie.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}var{env:ig}=ie,ag;rg(`no-color`)||rg(`no-colors`)||rg(`color=false`)||rg(`color=never`)?ag=0:(rg(`color`)||rg(`colors`)||rg(`color=true`)||rg(`color=always`))&&(ag=1);function og(){if(`FORCE_COLOR`in ig)return ig.FORCE_COLOR===`true`?1:ig.FORCE_COLOR===`false`?0:ig.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(ig.FORCE_COLOR,10),3)}function sg(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function cg(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=og();r!==void 0&&(ag=r);let i=n?ag:r;if(i===0)return 0;if(n){if(rg(`color=16m`)||rg(`color=full`)||rg(`color=truecolor`))return 3;if(rg(`color=256`))return 2}if(`TF_BUILD`in ig&&`AGENT_NAME`in ig)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(ig.TERM===`dumb`)return a;if(ie.platform===`win32`){let e=ae.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in ig)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in ig)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in ig)||ig.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in ig)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ig.TEAMCITY_VERSION);if(ig.COLORTERM===`truecolor`||ig.TERM===`xterm-kitty`||ig.TERM===`xterm-ghostty`||ig.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in ig){let e=Number.parseInt((ig.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(ig.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(ig.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ig.TERM)||`COLORTERM`in ig?1:a}function lg(e,t={}){return sg(cg(e,{streamIsTTY:e&&e.isTTY,...t}))}var ug={stdout:lg({isTTY:de.isatty(1)}),stderr:lg({isTTY:de.isatty(2)})};function dg(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function fg(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
192
192
|
`:`
|
|
193
193
|
`)+n,i=r+1,r=e.indexOf(`
|
|
194
|
-
`,i)}while(r!==-1);return a+=e.slice(i),a}var{stdout:
|
|
195
|
-
`);return a!==-1&&(t=
|
|
194
|
+
`,i)}while(r!==-1);return a+=e.slice(i),a}var{stdout:pg,stderr:mg}=ug,hg=Symbol(`GENERATOR`),gg=Symbol(`STYLER`),_g=Symbol(`IS_EMPTY`),vg=[`ansi`,`ansi`,`ansi256`,`ansi16m`],yg=Object.create(null),bg=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=pg?pg.level:0;e.level=t.level===void 0?n:t.level},xg=e=>{let t=(...e)=>e.join(` `);return bg(t,e),Object.setPrototypeOf(t,Sg.prototype),t};function Sg(e){return xg(e)}Object.setPrototypeOf(Sg.prototype,Function.prototype);for(let[e,t]of Object.entries(ng))yg[e]={get(){let n=Eg(this,Tg(t.open,t.close,this[gg]),this[_g]);return Object.defineProperty(this,e,{value:n}),n}};yg.visible={get(){let e=Eg(this,this[gg],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var Cg=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?ng[n].ansi16m(...r):t===`ansi256`?ng[n].ansi256(ng.rgbToAnsi256(...r)):ng[n].ansi(ng.rgbToAnsi(...r)):e===`hex`?Cg(`rgb`,t,n,...ng.hexToRgb(...r)):ng[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){yg[e]={get(){let{level:t}=this;return function(...n){let r=Tg(Cg(e,vg[t],`color`,...n),ng.color.close,this[gg]);return Eg(this,r,this[_g])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);yg[t]={get(){let{level:t}=this;return function(...n){let r=Tg(Cg(e,vg[t],`bgColor`,...n),ng.bgColor.close,this[gg]);return Eg(this,r,this[_g])}}}}var wg=Object.defineProperties(()=>{},{...yg,level:{enumerable:!0,get(){return this[hg].level},set(e){this[hg].level=e}}}),Tg=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},Eg=(e,t,n)=>{let r=(...e)=>Dg(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,wg),r[hg]=e,r[gg]=t,r[_g]=n,r},Dg=(e,t)=>{if(e.level<=0||!t)return e[_g]?``:t;let n=e[gg];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=dg(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
195
|
+
`);return a!==-1&&(t=fg(t,i,r,a)),r+t+i};Object.defineProperties(Sg.prototype,yg);var Og=Sg();Sg({level:mg?mg.level:0});var kg={debug:`DEBUG`,error:`ERROR`,info:`INFO`,progress:`PROGRESS`,success:`SUCCESS`,warning:`WARNING`};function Ag(e,t){return`${jg(e)} ${t}`}function jg(e){return`[${kg[e]}]`}var Mg=!1,Ng=e=>{Mg=e},Pg=e=>{Mg||(process.env.DEBUG===`true`||process.env.DEBUG===`1`)&&console.error(Og.gray(Ag(`debug`,e)))},Fg=e=>{Mg||console.error(Og.blue(Ag(`info`,e)))},Ig=e=>{Mg||console.warn(Og.yellow(Ag(`warning`,e)))},Lg=class extends Error{code;data;hint;constructor(e,t={}){let n=t.code===void 0?e:`[${t.code}] ${e}`;super(n),this.name=`CLIError`,this.code=t.code,this.data=t.data,this.hint=t.hint}},Rg=e=>{if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}},zg=P({repository:P({issue:P({blockedBy:P({nodes:N(P({id:A(),number:j().int().positive(),state:I([`OPEN`,`CLOSED`]),title:A(),repository:P({nameWithOwner:A()}).strict().optional()}).strict()),pageInfo:P({endCursor:A().nullable(),hasNextPage:M()}).strict()}).strict(),parent:P({id:A(),number:j().int().positive().optional(),repository:P({nameWithOwner:A()}).strict().optional()}).strict().nullable()}).strict()}).strict()}).strict();P({repository:P({issue:P({blocking:P({nodes:N(P({id:A(),number:j().int().positive(),state:I([`OPEN`,`CLOSED`]),title:A()}).strict()),pageInfo:P({endCursor:A().nullable(),hasNextPage:M()}).strict()}).strict()}).strict()}).strict()}).strict();async function Bg(e){return(await Vg(e)).blockers.map(e=>e.number)}async function Vg({graphql:e,issueNumber:t,repo:n,requireRepositoryIdentity:r=!1}){let i=new Map,a=null,o=!0,s=null,c=null,l=null,u=new Set;for(;o;){let d=await e(`
|
|
196
196
|
query ($owner: String!, $name: String!, $number: Int!, $cursor: String) {
|
|
197
197
|
repository(owner: $owner, name: $name) {
|
|
198
198
|
issue(number: $number) {
|
|
@@ -221,7 +221,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
221
221
|
}
|
|
222
222
|
}
|
|
223
223
|
}
|
|
224
|
-
`,{cursor:a,name:n.repo,number:t,owner:n.owner}),f=
|
|
224
|
+
`,{cursor:a,name:n.repo,number:t,owner:n.owner}),f=zg.safeParse(d);if(!f.success)throw new Lg(`GitHub returned invalid blocked-by relationship evidence for issue #${String(t)}.`);let p=f.data.repository.issue;for(let e of p.blockedBy.nodes){if(r&&!e.repository?.nameWithOwner.match(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u))throw new Lg(`Native blocker omitted its repository identity.`);let{repository:t,...n}=e;i.set(e.id,{...n,...r?{repository:t.nameWithOwner}:{}})}if(r&&p.parent&&(!p.parent.number||!p.parent.repository?.nameWithOwner.match(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u)))throw new Lg(`Native parent omitted its repository identity.`);c=p.parent?.repository?.nameWithOwner??null,s=p.parent?.id??null,l=p.parent?.number??null,o=p.blockedBy.pageInfo.hasNextPage;let m=p.blockedBy.pageInfo.endCursor;if(o&&m===null)throw new Lg(`Native blocked-by pagination for issue #${String(t)} omitted its next cursor.`);if(o&&m!==null&&(m===a||u.has(m)))throw new Lg(`Native blocked-by pagination for issue #${String(t)} repeated a non-advancing cursor.`);m!==null&&u.add(m),a=m}return{blockers:[...i.values()].sort((e,t)=>e.number-t.number),parentId:s,parentNumber:l,...r?{parentRepository:c}:{}}}async function Hg({issueNumber:e,repo:t,rest:n}){return(await n.issues.listSubIssues({issue_number:e,owner:t.owner,per_page:1,repo:t.repo})).data.length>0}async function Ug({parentIssueNumber:e,repo:t,rest:n,subIssueId:r,subIssueNumber:i}){if(e===i)throw new Lg(`Issue #${String(i)} cannot be its own parent.`);let a=typeof r==`number`&&Number.isFinite(r)?r:await qg({issueNumber:i,repo:t,rest:n});if(await Yg({parentIssueNumber:e,repo:t,rest:n,subIssueNumber:i})){Fg(`Issue #${String(i)} is already a sub-issue of issue #${String(e)}.`);return}if(await n.issues.addSubIssue({issue_number:e,owner:t.owner,repo:t.repo,sub_issue_id:a}),!await Yg({parentIssueNumber:e,repo:t,rest:n,subIssueNumber:i}))throw new Lg(`Native sub-issue readback for parent #${String(e)} omitted requested issue #${String(i)}.`);Fg(`Linked issue #${String(i)} as sub-issue of issue #${String(e)}.`)}async function Wg({blockers:e,graphql:t,issueNumber:n,repo:r,rest:i}){let a=[...new Set(e)].sort((e,t)=>e-t),o=await Vg({graphql:t,issueNumber:n,repo:r}),s=new Set(a),c=await Jg({issueNumber:n,repo:r,rest:i});for(let e of o.blockers.filter(e=>!s.has(e.number)))await t(`
|
|
225
225
|
mutation ($issue: ID!, $blocking: ID!) {
|
|
226
226
|
removeBlockedBy(input: { issueId: $issue, blockingIssueId: $blocking }) {
|
|
227
227
|
issue {
|
|
@@ -237,11 +237,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
237
237
|
}
|
|
238
238
|
}
|
|
239
239
|
}
|
|
240
|
-
`,{blocking:await
|
|
241
|
-
`)),n=null):n.push(r);continue}let e=r.trimStart();if(r.length-e.length>3||!e.startsWith("```"))continue;let i=e.slice(3).trim().toLowerCase();[``,`bash`,`console`,`sh`,`shell`,`zsh`].includes(i)&&(n=[])}return t}function
|
|
242
|
-
`).trim()}function
|
|
240
|
+
`,{blocking:await Jg({issueNumber:e,repo:r,rest:i}),issue:c});let u=(await Bg({graphql:t,issueNumber:n,repo:r})).sort((e,t)=>e-t);if(u.join(`,`)!==a.join(`,`))throw new Lg(`Native blocked-by replacement readback mismatch for issue #${String(n)}: expected ${a.join(`,`)||`(none)`}, found ${u.join(`,`)||`(none)`}.`)}async function Gg({graphql:e,issueNumber:t,parentIssueNumber:n,repo:r,rest:i}){if(n===t)throw new Lg(`Issue #${String(t)} cannot be its own parent.`);let a=await Vg({graphql:e,issueNumber:t,repo:r});if(a.parentNumber===n)return;let o=await qg({issueNumber:t,repo:r,rest:i});a.parentNumber!==null&&await i.issues.removeSubIssue({issue_number:a.parentNumber,owner:r.owner,repo:r.repo,sub_issue_id:o}),n!==null&&await Ug({parentIssueNumber:n,repo:r,rest:i,subIssueId:o,subIssueNumber:t});let s=await Vg({graphql:e,issueNumber:t,repo:r});if(s.parentNumber!==n){let e=n===null?`(none)`:`#${String(n)}`,r=s.parentNumber===null?`(none)`:`#${String(s.parentNumber)}`;throw new Lg(`Native parent replacement readback mismatch for issue #${String(t)}: expected ${e}, found ${r}.`)}}async function Kg({blockers:e,parentIssueNumber:t,repo:n,rest:r}){let i=new Map,a=[];for(let t of new Set(e)){let e=await Zg({issueNumber:t,repo:n,rest:r});i.set(t,e.nodeId),e.state===`OPEN`&&a.push(t)}return t!==void 0&&await Xg({issueNumber:t,relationship:`parent`,repo:n,rest:r}),{blockerNodeIds:i,unresolvedBlockers:a}}async function qg({issueNumber:e,repo:t,rest:n}){try{let r=(await n.issues.get({issue_number:e,owner:t.owner,repo:t.repo})).data.id;if(typeof r!=`number`)throw new Lg(`GitHub omitted the numeric issue id for issue #${String(e)}.`);return r}catch(t){throw t instanceof Lg?t:new Lg(`Unable to resolve sub-issue id for issue #${String(e)}: ${Rg(t)}.`)}}async function Jg({issueNumber:e,repo:t,rest:n}){try{let r=(await n.issues.get({issue_number:e,owner:t.owner,repo:t.repo})).data.node_id;if(typeof r!=`string`)throw new Lg(`GitHub omitted the node id for issue #${String(e)}.`);return r}catch(t){throw t instanceof Lg?t:new Lg(`Unable to resolve blocker issue #${String(e)}: ${Rg(t)}.`)}}async function Yg({parentIssueNumber:e,repo:t,rest:n,subIssueNumber:r}){return(await n.paginate(n.issues.listSubIssues,{issue_number:e,owner:t.owner,per_page:100,repo:t.repo})).some(e=>e.number===r)}async function Xg({issueNumber:e,relationship:t,repo:n,rest:r}){try{await r.issues.get({issue_number:e,owner:n.owner,repo:n.repo})}catch(n){throw new Lg(`Unable to resolve ${t} issue #${String(e)}: ${Rg(n)}.`)}}async function Zg({issueNumber:e,repo:t,rest:n}){try{let r=await n.issues.get({issue_number:e,owner:t.owner,repo:t.repo}),i=r.data.node_id,a=r.data.state;if(typeof i!=`string`||a!==`open`&&a!==`closed`)throw new Lg(`GitHub omitted the node id or state for blocker issue #${String(e)}.`);return{nodeId:i,state:a===`open`?`OPEN`:`CLOSED`}}catch(t){throw t instanceof Lg?t:new Lg(`Unable to resolve blocker issue #${String(e)}: ${Rg(t)}.`)}}function Qg(e){let t=[],n=e.body.trim(),r=n_(n);o_(n)||t.push({code:`outcome`,message:`Add a substantive Outcome or Problem section.`});let i=$g(r_(n,`Acceptance Criteria`));return(i.length<2||i.length>5)&&t.push({code:`acceptance-criteria`,message:`Declare two to five checkbox acceptance criteria.`}),i_(n)||t.push({code:`verification`,message:`Include an executable verification command in inline or fenced code.`}),(r.length===0||r.some(t=>!l_(t,e.repoRoot)))&&t.push({code:`scope`,message:`Declare scope paths that exist in the repository.`}),(e.blockedBy?.length??0)>0&&t.push({code:`blocked`,message:`Resolve native blocked-by issue${e.blockedBy?.length===1?``:`s`} before autonomous development.`}),f_({body:n,scope:r})&&!a_(n,e.repoRoot)&&t.push({code:`evidence`,message:`Add repository-backed current-state evidence for this scope.`}),e.trackingParent===!0?t.push({code:`tracking-parent`,message:`Dispatch an executable sub-issue instead of the tracking parent.`}):e.points===void 0&&t.push({code:`points`,message:`Set configured native Points before autonomous development.`}),s_(n)&&t.push({code:`unresolved`,message:`Resolve TODO, TBD, policy-choice, or architectural-fork markers.`}),{failures:t,ready:t.length===0}}function $g(e){return e.split(/\r?\n/u).map(e=>{let t=e.trimStart();if(![`*`,`+`,`-`].includes(t.charAt(0)))return;let n=t.slice(1).trimStart();if(!(n.length<4||!n.startsWith(`[`)||![` `,`x`,`X`].includes(n.charAt(1))||n.charAt(2)!==`]`||![` `,` `].includes(n.charAt(3))))return n.slice(4).trim()}).filter(e=>e!==void 0&&e.length>0)}function e_(e){let t=[],n=null;for(let r of e.split(/\r?\n/u)){if(n!==null){r.trim()==="```"?(t.push(n.join(`
|
|
241
|
+
`)),n=null):n.push(r);continue}let e=r.trimStart();if(r.length-e.length>3||!e.startsWith("```"))continue;let i=e.slice(3).trim().toLowerCase();[``,`bash`,`console`,`sh`,`shell`,`zsh`].includes(i)&&(n=[])}return t}function t_(e){return Array.from(e.matchAll(/`([^`\r\n]+)`/gu),e=>e[1]?.trim()??``).filter(Boolean)}function n_(e){return t_(r_(e,`Scope`)).filter(e=>!/^\$\d+(?:,\d{3})*(?:\.\d{1,2})?(?:\s*[/–-]\s*\$\d+(?:,\d{3})*(?:\.\d{1,2})?)*$/u.test(e))}function r_(e,t){let n=e.split(/\r?\n/u),r=n.findIndex(e=>d_(e)?.toLowerCase()===t.toLowerCase());if(r===-1)return``;let i=[];for(let e of n.slice(r+1)){if(d_(e)!==null)break;i.push(e)}return i.join(`
|
|
242
|
+
`).trim()}function i_(e){let t=new Set([`bash`,`cargo`,`git`,`go`,`make`,`node`,`npm`,`npx`,`pnpm`,`python`,`python3`,`sh`,`tsc`,`tsx`,`zsh`]);return[...t_(e),...e_(e)].some(e=>e.split(/\r?\n/u).some(e=>{let n=e.trimStart().split(/\s/u,1)[0];return n!==void 0&&t.has(n)}))}function a_(e,t){let n=e.replace(r_(e,`Scope`),``);return/\b[0-9a-f]{40}:[^\s`]+/iu.test(n)||/\/blob\/[0-9a-f]{40}\//iu.test(n)?!0:t_(n).some(e=>l_(e,t))}function o_(e){return[r_(e,`Outcome`),r_(e,`Problem`)].some(e=>p_(e).length>=24)}function s_(e){return/\b(?:TODO|TBD|policy choice|architectural fork)\b/iu.test(e)}function c_(e){let t=u_(e);return t===null?!1:t.length===0||[`.`,`apps`,`packages`,`plugins`].includes(t)}function l_(e,t){let r=u_(e);if(r===null)return!1;if(t===void 0)return!0;let i=te(T(t,r)),a=te(t);return(i===a||i.startsWith(`${a}/`))&&n(i)}function u_(e){let t=e.replace(/(?::\d+(?::\d+)?)$/u,``).replace(/\\/gu,`/`);return t.startsWith(`/`)||t.split(`/`).includes(`..`)?null:t.split(`/`).filter(e=>e.length>0&&e!==`.`).join(`/`)}function d_(e){let t=0;for(;e.charAt(t)===` `&&t<4;)t+=1;if(t>3||e.charAt(t)!==`#`)return null;let n=0;for(;e.charAt(t+n)===`#`&&n<7;)n+=1;return n===0||n>6||![` `,` `].includes(e.charAt(t+n))?null:e.slice(t+n).trim()}function f_({body:e,scope:t}){let n=new Set(t.map(e=>u_(e)).filter(e=>e!==null).map(e=>e.split(`/`).filter(Boolean).slice(0,2).join(`/`)).filter(Boolean));return t.some(c_)||n.size>1||/\b(?:migration|production|data|contract-sensitive)\b/iu.test(e)}function p_(e){return e.replace(/[`*_>#-]/gu,``).replace(/\s+/gu,` `).trim()}var m_=A().trim().min(1).max(1e4),h_=m_.max(500).refine(e=>!/[\r\n]/u.test(e),`Summary must be one plain-language line.`),g_=hu(),__=tl({protocol:/^https$/u}).refine(e=>{let t;try{t=new URL(e)}catch{return!1}let n=t.hostname.replace(/^\[|\]$/gu,``).replace(/\.$/u,``);return!t.username&&!t.password&&fe(n)===0&&n.includes(`.`)&&n!==`localhost`&&!n.endsWith(`.localhost`)&&!n.endsWith(`.local`)},`Evidence must be an HTTPS link with a public DNS hostname and no credentials or IP literal.`),v_={issueNumber:j().int().positive(),summary:h_,status:m_,nextStep:m_,nextDate:g_.nullable(),keyNumbers:N(m_),evidence:N(__),details:m_.optional(),lengthCap:j().int().min(600).max(1e4).optional()},y_=Nl(`kind`,[F({...v_,kind:L(`start`),outcome:m_}),F({...v_,kind:L(`progress`),evidence:N(__).min(1),done:N(m_).min(1),decisionNeeded:m_}),F({...v_,kind:L(`decision`),decision:m_,rationale:m_}),F({...v_,kind:L(`blocker`),blocker:m_,resolution:m_}),F({...v_,kind:L(`closeout`),acceptance:N(F({criterion:m_,evidence:__})).min(1),followUps:N(m_)})]),b_=F({...v_,kind:I([`start`,`progress`,`decision`,`blocker`,`closeout`]),outcome:m_.optional(),done:N(m_).min(1).optional(),decisionNeeded:m_.optional(),decision:m_.optional(),rationale:m_.optional(),blocker:m_.optional(),resolution:m_.optional(),acceptance:N(F({criterion:m_,evidence:__})).min(1).optional(),followUps:N(m_).optional()}).superRefine((e,t)=>{let n=y_.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})});function x_(e,t){let n=y_.parse(e),r=[`**Kind:** ${n.kind}. **Status:** ${n.status}`];switch(n.kind){case`start`:r.push(`**Outcome:** ${n.outcome}`);break;case`progress`:r.push(`**Done since last:**\n${n.done.map(e=>`- ${e}`).join(`
|
|
243
243
|
`)}`,`**Decision needed:** ${n.decisionNeeded}`);break;case`decision`:r.push(`**Decision:** ${n.decision}`,`**Rationale:** ${n.rationale}`);break;case`blocker`:r.push(`**Blocker:** ${n.blocker}`,`**Resolution needed:** ${n.resolution}`);break;case`closeout`:r.push(`**Acceptance evidence:**\n${n.acceptance.map(e=>`- ${e.criterion} — ${e.evidence}`).join(`
|
|
244
|
-
`)}`,`**Follow-ups:** ${n.followUps.length?n.followUps.join(`; `):`None.`}`)}r.push(`**Key numbers:** ${n.keyNumbers.length?n.keyNumbers.join(`; `):`None reported.`}`,`**Next:** ${n.nextStep} (${n.nextDate??`date not scheduled`}).`,`**Evidence:** ${n.evidence.length?n.evidence.join(` · `):`None yet.`}`),n.details&&r.push(n.details);let i=n.summary,a=``;for(let e of r)a||i.length+e.length+2>(n.lengthCap??1800)?a+=`\n\n${e}`:i+=`\n\n${e}`;return a&&(i+=`\n\n<details>\n<summary>Additional journal detail</summary>${a}\n\n</details>`),t===void 0?i:`${i}\n\n${t}`}var C_=65536,w_=P({issueNumber:j().int().positive(),body:A()});async function T_(e,t,n){let r=`body`in t?w_.parse(t):x_.parse(t),i=`body`in r?r.body:void 0;if(i!==void 0&&n!==void 0)throw new L(`Raw issue comments do not accept a lifecycle journal key.`);let a=i===void 0?`<!-- ai-delivery:journal@1:${B({issueNumber:r.issueNumber,key:n??r})} -->`:void 0,o=i??S_(r,a);if(o.length>65536||!o.trim())throw new L(`Issue comment body must contain text and fit ${String(C_)} UTF-16 code units.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new L(`Issue comments require the authenticated author role.`);let s=(await e.clients.authenticatedAuthor()).actorLogin;if(!s)throw new L(`Issue comment author identity is missing.`);return(async()=>{let r=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber)throw new L(`Issue comment target is not the requested issue.`);let i=[];for(let n=1;n<=20;n+=1){let r=(await e.clients.rest.issues.listComments({...e.repo,issue_number:t.issueNumber,page:n,per_page:100})).data;if(i.push(...r.filter(e=>(a===void 0?e.body===o:e.body?.endsWith(a))&&e.user?.login.toLowerCase()===s.toLowerCase())),r.length<100)break;if(n===20)throw new L(`Issue comment history exceeds the bounded readback window.`)}if(i.length>1)throw new L(`Issue comment has duplicate authored retry matches.`);let c=i[0],l=c??(await e.clients.rest.issues.createComment({...e.repo,issue_number:t.issueNumber,body:o})).data,u=(await e.clients.rest.issues.getComment({...e.repo,comment_id:l.id})).data,d=`/repos/${e.repo.owner}/${e.repo.repo}/issues/${String(t.issueNumber)}`;if(!Number.isSafeInteger(u.id)||u.id<=0||u.id!==l.id||u.html_url!==l.html_url||u.body!==(c?.body??o)||n===void 0&&u.body!==o||u.user?.login.toLowerCase()!==s.toLowerCase()||new URL(u.issue_url).pathname.toLowerCase()!==d.toLowerCase()||!u.html_url.startsWith(`https://`))throw new L(`Issue comment readback disagrees with the authored issue comment.`);return{commentId:u.id,url:u.html_url,body:u.body,reused:c!==void 0}})()}async function E_(e,t){let n=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;return T_(e,{issueNumber:t,kind:`start`,summary:`Work started on ${n.title}.`,status:`Started`,outcome:n.title,keyNumbers:[`Issue #${String(t)}`],evidence:[n.html_url],nextStep:`Implement the issue acceptance criteria and run its verification`,nextDate:null},`start:${n.created_at}`)}async function D_(e){let t=await ch(e.repoRoot,{...e.repository===void 0?{}:{repository:e.repository},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}}),n=t.config,[r,i]=n.repository.split(`/`);if(!r||!i)throw new L(`Repository must be owner/name.`);let a={owner:r,repo:i},o=await vm({config:n,identity:e.identity,...e.personalAuth?{personalAuth:{enabled:!0}}:{},role:e.role,...e.signal===void 0?{}:{signal:e.signal}}),s=t.routing;return{clients:o,config:n,configuration:t,projectConfiguration:{projectId:s.projectId,projectNumber:n.native.project.number,title:n.native.project.title,pointsFieldId:s.pointsFieldId,priorityFieldId:s.priorityFieldId,statusFieldId:s.statusFieldId,statusOptionIds:s.statusOptionIds,settings:Tm(n),writable:!0},repo:a,root:``}}async function O_(e,t){let n=t??[];if(n.some(e=>!e.trim())||new Set(n.map(e=>e.toLowerCase())).size!==n.length)throw new L(`Issue labels must be non-empty and unique.`);if(n.length===0)return[];let r=new Set;for(let t=1;t<=100;t++){let i=(await e.clients.rest.issues.listLabelsForRepo({...e.repo,page:t,per_page:100})).data;for(let e of i)r.add(e.name.toLowerCase());if(i.length<100){let e=n.filter(e=>!r.has(e.toLowerCase()));if(e.length)throw new L(`Unknown repository label(s): ${e.join(`, `)}.`);return[...n]}}throw new L(`Repository label listing exceeds the bounded readback window.`)}var k_=class extends L{created;constructor(e,t){super(`Issue #${e.number} was created but native tracking did not complete: ${String(t)}. Resume this known issue; do not create another.`),this.created=e}};async function A_(e,t){if(!t.title.trim())throw new L(`Issue title is required.`);if(t.issueType!==void 0&&!e.config.native.issueTypes.includes(t.issueType))throw new L(`Unsupported configured Issue Type.`);if(t.points!==void 0&&!e.config.native.points.values.includes(String(t.points)))throw new L(`Unsupported configured Points value.`);if(t.priority!==void 0&&!e.config.native.priority.values.includes(t.priority))throw new L(`Unsupported configured Priority value.`);let{clients:n,config:r,repo:i}=e,a=await qg({blockers:t.blockedBy??[],...t.parentIssueNumber===void 0?{}:{parentIssueNumber:t.parentIssueNumber},repo:i,rest:n.rest}),o=await n.rest.issues.create({body:t.body??``,labels:await O_(e,t.labels),...t.milestone===void 0?{}:{milestone:t.milestone},owner:i.owner,repo:i.repo,title:t.title,...t.issueType===void 0?{}:{type:t.issueType}}),s=o.data.number;try{(t.points!==void 0||t.priority!==void 0)&&await Vh({issueNumber:s,metadata:{...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority}},org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Ph(r)}),t.parentIssueNumber!==void 0&&await Kg({graphql:n.graphql,issueNumber:s,parentIssueNumber:t.parentIssueNumber,repo:i,rest:n.rest}),t.parentIssueNumber!==void 0&&await Ih({issueNumber:t.parentIssueNumber,org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Ph(r)}),(t.blockedBy?.length??0)>0&&await Gg({blockers:t.blockedBy??[],graphql:n.graphql,issueNumber:s,repo:i,rest:n.rest}),await Dm({graphql:n.graphql,issueNodeId:o.data.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tm(r),status:a.unresolvedBlockers.length>0?`Blocked`:`Todo`})}catch(e){throw new k_({number:s,title:o.data.title,url:o.data.html_url},e)}return{...e.configuration?{routing:e.configuration.routing}:{},body:o.data.body??t.body??``,created:{number:s,title:o.data.title,url:o.data.html_url}}}var j_=N({id:j().int().positive().safe(),name:A().min(1),data_type:F([`text`,`number`,`date`,`single_select`,`multi_select`])}),M_=N({issue_field_id:j().int().positive().safe(),issue_field_name:A().min(1),data_type:j_.shape.data_type,value:Tl().optional(),single_select_option:N({name:A().min(1)}).nullable().optional(),multi_select_options:M(N({name:A().min(1)})).optional()}),N_=N({number:j().int().positive().safe(),node_id:A().min(1),title:A(),state:F([`open`,`closed`]),labels:M(Ml([A(),N({name:A()})])),type:N({name:A()}).nullable().optional(),html_url:tl(),updated_at:hu({offset:!0})});async function P_(e,t,n){let r=[],i=new Set;for(let a=1;;a+=1){let o=await e.clients.rest.request(t,{...n,headers:{"X-GitHub-Api-Version":Nh},page:a,per_page:100});if(!Array.isArray(o.data))throw new L(`GitHub returned invalid native issue fields.`);let s=B(o.data);if(o.data.length>0&&i.has(s))throw new L(`Native issue fields repeated a pagination page.`);if(i.add(s),r.push(...o.data),o.data.length<100)return r}}async function F_(e,t){let n=t.page??1,r=t.perPage??30;if(!Number.isSafeInteger(n)||n<=0||!Number.isSafeInteger(r)||r<=0||r>100)throw new L(`Issue pagination must use a positive page and perPage from 1 to 100.`);if(t.query!==void 0&&(!t.query.trim()||t.query.length>256||/["\\\r\n]/u.test(t.query)))throw new L(`Issue search requires literal text without quotes, backslashes or newlines.`);if(t.labels?.some(e=>!e||/["\\\r\n]/u.test(e)))throw new L(`Issue filter labels must be nonempty literal names.`);if(t.updatedSince!==void 0&&!hu({offset:!0}).safeParse(t.updatedSince).success)throw new L(`updatedSince must be an ISO timestamp.`);let i,a;if(t.query!==void 0){let o=[`repo:${e.repo.owner}/${e.repo.repo}`,`is:issue`,JSON.stringify(t.query.trim()),...t.state===void 0||t.state===`all`?[]:[`is:${t.state}`],...(t.labels??[]).map(e=>`label:${JSON.stringify(e)}`),...t.updatedSince===void 0?[]:[`updated:>=${t.updatedSince}`]].join(` `),s=(await e.clients.rest.search.issuesAndPullRequests({q:o,page:n,per_page:r,sort:`updated`,order:`desc`,headers:{"X-GitHub-Api-Version":Nh}})).data;if(s.incomplete_results)throw new L(`GitHub issue search returned incomplete results; narrow the query.`);if(s.total_count>1e3)throw new L(`GitHub issue search exceeds its 1000-result window; narrow the query.`);i=s.items,a=n*r<s.total_count?n+1:null}else i=(await e.clients.rest.issues.listForRepo({...e.repo,state:t.state??`open`,...t.labels===void 0?{}:{labels:t.labels.join(`,`)},...t.updatedSince===void 0?{}:{since:t.updatedSince},page:n,per_page:r,sort:`updated`,direction:`desc`,headers:{"X-GitHub-Api-Version":Nh}})).data,a=i.length===r?n+1:null;let o=M(j_).parse(await P_(e,`GET /orgs/{org}/issue-fields`,{org:e.config.native.organization}));if(new Set(o.map(e=>e.name)).size!==o.length||new Set(o.map(e=>e.id)).size!==o.length)throw new L(`Native issue field catalog has duplicate identities or names.`);let s=[],c=new Set;for(let n of i){if(typeof n==`object`&&n&&`pull_request`in n)continue;let r=N_.parse(n);if(c.has(r.number))throw new L(`GitHub issue page repeats an issue.`);if(c.add(r.number),new URL(r.html_url).pathname.toLowerCase()!==`/${e.repo.owner}/${e.repo.repo}/issues/${String(r.number)}`.toLowerCase())throw new L(`GitHub issue list returned a foreign repository issue.`);let i=r.labels.map(e=>typeof e==`string`?e:e.name);if(t.state!==void 0&&t.state!==`all`&&r.state!==t.state||(t.labels??[]).some(e=>!i.some(t=>t.toLowerCase()===e.toLowerCase()))||t.issueType!==void 0&&r.type?.name!==t.issueType||t.updatedSince!==void 0&&Date.parse(r.updated_at)<Date.parse(t.updatedSince))continue;let a=await Hg({graphql:e.clients.graphql,issueNumber:r.number,repo:e.repo,requireRepositoryIdentity:!0}),l=a.parentRepository?.toLowerCase()===`${e.repo.owner}/${e.repo.repo}`.toLowerCase()?a.parentNumber:null;if(t.parentIssueNumber!==void 0&&(t.parentIssueNumber===null?a.parentNumber!==null:l!==t.parentIssueNumber))continue;let u=await Sm({graphql:e.clients.graphql,issueNodeId:r.node_id,org:e.config.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tm(e.config)});if(t.projectStatus!==void 0&&(u?.status??null)!==t.projectStatus)continue;let d=Object.fromEntries(o.map(e=>[e.name,null])),f=M(M_).parse(await P_(e,`GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values`,{...e.repo,issue_number:r.number})),p=new Set;for(let e of f){let t=o.find(t=>t.id===e.issue_field_id);if(!t||t.name!==e.issue_field_name||t.data_type!==e.data_type||p.has(e.issue_field_id))throw new L(`Native issue field readback conflicts with its catalog.`);if(p.add(e.issue_field_id),(e.data_type===`single_select`&&!e.single_select_option||e.data_type===`multi_select`&&e.multi_select_options===void 0)&&e.value!==null&&e.value!==void 0)throw new L(`Native select field omitted its named option readback.`);let n=e.data_type===`single_select`?e.single_select_option?.name??null:e.data_type===`multi_select`?e.multi_select_options?.map(e=>e.name):e.value;if(e.data_type===`date`&&n!=null&&!gu().safeParse(n).success)throw new L(`Native date field has an invalid date value.`);if(n==null)d[t.name]=null;else if(e.data_type===`number`?typeof n==`number`&&Number.isFinite(n):e.data_type===`multi_select`?Array.isArray(n):typeof n==`string`)d[t.name]=n;else throw new L(`Native issue field has an invalid value type.`)}s.push({number:r.number,title:r.title,state:r.state,labels:i,issueType:r.type?.name??null,parentIssueNumber:l,parent:a.parentNumber===null?null:{repository:a.parentRepository,number:a.parentNumber},blockers:a.blockers.map(({number:e,title:t,state:n,repository:r})=>({repository:r,number:e,title:t,state:n})),projectStatus:u?.status??null,fields:d,url:r.html_url,updatedAt:r.updated_at})}return{issues:s,page:n,perPage:r,nextPage:a}}function I_(e,t){let n=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);return`<details>\n<summary>Previous issue title and body</summary>\n\nTitle:\n<pre>${n(e)}</pre>\n\nBody:\n<pre>${n(t)}</pre>\n\n</details>`}async function L_(e,t){let n=N({nameWithOwner:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u)}),r=await e.clients.graphql(`
|
|
244
|
+
`)}`,`**Follow-ups:** ${n.followUps.length?n.followUps.join(`; `):`None.`}`)}r.push(`**Key numbers:** ${n.keyNumbers.length?n.keyNumbers.join(`; `):`None reported.`}`,`**Next:** ${n.nextStep} (${n.nextDate??`date not scheduled`}).`,`**Evidence:** ${n.evidence.length?n.evidence.join(` · `):`None yet.`}`),n.details&&r.push(n.details);let i=n.summary,a=``;for(let e of r)a||i.length+e.length+2>(n.lengthCap??1800)?a+=`\n\n${e}`:i+=`\n\n${e}`;return a&&(i+=`\n\n<details>\n<summary>Additional journal detail</summary>${a}\n\n</details>`),t===void 0?i:`${i}\n\n${t}`}var S_=65536,C_=F({issueNumber:j().int().positive(),body:A()});async function w_(e,t,n){let r=`body`in t?C_.parse(t):b_.parse(t),i=`body`in r?r.body:void 0;if(i!==void 0&&n!==void 0)throw new R(`Raw issue comments do not accept a lifecycle journal key.`);let a=i===void 0?`<!-- ai-delivery:journal@1:${V({issueNumber:r.issueNumber,key:n??r})} -->`:void 0,o=i??x_(r,a);if(o.length>65536||!o.trim())throw new R(`Issue comment body must contain text and fit ${String(S_)} UTF-16 code units.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new R(`Issue comments require the authenticated author role.`);let s=(await e.clients.authenticatedAuthor()).actorLogin;if(!s)throw new R(`Issue comment author identity is missing.`);return(async()=>{let r=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber)throw new R(`Issue comment target is not the requested issue.`);let i=[];for(let n=1;n<=20;n+=1){let r=(await e.clients.rest.issues.listComments({...e.repo,issue_number:t.issueNumber,page:n,per_page:100})).data;if(i.push(...r.filter(e=>(a===void 0?e.body===o:e.body?.endsWith(a))&&e.user?.login.toLowerCase()===s.toLowerCase())),r.length<100)break;if(n===20)throw new R(`Issue comment history exceeds the bounded readback window.`)}if(i.length>1)throw new R(`Issue comment has duplicate authored retry matches.`);let c=i[0],l=c??(await e.clients.rest.issues.createComment({...e.repo,issue_number:t.issueNumber,body:o})).data,u=(await e.clients.rest.issues.getComment({...e.repo,comment_id:l.id})).data,d=`/repos/${e.repo.owner}/${e.repo.repo}/issues/${String(t.issueNumber)}`;if(!Number.isSafeInteger(u.id)||u.id<=0||u.id!==l.id||u.html_url!==l.html_url||u.body!==(c?.body??o)||n===void 0&&u.body!==o||u.user?.login.toLowerCase()!==s.toLowerCase()||new URL(u.issue_url).pathname.toLowerCase()!==d.toLowerCase()||!u.html_url.startsWith(`https://`))throw new R(`Issue comment readback disagrees with the authored issue comment.`);return{commentId:u.id,url:u.html_url,body:u.body,reused:c!==void 0}})()}async function T_(e,t){let n=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;return w_(e,{issueNumber:t,kind:`start`,summary:`Work started on ${n.title}.`,status:`Started`,outcome:n.title,keyNumbers:[`Issue #${String(t)}`],evidence:[n.html_url],nextStep:`Implement the issue acceptance criteria and run its verification`,nextDate:null},`start:${n.created_at}`)}async function E_(e){let t=await sh(e.repoRoot,{...e.repository===void 0?{}:{repository:e.repository},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}}),n=t.config,[r,i]=n.repository.split(`/`);if(!r||!i)throw new R(`Repository must be owner/name.`);let a={owner:r,repo:i},o=await _m({config:n,identity:e.identity,...e.personalAuth?{personalAuth:{enabled:!0}}:{},role:e.role,...e.signal===void 0?{}:{signal:e.signal}}),s=t.routing;return{clients:o,config:n,configuration:t,projectConfiguration:{projectId:s.projectId,projectNumber:n.native.project.number,title:n.native.project.title,pointsFieldId:s.pointsFieldId,priorityFieldId:s.priorityFieldId,statusFieldId:s.statusFieldId,statusOptionIds:s.statusOptionIds,settings:wm(n),writable:!0},repo:a,root:``}}async function D_(e,t){let n=t??[];if(n.some(e=>!e.trim())||new Set(n.map(e=>e.toLowerCase())).size!==n.length)throw new R(`Issue labels must be non-empty and unique.`);if(n.length===0)return[];let r=new Set;for(let t=1;t<=100;t++){let i=(await e.clients.rest.issues.listLabelsForRepo({...e.repo,page:t,per_page:100})).data;for(let e of i)r.add(e.name.toLowerCase());if(i.length<100){let e=n.filter(e=>!r.has(e.toLowerCase()));if(e.length)throw new R(`Unknown repository label(s): ${e.join(`, `)}.`);return[...n]}}throw new R(`Repository label listing exceeds the bounded readback window.`)}var O_=class extends R{created;constructor(e,t){super(`Issue #${e.number} was created but native tracking did not complete: ${String(t)}. Resume this known issue; do not create another.`),this.created=e}};async function k_(e,t){if(!t.title.trim())throw new R(`Issue title is required.`);if(t.issueType!==void 0&&!e.config.native.issueTypes.includes(t.issueType))throw new R(`Unsupported configured Issue Type.`);if(t.points!==void 0&&!e.config.native.points.values.includes(String(t.points)))throw new R(`Unsupported configured Points value.`);if(t.priority!==void 0&&!e.config.native.priority.values.includes(t.priority))throw new R(`Unsupported configured Priority value.`);let{clients:n,config:r,repo:i}=e,a=await Kg({blockers:t.blockedBy??[],...t.parentIssueNumber===void 0?{}:{parentIssueNumber:t.parentIssueNumber},repo:i,rest:n.rest}),o=await n.rest.issues.create({body:t.body??``,labels:await D_(e,t.labels),...t.milestone===void 0?{}:{milestone:t.milestone},owner:i.owner,repo:i.repo,title:t.title,...t.issueType===void 0?{}:{type:t.issueType}}),s=o.data.number;try{(t.points!==void 0||t.priority!==void 0)&&await Bh({issueNumber:s,metadata:{...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority}},org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Nh(r)}),t.parentIssueNumber!==void 0&&await Gg({graphql:n.graphql,issueNumber:s,parentIssueNumber:t.parentIssueNumber,repo:i,rest:n.rest}),t.parentIssueNumber!==void 0&&await Fh({issueNumber:t.parentIssueNumber,org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Nh(r)}),(t.blockedBy?.length??0)>0&&await Wg({blockers:t.blockedBy??[],graphql:n.graphql,issueNumber:s,repo:i,rest:n.rest}),await Em({graphql:n.graphql,issueNodeId:o.data.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:wm(r),status:a.unresolvedBlockers.length>0?`Blocked`:`Todo`})}catch(e){throw new O_({number:s,title:o.data.title,url:o.data.html_url},e)}return{...e.configuration?{routing:e.configuration.routing}:{},body:o.data.body??t.body??``,created:{number:s,title:o.data.title,url:o.data.html_url}}}var A_=P({id:j().int().positive().safe(),name:A().min(1),data_type:I([`text`,`number`,`date`,`single_select`,`multi_select`])}),j_=P({issue_field_id:j().int().positive().safe(),issue_field_name:A().min(1),data_type:A_.shape.data_type,value:wl().optional(),single_select_option:P({name:A().min(1)}).nullable().optional(),multi_select_options:N(P({name:A().min(1)})).optional()}),M_=P({number:j().int().positive().safe(),node_id:A().min(1),title:A(),state:I([`open`,`closed`]),labels:N(jl([A(),P({name:A()})])),type:P({name:A()}).nullable().optional(),html_url:tl(),updated_at:mu({offset:!0})});async function N_(e,t,n){let r=[],i=new Set;for(let a=1;;a+=1){let o=await e.clients.rest.request(t,{...n,headers:{"X-GitHub-Api-Version":Mh},page:a,per_page:100});if(!Array.isArray(o.data))throw new R(`GitHub returned invalid native issue fields.`);let s=V(o.data);if(o.data.length>0&&i.has(s))throw new R(`Native issue fields repeated a pagination page.`);if(i.add(s),r.push(...o.data),o.data.length<100)return r}}async function P_(e,t){let n=t.page??1,r=t.perPage??30;if(!Number.isSafeInteger(n)||n<=0||!Number.isSafeInteger(r)||r<=0||r>100)throw new R(`Issue pagination must use a positive page and perPage from 1 to 100.`);if(t.query!==void 0&&(!t.query.trim()||t.query.length>256||/["\\\r\n]/u.test(t.query)))throw new R(`Issue search requires literal text without quotes, backslashes or newlines.`);if(t.labels?.some(e=>!e||/["\\\r\n]/u.test(e)))throw new R(`Issue filter labels must be nonempty literal names.`);if(t.updatedSince!==void 0&&!mu({offset:!0}).safeParse(t.updatedSince).success)throw new R(`updatedSince must be an ISO timestamp.`);let i,a;if(t.query!==void 0){let o=[`repo:${e.repo.owner}/${e.repo.repo}`,`is:issue`,JSON.stringify(t.query.trim()),...t.state===void 0||t.state===`all`?[]:[`is:${t.state}`],...(t.labels??[]).map(e=>`label:${JSON.stringify(e)}`),...t.updatedSince===void 0?[]:[`updated:>=${t.updatedSince}`]].join(` `),s=(await e.clients.rest.search.issuesAndPullRequests({q:o,page:n,per_page:r,sort:`updated`,order:`desc`,headers:{"X-GitHub-Api-Version":Mh}})).data;if(s.incomplete_results)throw new R(`GitHub issue search returned incomplete results; narrow the query.`);if(s.total_count>1e3)throw new R(`GitHub issue search exceeds its 1000-result window; narrow the query.`);i=s.items,a=n*r<s.total_count?n+1:null}else i=(await e.clients.rest.issues.listForRepo({...e.repo,state:t.state??`open`,...t.labels===void 0?{}:{labels:t.labels.join(`,`)},...t.updatedSince===void 0?{}:{since:t.updatedSince},page:n,per_page:r,sort:`updated`,direction:`desc`,headers:{"X-GitHub-Api-Version":Mh}})).data,a=i.length===r?n+1:null;let o=N(A_).parse(await N_(e,`GET /orgs/{org}/issue-fields`,{org:e.config.native.organization}));if(new Set(o.map(e=>e.name)).size!==o.length||new Set(o.map(e=>e.id)).size!==o.length)throw new R(`Native issue field catalog has duplicate identities or names.`);let s=[],c=new Set;for(let n of i){if(typeof n==`object`&&n&&`pull_request`in n)continue;let r=M_.parse(n);if(c.has(r.number))throw new R(`GitHub issue page repeats an issue.`);if(c.add(r.number),new URL(r.html_url).pathname.toLowerCase()!==`/${e.repo.owner}/${e.repo.repo}/issues/${String(r.number)}`.toLowerCase())throw new R(`GitHub issue list returned a foreign repository issue.`);let i=r.labels.map(e=>typeof e==`string`?e:e.name);if(t.state!==void 0&&t.state!==`all`&&r.state!==t.state||(t.labels??[]).some(e=>!i.some(t=>t.toLowerCase()===e.toLowerCase()))||t.issueType!==void 0&&r.type?.name!==t.issueType||t.updatedSince!==void 0&&Date.parse(r.updated_at)<Date.parse(t.updatedSince))continue;let a=await Vg({graphql:e.clients.graphql,issueNumber:r.number,repo:e.repo,requireRepositoryIdentity:!0}),l=a.parentRepository?.toLowerCase()===`${e.repo.owner}/${e.repo.repo}`.toLowerCase()?a.parentNumber:null;if(t.parentIssueNumber!==void 0&&(t.parentIssueNumber===null?a.parentNumber!==null:l!==t.parentIssueNumber))continue;let u=await xm({graphql:e.clients.graphql,issueNodeId:r.node_id,org:e.config.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:wm(e.config)});if(t.projectStatus!==void 0&&(u?.status??null)!==t.projectStatus)continue;let d=Object.fromEntries(o.map(e=>[e.name,null])),f=N(j_).parse(await N_(e,`GET /repos/{owner}/{repo}/issues/{issue_number}/issue-field-values`,{...e.repo,issue_number:r.number})),p=new Set;for(let e of f){let t=o.find(t=>t.id===e.issue_field_id);if(!t||t.name!==e.issue_field_name||t.data_type!==e.data_type||p.has(e.issue_field_id))throw new R(`Native issue field readback conflicts with its catalog.`);if(p.add(e.issue_field_id),(e.data_type===`single_select`&&!e.single_select_option||e.data_type===`multi_select`&&e.multi_select_options===void 0)&&e.value!==null&&e.value!==void 0)throw new R(`Native select field omitted its named option readback.`);let n=e.data_type===`single_select`?e.single_select_option?.name??null:e.data_type===`multi_select`?e.multi_select_options?.map(e=>e.name):e.value;if(e.data_type===`date`&&n!=null&&!hu().safeParse(n).success)throw new R(`Native date field has an invalid date value.`);if(n==null)d[t.name]=null;else if(e.data_type===`number`?typeof n==`number`&&Number.isFinite(n):e.data_type===`multi_select`?Array.isArray(n):typeof n==`string`)d[t.name]=n;else throw new R(`Native issue field has an invalid value type.`)}s.push({number:r.number,title:r.title,state:r.state,labels:i,issueType:r.type?.name??null,parentIssueNumber:l,parent:a.parentNumber===null?null:{repository:a.parentRepository,number:a.parentNumber},blockers:a.blockers.map(({number:e,title:t,state:n,repository:r})=>({repository:r,number:e,title:t,state:n})),projectStatus:u?.status??null,fields:d,url:r.html_url,updatedAt:r.updated_at})}return{issues:s,page:n,perPage:r,nextPage:a}}function F_(e,t){let n=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);return`<details>\n<summary>Previous issue title and body</summary>\n\nTitle:\n<pre>${n(e)}</pre>\n\nBody:\n<pre>${n(t)}</pre>\n\n</details>`}async function I_(e,t){let n=P({nameWithOwner:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u)}),r=await e.clients.graphql(`
|
|
245
245
|
query IssueClosureReadback($owner: String!, $name: String!, $number: Int!) {
|
|
246
246
|
repository(owner: $owner, name: $name) {
|
|
247
247
|
issue(number: $number) {
|
|
@@ -250,27 +250,27 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
250
250
|
}
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
|
-
`,{owner:e.repo.owner,name:e.repo.repo,number:t}),i=N({repository:N({issue:N({number:j().int().positive().safe(),repository:n,state:F([`OPEN`,`CLOSED`]),stateReason:F([`COMPLETED`,`NOT_PLANNED`,`DUPLICATE`,`REOPENED`]).nullable(),duplicateOf:N({number:j().int().positive().safe(),repository:n}).nullable()})})}).parse(r).repository.issue;if(i.number!==t||i.repository.nameWithOwner.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Native closure readback returned a foreign issue identity.`);if(i.state===`OPEN`&&i.stateReason!==null&&i.stateReason!==`REOPENED`||i.state===`CLOSED`&&i.stateReason===`REOPENED`||i.duplicateOf!==null&&i.stateReason!==`DUPLICATE`)throw new L(`Native closure readback has contradictory state evidence.`);return{state:i.state===`OPEN`?`open`:`closed`,closeReason:i.stateReason===null||i.stateReason===`REOPENED`?null:i.stateReason.toLowerCase(),duplicateOf:i.duplicateOf===null?null:{number:i.duplicateOf.number,repository:i.duplicateOf.repository.nameWithOwner}}}async function R_(e,t){if(t.closeReason!==void 0&&![`completed`,`not_planned`,`duplicate`].includes(t.closeReason)||(t.closeReason!==void 0||t.supersededBy!==void 0)&&t.state!==`closed`)throw new L(`Closure details require state closed and a supported close reason.`);if(t.supersededBy!==void 0&&(!Number.isSafeInteger(t.supersededBy)||t.supersededBy<=0||t.supersededBy===t.issueNumber))throw new L(`A superseding issue must be a different positive issue number.`);let{clients:n,config:r,repo:i}=e,a=t.labels===void 0?void 0:await O_(e,t.labels);if(t.issueType!==void 0&&!r.native.issueTypes.includes(t.issueType))throw new L(`Unsupported configured Issue Type.`);if(t.points!==void 0&&!r.native.points.values.includes(String(t.points)))throw new L(`Unsupported configured Points value.`);if(t.priority!==void 0&&!r.native.priority.values.includes(t.priority))throw new L(`Unsupported configured Priority value.`);if(t.parentIssueNumber!==void 0||t.blockedBy!==void 0){let e=await Hg({graphql:n.graphql,issueNumber:t.issueNumber,repo:i});await qg({blockers:e.blockers.map(e=>e.number),...e.parentNumber===null?{}:{parentIssueNumber:e.parentNumber},repo:i,rest:n.rest}),await qg({blockers:t.blockedBy??[],...t.parentIssueNumber===void 0||t.parentIssueNumber===null?{}:{parentIssueNumber:t.parentIssueNumber},repo:i,rest:n.rest})}let o=t.closeReason??(t.supersededBy===void 0?void 0:`completed`),s;if(t.supersededBy!==void 0){let e=(await n.rest.issues.get({...i,issue_number:t.supersededBy})).data;if(e.number!==t.supersededBy||`pull_request`in e||!Number.isSafeInteger(e.id)||e.id<=0||new URL(e.html_url).pathname.toLowerCase()!==`/${i.owner}/${i.repo}/issues/${String(t.supersededBy)}`.toLowerCase())throw new L(`Superseding issue readback is not the requested repository issue.`);s=e.id}let c=e=>{if(e.state!==`closed`||e.closeReason!==o||o===`duplicate`&&t.supersededBy!==void 0&&(e.duplicateOf?.number!==t.supersededBy||e.duplicateOf.repository.toLowerCase()!==`${i.owner}/${i.repo}`.toLowerCase()))throw new L(`Native closure readback disagrees with the requested reason or superseding issue.`)};if(o!==void 0){let n=await L_(e,t.issueNumber);if(n.state===`closed`)try{c(n)}catch{throw new L(`Issue is already closed with different closure evidence; reopen it explicitly first.`)}}let l,u;if(t.preserveHistory===!0&&(t.title!==void 0||t.body!==void 0)){let r=(await n.rest.issues.get({...i,issue_number:t.issueNumber})).data;if(r.number!==t.issueNumber||`pull_request`in r)throw new L(`History target is not the requested issue.`);let a={title:r.title,body:r.body??``};if(t.title!==void 0&&t.title!==a.title||t.body!==void 0&&t.body!==a.body){let n=I_(a.title,a.body);if(n.length>65536)throw new L(`Complete issue history exceeds the supported comment body limit; issue was not rewritten.`);u=a,l=await T_(e,{issueNumber:t.issueNumber,body:n})}}let d;if(o!==void 0&&(d=await T_(e,{issueNumber:t.issueNumber,body:`Requested closure reason: ${o}.${t.supersededBy===void 0?``:`\nSuperseded by ${i.owner}/${i.repo}#${String(t.supersededBy)}.`}`})),u!==void 0){let e=(await n.rest.issues.get({...i,issue_number:t.issueNumber})).data;if(e.number!==t.issueNumber||`pull_request`in e||e.title!==u.title||(e.body??``)!==u.body)throw new L(`Issue content changed after history readback; retry against the current title and body.`)}await n.rest.issues.update({issue_number:t.issueNumber,owner:i.owner,repo:i.repo,...t.body===void 0?{}:{body:t.body},...t.issueType===void 0?{}:{type:t.issueType},...a===void 0?{}:{labels:a},...t.milestone===void 0?{}:{milestone:t.milestone},...t.state===void 0?{}:{state:t.state},...o===void 0?{}:{state_reason:o,headers:{"X-GitHub-Api-Version":Nh}},...o!==`duplicate`||s===void 0?{}:{duplicate_issue_id:s},...t.title===void 0?{}:{title:t.title}});let f=o===void 0?void 0:await L_(e,t.issueNumber);f!==void 0&&c(f),(t.points!==void 0||t.priority!==void 0)&&await Vh({issueNumber:t.issueNumber,metadata:{...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority}},org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Ph(r)}),t.parentIssueNumber!==void 0&&await Kg({graphql:n.graphql,issueNumber:t.issueNumber,parentIssueNumber:t.parentIssueNumber,repo:i,rest:n.rest}),t.parentIssueNumber!==void 0&&t.parentIssueNumber!==null&&await Ih({issueNumber:t.parentIssueNumber,org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Ph(r)}),t.blockedBy!==void 0&&await Gg({blockers:t.blockedBy,graphql:n.graphql,issueNumber:t.issueNumber,repo:i,rest:n.rest});let p=await B_(e,t.issueNumber),m=p.state===`closed`||p.projectStatus===`Done`?`Done`:p.blockedBy.length>0?`Blocked`:t.park===!0||t.blockedBy!==void 0||p.projectStatus===null?`Todo`:p.projectStatus===`In Progress`||p.projectStatus===`Blocked`&&t.state===void 0?p.projectStatus:`Todo`,h=(await n.rest.issues.get({issue_number:t.issueNumber,...i})).data;await Dm({graphql:n.graphql,issueNodeId:h.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tm(r),status:m});let g=await B_(e,t.issueNumber);if((t.preserveHistory===!0||o!==void 0)&&(t.title!==void 0&&g.title!==t.title||t.body!==void 0&&g.body!==t.body||t.state!==void 0&&g.state!==t.state))throw new L(`Issue update readback disagrees with the requested content or state.`);return{...g,...l===void 0?{}:{historyComment:l},...f===void 0||d===void 0?{}:{closure:{...f,supersededBy:t.supersededBy??null,comment:d}}}}async function z_(e,t){return R_(e,t)}async function B_(e,t){let{clients:n,config:r,repo:i}=e,a=(await n.rest.issues.get({issue_number:t,owner:i.owner,repo:i.repo})).data;if(`pull_request`in a)throw new L(`Requested issue number is a pull request.`);let[o,s,c]=await Promise.all([Rh({issueNumber:t,owner:i.owner,repo:i.repo,rest:n.rest,settings:Ph(r)}),Hg({graphql:n.graphql,issueNumber:t,repo:i}),Sm({graphql:n.graphql,issueNodeId:a.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:Tm(r)})]);return{...e.configuration?{routing:e.configuration.routing}:{},blockedBy:s.blockers.filter(e=>e.state===`OPEN`).map(e=>e.number),body:a.body??``,issueNumber:t,issueType:a.type?.name??null,parentIssueNumber:s.parentNumber,...o.points===void 0?{}:{points:o.points},...o.priority===void 0?{}:{priority:o.priority},projectStatus:c?.status??null,state:a.state,title:a.title,url:a.html_url,worktree:null}}async function V_(e,t){if(`pull_request`in(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data)throw new L(`Requested issue number is a pull request.`);return(await e.clients.rest.paginate(e.clients.rest.issues.listSubIssues,{...e.repo,issue_number:t,per_page:100})).map(e=>e.number).sort((e,t)=>e-t)}async function H_(e,t){let n=await B_(e,t),r=await Ug({issueNumber:t,repo:e.repo,rest:e.clients.rest});return $g({blockedBy:n.blockedBy,body:n.body,...n.points===void 0?{}:{points:n.points},repoRoot:void 0,title:n.title,trackingParent:r})}async function U_(e,t){let n=[],r=new Set,i=null;for(let a=0;a<20;a++){let a=(await e.clients.graphql(`query DeliveryIssueBranches($owner:String!,$repo:String!,$issue:Int!,$cursor:String){repository(owner:$owner,name:$repo){issue(number:$issue){linkedBranches(first:100,after:$cursor){nodes{ref{name target{oid} repository{nameWithOwner}}} pageInfo{hasNextPage endCursor}}}}}`,{owner:e.repo.owner,repo:e.repo.repo,issue:t,cursor:i})).repository?.issue?.linkedBranches;if(!a||!Array.isArray(a.nodes)||typeof a.pageInfo?.hasNextPage!=`boolean`)throw new L(`Incomplete GitHub linked issue branch readback.`);for(let t of a.nodes){let r=t?.ref;if(!r||!r.name||!/^[a-f0-9]{40}$/u.test(r.target.oid)||!r.repository.nameWithOwner)throw new L(`Incomplete GitHub linked branch identity.`);r.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()&&n.push({name:r.name,sha:r.target.oid,repository:r.repository.nameWithOwner})}if(!a.pageInfo.hasNextPage)return n;let o=a.pageInfo.endCursor;if(!o||r.has(o))throw new L(`GitHub linked branch pagination did not advance.`);r.add(o),i=o}throw new L(`GitHub linked issue branches exceed the bounded readback window.`)}async function W_(e,t,n){let r=(await U_(e,t)).filter(e=>n===void 0||e.name===n);if(r.length!==1)throw new L(`Select exactly one GitHub-linked issue branch; no local worktree or receipt fallback is available.`);return r[0].name}async function G_(e,t,n){let r=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(r.number!==t||`pull_request`in r||r.state!==`open`)throw new L(`Start requires the requested open GitHub issue.`);let i=await U_(e,t),a=n??(i.length===1?i[0].name:`issue/${t}`);if(!/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u.test(a)||a.startsWith(`/`)||a.endsWith(`/`)||a.endsWith(`.lock`))throw new L(`Invalid issue branch name.`);let o=i.filter(e=>e.name===a);if(i.length>0&&o.length!==1)throw new L(`Select exactly one existing GitHub-linked issue branch before start.`);if(o.length>1)throw new L(`GitHub issue branch has conflicting linked matches.`);if(o.length===1)return{issueNumber:t,issueUrl:r.html_url,branch:a,headSha:o[0].sha,reused:!0};let s=(await e.clients.rest.repos.get({...e.repo})).data,c=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${s.default_branch}`})).data.object.sha;if(!/^[a-f0-9]{40}$/u.test(c)||!s.node_id)throw new L(`GitHub repository default branch identity is incomplete.`);await e.clients.graphql(`mutation DeliveryStartBranch($input:CreateLinkedBranchInput!){createLinkedBranch(input:$input){linkedBranch{ref{name target{oid}}}}}`,{input:{issueId:r.node_id,repositoryId:s.node_id,oid:c,name:a,clientMutationId:B({repository:e.config.repository,issueNumber:t,name:a,base:c})}});let l=(await U_(e,t)).filter(e=>e.name===a);if(l.length!==1||l[0].sha!==c)throw new L(`Started GitHub branch/link readback disagrees; resume this issue without creating another.`);return{issueNumber:t,issueUrl:r.html_url,branch:a,headSha:c,reused:!1}}function K_(e){Y_(e,448)}function q_(e,t){Z_({directoryMode:511,mode:438,path:e,value:t})}function J_(e,t){Z_({directoryMode:448,mode:384,path:e,value:t})}function Y_(e,t){let r=[],i=e;for(;!n(i);){r.push(i);let e=w(i);if(e===i)break;i=e}for(let e of r.reverse()){try{s(e,{mode:t})}catch(n){if(n.code!==`EEXIST`)throw n;let r=o(e);if(!r.isDirectory()||r.isSymbolicLink()||t===448&&r.mode&63)throw Error(`Concurrent directory creation did not publish a safe directory.`)}X_(w(e))}}function X_(e){let n=c(e,`r`);try{i(n)}finally{t(n)}}function Z_({directoryMode:e,mode:n,path:r,value:a}){let o=w(r);Y_(o,e);let s=T(o,`.${String(process.pid)}.${le()}.tmp`),l,u,d;try{l=c(s,`wx`,n),t(l),l=void 0,y(s,`${JSON.stringify(a,null,2)}\n`,`utf8`),u=c(s,`r`),i(u),t(u),u=void 0,m(s,r),d=c(o,`r`),i(d),t(d),d=void 0}catch(e){l!==void 0&&t(l),u!==void 0&&t(u),d!==void 0&&t(d);try{v(s)}catch{}throw e}}var Q_=A().regex(/^[a-f0-9]{40}$/u),$_=A().regex(/^sha256:[a-f0-9]{64}$/u),ev=N({artifactId:$_,authorIdentity:A().min(1),checks:M(A().min(1)).min(1),diffScopeHash:$_,deliveryMetrics:N({blockerTimeMs:j().int().nonnegative().nullable(),reviewRound:j().int().positive()}).strict().optional(),elapsedMs:j().int().nonnegative(),findings:M(A()),head:N({sha:Q_,tree:Q_}).strict(),issueNumber:j().int().positive(),prNumber:j().int().positive().nullable(),readOnly:I(!0),requestedEffort:A().min(1),requestedModel:A().min(1),effectiveEffort:A().min(1),effectiveModel:A().min(1),reviewerIdentity:A().min(1),schemaVersion:I(`ai-delivery.review-artifact@1`),summary:A().min(1),verdict:F([`approve`,`request-changes`])}).strict().superRefine((e,t)=>{let{artifactId:n,...r}=e;(n!==B(r)||e.authorIdentity===e.reviewerIdentity)&&t.addIssue({code:`custom`,message:`Review artifact identity or role separation is invalid.`})});N({artifact:ev,completedAt:hu(),githubReviewId:j().int().positive(),githubReviewUrl:tl(),headSha:Q_,login:A().min(1),prNumber:j().int().positive(),publicationEvidenceId:$_,receiptId:$_,schemaVersion:I(`ai-delivery.review-receipt@1`),state:I(`APPROVED`)}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==B(r)||e.headSha!==e.artifact.head.sha||e.artifact.prNumber!==null&&e.artifact.prNumber!==e.prNumber)&&t.addIssue({code:`custom`,message:`Submitted review receipt is not bound to its artifact.`})});async function tv(e,t,n,r){let i;try{i=await e.clients.graphql(`query DeliveryReviewDecision($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid reviewDecision } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t})}catch{return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is unavailable.`}}let a=i.repository?.pullRequest;if(!a)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; PR decision readback is unavailable.`};if(a.headRefOid!==n)throw new L(`GitHub review decision does not match the exact PR head.`);let o=null;if(r)try{let i=await e.clients.graphql(`query DeliveryReviewAccess($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviews(last: 100) { nodes { fullDatabaseId author { login } authorCanPushToRepository commit { oid } state } } } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t}),a=r.login.toLowerCase().replace(/\[bot\]$/u,``),s=i.repository?.pullRequest?.reviews.nodes.find(e=>e!==null&&String(e.fullDatabaseId)===String(r.id)&&e.author?.login.toLowerCase().replace(/\[bot\]$/u,``)===a&&e.commit?.oid===n&&e.state===`APPROVED`);typeof s?.authorCanPushToRepository==`boolean`&&(o=s.authorCanPushToRepository)}catch{}return a.reviewDecision===`APPROVED`?{reviewDecision:`APPROVED`,submittedReviewAuthorCanPushToRepository:o,status:`satisfied`,nextAction:`Continue only after required checks pass.`}:a.reviewDecision===`REVIEW_REQUIRED`?{reviewDecision:`REVIEW_REQUIRED`,submittedReviewAuthorCanPushToRepository:o,status:`still-required`,nextAction:o===!1?`GitHub still requires a qualifying approval; the submitted reviewer App review has no repository write access. Inspect the active rule and the App installation Contents grant, then obtain approval from an eligible independent reviewer.`:`GitHub still requires a qualifying approval. Inspect the active rule and obtain approval from an eligible independent reviewer; do not change actors or protections automatically.`}:a.reviewDecision===`CHANGES_REQUESTED`?{reviewDecision:`CHANGES_REQUESTED`,submittedReviewAuthorCanPushToRepository:o,status:`changes-requested`,nextAction:`Resolve the blocking review and obtain a fresh exact-head independent approval.`}:{reviewDecision:null,submittedReviewAuthorCanPushToRepository:o,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; no required-review decision was exposed.`}}function nv(e){let t=typeof e==`string`?JSON.parse(e):e;return ev.parse(t)}function rv(e){try{if(typeof e!=`string`||Buffer.byteLength(e,`utf8`)>65536)throw Error(`Invalid size.`);let t=e.match(/<!-- ai-delivery-review-artifact:[\s\S]*?-->/gu)??[],n=e.match(/<!-- ai-delivery-review-artifact-data:[\s\S]*?-->/gu)??[];if(t.length!==1||n.length!==1)throw Error(`Ambiguous binding.`);let r=t[0].match(/^<!-- ai-delivery-review-artifact: (sha256:[a-f0-9]{64}) -->$/u)?.[1],i=n[0].match(/^<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->$/u)?.[1];if(!r||!i)throw Error(`Invalid binding.`);let a=Buffer.from(i,`base64url`),o=a.toString(`utf8`);if(a.toString(`base64url`)!==i||!Buffer.from(o,`utf8`).equals(a))throw Error(`Invalid encoding.`);let s=nv(o);if(s.artifactId!==r)throw Error(`Artifact identity differs.`);return s}catch{throw new L(`GitHub review artifact binding is missing, invalid or ambiguous; obtain a fresh review.`)}}function iv(e){ev.parse(e);let t=`${e.summary}\n\n<!-- ai-delivery-review-artifact: ${e.artifactId} -->\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(e)).toString(`base64url`)} -->`;return rv(t),t}async function av(e,t,n){let r=[];for(let n=1;n<=30;n++){let i=(await e.clients.rest.pulls.listFiles({...e.repo,pull_number:t,page:n,per_page:100})).data;if(r.push(...i.map(e=>e.filename)),i.length<100)break}if(!Number.isSafeInteger(n)||r.length!==n||new Set(r).size!==r.length)throw new L(`Independent review scope is incomplete or differs from the remote PR diff.`);return B(r.sort())}async function ov(e,t){let n=[];for(let r=1;r<=20;r+=1){let i=await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,per_page:100,page:r});if(n.push(...i.data),i.data.length<100)return n}throw new L(`Review history exceeds the bounded readback window.`)}async function sv(e){let{artifact:t,context:n,issueNumber:r,prNumber:i}=e;if(ev.parse(t),t.verdict!==`approve`||t.issueNumber!==r||t.authorIdentity!==n.config.roles.author.identity||t.reviewerIdentity!==n.config.roles.reviewer.identity||t.prNumber!==null&&t.prNumber!==i)throw new L(`Independent review artifact is foreign or rejected.`);if(n.clients.authSource!==`app`||n.clients.role!==`reviewer`||!n.clients.appActorLogin)throw new L(`Formal review requires the independent reviewer GitHub App role.`);let a=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(a.number!==i||a.head.sha!==t.head.sha||a.state!==`open`||a.base.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase()||a.head.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase())throw new L(`PR identity or head changed before formal review.`);let o=await n.clients.appActorLogin();if(!o||!a.user?.login||o.toLowerCase()===a.user.login.toLowerCase())throw new L(`Reviewer GitHub actor must differ from PR author.`);let s=(await n.clients.rest.git.getCommit({...n.repo,commit_sha:t.head.sha})).data;if(s.sha!==t.head.sha||s.tree.sha!==t.head.tree)throw new L(`Independent review tree differs from the remote commit.`);if(t.diffScopeHash!==await av(n,i,a.changed_files))throw new L(`Independent review scope is incomplete or differs from the remote PR diff.`);let c=iv(t),l=`<!-- ai-delivery-review-artifact: ${t.artifactId} -->`,u=await ov(n,i);if(u.some(e=>e.user?.login.toLowerCase()===o.toLowerCase()&&e.commit_id===t.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``)&&!e.body?.includes(l)))throw new L(`Another independent artifact conflicts with the existing exact-head App approval.`);let d=u.filter(e=>e.body?.includes(l));if(d.length>1)throw new L(`Conflicting GitHub reviews claim the same artifact identity.`);let f=d[0];if(f&&(f.state!==`APPROVED`||f.commit_id!==t.head.sha||f.user?.login.toLowerCase()!==o.toLowerCase()||!f.html_url||rv(f.body).artifactId!==t.artifactId))throw new L(`Prior GitHub review marker conflicts with exact-head approval.`);let p=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(p.head.sha!==t.head.sha||p.base.sha!==a.base.sha||p.state!==`open`)throw new L(`PR moved during independent review validation.`);if(e.dryRun)return{dryRun:!0,artifactId:t.artifactId,headSha:t.head.sha};let m=f??(await n.clients.rest.pulls.createReview({...n.repo,pull_number:i,commit_id:t.head.sha,body:c,event:`APPROVE`})).data;if(!m.id||m.state!==`APPROVED`||m.commit_id!==t.head.sha||m.user?.login.toLowerCase()!==o.toLowerCase()||!m.html_url)throw new L(`GitHub did not return complete exact-head independent approval.`);let h={artifact:t,repository:n.config.repository,baseSha:a.base.sha,headSha:t.head.sha,githubReviewId:m.id,githubReviewUrl:m.html_url,login:m.user.login,prNumber:i,schemaVersion:`ai-delivery.github-review@1`,state:`APPROVED`},g={...h,receiptId:B(h)},_=(await n.clients.rest.pulls.getReview({...n.repo,pull_number:i,review_id:m.id})).data;if(_.id!==g.githubReviewId||_.html_url!==g.githubReviewUrl||_.state!==`APPROVED`||_.commit_id!==g.headSha||_.user?.login!==g.login||rv(_.body).artifactId!==t.artifactId)throw new L(`GitHub exact-head App review readback disagrees.`);let v=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(v.head.sha!==t.head.sha||v.base.sha!==a.base.sha||v.state!==`open`)throw new L(`PR moved during independent review submission; approval is not current.`);return g}var cv=/^[a-f0-9]{40}$/u,lv=/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u;function uv(e){return typeof e==`string`&&cv.test(e)}function dv(e){if(!lv.test(e)||e.startsWith(`/`)||e.endsWith(`/`)||e.endsWith(`.lock`))throw new L(`Invalid GitHub branch name.`)}async function fv(e,t){if(e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Configured and selected GitHub repository identities disagree.`);let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data;if(n.number!==t||n.base.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||n.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!uv(n.head.sha))throw new L(`GitHub PR identity or exact head readback is invalid.`);return n}async function pv(e,t,n){let r=null,i=new Set,a=0;for(let o=0;o<20;o++){let o=(await e.clients.graphql(`query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){pullRequest(number:$number){closingIssuesReferences(first:100,after:$cursor){nodes{number repository{nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:r})).repository?.pullRequest?.closingIssuesReferences;if(!o||!Array.isArray(o.nodes)||typeof o.pageInfo?.hasNextPage!=`boolean`)throw new L(`Incomplete merged GitHub PR issue association readback.`);for(let t of o.nodes){if(!t||!Number.isSafeInteger(t.number)||t.number<=0||!t.repository?.nameWithOwner)throw new L(`Incomplete merged PR issue identity.`);t.number===n&&t.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()&&a++}if(!o.pageInfo.hasNextPage){if(a!==1)throw new L(`Merged GitHub PR does not identify the intended issue; issue remains open.`);return}let s=o.pageInfo.endCursor;if(!s||i.has(s))throw new L(`Merged PR issue pagination did not advance.`);i.add(s),r=s}throw new L(`Merged PR issue association exceeds the bounded readback window.`)}async function mv(e,t,n){let r=[];for(let i=1;i<=20;i++){let a=(await e.clients.rest.pulls.list({...e.repo,head:`${e.repo.owner}:${t}`,...n===void 0?{}:{base:n},state:`all`,page:i,per_page:100})).data;if(r.push(...a),a.length<100)return r}throw new L(`GitHub PR match history exceeds the bounded readback window.`)}async function hv(e,t,n){let r=await fv(e,n);if(await pv(e,n,t),!r.merged){let n=await W_(e,t,r.head.ref);if(r.head.ref!==n)throw new L(`GitHub PR is not linked to the requested issue branch.`)}return r}async function gv(e,t){let n=t.prNumber;if(n===void 0){if(t.issueNumber===void 0)throw new L(`prNumber or issueNumber is required.`);let r=await mv(e,await W_(e,t.issueNumber));if(r.length!==1)throw new L(`Select an explicit PR number when the remote issue branch has zero or multiple PRs.`);n=r[0].number}let r=await fv(e,n);return{prNumber:r.number,url:r.html_url,state:r.state,draft:r.draft,headSha:r.head.sha,headBranch:r.head.ref,baseBranch:r.base.ref,merged:r.merged}}async function _v(e,t=`open`){return{schemaVersion:`ai-delivery.pr-list@1`,pullRequests:(await e.clients.rest.paginate(e.clients.rest.pulls.list,{...e.repo,state:t,per_page:100})).map(e=>({number:e.number,state:e.state,draft:e.draft??!1,headSha:e.head.sha,baseSha:e.base.sha,url:e.html_url}))}}async function vv(e,t){let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data,[r,i,a]=await Promise.all([e.clients.rest.checks.listForRef({...e.repo,ref:n.head.sha,per_page:100}),e.clients.rest.repos.getCombinedStatusForRef({...e.repo,ref:n.head.sha}),tv(e,t,n.head.sha)]);return{schemaVersion:`ai-delivery.pr-checks@1`,prNumber:n.number,headSha:n.head.sha,combinedStatus:i.data.state,reviewState:a,checkRuns:r.data.check_runs.map(e=>({name:e.name,status:e.status,conclusion:e.conclusion}))}}function yv(e){if(typeof e!=`object`||!e)return null;let t=e.required_approving_review_count;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:null}async function bv(e,t,n,r=`publication`,i){if(t===void 0)try{t=(await e.clients.rest.repos.get({...e.repo})).data.default_branch}catch{throw new L(`Author cannot read the selected GitHub repository; verify configured access.`)}let a=async()=>{await i?.checkResources(),i?.signal.throwIfAborted()};await a();let o=e.config.roles.author.authSource??`app`,s=r===`development`&&o===`app`&&e.clients.authSource===`personal`;if(e.clients.authSource!==o&&!s)throw new L(r===`publication`?`PR publication requires the configured author credential; configure the personal author role for personal publication.`:`Development access preflight requires the configured author credential or the explicit personal author override.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new L(`Delivery access preflight requires authenticated author identity readback.`);let c=await e.clients.authenticatedAuthor(i?.signal);if(await a(),!c.actorLogin||!c.credentialIdentity)throw new L(`Author GitHub identity readback is incomplete.`);let l=n??e.reviewerClients??await vm({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients,...i===void 0?{}:{signal:i.signal}});if(await a(),l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new L(`Configured reviewer GitHub App identity is unavailable.`);let u=await l.appActorLogin(i?.signal);if(await a(),!u)throw new L(`Reviewer GitHub App actor lookup is incomplete.`);if(c.actorLogin.toLowerCase()===u.toLowerCase())throw new L(`Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.`);try{let t=(await l.rest.repos.get({...e.repo,...i===void 0?{}:{request:{signal:i.signal}}})).data;if(await a(),t.full_name.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new L(`Reviewer GitHub App repository readback disagrees with the selected checkout.`)}catch(e){throw e instanceof L?e:new L(`Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`)}let[d,f]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}/rules/branches/{branch}`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}}),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}/protection`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}})]);await a();let p=[];if(d.status===`fulfilled`&&Array.isArray(d.value.data)){for(let e of d.value.data)if(e.type===`pull_request`){let t=yv(e.parameters);t!==null&&p.push(t)}}if(f.status===`fulfilled`){let e=f.value.data,t=yv(e.required_pull_request_reviews);t!==null&&p.push(t)}let m=Number(d.status===`fulfilled`)+Number(f.status===`fulfilled`),h=m===2?`complete`:m===1?`partial`:`unknown`,g=p.length>0?Math.max(...p):null,_=g!==null&&g>0&&l.effectiveContentsPermission===`read`;return{author:{actorLogin:c.actorLogin,authSource:e.clients.authSource,credentialSource:e.clients.credentialSource??`unreported`,identity:s?`personal`:e.config.roles.author.identity},reviewer:{actorLogin:u,credentialSource:l.credentialSource??`unreported`,effectiveContentsPermission:l.effectiveContentsPermission??`unknown`,identity:e.config.roles.reviewer.identity,repositoryAccess:`readable`},rules:{observedRequiredApprovals:g,visibility:h},approvalEligibility:_?`insufficient-permission`:`unknown`,nextAction:_?`The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.`:h===`complete`&&g===null?`No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.`:h===`complete`?`Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.`:`Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.`}}async function xv(e,t){let n=await W_(e,t.issueNumber,t.headBranch);if(t.headBranch!==void 0&&t.headBranch!==n)throw new L(`Requested PR branch differs from the GitHub-linked issue branch.`);dv(n);let r=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber||r.state!==`open`)throw new L(`PR creation requires the requested open GitHub issue.`);let i=(await e.clients.rest.repos.get({...e.repo})).data.default_branch,a=t.baseBranch??i;if(a!==i)throw new L(`PR delivery requires the repository default branch for durable issue association.`);dv(a);let o=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${n}`})).data;if(!uv(o.object.sha))throw new L(`Remote issue branch head is invalid.`);let s=t.body??`Closes #${t.issueNumber}`;if(!s.trim())throw new L(`PR body must contain text.`);let c=RegExp(`(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\s+#${t.issueNumber}(?![0-9])`,`iu`).test(s)?s:`${s}\n\nCloses #${t.issueNumber}`,l=await mv(e,n,a);if(l.length>1)throw new L(`Remote issue branch has conflicting PR matches.`);let u=l[0]===void 0?void 0:await fv(e,l[0].number);if(u&&(u.head.sha!==o.object.sha||u.head.ref!==n||u.base.ref!==a||u.state!==`open`||t.body!==void 0&&u.body!==c||t.title!==void 0&&u.title!==t.title))throw new L(`Existing remote PR conflicts with the requested branch, intent or state.`);let d=await bv(e,a);if(u&&u.user?.login.toLowerCase()!==d.author.actorLogin.toLowerCase())throw new L(`Existing PR author differs from the configured authenticated author.`);if(u&&await pv(e,u.number,t.issueNumber),t.dryRun)return{dryRun:!0,headSha:o.object.sha,headBranch:n,baseBranch:a,reviewRoute:d};if(u){if(t.draft===!1&&u.draft&&(await e.clients.graphql(`mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}`,{id:u.node_id}),u=await fv(e,u.number),u.draft))throw new L(`PR promotion readback is still draft.`)}else u=(await e.clients.rest.pulls.create({...e.repo,head:n,base:a,title:t.title??r.title,body:c,draft:t.draft!==!1})).data,u=await fv(e,u.number);if(u.head.sha!==o.object.sha||u.head.ref!==n||u.base.ref!==a)throw new L(`GitHub PR creation readback drifted.`);if(u.user?.login.toLowerCase()!==d.author.actorLogin.toLowerCase())throw new L(`Published PR author differs from the configured authenticated author.`);return await pv(e,u.number,t.issueNumber),{prNumber:u.number,url:u.html_url,headSha:u.head.sha,draft:u.draft,reviewRoute:d}}async function Sv(e,t){return await hv(e,t.issueNumber,t.prNumber),sv({context:e,artifact:nv(t.artifact),issueNumber:t.issueNumber,prNumber:t.prNumber,...t.dryRun===void 0?{}:{dryRun:t.dryRun}})}async function Cv(e,t){let n=[];for(let r=1;r<=20;r++){let i=(await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,page:r,per_page:100})).data;if(n.push(...i),i.length<100)return n}throw new L(`GitHub review history exceeds the bounded readback window.`)}async function wv(e,t){if(e.clients.role!==`author`||e.clients.authSource!==(e.config.roles.author.authSource??`app`)||!e.clients.authenticatedAuthor)throw new L(`Merge and finish require the configured authenticated author role.`);let n=await e.clients.authenticatedAuthor();if(!n.actorLogin||!n.credentialIdentity)throw new L(`Author identity readback is incomplete.`);let r=await hv(e,t.issueNumber,t.prNumber);if(t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==r.head.sha)throw new L(`Requested reviewed head differs from the GitHub PR.`);if(r.merged&&r.state===`closed`&&uv(r.merge_commit_sha))return{mergeSha:r.merge_commit_sha,headSha:r.head.sha,reused:!0};if((await bv(e,r.base.ref)).approvalEligibility===`insufficient-permission`)throw new L(`Configured reviewer App is ineligible for the required approval.`);if(r.state!==`open`||r.draft)throw new L(`GitHub PR must be open and ready for merge.`);let i=e.reviewerClients??await vm({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(i.role!==`reviewer`||i.authSource!==`app`||!i.appActorLogin)throw new L(`Independent reviewer App route is unavailable.`);let a=await i.appActorLogin();if(!r.user?.login||a.toLowerCase()===r.user.login.toLowerCase())throw new L(`Reviewer App must differ from the PR author.`);let o=(await Cv(e,t.prNumber)).filter(e=>e.user?.login.toLowerCase()===a.toLowerCase()&&e.commit_id===r.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``));if(o.length!==1)throw new L(`GitHub requires one unambiguous exact-head independent App review.`);let s=o[0],c=(await e.clients.rest.pulls.getReview({...e.repo,pull_number:t.prNumber,review_id:s.id})).data;if(c.id!==s.id||c.state!==`APPROVED`||c.commit_id!==r.head.sha||c.user?.login.toLowerCase()!==a.toLowerCase()||c.body!==s.body)throw new L(`Independent GitHub review readback changed or was dismissed.`);let l=rv(c.body);if(l.verdict!==`approve`||l.issueNumber!==t.issueNumber||l.prNumber!==null&&l.prNumber!==t.prNumber||l.authorIdentity!==e.config.roles.author.identity||l.reviewerIdentity!==e.config.roles.reviewer.identity||l.head.sha!==r.head.sha)throw new L(`Independent review artifact binding is stale, foreign or rejected.`);let u=(await e.clients.rest.git.getCommit({...e.repo,commit_sha:r.head.sha})).data;if(u.sha!==l.head.sha||u.tree.sha!==l.head.tree)throw new L(`Independent review tree differs from the remote commit.`);if(l.diffScopeHash!==await av(e,t.prNumber,r.changed_files))throw new L(`Independent review scope differs from the remote PR diff.`);let d=l.head.sha;if(t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==d)throw new L(`Requested reviewed head differs from the independent GitHub review.`);let f=await tv(e,t.prNumber,d,{id:s.id,login:a});if(f.submittedReviewAuthorCanPushToRepository!==!0)throw new L(`Specific reviewer App approval is not verifiably qualifying for required review.`);if(f.status!==`satisfied`)throw new L(`GitHub review eligibility is ${f.status}: ${f.nextAction}`);if((await Hg({graphql:e.clients.graphql,issueNumber:t.issueNumber,repo:e.repo})).blockers.some(e=>e.state===`OPEN`))throw new L(`GitHub issue has unresolved native blockers.`);if(r=await hv(e,t.issueNumber,t.prNumber),r.head.sha!==d||r.state!==`open`||r.draft||r.mergeable!==!0||r.mergeable_state!==`clean`)throw new L(`GitHub merge eligibility is ${r.mergeable_state??`unknown`}; CLEAN at the reviewed head is required.`);let p=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${r.base.ref}`})).data.object.sha;if(!uv(p)||p!==r.base.sha)throw new L(`GitHub base moved; refresh clean eligibility and independent review before merge.`);if(t.dryRun)return{dryRun:!0,headSha:d,prNumber:r.number};let m=(await e.clients.rest.pulls.merge({...e.repo,pull_number:t.prNumber,sha:d,merge_method:t.strategy??`squash`})).data;if(!m.merged||!uv(m.sha))throw new L(`GitHub refused the reviewed-head merge.`);let h=await hv(e,t.issueNumber,t.prNumber);if(!h.merged||h.state!==`closed`||h.head.sha!==d||h.merge_commit_sha!==m.sha)throw new L(`GitHub merged PR readback disagrees with the reviewed-head mutation.`);return{mergeSha:m.sha,headSha:d,reused:!1}}async function Tv(e,t){let n=await wv(e,t);if(t.dryRun)return n;let r=await hv(e,t.issueNumber,t.prNumber);if(!r.merged||r.state!==`closed`||r.merge_commit_sha!==n.mergeSha)throw new L(`Intended GitHub PR is not verifiably merged; issue remains open.`);let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(i.number!==t.issueNumber||`pull_request`in i)throw new L(`Finish target is not the intended GitHub issue.`);i.state!==`closed`&&await e.clients.rest.issues.update({...e.repo,issue_number:t.issueNumber,state:`closed`,state_reason:`completed`});let a=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(a.number!==t.issueNumber||a.state!==`closed`)throw new L(`GitHub issue closure readback disagrees.`);return{...n,issueClosed:!0}}var Ev=A().regex(/^sha256:[a-f0-9]{64}$/u),Dv=2,Ov=N({admissionId:Ev,capability:N({cli:j().int().positive(),mcp:j().int().positive()}).strict(),cliPath:A().min(1),cliSha256:Ev,configDigest:Ev,mcpLauncherPath:A().min(1),mcpLauncherSha256:Ev,packageDistSha256:Ev,packageManifestSha256:Ev,packageVersion:A().min(1),pluginManifestPath:A().min(1),pluginManifestSha256:Ev,repository:A().min(1),schemaVersion:I(`ai-delivery.runtime-admission@2`),sourceArchiveSha256:Ev,sourceCommit:A().regex(/^[a-f0-9]{40}$/u)}).strict().superRefine((e,t)=>{let{admissionId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Runtime admission identity is invalid.`})});function kv(e){return`sha256:${se(`sha256`).update(l(e)).digest(`hex`)}`}function Av(e){let t=[],n=(e,r)=>{for(let i of d(e,{withFileTypes:!0}).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))){let a=T(e,i.name),o=r?`${r}/${i.name}`:i.name;if(i.isDirectory())n(a,o);else if(i.isFile())t.push({path:o,sha256:kv(a)});else throw new L(`Runtime distribution contains an unsupported link or file type.`)}};if(n(e,``),t.length===0)throw new L(`Runtime distribution is empty.`);return B(t)}function jv(e){let t=JSON.parse(l(e,`utf8`));if(typeof t!=`object`||!t||Array.isArray(t))throw new L(`Runtime package or plugin manifest is invalid.`);return t}async function Mv(e){let t=Du(e.repoRoot),n=e.configuration??await ch(t,e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}),r=T(Ou(t),`ai-delivery`,`runtime-admission.json`),i;try{i=Ov.parse(JSON.parse(H(r).toString(`utf8`)))}catch{throw new L(`Missing or invalid private ai-delivery runtime admission; refresh the installed binding before lifecycle mutation.`)}return Nv(i,n,e.runtimeEntryPath)}function Nv(e,t,n){let r=n??process.argv[1];if(!r)throw new L(`Running ai-delivery entry path is unavailable.`);try{let n=p(r),i=p(e.mcpLauncherPath),a=p(e.pluginManifestPath),o=w(n),s=T(w(o),`package.json`),c=jv(s),l=jv(a);if(n!==e.cliPath||i!==e.mcpLauncherPath||a!==e.pluginManifestPath||p(T(w(w(i)),`.claude-plugin`,`plugin.json`))!==a||kv(n)!==e.cliSha256||kv(i)!==e.mcpLauncherSha256||kv(a)!==e.pluginManifestSha256||kv(s)!==e.packageManifestSha256||Av(o)!==e.packageDistSha256||e.configDigest!==t.configDigest||e.repository!==t.config.repository||e.capability.cli!==Dv||e.capability.mcp!==Dv||c.name!==`@aviaratech/ai-delivery`||c.version!==e.packageVersion||l.name!==`ai-delivery`||l.packageVersion!==e.packageVersion||l.deliveryCapabilityVersion!==Dv)throw new L(`Installed CLI/MCP source, capability or repository admission disagrees with the running delivery contract.`)}catch(e){throw e instanceof L?e:new L(`Installed CLI/MCP source or capability readback is unavailable.`)}return e}function Pv(e){for(let t of[e.cliPath,e.mcpLauncherPath,e.pluginManifestPath])if(p(t)!==t)throw new L(`Installed runtime paths must be canonical regular files.`);let t=w(e.cliPath),n=T(w(t),`package.json`),r=jv(n).bin;if(typeof r!=`object`||!r||!(`ai-delivery`in r)||r[`ai-delivery`]!==`./dist/cli.js`)throw new L(`Installed package CLI entry is not the supported ai-delivery executable.`);let i={capability:{cli:Dv,mcp:Dv},cliPath:e.cliPath,cliSha256:kv(e.cliPath),configDigest:e.configuration.configDigest,mcpLauncherPath:e.mcpLauncherPath,mcpLauncherSha256:kv(e.mcpLauncherPath),packageDistSha256:Av(t),packageManifestSha256:kv(n),packageVersion:e.packageVersion,pluginManifestPath:e.pluginManifestPath,pluginManifestSha256:kv(e.pluginManifestPath),repository:e.configuration.config.repository,schemaVersion:`ai-delivery.runtime-admission@2`,sourceArchiveSha256:e.sourceArchiveSha256,sourceCommit:e.sourceCommit};return Nv(Ov.parse({...i,admissionId:B(i)}),e.configuration,e.cliPath)}var Fv=D(((e,t)=>{var n=De(`constants`),r=process.cwd,i=null,a=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return i||=r.call(process),i};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var o=process.chdir;process.chdir=function(e){i=null,o.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,o)}t.exports=s;function s(e){n.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),a===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,r,i){e.open(t,n.O_WRONLY|n.O_SYMLINK,r,function(t,n){if(t){i&&i(t);return}e.fchmod(n,r,function(t){e.close(n,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,r){var i=e.openSync(t,n.O_WRONLY|n.O_SYMLINK,r),a=!0,o;try{o=e.fchmodSync(i,r),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function r(e){n.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,r,i,a){e.open(t,n.O_SYMLINK,function(t,n){if(t){a&&a(t);return}e.futimes(n,r,i,function(t){e.close(n,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,r,i){var a=e.openSync(t,n.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,r,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function o(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!(e&&e.code!==`ENOSYS`&&(process.getuid&&process.getuid()===0||e.code!==`EINVAL`&&e.code!==`EPERM`))}}})),Iv=D(((e,t)=>{var n=De(`stream`).Stream;t.exports=r;function r(e){return{ReadStream:t,WriteStream:r};function t(r,i){if(!(this instanceof t))return new t(r,i);n.call(this);var a=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function r(t,i){if(!(this instanceof r))return new r(t,i);n.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),Lv=D(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),Rv=D(((e,t)=>{var n=De(`fs`),r=Fv(),i=Iv(),a=Lv(),o=De(`util`),s,c;typeof Symbol==`function`&&typeof Symbol.for==`function`?(s=Symbol.for(`graceful-fs.queue`),c=Symbol.for(`graceful-fs.previous`)):(s=`___graceful-fs.queue`,c=`___graceful-fs.previous`);function l(){}function u(e,t){Object.defineProperty(e,s,{get:function(){return t}})}var d=l;o.debuglog?d=o.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(d=function(){var e=o.format.apply(o,arguments);e=`GFS4: `+e.split(/\n/).join(`
|
|
254
|
-
GFS4: `),console.error(e)}),n[s]||(u(n,global[s]||[]),n.close=(function(e){function t(t,r){return e.call(n,t,function(e){e||h(),typeof r==`function`&&r.apply(this,arguments)})}return Object.defineProperty(t,c,{value:e}),t})(n.close),n.closeSync=(function(e){function t(t){e.apply(n,arguments),h()}return Object.defineProperty(t,c,{value:e}),t})(n.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){d(n[s]),De(`assert`).equal(n[s].length,0)})),global[s]||u(global,n[s]),t.exports=f(a(n)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!n.__patched&&(t.exports=f(n),n.__patched=!0);function f(e){r(e),e.gracefulify=f,e.createReadStream=ee,e.createWriteStream=T;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?p([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var a=e.writeFile;e.writeFile=o;function o(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,o){return a(e,t,n,function(a){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([i,[e,t,n,r],a,o||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var m=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=m.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=i(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;ne(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;ne(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ee(t,n){return new e.ReadStream(t,n)}function T(t,n){return new e.WriteStream(t,n)}var te=e.open;e.open=ne;function ne(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return te(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function p(e){d(`ENQUEUE`,e[0].name,e[1]),n[s].push(e),g()}var m;function h(){for(var e=Date.now(),t=0;t<n[s].length;++t)n[s][t].length>2&&(n[s][t][3]=e,n[s][t][4]=e);g()}function g(){if(clearTimeout(m),m=void 0,n[s].length!==0){var e=n[s].shift(),t=e[0],r=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)d(`RETRY`,t.name,r),t.apply(null,r);else if(Date.now()-a>=6e4){d(`TIMEOUT`,t.name,r);var c=r.pop();typeof c==`function`&&c.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(d(`RETRY`,t.name,r),t.apply(null,r.concat([a]))):n[s].push(e)}m===void 0&&(m=setTimeout(g,0))}}})),zv=D(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),Bv=D((e=>{var t=zv();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),Vv=D(((e,t)=>{t.exports=Bv()})),Hv=D(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),Uv=D(((e,t)=>{var n=global.process,r=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!r(n))t.exports=function(){return function(){}};else{var i=De(`assert`),a=Hv(),o=/^win/i.test(n.platform),s=De(`events`);typeof s!=`function`&&(s=s.EventEmitter);var c;n.__signal_exit_emitter__?c=n.__signal_exit_emitter__:(c=n.__signal_exit_emitter__=new s,c.count=0,c.emitted={}),c.infinite||(c.setMaxListeners(1/0),c.infinite=!0),t.exports=function(e,t){if(!r(global.process))return function(){};i.equal(typeof e,`function`,`a callback must be provided for exit handler`),f===!1&&p();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),c.on(n,e),function(){c.removeListener(n,e),c.listeners(`exit`).length===0&&c.listeners(`afterexit`).length===0&&l()}};var l=function(){f&&r(global.process)&&(f=!1,a.forEach(function(e){try{n.removeListener(e,d[e])}catch{}}),n.emit=g,n.reallyExit=m,--c.count)};t.exports.unload=l;var u=function(e,t,n){c.emitted[e]||(c.emitted[e]=!0,c.emit(e,t,n))},d={};a.forEach(function(e){d[e]=function(){r(global.process)&&n.listeners(e).length===c.count&&(l(),u(`exit`,null,e),u(`afterexit`,null,e),o&&e===`SIGHUP`&&(e=`SIGINT`),n.kill(n.pid,e))}}),t.exports.signals=function(){return a};var f=!1,p=function(){!f&&r(global.process)&&(f=!0,c.count+=1,a=a.filter(function(e){try{return n.on(e,d[e]),!0}catch{return!1}}),n.emit=_,n.reallyExit=h)};t.exports.load=p;var m=n.reallyExit,h=function(e){r(global.process)&&(n.exitCode=e||0,u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),m.call(n,n.exitCode))},g=n.emit,_=function(e,t){if(e===`exit`&&r(global.process)){t!==void 0&&(n.exitCode=t);var i=g.apply(this,arguments);return u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),i}return g.apply(this,arguments)}}})),Wv=D(((e,t)=>{var n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),Gv=D(((e,t)=>{var n=De(`path`),r=Rv(),i=Vv(),a=Uv(),o=Wv(),s={};function c(e,t){return t.lockfilePath||`${e}.lock`}function l(e,t,r){if(!t.realpath)return r(null,n.resolve(e));t.fs.realpath(e,r)}function u(e,t,n){let r=c(e,t);t.fs.mkdir(r,i=>{if(!i)return o.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?u(e,{...t,stale:0},n):n(r);if(!d(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));f(e,t,r=>{if(r)return n(r);u(e,{...t,stale:0},n)})})})}function d(e,t){return e.mtime.getTime()<Date.now()-t.stale}function f(e,t,n){t.fs.rmdir(c(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function p(e,t){let n=s[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return m(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let s=o.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,s,s,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));n.mtime=s,n.lastUpdate=Date.now(),n.updateDelay=null,p(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function m(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),s[e]===t&&delete s[e],t.options.onCompromised(n)}function h(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:r,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),l(e,t,(e,r)=>{if(e)return n(e);let a=i.operation(t.retries);a.attempt(()=>{u(r,t,(e,i,o)=>{if(a.retry(e))return;if(e)return n(a.mainError());let l=s[r]={lockfilePath:c(r,t),mtime:i,mtimePrecision:o,options:t,lastUpdate:Date.now()};p(r,t),n(null,e=>{if(l.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));g(r,{...t,realpath:!1},e)})})})})}function g(e,t,n){t={fs:r,realpath:!0,...t},l(e,t,(e,r)=>{if(e)return n(e);let i=s[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete s[r],f(r,t,n)})}function _(e,t,n){t={stale:1e4,realpath:!0,fs:r,...t},t.stale=Math.max(t.stale||0,2e3),l(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(c(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!d(r,t)))})}function v(){return s}a(()=>{for(let e in s){let t=s[e].options;try{t.fs.rmdirSync(c(e,t))}catch{}}}),t.exports.lock=h,t.exports.unlock=g,t.exports.check=_,t.exports.getLocks=v})),Kv=D(((e,t)=>{var n=Rv();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),qv=Te(D(((e,t)=>{var n=Gv(),{toPromise:r,toSync:i,toSyncOptions:a}=Kv();async function o(e,t){return r(await r(n.lock)(e,t))}function s(e,t){return i(i(n.lock)(e,a(t)))}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1),Jv={realpath:!1,retries:0,stale:1e4},Yv=200;async function Xv(e,{onCompromised:t,onReleaseError:n,onTimeout:r,operation:i,projectRoot:a,timeout:o}){let s=a??process.cwd(),c=E(s,e),l=null,u=typeof o==`number`&&o>0?o:null,d=u===null?null:Math.ceil(u/Yv),f=0,p=u===null?null:Date.now()+u,m=!1;try{for(;;){if(d!==null&&f>=d)throw Error(`Lock acquisition timeout after ${u===null?`unknown`:String(u)}ms on ${c}. Another process may be holding the lock.`);f+=1,Fg(`Acquiring lock on ${c}... (attempt ${d===null?String(f):`${String(f)}/${String(d)}`})`);try{l=await qv.lock(c,{...Jv,...t===void 0?{}:{onCompromised:t}}),Fg(`Lock acquired on ${c}`);break}catch(e){if(!Qv(e))throw e;m||=(Lg(`Unable to acquire lock on ${c} - another agent is modifying it. Retrying...`),!0),p!==null&&u!==null&&Date.now()>=p&&(r?.(),p=Date.now()+u),await Zv(Yv)}}return await i()}finally{if(l!==null)try{await l(),Fg(`Lock released on ${c}`)}catch(e){n?.(e),Fg(`Failed to release lock on ${c}: ${e instanceof Error?e.message:String(e)}`)}}}function Zv(e){return new Promise(t=>setTimeout(t,e))}function Qv(e){return typeof e!=`object`||!e?!1:e.code===`ELOCKED`}var $v=P({bounds:P({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe().optional(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:M(A().min(1)).min(1).optional()}),maxSampledAggregateRssBytes:j().int().nonnegative().safe().nullable(),maxSampledNewOutputBytes:j().int().nonnegative().safe().nullable(),minSampledFreeDiskBytes:j().int().nonnegative().safe().nullable(),observation:I(`sampled`),outputBaselineId:A().regex(/^sha256:[a-f0-9]{64}$/u).optional(),processCoverage:I(`observed-processes-only`),sampleCount:j().int().nonnegative().safe()}).superRefine((e,t)=>{(e.maxSampledAggregateRssBytes!==null&&e.maxSampledAggregateRssBytes>e.bounds.maxAggregateRssBytes||e.maxSampledNewOutputBytes!==null&&e.bounds.maxNewOutputBytes!==void 0&&e.maxSampledNewOutputBytes>e.bounds.maxNewOutputBytes||e.minSampledFreeDiskBytes!==null&&e.minSampledFreeDiskBytes<e.bounds.minFreeDiskBytes||e.sampleCount>0&&(e.maxSampledAggregateRssBytes===null||e.minSampledFreeDiskBytes===null)||e.bounds.maxNewOutputBytes!==void 0&&e.sampleCount>0&&e.maxSampledNewOutputBytes===null||e.bounds.maxNewOutputBytes!==void 0!=(e.outputBaselineId!==void 0))&&t.addIssue({code:`custom`,message:`Resource samples do not satisfy their declared bounds.`})});function ey(e){let t=[[`maxAggregateRssBytes`,e.maxAggregateRssBytes],[`minFreeDiskBytes`,e.minFreeDiskBytes]];e.maxNewOutputBytes!==void 0&&t.push([`maxNewOutputBytes`,e.maxNewOutputBytes]);for(let[e,n]of t)if(!Number.isSafeInteger(n)||n<=0)throw new L(`Invalid ${e} resource bound.`);if(e.maxNewOutputBytes===void 0!=(e.outputRoots===void 0))throw new L(`Filesystem output limit and output roots must be supplied together.`);if(e.outputRoots!==void 0&&(e.outputRoots.length===0||e.outputRoots.some(e=>!e)))throw new L(`Filesystem output roots must be nonempty paths.`);if(process.platform===`win32`)throw new L(`Resource observation requires POSIX process support.`)}var ty=`AI_DELIVERY_OUTPUT_OBSERVATION_GATE`,ny=P({pid:j().int().positive(),identity:A().min(1)}),ry=P({directory:A().min(1),id:$c(),owner:ny}),iy=P({gateId:$c(),id:$c(),kind:F([`scan`,`fixture`]),owner:ny});function ay(){let e=Sy().get(process.pid);if(!e)throw new L(`Filesystem observation gate owner is unavailable.`);return{pid:e.pid,identity:e.identity}}function oy(e){let t=o(e);if(!t.isDirectory()||t.mode&63||p(e)!==e)throw new L(`Filesystem observation gate directory is invalid.`)}function sy(e){try{let t=ry.parse(JSON.parse(e));return ly(t),t}catch(e){throw new L(`Filesystem observation gate capability is invalid or stale: `+(e instanceof Error?e.message:String(e)))}}function cy(e,t=Sy()){let n=t.get(e.pid);return n?.identity===e.identity&&!n.status.startsWith(`Z`)}function ly(e,t=!1){oy(e.directory);let n=ry.parse(JSON.parse(H(T(e.directory,`gate.json`)).toString(`utf8`))),r=Sy(),i=r.get(process.pid),a=new Set;for(;i&&i.pid!==e.owner.pid&&!a.has(i.pid);)a.add(i.pid),i=r.get(i.ppid);if(B(n)!==B(e)||(t?cy(e.owner,r):!cy(e.owner,r)||i?.identity!==e.owner.identity))throw new L(`Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor.`)}function uy(e,t){let n=iy.parse(JSON.parse(H(t).toString(`utf8`)));if(n.gateId!==e.id)throw new L(`Filesystem observation gate claim belongs to another run.`);return n}function dy(e){let t=T(e.directory,`requests`);oy(t);let n=d(t);if(n.length>1024||n.some(e=>!/^[a-f0-9-]{36}\.json$/u.test(e)))throw new L(`Filesystem observation gate scan requests are invalid.`);let r=[],i=Sy();for(let a of n){let n;try{n=uy(e,T(t,a))}catch(e){if(e.code===`ENOENT`)continue;throw e}if(n.kind!==`scan`||a!==n.id+`.json`||!cy(n.owner,i))throw new L(`Filesystem observation gate scan request was abandoned.`);r.push(a)}return r}function fy(e,t,n){if(B(uy(e,t))!==B(n))throw new L(`Filesystem observation gate claim changed before release.`);v(t)}async function py(e,t,r,i){if(!e)return r();ly(e);let a={gateId:e.id,id:le(),kind:t,owner:ay()},c=t===`scan`?T(e.directory,`requests`,a.id+`.json`):void 0,l=T(e.directory,`held`),u=T(l,`owner.json`);if(c){let t=T(e.directory,a.id+`.pending`);J_(t,a),m(t,c)}let f,p,h,_=()=>{if(!f)return;let t=o(l);if(!t.isDirectory()||t.dev!==f.dev||t.ino!==f.ino)throw new L(`Filesystem observation gate lock changed before release.`);if(d(l).join(`,`)!==`owner.json`)throw new L(`Filesystem observation gate lock has unrelated metadata.`);fy(e,u,a),g(l),f=void 0};try{for(;;){if(i?.aborted)throw new L(`Filesystem observation gate wait cancelled.`);ly(e);let c=dy(e);if(t===`scan`||c.length===0){let n=!1;try{s(l,{mode:448}),n=!0}catch(e){if(e.code!==`EEXIST`)throw e}if(n){let n=o(l);if(f={dev:n.dev,ino:n.ino},J_(u,a),t===`scan`||dy(e).length===0)return await r();_()}}if(n(l))try{oy(l);let n=uy(e,u);if(p=void 0,!cy(n.owner))throw new L(`Filesystem observation gate fixture or scanner was abandoned.`);if(t===`scan`&&n.kind===`fixture`){if(h?.claimId!==n.id&&(h={claimId:n.id,since:Date.now()}),Date.now()-h.since>5e3)throw new L(`Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled.`)}else h=void 0}catch(e){if(e.code!==`ENOENT`)throw e;if(p??=Date.now(),Date.now()-p>2e3)throw new L(`Filesystem observation gate owner publication is incomplete.`)}await new Promise(e=>setTimeout(e,100))}}finally{try{_()}finally{c&&fy(e,c,a)}}}function my(e,t=!1){ly(e,t);let r=T(e.directory,`requests`),i=T(e.directory,`held`);if(d(e.directory).some(e=>![`gate.json`,`requests`,`held`].includes(e)))throw new L(`Filesystem observation gate has unrelated or incomplete metadata.`);if(n(i)){if(oy(i),d(i).join(`,`)!==`owner.json`)throw new L(`Filesystem observation gate lock has unrelated metadata.`);let t=uy(e,T(i,`owner.json`));if(cy(t.owner))throw new L(`Filesystem observation gate still has a live holder.`);fy(e,T(i,`owner.json`),t),g(i)}for(let t of d(r)){if(!/^[a-f0-9-]{36}\.json$/u.test(t))throw new L(`Filesystem observation gate has unrelated metadata.`);let n=T(r,t),i=uy(e,n);if(i.kind!==`scan`||t!==i.id+`.json`)throw new L(`Filesystem observation gate has unrelated scan metadata.`);if(cy(i.owner))throw new L(`Filesystem observation gate still has a live scan request.`);fy(e,n,i)}if(g(r),B(JSON.parse(H(T(e.directory,`gate.json`)).toString(`utf8`)))!==B(e))throw new L(`Filesystem observation gate changed before retirement.`);v(T(e.directory,`gate.json`)),g(e.directory)}async function hy(e,t,n){let r=process.env[ty];if(r!==void 0)return n(sy(r));if(!t)return n(void 0);let i=le(),a=T(Ou(e),`ai-delivery`,`output-observation`,Py(e).slice(7));K_(a);for(let e of d(a)){$c().parse(e);let t=T(a,e);oy(t);let n=ry.parse(JSON.parse(H(T(t,`gate.json`)).toString(`utf8`)));if(n.id!==e||n.directory!==t||cy(n.owner))throw new L(`Prior filesystem observation gate is live or has conflicting ownership.`);my(n,!0)}let o=T(a,i);K_(T(o,`requests`));let s={directory:o,id:i,owner:ay()};J_(T(o,`gate.json`),s);try{return await n(s)}finally{my(s)}}var gy=class extends L{cause;code;constructor(e,t,n){let r=n.code;super(`${e} Path ${JSON.stringify(t)} (${r??`unknown errno`}): ${n instanceof Error?n.message:String(n)}`),this.code=r,this.cause=n}};function _y(e,t,r=!1,i){let a=new Map,s=new Map,c=n=>{let l;try{l=o(n)}catch(e){if(e.code===`ENOENT`)return;throw new gy(`Filesystem output lstat failed.`,n,e)}if(l.isSymbolicLink()){let a;try{a=f(n)}catch(e){throw new gy(`Filesystem output readlink failed.`,n,e)}let c=B({device:l.dev,inode:l.ino,changed:l.ctimeMs,modified:l.mtimeMs,link:a}),u,d=!1;try{u=p(n)}catch(e){let s=new gy(`Filesystem output observation encountered a broken or cyclic symbolic link.`,n,e),l=t.get(n);if(l!==void 0&&l.identity!==c)throw new L(`Filesystem output alias identity changed. Path ${JSON.stringify(n)}.`);if(!r||s.code!==`ENOENT`||l?.identity!==c)throw s;let m=E(w(n),a),h=m,g=new Set([n]);for(;;)try{u=T(p(h),m.slice(h.length));break}catch(e){if(e.code!==`ENOENT`||w(h)===h)throw new gy(`Filesystem output ancestor resolution failed.`,h,e);let n;try{n=o(h)}catch(e){if(e.code!==`ENOENT`)throw new gy(`Filesystem output ancestor lstat failed.`,h,e)}if(n?.isSymbolicLink()){let e,r;try{e=f(h),r=o(h)}catch(e){throw new gy(`Filesystem output ancestor alias read failed.`,h,e)}let i=B({device:n.dev,inode:n.ino,changed:n.ctimeMs,modified:n.mtimeMs,link:e}),a=t.get(h);if(a===void 0)throw s;if(g.has(h)||a.identity!==i||!r.isSymbolicLink()||r.dev!==n.dev||r.ino!==n.ino||r.ctimeMs!==n.ctimeMs||r.mtimeMs!==n.mtimeMs)throw new L(`Filesystem output ancestor alias identity changed. Path ${JSON.stringify(h)}.`);g.add(h),m=T(E(w(h),e),m.slice(h.length)),h=m;continue}h=w(h)}if(u!==l.target)throw new L(`Filesystem output alias target identity changed. Path ${JSON.stringify(n)}.`);d=!0,i?.(s.message)}let m=t.get(n);if(m?.missing&&(m.identity!==c||m.target!==u))throw new L(`Filesystem output alias identity changed after target absence. Path ${JSON.stringify(n)}.`);if(!e.some(e=>u===e||u.startsWith(`${e}${re}`)))throw new L(`Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(n)} resolves to ${JSON.stringify(u)}.`);let h;try{h=o(n)}catch(e){if(r&&e.code===`ENOENT`&&m?.identity===c)return;throw new gy(`Filesystem output alias identity readback failed.`,n,e)}if(!h.isSymbolicLink()||h.dev!==l.dev||h.ino!==l.ino||h.ctimeMs!==l.ctimeMs||h.mtimeMs!==l.mtimeMs)throw new L(`Filesystem output alias identity changed during observation. Path ${JSON.stringify(n)}.`);s.set(n,{identity:c,target:u,missing:d});return}if(l.isDirectory()){let e;try{e=d(n)}catch(e){if(e.code===`ENOENT`)return;throw new gy(`Filesystem output readdir failed.`,n,e)}for(let t of e)c(T(n,t));return}if(!l.isFile()&&!l.isSocket()||!Number.isSafeInteger(l.size))throw new L(`Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(n)}.`);if(a.set(n,l.isSocket()?0:l.size),a.size>1e6)throw new L(`Filesystem output observation exceeded its file limit.`)};for(let t of e){if(n(t)&&p(t)!==t)throw new L(`Filesystem output roots must not be symbolic links.`);c(t)}t.clear();for(let[e,n]of s)t.set(e,n);return a}async function vy(e,t,n=!1,r){let i,a,o,s,c=()=>{if(s!==void 0&&Date.now()-s>=1e3)throw new L(`Filesystem output observation remained unavailable for 1 second. First observation: ${a.message} Last observation: ${o.message}`)};for(;;){if(t?.aborted)throw new L(`Filesystem output observation cancelled.`);c();try{i=await py(e.gate,`scan`,()=>_y(e.roots,e.links,n,r),t),c();break}catch(e){if(!n||!(e instanceof gy)||e.code!==`ENOENT`)throw e;o=e,a===void 0&&(s=Date.now(),a=e,r?.(e.message)),c(),await new Promise(e=>setTimeout(e,25))}}let l=0;for(let[t,n]of i)if(l+=Math.max(0,n-(e.files.get(t)??0)),!Number.isSafeInteger(l))throw new L(`Filesystem output observation overflowed.`);return l}function yy(e){let t=e;for(;;)try{let e=_(t,{bigint:!0});return e.bavail*e.bsize}catch(e){if(e.code!==`ENOENT`||w(t)===t)throw e;t=w(t)}}function by(e,t){let n=(t===void 0?[e]:[e,...t.roots]).reduce((e,t)=>{let n=yy(t);return n<e?n:e},BigInt(2**53-1));if(n>BigInt(2**53-1))throw new L(`Free disk observation overflowed.`);return Number(n)}function xy(e,t,n){if(by(e,n)<t.minFreeDiskBytes)throw new L(`Free disk fell below limit ${t.minFreeDiskBytes}.`)}function Sy(){let e=n(`/usr/bin/ps`)?`/usr/bin/ps`:`/bin/ps`,t=S(e,[`-A`,`-o`,`pid=,ppid=,pgid=,rss=,stat=,lstart=`],{encoding:`utf8`,env:{...process.env,LC_ALL:`C`},maxBuffer:4194304,timeout:1e3});if(t.status!==0||t.error||t.signal||!t.stdout.endsWith(`
|
|
255
|
-
`))throw new
|
|
256
|
-
`)){let t=/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(e.trim());if(!t)throw new L(`Owned process resource observation is ambiguous.`);let n={pid:Number(t[1]),ppid:Number(t[2]),pgid:Number(t[3]),rssBytes:Number(t[4])*1024,status:t[5],identity:t[6]};if(!Number.isSafeInteger(n.pid)||n.pid<=0||!Number.isSafeInteger(n.ppid)||!Number.isSafeInteger(n.pgid)||!Number.isSafeInteger(n.rssBytes)||r.has(n.pid))throw new L(`Owned process resource observation is ambiguous.`);r.set(n.pid,n)}return r}function Cy(e,t){let n=t.get(e.rootPid);if(e.rootIdentity===void 0){if(n===void 0||n.status.startsWith(`Z`)||n.pgid!==e.rootPid)throw new L(`Owned process identity could not be established before the command exited.`);e.rootIdentity=n.identity,e.tracked.set(n.pid,n)}else if(n!==void 0&&n.identity!==e.rootIdentity)throw new L(`Owned process identity changed during verification.`);let r=new Map;for(let[n,i]of e.tracked){let a=t.get(n);if(a===void 0||a.status.startsWith(`Z`))e.tracked.delete(n);else if(a.identity!==i.identity)throw new L(`Tracked process identity changed during verification.`);else r.set(n,a)}for(let n of t.values())!n.status.startsWith(`Z`)&&n.pgid===e.rootPid&&r.set(n.pid,n);let i=new Map;for(let e of t.values()){let t=i.get(e.ppid)??[];t.push(e),i.set(e.ppid,t)}let a=[...r.values()];for(let e of a)for(let t of i.get(e.pid)??[])!t.status.startsWith(`Z`)&&!r.has(t.pid)&&(r.set(t.pid,t),a.push(t));for(let t of r.values())e.tracked.set(t.pid,t);return e.sampled=!0,[...r.values()]}function wy(e,t,n,r,i,a=0,o=!1){let s=Sy(),c=Cy(e,s),l=o?Ty(s,new Set(c.map(e=>e.pid))):a,u=c.reduce((e,t)=>e+t.rssBytes,l);if(!Number.isSafeInteger(u))throw new L(`Owned aggregate RSS is outside the safe integer range.`);if(u>n.maxAggregateRssBytes)throw new L(`Owned aggregate RSS ${u} exceeded limit ${n.maxAggregateRssBytes}.`);let d=by(t,r);if(d<n.minFreeDiskBytes)throw new L(`Free disk fell below limit ${n.minFreeDiskBytes}.`);if(i!==void 0&&!Number.isSafeInteger(i))throw new L(`Filesystem output observation overflowed.`);if(r!==void 0&&n.maxNewOutputBytes!==void 0&&i!==void 0&&i>n.maxNewOutputBytes)throw new L(`Positive new filesystem output ${i} exceeded limit ${n.maxNewOutputBytes}.`);return{aggregateRssBytes:u,freeDiskBytes:d,...i===void 0?{}:{newOutputBytes:i},ownedProcessCount:c.length}}function Ty(e=Sy(),t=new Set){let n=e.get(process.pid);if(n===void 0||n.status.startsWith(`Z`))throw new L(`Runtime setup controller resource observation is unavailable.`);let r=new Set([process.pid]),i=process.memoryUsage().rss;for(let n of r)for(let a of e.values())a.ppid===n&&!a.status.startsWith(`Z`)&&!r.has(a.pid)&&(r.add(a.pid),t.has(a.pid)||(i+=a.rssBytes));if(!Number.isSafeInteger(i))throw new L(`Controller aggregate RSS observation overflowed.`);return i}async function Ey(e){if(!e.sampled||e.rootIdentity===void 0)throw new L(`Owned process cleanup cannot be verified without a root identity.`);let t=Date.now()+2e3;for(;;){let n=Sy(),r=n.get(e.rootPid);if(r!==void 0&&r.identity!==e.rootIdentity)throw new L(`Owned process group identity changed before cleanup readback.`);let i=[...n.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)),a=[...e.tracked.values()].some(e=>{let t=n.get(e.pid);if(t===void 0||t.status.startsWith(`Z`))return!1;if(t.identity!==e.identity)throw new L(`Tracked process identity changed before cleanup readback.`);return!0});if(!i&&!a)return;if(Date.now()>=t)throw new L(`Owned process cleanup did not release every sampled process.`);await new Promise(e=>setTimeout(e,100))}}function Dy(e){if(!e.sampled||e.rootIdentity===void 0)throw new L(`Owned process identity is unknown.`);let t=Sy(),n=t.get(e.rootPid);if(n!==void 0&&n.identity!==e.rootIdentity)throw new L(`Owned process group identity changed before cleanup.`);let r=[...e.tracked.values()].flatMap(e=>{let n=t.get(e.pid);if(n===void 0||n.status.startsWith(`Z`))return[];if(n.identity!==e.identity)throw new L(`Tracked process identity changed before cleanup.`);return[n]}),i=[...t.values()].filter(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`));if(i.length>0&&!r.some(t=>t.pgid===e.rootPid))throw new L(`Owned process group has no surviving recorded identity; cleanup is ambiguous.`);let a=t=>{try{process.kill(t,`SIGKILL`)}catch(n){let r=n.code;if(r===`ESRCH`)return;if(r!==`EPERM`)throw n;let i=Sy();if(t<0){let t=i.get(e.rootPid);if(t!==void 0&&t.identity!==e.rootIdentity)throw new L(`Owned process group identity changed during cleanup signal readback.`);if([...i.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)))throw n}else{let r=i.get(t);if(r!==void 0&&r.identity!==e.tracked.get(t)?.identity)throw new L(`Tracked process identity changed during cleanup signal readback.`);if(r!==void 0&&!r.status.startsWith(`Z`))throw n}}};i.length>0&&a(-e.rootPid);for(let e of r.reverse())a(e.pid)}var Oy=P({pid:j().int().positive(),identity:A().min(1)}),ky=P({schemaVersion:I(`ai-delivery.verification-writer@1`),writerId:$c(),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),owner:Oy,command:Ml([P({phase:I(`idle`)}),P({phase:I(`starting`)}),P({phase:I(`running`),root:Oy,tracked:M(P({...Oy.shape,pgid:j().int().positive()}))})]),stateId:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{stateId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Writer state is corrupt.`})});function Ay(e,t){if(t===void 0)return;let n=ky.parse(JSON.parse(t.toString(`utf8`)));if(n.worktreeDigest!==Py(e))throw new L(`Verification writer belongs to another worktree.`);let r=Sy(),i=r.get(n.owner.pid);if(i?.identity===n.owner.identity&&!i.status.startsWith(`Z`))throw new L(`A live verification writer still owns this worktree.`);if(n.command.phase===`starting`)throw new L(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(n.command.phase===`running`){let e=[n.command.root,...n.command.tracked],t=new Set([n.command.root.pid,...n.command.tracked.map(e=>e.pgid)]);if(e.some(e=>r.has(e.pid))||[...r.values()].some(e=>t.has(e.pgid)))throw new L(`Transition requires identity-bound command and process-group absence.`)}}async function jy(e,r,a,s,l=!1){let u=Py(e),d=T(s??Ou(e),`ai-delivery`,`writers@1`,`${u.slice(7)}.json`);return K_(w(d)),Xv(d,{projectRoot:e,timeout:200,...a?.onLockReleaseError===void 0?{}:{onReleaseError:a.onLockReleaseError},...a?.onLockCompromised===void 0?{}:{onCompromised:a.onLockCompromised},operation:async()=>{await nb(s??Ou(e),u,l);let f=Sy(),p=f.get(process.pid);if(p===void 0||p.status.startsWith(`Z`))throw new L(`Verification writer identity is unknown.`);let m;if(a)try{o(d),m=H(d)}catch(e){if(e.code!==`ENOENT`)throw e}else n(d)&&(m=H(d));if(a&&Ay(e,m),m!==void 0&&!a){let e=ky.parse(JSON.parse(m.toString(`utf8`)));if(e.worktreeDigest!==u)throw new L(`Verification writer belongs to another worktree.`);let t=f.get(e.owner.pid);if(t?.identity===e.owner.identity&&!t.status.startsWith(`Z`))throw new L(`A live verification writer still owns this worktree.`);if(e.command.phase===`starting`)throw new L(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(e.command.phase===`running`){let t={rootPid:e.command.root.pid,rootIdentity:e.command.root.identity,sampled:!0,tracked:new Map(e.command.tracked.map(e=>[e.pid,{...e,ppid:0,rssBytes:0,status:``}]))};Dy(t),await Ey(t),Vy({state:`recovered`,stageId:`writer`,completedStages:0,reusedStages:0,remainingStages:0,elapsedMs:0,reason:`Recorded interrupted command cleanup confirmed; compatible completed stages remain available.`})}}a&&await a.beforeClaim({previousBytes:m===void 0?void 0:Buffer.from(m),owner:{pid:p.pid,identity:p.identity}});let h={schemaVersion:`ai-delivery.verification-writer@1`,writerId:a?.writerId??le(),worktreeDigest:u,owner:{pid:p.pid,identity:p.identity},command:{phase:`idle`}},g=e=>{h={...h,command:e},J_(d,{...h,stateId:B(h)})};if(a){let e=Buffer.from(`${JSON.stringify({...h,stateId:B(h)},null,2)}\n`);await a.recordClaim(Buffer.from(e));let t;try{o(d),t=H(d)}catch(e){if(e.code!==`ENOENT`)throw e}if(t===void 0!=(m===void 0)||t!==void 0&&m!==void 0&&!t.equals(m))throw new L(`Writer changed after transition intent preservation.`)}g({phase:`idle`});let _={starting:()=>g({phase:`starting`}),observed:e=>{if(e.rootIdentity===void 0)throw new L(`Cannot persist an unknown command owner.`);g({phase:`running`,root:{pid:e.rootPid,identity:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,identity:t,pgid:n}))})},idle:()=>g({phase:`idle`}),assertQuiescent:()=>{let e=ky.parse(JSON.parse(H(d).toString(`utf8`)));if(e.writerId!==h.writerId||e.command.phase!==`idle`)throw new L(`Verification writer command quiescence is not confirmed.`)}},y=async()=>{let e=H(d),n=ky.parse(JSON.parse(e.toString(`utf8`)));if(n.writerId!==h.writerId)throw new L(`Verification writer ownership changed.`);if(n.command.phase===`idle`){if(a&&(await a.recordRelease(Buffer.from(e)),!H(d).equals(e)))throw new L(`Writer changed before recorded release.`);if(v(d),a){let e=c(w(d),`r`);try{i(e)}finally{t(e)}try{o(d)}catch(e){if(e.code!==`ENOENT`)throw e;await a.afterRelease?.();return}throw new L(`Writer absence is not confirmed after recorded release.`)}}};try{return await a?.afterClaim?.(Buffer.from(H(d))),await r(_)}finally{await y()}}})}async function My(e,t,n){let r=T(Ou(e),`ai-delivery`,`writers@1`,`${Py(t).slice(7)}.json`);return Xv(r,{projectRoot:e,timeout:200,operation:async()=>{await nb(Ou(e),Py(t));try{o(r)}catch(e){if(e.code!==`ENOENT`)throw e;return n()}throw new L(`Sealed transition writer absence postcondition drifted.`)}})}async function Ny(e,t){$c().parse(e.writerId);let n=Du(e.repoRoot);return jy(e.worktreePath===void 0?n:E(e.worktreePath),async e=>{e.assertQuiescent();let n=await t();return e.assertQuiescent(),n},e,Ou(n))}function Py(e){return B(E(e))}function Fy(t){let r=[],i=e=>{for(let n of d(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=T(e,n.name);n.isDirectory()?i(a):n.isFile()&&n.name.endsWith(`.js`)&&!n.name.endsWith(`.test.js`)&&r.push({path:a.slice(t.length+1),digest:V(l(a))})}};i(t);let a=new Map,o=t=>{if(a.has(t))return;let r=l(t),i=N({dependencies:Bl(A(),A()).optional()}).parse(JSON.parse(r.toString(`utf8`)));a.set(t,V(r));let s=e(t);for(let e of Object.keys(i.dependencies??{}).sort()){let t;try{t=s.resolve(`${e}/package.json`)}catch{t=s.resolve(e)}let r=w(t);for(;;){let t=T(r,`package.json`);if(n(t)&&N({name:A().optional()}).parse(JSON.parse(l(t,`utf8`))).name===e){o(t);break}let i=w(r);if(i===r)throw new L(`Producer dependency identity is unavailable for ${e}.`);r=i}}};return o(T(w(t),`package.json`)),{code:r,dependencies:[...a].sort(([e],[t])=>e.localeCompare(t))}}function Iy(e=w(me(import.meta.url))){return B(Fy(e))}function Ly(e){return Iy(p(e))}function Ry(e){return Fy(p(e)).dependencies.map(([e,t])=>({source:e,digest:t}))}function zy(e){return By(JSON.parse(e.toString(`utf8`)))}function By(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new L(`Invalid run manifest.`);let t=e,n=_h.parse(t.classification),r=wh.parse(t.aggregate),i=Ch.array().parse(t.stageReceipts);if(![`ai-delivery.run@1`,`ai-delivery.run@2`,`ai-delivery.run@3`].includes(String(t.schemaVersion)))throw new L(`Run manifest schema version is unsupported.`);if(t.schemaVersion===`ai-delivery.run@1`&&t.resources!==void 0)throw new L(`Historical run manifest has unexpected resource evidence.`);let a=t.resources===void 0?void 0:$v.parse(t.resources);if(t.schemaVersion===`ai-delivery.run@2`&&a===void 0)throw new L(`Historical bounded run lacks resource evidence.`);let o=t.schemaVersion===`ai-delivery.run@3`?P({worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).parse(t.writer):void 0,s={aggregate:r,classification:n,completedAt:t.completedAt,...a===void 0?{}:{resources:a},...o===void 0?{}:{writer:o},schemaVersion:t.schemaVersion,stageReceipts:i};if(typeof t.completedAt!=`string`||t.manifestId!==B(s)||Dh({classification:n,receipts:i}).aggregateId!==r.aggregateId)throw new L(`Run manifest identity or aggregate is invalid.`);return{...s,completedAt:t.completedAt,manifestId:t.manifestId}}function Vy(e){process.stderr.write(`ai-delivery.verify ${JSON.stringify(e)}\n`)}function Hy(e,t,n,r,i,a,o,s,c){let[l,...u]=t;if(!l)throw new L(`Policy selected an empty stage command.`);if(n?.aborted)throw new L(`Selected policy stage command cancelled.`);return s?.starting(),new Promise((t,d)=>{let f=x(`/bin/sh`,[`-c`,`IFS= read -r ready || exit 125; [ "$ready" = run ] || exit 125; exec "$@" </dev/null`,`ai-delivery-command`,l,...u],{cwd:c?.cwd??e,detached:process.platform!==`win32`,stdio:[`pipe`,`pipe`,`pipe`],...a?.gate===void 0&&c===void 0?{}:{env:{...c?.environment??process.env,...a?.gate===void 0?{}:{[ty]:JSON.stringify(a.gate)}}}}),p=[],m=[],h=process.platform===`win32`||f.pid===void 0?void 0:{rootPid:f.pid,sampled:!1,tracked:new Map},g=0,_=0,v=c?.maxCapturedOutputBytes??8388608,y=0,b,S,C,w=!1,ee=!1,T=!1,te,ne,E,re=new AbortController,ie=()=>{let t=te===void 0?``:` First filesystem observation: ${te} Last filesystem observation: ${ne}`;try{let n=Buffer.concat([...p,...m]);return c?.failedOutput?c.failedOutput(n):` Command output ${Ah({bytes:n,gitCommonDir:Ou(e)})}.${t}`}catch(e){return` Command output persistence failed (${e instanceof Error?e.message:String(e)}).${t}`}},ae,oe,se,ce=()=>{clearInterval(fe),se!==void 0&&clearInterval(se),ae!==void 0&&clearTimeout(ae),oe!==void 0&&clearTimeout(oe),n?.removeEventListener(`abort`,pe),process.removeListener(`SIGINT`,me),process.removeListener(`SIGTERM`,he)},le=()=>{if(f.pid!==void 0){if(h?.sampled){try{Cy(h,Sy())}catch(e){S??=e instanceof Error?e.message:String(e)}try{s?.observed(h)}catch(e){C??=e instanceof Error?e.message:String(e)}try{Dy(h)}catch(e){S??=e instanceof Error?e.message:String(e)}}else try{f.exitCode===null&&f.signalCode===null&&f.kill(`SIGKILL`),T&&(S??=`owned process identity was not observed before cleanup`)}catch(e){S??=e instanceof Error?e.message:String(e)}}},ue=e=>{b===void 0&&(b=e,re.abort(),le(),w||(ae=setTimeout(()=>{ee||w||(ee=!0,ce(),f.stdout.destroy(),f.stderr.destroy(),f.unref(),c?.onCleanupFailure?.(`Owned command pipes did not close; descendant cleanup could not be verified.`),d(new L(`Selected policy stage command failed (${b}).${ie()}${C===void 0?``:` Writer state persistence failed (${C}).`} Owned process cleanup failed (owned command pipes did not close; descendant cleanup could not be verified).`)))},2e3)))},de=(e,t)=>{if(g+=t.length,c?.onCaptured?.(g),c!==void 0&&i?.maxNewOutputBytes!==void 0&&g+y>i.maxNewOutputBytes){ue(`source-phase captured output exceeded remaining cumulative allowance`);return}if(g>v){let n=v-_;n>0&&(e.push(Buffer.from(t.subarray(0,n))),_+=Math.min(n,t.length)),ue(c?.maxCapturedOutputBytes===void 0?`captured output exceeded 8 MiB`:`captured output exceeded ${v} bytes`);return}e.push(t),_+=t.length};f.stdout.on(`data`,e=>de(p,e)),f.stderr.on(`data`,e=>de(m,e)),f.stdout.once(`error`,e=>ue(e.message)),f.stderr.once(`error`,e=>ue(e.message)),f.stdin.once(`error`,e=>ue(e.message)),f.once(`error`,e=>{f.pid===void 0&&s?.idle(),ue(e.message)}),f.once(`exit`,(e,t)=>{e!==0||t!==null?ue(`exit ${String(e)}${t===null?``:` signal ${t}`}`):w||(oe=setTimeout(()=>{w||ue(`owned command pipes did not close after direct child exit`)},1e3))}),f.once(`spawn`,()=>{let t=()=>{if(b===void 0&&f.pid!==void 0)try{if(h===void 0)throw new L(`Owned process identity is unavailable on this platform.`);if(Cy(h,Sy()),s?.observed(h),i!==void 0){let t=wy(h,e,i,a,void 0,c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(w||E!==void 0)return;E=(async()=>{if(i!==void 0&&a!==void 0){let t=await vy(a,re.signal,T,e=>{te??=e,ne=e,r?.(g,void 0,e)});if(b!==void 0)return;y=t;let n=wy(h,e,i,a,t+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(n),r?.(g,n)}b===void 0&&!T&&(T=!0,f.stdin.end(`run
|
|
257
|
-
`))})().catch(e=>ue(e instanceof Error?e.message:String(e))).finally(()=>{E=void 0})}catch(e){ue(e instanceof Error?e.message:String(e))}};t(),se=setInterval(t,1e3),se.unref()});let fe=setInterval(()=>r?.(g),5e3);fe.unref();let pe=()=>ue(`cancelled`),me=()=>ue(`cancelled by SIGINT`),he=()=>ue(`cancelled by SIGTERM`);n?.addEventListener(`abort`,pe,{once:!0}),process.once(`SIGINT`,me),process.once(`SIGTERM`,he),n?.aborted&&pe();let ge=async(n,l)=>{if(w=!0,!ee){if(await E,b===void 0&&h!==void 0)try{if(i!==void 0){let t=wy(h,e,i,a,a===void 0?void 0:await vy(a,re.signal)+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(!h.sampled)throw new L(`Owned process resource observation was unavailable.`);if(Cy(h,Sy()).length>0)throw new L(`A sampled owned descendant survived command exit.`)}catch(e){ue(e instanceof Error?e.message:String(e))}if(b!==void 0||n!==0||l!==null){let e=b??`exit ${String(n)}${l===null?``:` signal ${l}`}`,t=f.pid===void 0||!T;if(h!==void 0&&h.sampled)try{await Ey(h),t=!0}catch(e){S??=e instanceof Error?e.message:String(e)}if(t)try{s?.idle()}catch(e){C??=e instanceof Error?e.message:String(e)}ee=!0,S!==void 0&&c?.onCleanupFailure?.(S),d(new L(`Selected policy stage command failed (${e}). Command exit ${String(n)}${l===null?``:` signal ${l}`}.${ie()}${C===void 0?``:` Writer state persistence failed (${C}).`}${S===void 0?``:` Owned process cleanup failed (${S}).`}`));return}s?.idle(),ee=!0,t(c?.stdoutOnly?Buffer.concat(p):Buffer.concat([...p,...m],g))}};f.once(`close`,(e,t)=>{ge(e,t).catch(e=>{ee=!0,d(e)}).finally(ce)})})}var Uy=A().regex(/^sha256:[a-f0-9]{64}$/u),Wy=A().regex(/^[a-f0-9]{40}$/u),Gy=P({path:A().min(1),digest:Uy}),Ky=Gy.extend({device:j().int().nonnegative().safe(),inode:j().int().nonnegative().safe(),uid:j().int().nonnegative().safe(),mode:j().int().nonnegative().safe()}),qy=P({argv:M(A()).min(1),cwd:A().min(1),executable:Ky}),Jy=P({head:Wy,indexTree:Wy,branch:A().min(1),configDigest:Uy,dirty:M(P({path:A().min(1),digest:Uy.nullable()}))}),Yy=P({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:M(A().min(1)).min(1)}),Xy=P({phaseId:Uy,recordId:Uy,baselineId:Uy.optional(),authorizationDigest:Uy}),Zy=P({repoRoot:A().min(1),issueNumber:j().int().positive().safe(),identity:A().min(1),rowDigest:Uy,controller:P({head:Wy,configDigest:Uy,admissionId:Uy,runtimeEntryPath:A().min(1),packageVersion:A().min(1),archiveDigest:Uy}),source:Jy.extend({path:A().min(1),effect:Pl(`kind`,[P({kind:I(`preserve`)}),P({kind:I(`commitOnce`),parent:Wy,tree:Wy,configDigest:Uy.optional()})])}),caller:Gy,authorization:Gy,inputs:M(Gy),commands:M(qy).min(1),commandGraphDigest:Uy,environment:P({digest:Uy,overrides:Bl(A(),A().nullable())}),bounds:Yy,completionArtifacts:M(A().min(1)),reconciliation:Xy.optional()}).omit({environment:!0}).extend({environmentDigest:Uy}),Qy=P({roots:M(A().min(1)).min(1),files:M(Rl([A(),j().int().nonnegative().safe()])),links:M(Rl([A(),P({identity:A(),target:A(),missing:xl()})])),baselineId:Uy}),$y=P({index:j().int().nonnegative().safe(),outputDigest:Uy.nullable(),outputBytes:j().int().nonnegative().safe(),status:F([`complete`,`failed`])}),eb=P({source:Jy,artifacts:M(Ky),newOutputBytes:j().int().nonnegative().safe(),writerReleased:I(!0),lockReleased:I(!0)}),tb=P({schemaVersion:I(`ai-delivery.source-phase@1`),phaseId:Uy,recordId:Uy,worktreeDigest:Uy,bindingDigest:Uy,authorizationDigest:Uy,status:F([`preparing`,`intent`,`complete`,`failed-quiescent`,`rejected-before-work`,`unresolved`]),writerId:$c(),binding:Zy.optional(),baseline:Qy.optional(),allocation:Yy.optional(),owner:P({pid:j().int().positive().safe(),identity:A().min(1)}),bootstrapFiles:M(Rl([A(),j().int().nonnegative().safe()])),bootstrapBytes:j().int().nonnegative().safe(),capturedBytes:j().int().nonnegative().safe(),nextCommandIndex:j().int().nonnegative().safe(),commands:M($y),claimDigest:Uy.optional(),releaseDigest:Uy.optional(),preparationArtifact:Ky.optional(),writerArtifact:Ky.optional(),producerDigest:Uy.optional(),actor:P({identity:A().min(1),actorLogin:A().min(1),credentialIdentity:A().min(1)}).optional(),retainedArtifacts:M(Ky).optional(),retainedPredecessors:M(P({phaseId:Uy,recordId:Uy})),reconciliation:Xy.optional(),result:eb.optional(),failure:P({operation:A().optional(),accounting:A().optional(),cleanup:A().optional(),writerRelease:A().optional(),lockRelease:A().optional()}).optional()}).superRefine((e,t)=>{let{recordId:n,...r}=e;if((n!==B(r)||e.phaseId!==e.bindingDigest)&&t.addIssue({code:`custom`,message:`Source-phase record identity is invalid.`}),e.binding!==void 0&&B(e.binding)!==e.bindingDigest&&t.addIssue({code:`custom`,message:`Source-phase input binding is invalid.`}),e.baseline!==void 0){let{baselineId:n,...r}=e.baseline;n!==B(r)&&t.addIssue({code:`custom`,message:`Source-phase baseline is invalid.`})}e.status===`rejected-before-work`&&(e.commands.length!==0||e.nextCommandIndex!==0||e.capturedBytes!==0)&&t.addIssue({code:`custom`,message:`Rejected source-phase input cannot contain executed work.`}),e.status===`complete`&&(e.result===void 0||e.baseline===void 0||e.binding===void 0||e.failure!==void 0)&&t.addIssue({code:`custom`,message:`Source-phase completion is incomplete.`}),e.status===`complete`&&(e.commands.length!==e.binding?.commands.length||e.nextCommandIndex!==e.commands.length||e.commands.some((e,t)=>e.index!==t||e.status!==`complete`))&&t.addIssue({code:`custom`,message:`Source-phase completion does not contain its exact successful command graph.`})});async function nb(e,t,n=!1){let r=T(e,`ai-delivery`,`receipts`,`source-phase@1`,t.slice(7)),i;try{let e=o(r);if(!e.isDirectory()||e.isSymbolicLink())throw new L(`Source-phase admission metadata is not a canonical directory.`);i=d(r)}catch(e){if(e.code===`ENOENT`)return;throw e}if(i.length>1e5)throw new L(`Source-phase admission exceeded its entry bound.`);for(let e of i){let i=tb.parse(JSON.parse(H(T(r,e)).toString(`utf8`)));if(i.worktreeDigest!==t||e!==`${i.phaseId.slice(7)}.json`)throw new L(`Source-phase admission record belongs to another input or worktree.`);if(i.status===`preparing`||i.status===`intent`)throw new L(`An unsealed source phase still excludes another worktree writer.`);if(n&&i.status===`unresolved`)throw new L(`Unresolved source phase requires owning reconciliation before another attempt.`);await new Promise(e=>setImmediate(e))}}P({status:I(`complete`),phaseId:Uy,recordId:Uy,source:Jy,commands:M($y)});var rb=P({schemaVersion:I(`ai-delivery.runtime-output@1`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),limit:j().int().positive().safe().max(8*1024**2),outputs:M(P({digest:A().regex(/^sha256:[a-f0-9]{64}$/u),bytes:j().int().nonnegative().safe().max(8*1024**2),status:F([`reserved`,`complete`])})).max(4096),contentDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{contentDigest:n,...r}=e;(n!==B(r)||new Set(e.outputs.map(e=>e.digest)).size!==e.outputs.length||e.outputs.reduce((e,t)=>e+t.bytes,0)>e.limit)&&t.addIssue({code:`custom`,message:`Runtime retained-output ledger is corrupt.`})});async function ib(e,t,n){let r=new AbortController,i=n?.signal===void 0?r.signal:AbortSignal.any([n.signal,r.signal]),a,o,s=0,c=Date.now(),l=()=>{if(a!==void 0)throw a;if(i.aborted)throw new L(`Runtime setup cancelled.`);let t=n===void 0?0:Ty();if(n!==void 0){if(t>n.bounds.maxAggregateRssBytes)throw new L(`Controller aggregate RSS ${t} exceeded limit ${n.bounds.maxAggregateRssBytes}.`);xy(e,n.bounds,o)}return t};if(n!==void 0){if(ey(n.bounds),!Number.isSafeInteger(n.maxCapturedOutputBytes)||n.maxCapturedOutputBytes<=0||n.maxCapturedOutputBytes>8*1024**2)throw new L(`Invalid runtime setup captured-output bound; maximum is 8 MiB.`);l()}return e=Du(e),jy(e,async u=>hy(e,n!==void 0,async d=>{let f,p,m=Ou(e),h=()=>{if(f===void 0||p===void 0)throw new L(`Runtime output allowance is unbound.`);let{contentDigest:e,...t}=f;if(f=rb.parse({...t,contentDigest:B(t)}),Buffer.byteLength(JSON.stringify(f,null,2))>1024**2)throw new L(`Runtime retained-output ledger exceeds its evidence bound.`);J_(p,f)},g=e=>{try{if(jh({gitCommonDir:m,digest:e.digest,expectedBytes:e.bytes}).length!==e.bytes)throw new L(`Runtime retained-output evidence size changed.`);return!0}catch(t){if(e.status===`reserved`&&t.code===`ENOENT`)return!1;throw t}},_=t=>{if(n===void 0)return;if(f!==void 0)throw new L(`Runtime output allowance is already bound.`);let r={stageId:t,worktreeDigest:Py(e),producerDigest:Iy(),limit:n.maxCapturedOutputBytes};p=T(m,`ai-delivery`,`verification@1`,`runtime-output`,r.worktreeDigest.slice(7),`${t.slice(7)}.json`);let i;try{i=H(p,{maxBytes:1024**2})}catch(e){if(e.code!==`ENOENT`)throw e}if(i!==void 0){if(f=rb.parse(JSON.parse(i.toString(`utf8`))),f.stageId!==r.stageId||f.worktreeDigest!==r.worktreeDigest||f.producerDigest!==r.producerDigest||f.limit!==r.limit)throw new L(`Runtime retained-output ledger belongs to an incompatible stage or controller.`);let e=!1;for(let t of f.outputs)g(t)&&t.status===`reserved`&&(t.status=`complete`,e=!0);e&&h()}else{let e={schemaVersion:`ai-delivery.runtime-output@1`,...r,outputs:[]};f=rb.parse({...e,contentDigest:B(e)}),h()}},v=()=>{if(n===void 0)return 8*1024**2;if(f===void 0)throw new L(`Runtime output allowance is unbound.`);return f.limit-f.outputs.reduce((e,t)=>e+t.bytes,0)},y=e=>{if(f===void 0)throw new L(`Runtime output allowance is unbound.`);let t=V(e),n=f.outputs.find(e=>e.digest===t);if(n!==void 0){if(n.bytes!==e.length||!g(n))throw new L(`Runtime retained-output reservation is unresolved; identical output cannot be rewritten.`);return` Command output ${t}.`}if(e.length>v())throw new L(`Runtime retained-output allowance exceeded.`);let r={digest:t,bytes:e.length,status:`reserved`};if(f.outputs.push(r),h(),Ah({bytes:e,gitCommonDir:m}),!g(r))throw new L(`Runtime retained-output publication is unresolved.`);return f.outputs[f.outputs.length-1].status=`complete`,h(),` Command output ${t}.`};if(n!==void 0){let t=[...n.bounds.outputRoots??[],T(Ou(e),`ai-delivery`)].map(t=>E(e,t)).sort(),r=t.filter((e,n)=>!t.slice(0,n).some(t=>e===t||e.startsWith(`${t}${re}`))),a=new Map,s=await py(d,`scan`,()=>_y(r,a),i);o={roots:r,links:a,files:s,baselineId:B([...s]),...d===void 0?{}:{gate:d}}}let b=async()=>{let t=l();if(n===void 0||o===void 0)return;let r=s+await vy(o,i);if(l(),r>n.bounds.maxNewOutputBytes)throw new L(`Runtime setup output ${r} exceeded limit ${n.bounds.maxNewOutputBytes}.`);Vy({state:`running`,stageId:`runtime-setup`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:s,sampledAggregateRssBytes:t,sampledFreeDiskBytes:by(e,o),sampledNewOutputBytes:r})};await b();let x=n===void 0?void 0:setInterval(()=>{try{l()}catch(e){a??=e instanceof Error?e:new L(String(e)),r.abort()}},1e3);x?.unref();try{let r=await t({assertQuiescent:()=>u.assertQuiescent(),bindCapturedOutput:_,checkResources:b,signal:i,run:async(t,r,a,o,l)=>{await b(),ey(r);let f=r.outputRoots?.map(t=>E(e,t)).sort();if(f!==void 0){for(let e=1;e<f.length;e++)if(f[e]===f[e-1]||f[e].startsWith(`${f[e-1]}${re}`))throw new L(`Filesystem output roots must not overlap.`)}let p=async d=>{let p=v();if(p<=0)throw new L(`Runtime retained-output allowance is exhausted; installer was not started.`);let m=new Map,h=f===void 0?void 0:await py(d,`scan`,()=>_y(f,m),i),g=f===void 0||h===void 0?void 0:{roots:f,files:h,links:m,baselineId:B([...h]),...d===void 0?{}:{gate:d}};xy(e,r,g);let _=0,x=await Hy(e,t,a===void 0?i:AbortSignal.any([i,a]),(e,t,n)=>Vy({state:`running`,stageId:`runtime-setup:install`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:e,...n===void 0?{}:{reason:n},...t===void 0?{}:{sampledAggregateRssBytes:t.aggregateRssBytes,sampledFreeDiskBytes:t.freeDiskBytes,sampledNewOutputBytes:t.newOutputBytes}}),r,g,void 0,u,n===void 0&&o===void 0&&l===void 0?void 0:{environment:o??process.env,...l===void 0?{}:{cwd:l},...n===void 0?{}:{maxCapturedOutputBytes:p,includeControllerTree:!0,failedOutput:y},onCaptured:e=>{s+=e-_,_=e}});return await b(),x};return n===void 0?hy(e,f!==void 0,p):p(d)}});return await b(),Vy({state:`completed`,stageId:`runtime-setup`,completedStages:1,reusedStages:0,remainingStages:0,elapsedMs:Date.now()-c}),r}catch(e){throw a===void 0?i.aborted?new L(`Runtime setup cancelled. ${e instanceof Error?e.message:String(e)}`):e:new L(`${a.message} Runtime setup operation failed (${e instanceof Error?e.message:String(e)}).`)}finally{x!==void 0&&clearInterval(x)}}))}var ab=`.issue-cli`;function ob(e){let t=e??process.cwd(),r=E(t,ab);return n(r)||s(r,{recursive:!0}),r}var sb=`${ab}/worktrees.json`,cb=P({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:F([`active`,`error`,`merged`,`pr-published`,`stale`]),type:I(`issue`),updatedAt:A().min(1)}).transform(({prNumber:e,...t})=>({...t,...e===void 0?{}:{prNumber:e}})),lb=P({schemaVersion:I(`ai-delivery.committed-continuation-plan@1`),planId:R,repository:A().min(1),repoRoot:A().min(1),configDigest:R,currentRuntime:Ov,row:cb,replacement:cb,head:Iu,terminalHead:Iu,terminalMergeId:R,operator:P({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1),preserved:M(P({path:A().min(1),digest:R})).min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e,{prNumber:i,identity:a,status:o,updatedAt:s,...c}=e.row,{identity:l,status:u,updatedAt:d,...f}=e.replacement;(n!==B(r)||e.row.status!==`merged`||!e.row.prNumber||e.replacement.status!==`active`||e.replacement.prNumber!==void 0||z(c)!==z(f)||e.head.sha===e.terminalHead.sha||new Set(e.preserved.map(e=>e.path)).size!==e.preserved.length)&&t.addIssue({code:`custom`,message:`Committed continuation plan identity or disposition is invalid.`})}),ub=P({schemaVersion:I(`ai-delivery.committed-continuation-intent@1`),intentId:R,plan:lb,authorityCommentId:j().int().positive(),acceptanceCommentId:j().int().positive()}).superRefine(({intentId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Continuation intent identity is invalid.`})}),db=P({schemaVersion:I(`ai-delivery.committed-continuation-completion@1`),completionId:R,intentId:R,planId:R,row:cb,head:Iu,completed:I(!0)}).superRefine(({completionId:e,...t},n)=>{e!==B(t)&&n.addIssue({code:`custom`,message:`Continuation completion identity is invalid.`})});function fb(e,t,n){return T(Ou(e),`ai-delivery`,`continuations`,String(t),`${n}.plan.json`)}function pb(e){return fb(e.repoRoot,e.row.issueNumber,e.head.sha).replace(/\.plan\.json$/u,`.intent.json`)}function mb(e){return pb(e).replace(/\.intent\.json$/u,`.completion.json`)}function hb(e,t){return T(Ou(e.repoRoot),`ai-delivery`,`continuations`,`evidence`,`${t.slice(7)}.bin`)}function gb(e,t=!1){for(let n of e.preserved)if(V(H(n.path))!==n.digest||t&&V(H(hb(e,n.digest)))!==n.digest)throw Error(`Committed continuation original evidence changed.`);if(t){let t=Buffer.from(z(e.row));if(!H(hb(e,V(t))).equals(t))throw Error(`Committed continuation original row beforeimage changed.`)}}function _b(e,t){let r=T(Ou(t),`ai-delivery`,`continuations`,String(e));if(!n(r))return;let i;for(let a of d(r).filter(e=>e.endsWith(`.intent.json`)).sort()){let o=ub.parse(JSON.parse(H(T(r,a)).toString(`utf8`))),s=o.plan;if(s.repoRoot!==E(t)||s.row.issueNumber!==e||T(r,a)!==pb(s))throw Error(`Committed continuation checkpoint identity disagrees.`);gb(s,!0);let c=mb(s);if(n(c)){let e=db.parse(JSON.parse(H(c).toString(`utf8`)));if(e.intentId!==o.intentId||e.planId!==s.planId||z(e.row)!==z(s.replacement)||z(e.head)!==z(s.head))throw Error(`Committed continuation completion disagrees with its intent.`);Sb(s.replacement,t),Tb(t,r,!1),Tb(t,w(hb(s,s.preserved[0].digest)),!1),wb(c)}else{if(i)throw Error(`Issue has multiple incomplete committed continuations.`);i=o}}return i}function vb(e){if(!e.identity)throw Error(`ai-delivery worktree ownership requires the preparing identity.`);return{branch:e.branch,identity:e.identity,...e.issueNumber===void 0?{}:{issueNumber:e.issueNumber},path:e.path,...e.prNumber===void 0||e.type===`issue`?{}:{prNumber:e.prNumber},schemaVersion:`ai-delivery.worktree-owner@1`,type:e.type}}function yb(e,t){let n=B(vb(t)).slice(7);return T(Ou(e),`ai-delivery`,`worktree-owners`,`${n}.json`)}function bb(e,t){if(e.type!==`issue`||e.issueNumber===void 0)return;let n=T(Ou(t),`ai-delivery`,`worktree-owners`,`issue-${String(e.issueNumber)}.transition.json`);try{o(n)}catch(e){if(e.code===`ENOENT`)return;throw Error(`Worktree transition is incomplete or unreadable.`)}try{let r=JSON.parse(H(n).toString(`utf8`)),{intentId:i,...a}=r,{planId:o,...s}=r.plan;if(r.schemaVersion!==`ai-delivery.worktree-transition-intent@1`||i!==B(a)||o!==B(s)||r.plan.repoRoot!==E(t)||r.plan.row.issueNumber!==e.issueNumber)throw Error(`Invalid transition intent.`);if(r.plan.purpose===`merged-cleanup`)throw Error(`Worktree transition is terminal and cannot authorize ordinary source operations.`);let c=T(`${n}.evidence`,`completion.json`),l=JSON.parse(H(c).toString(`utf8`)),{completionId:u,...d}=l;if(l.schemaVersion!==`ai-delivery.worktree-transition-completion@1`||l.planId!==o||l.intentId!==i||l.completed!==!0||u!==B(d)||JSON.stringify(vb(e))!==JSON.stringify(vb(r.plan.row)))throw Error(`Invalid transition completion.`);return}catch(e){throw e instanceof Error&&e.message.includes(`transition is terminal`)?e:Error(`Worktree transition is incomplete or unreadable; resume its exact approved plan.`)}}function xb(e,t){if(bb(e,t),e.issueNumber!==void 0&&_b(e.issueNumber,t))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);Sb(e,t)}function Sb(e,t){let n=vb(e),r=yb(t,e),i;try{i=JSON.parse(H(r).toString(`utf8`))}catch{throw Error(`Worktree lacks its exact ai-delivery ownership witness.`)}if(JSON.stringify(i)!==JSON.stringify({...n,ownerId:B(n)}))throw Error(`Worktree ownership witness disagrees with the canonical registry identity.`)}function Cb(e,t,n=!1){let r=vb(e);zu(yb(t,e),Buffer.from(JSON.stringify({...r,ownerId:B(r)}))),n||xb(e,t)}function wb(e){let n=c(w(e),`r`);try{i(n)}finally{t(n)}}function Tb(e,t,n=!0){let r=T(Ou(e),`ai-delivery`),i=[r,T(r,`continuations`),t],a=(e,t)=>{let n;try{n=o(e)}catch(e){if(t&&e.code===`ENOENT`)return;throw e}if(!n.isDirectory()||n.isSymbolicLink()||e!==r&&n.mode&63)throw Error(`Committed continuation evidence requires a private directory.`)};for(let e of i)a(e,n&&e!==r);n&&K_(t);for(let e of i)a(e,!1),wb(e)}async function Eb(e,t){let n=e.repoRoot;if(_b(e.row.issueNumber,n))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);return kb(n),Xv(sb,{projectRoot:n,timeout:5e3,operation:async()=>{let r=jb(n),i=r.worktrees.filter(t=>t.type===`issue`&&t.issueNumber===e.row.issueNumber);if(i.length>1)throw Error(`Transition has duplicate canonical issue rows.`);if(r.worktrees.some(t=>!i.includes(t)&&Fb(t,e.row)))throw Error(`Transition conflicts with another canonical registry path, branch or PR identity.`);let a=i[0],o={...e.row,...e.row.prNumber===void 0?{}:{prNumber:e.row.prNumber}},s=e.purpose===`active-resume`?o:{...o,prNumber:e.terminalPrNumber,status:`merged`};if(a!==void 0&&![o,s].some(e=>z(a)===z(e)))throw Error(`Transition canonical row drifted.`);let c=T(Ou(n),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`),l=()=>{if(JSON.parse(H(c).toString(`utf8`)).plan?.planId!==e.planId)throw Error(`Transition lacks its exact durable intent.`)};return t({current:a,writeOwner:()=>{l(),Cb(s,n,!0)},commitRow:()=>{if(l(),a===void 0)throw Error(`Transition cannot recreate a removed canonical row.`);return r.worktrees.splice(r.worktrees.indexOf(a),1,s),a=s,zb(n,r),s},removeRow:()=>{if(l(),e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw Error(`Transition lacks explicit unheld terminal source disposition.`);a!==void 0&&(r.worktrees.splice(r.worktrees.indexOf(a),1),zb(n,r),a=void 0)}})}})}function Db(e){let t=e.row,n=vb(t);if(z(JSON.parse(H(yb(e.repoRoot,t)).toString(`utf8`)))!==z({...n,ownerId:B(n)}))throw Error(`Sealed transition owner witness drifted.`)}function Ob(e){return jb(e??process.cwd()).worktrees}function kb(e){ob(e)}function Ab(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jb(e){let t=E(e,sb);if(!n(t))return{worktrees:[]};try{let e=l(t,`utf8`),n=JSON.parse(e);if(!Ab(n)||Object.keys(n).length!==1||!Array.isArray(n.worktrees))throw Error(`Registry must be an object with a worktrees array.`);return{worktrees:n.worktrees.map((e,t)=>Mb(e,t))}}catch(e){throw Error(`Unable to read worktree registry: ${e instanceof Error?e.message:String(e)}`)}}function Mb(e,t){if(!Ab(e))throw Error(`worktrees[${String(t)}] must be an object.`);let n=new Set([`branch`,`createdAt`,`identity`,`issueNumber`,`path`,`prNumber`,`status`,`type`,`updatedAt`]),r=Object.keys(e).filter(e=>!n.has(e));if(r.length>0)throw Error(`worktrees[${String(t)}] has unsupported fields: ${r.join(`, `)}.`);let i=Ib(e.branch,`worktrees[${String(t)}].branch`),a=Ib(e.createdAt,`worktrees[${String(t)}].createdAt`),o=Ib(e.path,`worktrees[${String(t)}].path`),s=Rb(e.type,`worktrees[${String(t)}].type`),c=Lb(e.status,`worktrees[${String(t)}].status`),l=Pb(e.identity,`worktrees[${String(t)}].identity`),u=Nb(e.issueNumber,`worktrees[${String(t)}].issueNumber`),d=Nb(e.prNumber,`worktrees[${String(t)}].prNumber`),f=Ib(e.updatedAt,`worktrees[${String(t)}].updatedAt`);if(s===`issue`&&u===void 0)throw Error(`worktrees[${String(t)}].issueNumber is required for issue worktrees.`);return{branch:i,createdAt:a,...l===void 0?{}:{identity:l},...u===void 0?{}:{issueNumber:u},path:o,...d===void 0?{}:{prNumber:d},status:c,type:s,updatedAt:f}}function Nb(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer.`);return e}}function Pb(e,t){if(e!==void 0)return Ib(e,t)}function Fb(e,t){return e.path===t.path||e.branch===t.branch||e.issueNumber!==void 0&&t.issueNumber!==void 0&&e.issueNumber===t.issueNumber||e.prNumber!==void 0&&t.prNumber!==void 0&&e.prNumber===t.prNumber}function Ib(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string.`);return e}function Lb(e,t){if(e===`merged`||e===`pr-published`||e===`active`||e===`error`||e===`stale`)return e;throw Error(`${t} is invalid.`)}function Rb(e,t){if(e===`issue`||e===`pr`||e===`standalone`)return e;throw Error(`${t} is invalid.`)}function zb(e,t){kb(e);let n=E(e,sb);try{q_(n,t)}catch(e){throw Error(`Unable to save worktree registry: ${e instanceof Error?e.message:String(e)}`)}}function Bb(e,t){let n=ne(T(e,`.worktrees`),t);if(n===``||n.startsWith(`..`)||n.startsWith(`/`))throw new L(`Worktree path must be inside the repository .worktrees directory.`)}function Vb(e,t,r,i,a){if(Bb(t,e.path),e.status!==`merged`||e.path!==T(t,`.worktrees`,`issue-${String(e.issueNumber)}`))throw new L(`Only the exact registered merged issue worktree can be cleaned.`);let o=n(e.path);if(o&&Du(e.path)!==p(e.path))throw new L(`Registered worktree points elsewhere.`);if(!o&&!a)throw new L(`Registered worktree is missing.`);o&&ju(e.path);let s=Mu(t,r),c=Eu(t,`merge-base`,`--is-ancestor`,e.branch,s)===0;if(i){if(i.headBranch!==e.branch||i.headSha!==Tu(o?e.path:t,`rev-parse`,o?`HEAD`:e.branch)||i.remoteHeadSha!==null&&i.remoteHeadSha!==i.headSha||i.baseBranch!==s.slice(`refs/remotes/${Su(t,r)}/`.length)||i.remoteBaseSha!==Tu(t,`rev-parse`,s)||Eu(t,`merge-base`,`--is-ancestor`,i.baseSha,i.mergeSha)!==0||Eu(t,`merge-base`,`--is-ancestor`,i.mergeSha,s)!==0||Tu(t,`rev-parse`,`${i.mergeSha}^{tree}`)!==i.mergeTree||!c&&i.strategy===`merge`)throw new L(`Exact merged-result cleanup attestation disagrees with Git or remote readback.`)}else if(!c)throw new L(`Branch is not included in the current base and exact merged-result attestation is absent.`);o&&Tu(t,`worktree`,`remove`,e.path)}function Hb(e,t){if(e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw new L(`Transition cannot remove held or nonterminal source.`);let n=e.lineage.find(t=>t.prNumber===e.terminalPrNumber);if(!n?.merged||!n.mergeSha)throw new L(`Transition lacks exact native terminal merge lineage.`);let r=Tu(e.repoRoot,`rev-parse`,`${n.mergeSha}^{tree}`),i=Eu(e.repoRoot,`merge-base`,`--is-ancestor`,e.head.sha,n.mergeSha)===0?`merge`:`squash`;if(i===`squash`&&r!==e.head.tree)throw new L(`Transition lacks exact retained tree proof for non-merge source removal.`);if(!e.remoteRefs||e.remoteRefs.headSha!==null&&e.remoteRefs.headSha!==e.head.sha)throw new L(`Transition lacks exact authenticated remote branch readback.`);Vb({...e.row,status:`merged`,prNumber:n.prNumber},e.repoRoot,t,{baseBranch:n.baseBranch,baseSha:n.baseSha,headBranch:e.row.branch,headSha:e.head.sha,mergeSha:n.mergeSha,mergeTree:r,remoteBaseSha:e.remoteRefs.baseSha,remoteHeadSha:e.remoteRefs.headSha,strategy:i},!0)}var Ub=P({path:A().min(1),source:A().min(1),digest:R,size:j().int().nonnegative().safe()}),Wb=P({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:F([`active`,`error`,`merged`,`pr-published`,`stale`]),type:I(`issue`),updatedAt:A().min(1)}),Gb=P({prNumber:j().int().positive(),headSha:Nu,headBranch:A().min(1),baseSha:Nu,baseBranch:A().min(1),mergeSha:Nu.nullable(),merged:xl(),authorLogin:A().min(1)}),Kb=P({schemaVersion:I(`ai-delivery.worktree-transition-plan@1`),planId:R,repository:A().min(1),repoRoot:A().min(1),row:Wb,purpose:F([`active-resume`,`merged-cleanup`]),disposition:F([`retain`,`remove`]),head:P({sha:Nu,tree:Nu}),terminalPrNumber:j().int().positive().nullable(),lineage:M(Gb),retainedHoldCommentIds:M(j().int().positive()),remoteRefs:P({headSha:Nu.nullable(),baseSha:Nu}).nullable(),holdEvidence:M(P({commentId:j().int().positive(),digest:R})),inventory:M(Ub),inventoryId:R,historicalProducer:I(`UNKNOWN`),closure:P({family:I(`public-ai-delivery-0.3.5-posix@1`),admissionPath:A().min(1),archivePath:A().min(1),admission:Ov,admissionBytesDigest:R,producerDigest:R,runManifestIds:M(R).min(1)}),currentRuntime:Ov,policyDigest:R,operator:P({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e;(n!==B(r)||e.inventoryId!==B(e.inventory)||e.disposition===`remove`&&(e.purpose!==`merged-cleanup`||e.retainedHoldCommentIds.length!==0)||e.purpose===`active-resume`&&e.terminalPrNumber!==null||e.purpose===`merged-cleanup`&&e.terminalPrNumber===null||e.disposition===`remove`&&e.remoteRefs===null)&&t.addIssue({code:`custom`,message:`Transition plan identity or disposition is invalid.`})}),qb=`sha256:c561a94b7727ad5dfc520cbdcad803b9eaddfd49d334ccbc9253edeede26994e`;function Jb(e,t,n){if(!e.configuration)throw new L(`Transition requires the current repository configuration.`);let r=H(t),i=Ov.parse(JSON.parse(r.toString(`utf8`)));if(i.packageVersion!==`0.3.5`||i.sourceArchiveSha256!==qb)throw new L(`Retained operational producer is outside the supported public 0.3.5 family.`);Nv(i,{...e.configuration,configDigest:i.configDigest},i.cliPath);let a=Zb(n);if(V(a)!==qb)throw new L(`Retained official public archive bytes disagree.`);let o=pe(a,{maxOutputLength:8388608}),s=w(w(i.cliPath)),c=[],l=(e,t)=>{let n=Zb(e);c.push({source:e,path:t,digest:V(n),size:n.length})},u=0;for(let e=0;e+512<=o.length;){let t=o.subarray(e,e+512);if(t.every(e=>e===0))break;let n=t.subarray(0,100).toString(`utf8`).replace(/\0.*$/su,``),r=Number.parseInt(t.subarray(124,136).toString(`ascii`).replace(/\0.*$/su,``).trim(),8);if(t[156]!==48||!/^package\/(?!.*(?:^|\/)\.\.\/)[A-Za-z0-9_./-]+$/u.test(n)||!Number.isSafeInteger(r)||r<0)throw new L(`Retained public archive inventory is unsupported.`);let i=o.subarray(e+512,e+512+r),a=E(s,n.slice(8)),c=Zb(a);if(i.length!==r||!c.equals(i))throw new L(`Retained producer bytes drifted: ${n}`);u+=1,l(a,`retained/${n}`),e+=512+Math.ceil(r/512)*512}if(u!==155)throw new L(`Retained public producer inventory is incomplete.`);l(t,`retained/admission.json`),l(n,`retained/public-archive.tar.gz`);let d=Ry(w(i.cliPath));for(let e of d)l(e.source,`retained/dependency-manifests/${B(e.source).slice(7)}.json`);return c.sort((e,t)=>e.path.localeCompare(t.path)),{admissionPath:t,archivePath:n,admission:i,admissionBytesDigest:V(r),producerDigest:Ly(w(i.cliPath)),inventory:c}}function Yb(e,t,n,r,i){let a=n.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).map(e=>zy(Zb(e.source)));if(a.length===0||!a.some(e=>e.classification.head.sha===i.sha&&e.classification.head.tree===i.tree)||a.some(e=>e.schemaVersion!==`ai-delivery.run@3`||e.writer?.worktreeDigest!==B(t.path)||e.writer.producerDigest!==r||e.classification.repository===``||e.classification.requiredStages.some(e=>![`source_only`,`focused_node`,`canonical_verify`].includes(e.resourceClass))||e.classification.requiredStages.some(e=>e.commands.length>0)&&e.resources===void 0))throw new L(`Complete operational run inventory lacks supported producer-bound closure for the exact retained source head/tree.`);for(let t of a)for(let n of t.stageReceipts){let t=n.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,r=T(Ou(e),`ai-delivery`,`verification@${String(t)}`,`stages`,n.input.stageId,`${n.input.inputId.slice(7)}.json`);if(z(JSON.parse(H(r).toString(`utf8`)))!==z(n))throw new L(`Operational run inventory has a missing or conflicting stage checkpoint.`)}return a.map(e=>e.manifestId).sort()}function Xb(e){try{return o(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Zb(e){let t=o(e);if(!t.isFile()||t.isSymbolicLink()||t.nlink!==1||p(e)!==e)throw new L(`Historical evidence requires canonical regular files without links.`);return l(e)}function Qb(e,t,n=!1){let r=Ou(e),i=new Map,a=new Set;Xb(t.path)?a.add(Tu(t.path,`rev-parse`,`HEAD`)):n&&a.add(Tu(e,`rev-parse`,t.branch));let s=(e,c)=>{if(!Xb(e))return;let l=o(e);if(l.isSymbolicLink()||p(e)!==e)throw new L(`Historical evidence inventory contains a noncanonical path.`);if(l.isDirectory()){for(let t of d(e).sort())s(T(e,t),`${c}/${t}`);return}let u=Zb(e);if(i.set(c,{path:c,source:e,digest:V(u),size:u.length}),c.endsWith(`.json`)){let i;try{i=JSON.parse(u.toString(`utf8`))}catch{return}if(i&&typeof i.headSha==`string`&&/^[a-f0-9]{40}$/u.test(i.headSha)&&a.add(i.headSha),i?.schemaVersion===`issue-cli.terminal-evidence@1`){if(!Array.isArray(i.files))throw new L(`Historical terminal evidence manifest is incomplete.`);for(let t of i.files){if(typeof t.name!=`string`||!/^[A-Za-z0-9_.-]+$/u.test(t.name)||typeof t.sha256!=`string`)throw new L(`Historical terminal evidence inventory is invalid.`);let n=Zb(T(w(e),t.name));if(n.length!==t.size||V(n)!==`sha256:${t.sha256}`)throw new L(`Historical terminal evidence manifest disagrees with original bytes.`)}}if(c.startsWith(`git/ai-delivery/runs@2/`)&&i?.schemaVersion===`ai-delivery.run@3`){let e=zy(u),i=e.classification.head.sha;a.add(i);for(let i of e.stageReceipts){let e=i.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,a=`ai-delivery/verification@${String(e)}/stages/${i.input.stageId}/${i.input.inputId.slice(7)}.json`;s(T(r,a),`git/${a}`);let o=`ai-delivery/resource-stages@1/${i.input.inputId.slice(7)}.json`;s(T(r,o),`git/${o}`);for(let e of i.commands){let t=`ai-delivery/verification@1/command-output/${e.outputDigest.slice(7)}.bin`;if(V(Zb(T(r,t)))!==e.outputDigest)throw new L(`Historical command output is corrupt.`);s(T(r,t),`git/${t}`)}for(let e of i.artifacts){if(n)continue;let r=E(t.path,e.path);if(ne(t.path,r).startsWith(`..`)||V(Zb(r))!==e.digest)throw new L(`Historical stage artifact is missing or corrupt.`);s(r,`worktree/${e.path}`)}}if(e.resources?.outputBaselineId){let t=`ai-delivery/output-baselines@1/${e.resources.outputBaselineId.slice(7)}`;s(T(r,`${t}.json`),`git/${t}.json`),s(T(r,`${t}.state.json`),`git/${t}.state.json`)}}}};s(T(e,`.issue-cli`,`issues`,String(t.issueNumber)),`repository/.issue-cli/issues/${String(t.issueNumber)}`),n||s(T(t.path,`.issue-cli`),`worktree/.issue-cli`);let c=B(E(t.path)).slice(7);s(T(r,`ai-delivery`,`runs@2`,c),`git/ai-delivery/runs@2/${c}`),s(T(r,`ai-delivery`,`writers@1`,`${c}.json`),`git/ai-delivery/writers@1/${c}.json`);let l=T(e,`.issue-cli`,`receipts`),u=t=>{if(!Xb(t))return;let n=o(t);if(n.isSymbolicLink())throw new L(`Historical receipt inventory contains a link.`);if(n.isDirectory())for(let e of d(t).sort())u(T(t,e));else[...a].some(e=>t.includes(e))&&s(t,`repository/${ne(e,t)}`)};u(l);for(let e of[`publications`,`reviews`,`merges`,`merge-intents`,`merge-attempts`,`merge-results`])s(T(r,`ai-delivery`,e,String(t.issueNumber)),`git/ai-delivery/${e}/${String(t.issueNumber)}`);for(let e of[...a].sort())s(T(r,`ai-delivery`,`runs`,`${e}.json`),`git/ai-delivery/runs/${e}.json`);return[...i.values()].sort((e,t)=>e.path.localeCompare(t.path))}var $b=P({schemaVersion:I(`ai-delivery.worktree-transition-intent@1`),intentId:R,plan:Kb,relinquishmentCommentId:j().int().positive(),acceptanceCommentId:j().int().positive(),originalRegistryDigest:R,originalWriterDigest:R.nullable()}).superRefine((e,t)=>{let{intentId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Transition intent is corrupt.`})}),ex=P({schemaVersion:I(`ai-delivery.worktree-transition-step@1`),planId:R,intentId:R,attemptId:$c(),event:F([`authority`,`claim`,`claimed`,`release`,`released`,`row`,`owner`,`removal-intent`,`removed`]),sequence:j().int().positive().safe(),predecessorId:R.nullable(),data:Bl(A(),Tl()),stepId:R}),tx=P({schemaVersion:I(`ai-delivery.worktree-transition-completion@1`),completionId:R,planId:R,intentId:R,completed:I(!0),writerReleased:I(!0),result:F([`active-resumed`,`retained`,`removed`]),rowAfter:Wb.nullable(),inventoryId:R,attempts:M(R).min(1),completedAt:hu()}).superRefine((e,t)=>{let{completionId:n,...r}=e;n!==B(r)&&t.addIssue({code:`custom`,message:`Transition completion is corrupt.`})});function nx(e){let t=T(Ou(e.repoRoot),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`);return{intent:t,directory:`${t}.evidence`,blobs:T(`${t}.evidence`,`bytes`)}}function rx(e,t){zu(e,Buffer.from(z(t)))}function ix(e,t){let n=V(t);return zu(T(e,`${n.slice(7)}.bin`),t,n),n}function ax(e,t){let n=H(T(e,`${R.parse(t).slice(7)}.bin`));if(V(n)!==t)throw new L(`Preserved transition evidence is corrupt.`);return n}function ox(e){let t=B({planId:e.planId,purpose:`transition-writer`}).slice(7);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-8${t.slice(17,20)}-${t.slice(20,32)}`}function sx(e,t){if(!Xb(e))return[];let n=null;return d(e).sort((e,t)=>Number(e.split(`.`)[0])-Number(t.split(`.`)[0])).map((r,i)=>{if(!/^[1-9]\d*\.[a-f0-9-]{36}\.(?:authority|claim|claimed|release|released|row|owner|removal-intent|removed)\.json$/u.test(r))throw new L(`Transition attempt inventory contains an unsupported record.`);let a=ex.parse(JSON.parse(H(T(e,r)).toString(`utf8`))),{stepId:o,...s}=a;if(o!==B(s)||a.intentId!==t.intentId||a.planId!==t.plan.planId||a.sequence!==i+1||a.predecessorId!==n||r!==`${String(a.sequence)}.${a.attemptId}.${a.event}.json`)throw new L(`Transition attempt record is corrupt or belongs to another intent.`);return n=o,a})}function cx(e,t){let n=[e.originalWriterDigest],r,i;for(let e of t)if(e.event===`claim`){let t=R.parse(e.data.bytesDigest),a=e.data.previousBytesDigest===null?null:R.parse(e.data.previousBytesDigest);if(!n.includes(a))throw new L(`Transition claim predecessor is outside its exact writer lineage.`);n=[a,t],r={attemptId:e.attemptId,bytesDigest:t},i=void 0}else if(e.event===`claimed`||e.event===`release`){if(!r||e.attemptId!==r.attemptId||e.data.bytesDigest!==r.bytesDigest)throw new L(`Transition claim/release acknowledgement belongs to another writer lineage.`);n=e.event===`claimed`?[r.bytesDigest]:[r.bytesDigest,null],e.event===`release`&&(i=e.attemptId)}else if(e.event===`released`){if(i!==e.attemptId||e.data.absent!==!0)throw new L(`Transition absence lacks its exact latest release intent.`);n=[null]}return n}function lx(e,t,n){t.originalWriterDigest!==null&&ax(e,t.originalWriterDigest);for(let t of n)[`authority`,`claim`,`claimed`,`release`].includes(t.event)&&ax(e,R.parse(t.data.bytesDigest))}async function ux(e,t,n,r,i){if(!e.configuration||e.root!==t.repoRoot||e.config.repository!==t.repository)throw new L(`Transition repository or current configuration drifted.`);if(z(await Mv({repoRoot:t.repoRoot,configuration:e.configuration,...i===void 0?{}:{runtimeEntryPath:i}}))!==z(t.currentRuntime)||V(Zb(wx(e).policyModulePath))!==t.policyDigest)throw new L(`Transition current runtime/configuration/policy drifted.`);let{inventory:a,...o}=Jb(e,t.closure.admissionPath,t.closure.archivePath),{family:s,runManifestIds:c,...l}=t.closure;if(z(o)!==z(l))throw new L(`Retained operational producer drifted.`);for(let e of[`v1`,`v2`])if(Xb(T(Ou(t.repoRoot),`issue-cli`,`verification-stages`,e)))throw new L(`Unsupported operative issue-cli verification-stages/${e}; supported closure is missing.`);let u=!Xb(t.row.path);if(u&&(!r||t.disposition!==`remove`))throw new L(`Transition source disappeared without recorded removal intent.`);if(!u){if(Du(t.row.path)!==t.row.path||Ou(t.row.path)!==Ou(t.repoRoot)||Tu(t.row.path,`branch`,`--show-current`)!==t.row.branch)throw new L(`Transition worktree ownership or branch drifted.`);ju(t.row.path)}let d=u?t.repoRoot:t.row.path,f=u?t.row.branch:`HEAD`;if(Tu(d,`rev-parse`,f)!==t.head.sha||Tu(d,`rev-parse`,`${f}^{tree}`)!==t.head.tree)throw new L(`Transition exact source coordinates drifted.`);let p=await yx(e,t.row,t.terminalPrNumber);if(z(p)!==z(t.lineage))throw new L(`Transition authenticated native PR lineage or complete PR set drifted.`);if(t.disposition===`remove`){let n=t.lineage.find(e=>e.prNumber===t.terminalPrNumber);if(!n||z(await xx(e,t.row.branch,n.baseBranch))!==z(t.remoteRefs)||Tu(t.repoRoot,`rev-parse`,Mu(t.repoRoot,wx(e).remote))!==t.remoteRefs?.baseSha)throw new L(`Transition native remote branch readback or local retaining ref drifted.`);if(a.some(e=>{let n=ne(t.row.path,e.source);return n===``||!n.startsWith(`..`)&&!n.startsWith(`/`)}))throw new L(`Retained operational producer must remain outside the source selected for removal.`)}let m=(await e.clients.rest.issues.get({...e.repo,issue_number:t.row.issueNumber})).data;if(m.state!==(t.purpose===`merged-cleanup`?`closed`:`open`))throw new L(`Transition native issue state drifted.`);for(let n of t.holdEvidence){let t=(await e.clients.rest.issues.getComment({...e.repo,comment_id:n.commentId})).data;if(V(Buffer.from(z(t)))!==n.digest)throw new L(`Retained native hold evidence drifted.`)}let h=[...Qb(t.repoRoot,t.row,u),...a].sort((e,t)=>e.path.localeCompare(t.path));if(bx(t.repoRoot,t.row,t.purpose,t.terminalPrNumber,t.head,p,m.state,h),z(Yb(t.repoRoot,t.row,h,o.producerDigest,t.head))!==z(t.closure.runManifestIds))throw new L(`Operational run inventory IDs drifted.`);if(h.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(e=>zy(Zb(e.source)).classification.repository!==t.repository))throw new L(`Operational run inventory belongs to another repository.`);let g=e=>e.filter(e=>!e.path.startsWith(`git/ai-delivery/writers@1/`)&&!(u&&e.path.startsWith(`worktree/`)));if(z(g(h))!==z(g(t.inventory)))throw new L(`Transition complete historical writer/run/stage inventory drifted.`);if(n&&h.some(e=>e.path.startsWith(`git/ai-delivery/writers@1/`)&&!t.inventory.some(t=>z(t)===z(e))))throw new L(`Original transition writer evidence drifted.`)}async function dx(e,t){if(t.authority!==`worktree:transition`)throw new L(`Explicit exact-plan worktree transition authority is required.`);let n=Kb.parse(JSON.parse(Zb(p(t.planPath)).toString(`utf8`)));if(n.planId!==t.expectedPlanId)throw new L(`Transition expected plan identity disagrees.`);let r=nx(n),i=T(r.directory,`completion.json`),a=T(r.directory,`attempts`),o;if(Xb(r.intent)&&(o=$b.parse(JSON.parse(H(r.intent).toString(`utf8`))),z(o.plan)!==z(n)||o.relinquishmentCommentId!==t.relinquishmentCommentId||o.acceptanceCommentId!==t.acceptanceCommentId))throw new L(`Pending transition requires its original exact plan and native authority IDs.`);let s=n.purpose===`active-resume`?`active-resumed`:n.disposition===`retain`?`retained`:`removed`;if(Xb(i)){if(!o)throw new L(`Transition completion lacks its durable intent.`);let c=tx.parse(JSON.parse(H(i).toString(`utf8`))),l=sx(a,o);if(c.planId!==n.planId||c.intentId!==o.intentId||c.result!==s||c.inventoryId!==n.inventoryId||z(c.attempts)!==z(l.map(e=>e.stepId))||z(cx(o,l))!==z([null]))throw new L(`Transition completion is corrupt.`);for(let e of n.inventory)ax(r.blobs,e.digest);ax(r.blobs,o.originalRegistryDigest),lx(r.blobs,o,l);for(let e of n.holdEvidence)ax(r.blobs,e.digest);return await ux(e,n,!1,sx(a,o).some(e=>e.event===`removal-intent`),t.runtimeEntryPath),await gx(e,n,t),await My(n.repoRoot,n.row.path,()=>Eb(n,async({current:e})=>{if(z(e??null)!==z(c.rowAfter))throw new L(`Sealed transition registry postcondition drifted.`);if(Db(n),s===`removed`){if(Xb(n.row.path)||e!==void 0)throw new L(`Removed transition source was recreated; terminal absence postcondition drifted.`)}else if(!e||!Xb(n.row.path))throw new L(`Sealed transition source or owner witness disappeared.`)})),{planId:n.planId,result:s,replayed:!0,receiptPath:i}}let c=le(),l=o===void 0?[]:sx(a,o),u=(e,t)=>{if(!o)throw new L(`Transition step lacks durable intent.`);let r={schemaVersion:`ai-delivery.worktree-transition-step@1`,planId:n.planId,intentId:o.intentId,attemptId:c,event:e,data:t,sequence:l.length+1,predecessorId:l.at(-1)?.stepId??null},i=ex.parse({...r,stepId:B(r)});cx(o,[...l,i]),rx(T(a,`${String(i.sequence)}.${c}.${e}.json`),i),l.push(i)},d=[...l],f=null,m,h=!1,g=null;return await Ny({repoRoot:n.repoRoot,worktreePath:n.row.path,writerId:ox(n),beforeClaim:async({previousBytes:i})=>{await Eb(n,async({current:s})=>{o!==void 0&&(l=sx(a,o));let c=d.some(e=>e.event===`removal-intent`);if(s===void 0&&!c)throw new L(`Transition row disappeared without recorded removal intent.`);await ux(e,n,o===void 0,c,t.runtimeEntryPath);let p=await gx(e,n,t);if(o===void 0){let e=n.inventory.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));if(i===void 0!=(e===void 0)||i!==void 0&&V(i)!==e?.digest)throw new L(`Original transition writer bytes or absence drifted.`);let a=ix(r.blobs,Zb(T(n.repoRoot,`.issue-cli`,`worktrees.json`))),s={schemaVersion:`ai-delivery.worktree-transition-intent@1`,plan:n,relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId,originalRegistryDigest:a,originalWriterDigest:i===void 0?null:V(i)};o=$b.parse({...s,intentId:B(s)}),rx(r.intent,o),Cx(r.blobs,n.inventory)}else{for(let e of n.inventory){if(!Xb(T(r.blobs,`${e.digest.slice(7)}.bin`))){if(e.path.startsWith(`git/ai-delivery/writers@1/`)){if(i===void 0||V(i)!==e.digest)throw new L(`Original writer was lost before preservation.`);ix(r.blobs,i)}else Cx(r.blobs,[e])}ax(r.blobs,e.digest)}let e=i===void 0?null:V(i);if(!cx(o,l).includes(e))throw new L(`Writer bytes/absence are outside the latest exact transition claim/release lineage.`);e!==null&&ax(r.blobs,e)}f=i===void 0?null:V(i),ax(r.blobs,o.originalRegistryDigest),lx(r.blobs,o,l),u(`authority`,{bytesDigest:ix(r.blobs,Buffer.from(z(p))),relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId});for(let t of n.holdEvidence){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.commentId})).data;if(ix(r.blobs,Buffer.from(z(n)))!==t.digest)throw new L(`Retained hold changed during preservation.`)}})},recordClaim:e=>{m=ix(r.blobs,e),u(`claim`,{bytesDigest:m,previousBytesDigest:f})},afterClaim:e=>{if(V(e)!==m)throw new L(`Actual writer claim bytes disagree with their recorded intent.`);u(`claimed`,{bytesDigest:m})},recordRelease:e=>{if(V(e)!==m)throw new L(`Writer changed before its exact recorded release.`);u(`release`,{bytesDigest:ix(r.blobs,e)})},afterRelease:async()=>{u(`released`,{absent:!0}),h&&o&&await Eb(n,async({current:e})=>{if(z(e??null)!==z(g))throw new L(`Transition row changed before completion sealing.`);for(let e of n.inventory)ax(r.blobs,e.digest);let t=sx(a,o);lx(r.blobs,o,t);let c={schemaVersion:`ai-delivery.worktree-transition-completion@1`,planId:n.planId,intentId:o.intentId,completed:!0,writerReleased:!0,result:s,rowAfter:g,inventoryId:n.inventoryId,attempts:t.map(e=>e.stepId),completedAt:new Date().toISOString()};rx(i,{...c,completionId:B(c)})})}},async()=>{await Eb(n,async({current:r,writeOwner:i,commitRow:a,removeRow:o})=>{let s=d.some(e=>e.event===`removal-intent`);if(await ux(e,n,!1,s,t.runtimeEntryPath),await gx(e,n,t),r!==void 0&&(i(),u(`owner`,{exactWitness:!0}),g=a(),u(`row`,{rowDigest:B(g)})),n.disposition===`remove`){if(u(`removal-intent`,{head:n.head,path:n.row.path}),Hb(n,wx(e).remote),Xb(n.row.path))throw new L(`Terminal source removal readback is not absent.`);u(`removed`,{absent:!0}),o(),g=null}h=!0})}),{planId:n.planId,result:s,replayed:d.length>0,receiptPath:i}}async function fx(e){if(e.clients.authSource!==`personal`||e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new L(`Worktree relinquishment requires the configured authenticated personal operator.`);let t=await e.clients.authenticatedAuthor();if(!/^user:[1-9]\d*$/u.test(t.credentialIdentity))throw new L(`Operator user identity is unavailable.`);let n=await vm({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(n.authSource!==`app`||!n.appActorLogin)throw new L(`Configured reviewer App identity is unavailable.`);let r=await n.appActorLogin();if(r.toLowerCase()===t.actorLogin.toLowerCase())throw new L(`Transition acceptance requires a distinct configured reviewer App.`);return{operator:t,reviewerActor:r,reviewer:n}}function px(e){return z({schemaVersion:`ai-delivery.worktree-relinquishment@1`,plan:hx(e),acceptedScope:`the-complete-content-addressed-plan-and-every-original-in-its-inventory`,authority:`relinquish-only-the-inventoried-public-posix-writers`,operationalClosure:`the-inventory-is-the-complete-remaining-launcher-writer-and-managed-process-set-all-are-quiescent-no-unknown-resources`,maintainedExclusion:`all-old-launchers-and-writers-remain-excluded-through-apply-including-interruption-and-exact-plan-replay`,historicalAuthority:`preservation-only-no-current-verification-review-or-retirement-authority`,sourceDisposition:e.disposition===`remove`?`no-outstanding-holds-remove-only-clean-merged-source`:`retain-source-and-all-outstanding-holds`,exclusions:[`private-adoption`,`hold-release`,`launcher-changes`,`shared-runtime-admission`,`legacy-protocol-retirement`]})}function mx(e,t){return z({schemaVersion:`ai-delivery.worktree-transition-acceptance@1`,plan:hx(e),acceptedScope:`independent-acceptance-of-the-complete-content-addressed-plan-and-inventory-including-complete-launcher-set-and-maintained-exclusion`,relinquishmentCommentId:t,relinquishmentDigest:V(Buffer.from(px(e))),result:`approved`})}function hx(e){let t=Kb.parse(e);return{planId:t.planId,inventoryId:t.inventoryId,repository:t.repository,repoRoot:t.repoRoot,row:t.row,head:t.head,purpose:t.purpose,disposition:t.disposition,terminalPrNumber:t.terminalPrNumber,lineage:t.lineage,remoteRefs:t.remoteRefs,holdEvidence:t.holdEvidence,closure:t.closure,currentRuntimeId:t.currentRuntime.admissionId,currentConfigDigest:t.currentRuntime.configDigest,policyDigest:t.policyDigest,operator:t.operator,reviewerActor:t.reviewerActor,historicalProducer:t.historicalProducer}}async function gx(e,t,n){let r=await fx(e);if(z(r.operator)!==z(t.operator)||r.reviewerActor!==t.reviewerActor)throw new L(`Configured transition authority identities drifted.`);if(t.lineage.some(e=>e.authorLogin.toLowerCase()===r.reviewerActor.toLowerCase()))throw new L(`Configured transition reviewer App is also the native PR author.`);let i=t.terminalPrNumber??t.row.issueNumber;return _x(e,{repository:t.repository,subject:i,operator:t.operator,reviewerActor:t.reviewerActor,authorityCommentId:n.relinquishmentCommentId,acceptanceCommentId:n.acceptanceCommentId,operatorBody:px(t),reviewerBody:mx(t,n.relinquishmentCommentId),revokedBody:z({schemaVersion:`ai-delivery.worktree-relinquishment-revocation@1`,planId:t.planId,relinquishmentCommentId:n.relinquishmentCommentId})})}async function _x(e,t){let n=await fx(e);if(z(n.operator)!==z(t.operator)||n.reviewerActor!==t.reviewerActor)throw new L(`Configured transition authority identities drifted.`);let r=t.subject,i=`https://api.github.com/repos/${t.repository}/issues/${String(r)}`,a=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.authorityCommentId})).data,o=(await n.reviewer.rest.issues.getComment({...e.repo,comment_id:t.acceptanceCommentId})).data;if(a?.id!==t.authorityCommentId||a.issue_url?.toLowerCase()!==i.toLowerCase()||a.user?.type!==`User`||a.user?.login.toLowerCase()!==n.operator.actorLogin.toLowerCase()||`user:${String(a.user?.id)}`!==n.operator.credentialIdentity||a.body!==t.operatorBody)throw new L(`Native operator relinquishment is missing, changed or belongs to another subject.`);if(o?.id!==t.acceptanceCommentId||o.issue_url?.toLowerCase()!==i.toLowerCase()||o.user?.type!==`Bot`||o.user.login.toLowerCase()!==n.reviewerActor.toLowerCase()||o.body!==t.reviewerBody)throw new L(`Native configured reviewer-App exact-plan acceptance is missing or changed.`);for(let i=1;;i+=1){let a=(await e.clients.rest.issues.listComments({...e.repo,issue_number:r,per_page:100,page:i})).data;if(a.some(e=>e.body===t.revokedBody&&e.user?.login.toLowerCase()===n.operator.actorLogin.toLowerCase()&&`user:${String(e.user.id)}`===n.operator.credentialIdentity))throw new L(`Native operator relinquishment has been revoked.`);if(a.length<100)break}return{relinquishment:a,acceptance:o}}async function vx(e,t,n){let r=(await e.clients.rest.pulls.get({...e.repo,pull_number:n})).data,i=(await e.clients.graphql(`query WorktreeTransitionLineage($owner: String!, $repo: String!, $number: Int!) {
|
|
253
|
+
`,{owner:e.repo.owner,name:e.repo.repo,number:t}),i=P({repository:P({issue:P({number:j().int().positive().safe(),repository:n,state:I([`OPEN`,`CLOSED`]),stateReason:I([`COMPLETED`,`NOT_PLANNED`,`DUPLICATE`,`REOPENED`]).nullable(),duplicateOf:P({number:j().int().positive().safe(),repository:n}).nullable()})})}).parse(r).repository.issue;if(i.number!==t||i.repository.nameWithOwner.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new R(`Native closure readback returned a foreign issue identity.`);if(i.state===`OPEN`&&i.stateReason!==null&&i.stateReason!==`REOPENED`||i.state===`CLOSED`&&i.stateReason===`REOPENED`||i.duplicateOf!==null&&i.stateReason!==`DUPLICATE`)throw new R(`Native closure readback has contradictory state evidence.`);return{state:i.state===`OPEN`?`open`:`closed`,closeReason:i.stateReason===null||i.stateReason===`REOPENED`?null:i.stateReason.toLowerCase(),duplicateOf:i.duplicateOf===null?null:{number:i.duplicateOf.number,repository:i.duplicateOf.repository.nameWithOwner}}}async function L_(e,t){if(t.closeReason!==void 0&&![`completed`,`not_planned`,`duplicate`].includes(t.closeReason)||(t.closeReason!==void 0||t.supersededBy!==void 0)&&t.state!==`closed`)throw new R(`Closure details require state closed and a supported close reason.`);if(t.supersededBy!==void 0&&(!Number.isSafeInteger(t.supersededBy)||t.supersededBy<=0||t.supersededBy===t.issueNumber))throw new R(`A superseding issue must be a different positive issue number.`);let{clients:n,config:r,repo:i}=e,a=t.labels===void 0?void 0:await D_(e,t.labels);if(t.issueType!==void 0&&!r.native.issueTypes.includes(t.issueType))throw new R(`Unsupported configured Issue Type.`);if(t.points!==void 0&&!r.native.points.values.includes(String(t.points)))throw new R(`Unsupported configured Points value.`);if(t.priority!==void 0&&!r.native.priority.values.includes(t.priority))throw new R(`Unsupported configured Priority value.`);if(t.parentIssueNumber!==void 0||t.blockedBy!==void 0){let e=await Vg({graphql:n.graphql,issueNumber:t.issueNumber,repo:i});await Kg({blockers:e.blockers.map(e=>e.number),...e.parentNumber===null?{}:{parentIssueNumber:e.parentNumber},repo:i,rest:n.rest}),await Kg({blockers:t.blockedBy??[],...t.parentIssueNumber===void 0||t.parentIssueNumber===null?{}:{parentIssueNumber:t.parentIssueNumber},repo:i,rest:n.rest})}let o=t.closeReason??(t.supersededBy===void 0?void 0:`completed`),s;if(t.supersededBy!==void 0){let e=(await n.rest.issues.get({...i,issue_number:t.supersededBy})).data;if(e.number!==t.supersededBy||`pull_request`in e||!Number.isSafeInteger(e.id)||e.id<=0||new URL(e.html_url).pathname.toLowerCase()!==`/${i.owner}/${i.repo}/issues/${String(t.supersededBy)}`.toLowerCase())throw new R(`Superseding issue readback is not the requested repository issue.`);s=e.id}let c=e=>{if(e.state!==`closed`||e.closeReason!==o||o===`duplicate`&&t.supersededBy!==void 0&&(e.duplicateOf?.number!==t.supersededBy||e.duplicateOf.repository.toLowerCase()!==`${i.owner}/${i.repo}`.toLowerCase()))throw new R(`Native closure readback disagrees with the requested reason or superseding issue.`)};if(o!==void 0){let n=await I_(e,t.issueNumber);if(n.state===`closed`)try{c(n)}catch{throw new R(`Issue is already closed with different closure evidence; reopen it explicitly first.`)}}let l,u;if(t.preserveHistory===!0&&(t.title!==void 0||t.body!==void 0)){let r=(await n.rest.issues.get({...i,issue_number:t.issueNumber})).data;if(r.number!==t.issueNumber||`pull_request`in r)throw new R(`History target is not the requested issue.`);let a={title:r.title,body:r.body??``};if(t.title!==void 0&&t.title!==a.title||t.body!==void 0&&t.body!==a.body){let n=F_(a.title,a.body);if(n.length>65536)throw new R(`Complete issue history exceeds the supported comment body limit; issue was not rewritten.`);u=a,l=await w_(e,{issueNumber:t.issueNumber,body:n})}}let d;if(o!==void 0&&(d=await w_(e,{issueNumber:t.issueNumber,body:`Requested closure reason: ${o}.${t.supersededBy===void 0?``:`\nSuperseded by ${i.owner}/${i.repo}#${String(t.supersededBy)}.`}`})),u!==void 0){let e=(await n.rest.issues.get({...i,issue_number:t.issueNumber})).data;if(e.number!==t.issueNumber||`pull_request`in e||e.title!==u.title||(e.body??``)!==u.body)throw new R(`Issue content changed after history readback; retry against the current title and body.`)}await n.rest.issues.update({issue_number:t.issueNumber,owner:i.owner,repo:i.repo,...t.body===void 0?{}:{body:t.body},...t.issueType===void 0?{}:{type:t.issueType},...a===void 0?{}:{labels:a},...t.milestone===void 0?{}:{milestone:t.milestone},...t.state===void 0?{}:{state:t.state},...o===void 0?{}:{state_reason:o,headers:{"X-GitHub-Api-Version":Mh}},...o!==`duplicate`||s===void 0?{}:{duplicate_issue_id:s},...t.title===void 0?{}:{title:t.title}});let f=o===void 0?void 0:await I_(e,t.issueNumber);f!==void 0&&c(f),(t.points!==void 0||t.priority!==void 0)&&await Bh({issueNumber:t.issueNumber,metadata:{...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority}},org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Nh(r)}),t.parentIssueNumber!==void 0&&await Gg({graphql:n.graphql,issueNumber:t.issueNumber,parentIssueNumber:t.parentIssueNumber,repo:i,rest:n.rest}),t.parentIssueNumber!==void 0&&t.parentIssueNumber!==null&&await Fh({issueNumber:t.parentIssueNumber,org:r.native.organization,owner:i.owner,repo:i.repo,rest:n.rest,settings:Nh(r)}),t.blockedBy!==void 0&&await Wg({blockers:t.blockedBy,graphql:n.graphql,issueNumber:t.issueNumber,repo:i,rest:n.rest});let p=await z_(e,t.issueNumber),m=p.state===`closed`||p.projectStatus===`Done`?`Done`:p.blockedBy.length>0?`Blocked`:t.park===!0||t.blockedBy!==void 0||p.projectStatus===null?`Todo`:p.projectStatus===`In Progress`||p.projectStatus===`Blocked`&&t.state===void 0?p.projectStatus:`Todo`,h=(await n.rest.issues.get({issue_number:t.issueNumber,...i})).data;await Em({graphql:n.graphql,issueNodeId:h.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:wm(r),status:m});let g=await z_(e,t.issueNumber);if((t.preserveHistory===!0||o!==void 0)&&(t.title!==void 0&&g.title!==t.title||t.body!==void 0&&g.body!==t.body||t.state!==void 0&&g.state!==t.state))throw new R(`Issue update readback disagrees with the requested content or state.`);return{...g,...l===void 0?{}:{historyComment:l},...f===void 0||d===void 0?{}:{closure:{...f,supersededBy:t.supersededBy??null,comment:d}}}}async function R_(e,t){return L_(e,t)}async function z_(e,t){let{clients:n,config:r,repo:i}=e,a=(await n.rest.issues.get({issue_number:t,owner:i.owner,repo:i.repo})).data;if(`pull_request`in a)throw new R(`Requested issue number is a pull request.`);let[o,s,c]=await Promise.all([Lh({issueNumber:t,owner:i.owner,repo:i.repo,rest:n.rest,settings:Nh(r)}),Vg({graphql:n.graphql,issueNumber:t,repo:i}),xm({graphql:n.graphql,issueNodeId:a.node_id,org:r.native.organization,...e.projectConfiguration?{configuration:e.projectConfiguration}:{},settings:wm(r)})]);return{...e.configuration?{routing:e.configuration.routing}:{},blockedBy:s.blockers.filter(e=>e.state===`OPEN`).map(e=>e.number),body:a.body??``,issueNumber:t,issueType:a.type?.name??null,parentIssueNumber:s.parentNumber,...o.points===void 0?{}:{points:o.points},...o.priority===void 0?{}:{priority:o.priority},projectStatus:c?.status??null,state:a.state,title:a.title,url:a.html_url,worktree:null}}async function B_(e,t){if(`pull_request`in(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data)throw new R(`Requested issue number is a pull request.`);return(await e.clients.rest.paginate(e.clients.rest.issues.listSubIssues,{...e.repo,issue_number:t,per_page:100})).map(e=>e.number).sort((e,t)=>e-t)}async function V_(e,t){let n=await z_(e,t),r=await Hg({issueNumber:t,repo:e.repo,rest:e.clients.rest});return Qg({blockedBy:n.blockedBy,body:n.body,...n.points===void 0?{}:{points:n.points},repoRoot:void 0,title:n.title,trackingParent:r})}async function H_(e,t){let n=[],r=new Set,i=null;for(let a=0;a<20;a++){let a=(await e.clients.graphql(`query DeliveryIssueBranches($owner:String!,$repo:String!,$issue:Int!,$cursor:String){repository(owner:$owner,name:$repo){issue(number:$issue){linkedBranches(first:100,after:$cursor){nodes{ref{name target{oid} repository{nameWithOwner}}} pageInfo{hasNextPage endCursor}}}}}`,{owner:e.repo.owner,repo:e.repo.repo,issue:t,cursor:i})).repository?.issue?.linkedBranches;if(!a||!Array.isArray(a.nodes)||typeof a.pageInfo?.hasNextPage!=`boolean`)throw new R(`Incomplete GitHub linked issue branch readback.`);for(let t of a.nodes){let r=t?.ref;if(!r||!r.name||!/^[a-f0-9]{40}$/u.test(r.target.oid)||!r.repository.nameWithOwner)throw new R(`Incomplete GitHub linked branch identity.`);r.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()&&n.push({name:r.name,sha:r.target.oid,repository:r.repository.nameWithOwner})}if(!a.pageInfo.hasNextPage)return n;let o=a.pageInfo.endCursor;if(!o||r.has(o))throw new R(`GitHub linked branch pagination did not advance.`);r.add(o),i=o}throw new R(`GitHub linked issue branches exceed the bounded readback window.`)}async function U_(e,t,n){let r=(await H_(e,t)).filter(e=>n===void 0||e.name===n);if(r.length!==1)throw new R(`Select exactly one GitHub-linked issue branch; no local worktree or receipt fallback is available.`);return r[0].name}async function W_(e,t,n){let r=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(r.number!==t||`pull_request`in r||r.state!==`open`)throw new R(`Start requires the requested open GitHub issue.`);let i=await H_(e,t),a=n??(i.length===1?i[0].name:`issue/${t}`);if(!/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u.test(a)||a.startsWith(`/`)||a.endsWith(`/`)||a.endsWith(`.lock`))throw new R(`Invalid issue branch name.`);let o=i.filter(e=>e.name===a);if(i.length>0&&o.length!==1)throw new R(`Select exactly one existing GitHub-linked issue branch before start.`);if(o.length>1)throw new R(`GitHub issue branch has conflicting linked matches.`);if(o.length===1)return{issueNumber:t,issueUrl:r.html_url,branch:a,headSha:o[0].sha,reused:!0};let s=(await e.clients.rest.repos.get({...e.repo})).data,c=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${s.default_branch}`})).data.object.sha;if(!/^[a-f0-9]{40}$/u.test(c)||!s.node_id)throw new R(`GitHub repository default branch identity is incomplete.`);await e.clients.graphql(`mutation DeliveryStartBranch($input:CreateLinkedBranchInput!){createLinkedBranch(input:$input){linkedBranch{ref{name target{oid}}}}}`,{input:{issueId:r.node_id,repositoryId:s.node_id,oid:c,name:a,clientMutationId:V({repository:e.config.repository,issueNumber:t,name:a,base:c})}});let l=(await H_(e,t)).filter(e=>e.name===a);if(l.length!==1||l[0].sha!==c)throw new R(`Started GitHub branch/link readback disagrees; resume this issue without creating another.`);return{issueNumber:t,issueUrl:r.html_url,branch:a,headSha:c,reused:!1}}function G_(e){J_(e,448)}function K_(e,t){X_({directoryMode:511,mode:438,path:e,value:t})}function q_(e,t){X_({directoryMode:448,mode:384,path:e,value:t})}function J_(e,t){let r=[],i=e;for(;!n(i);){r.push(i);let e=w(i);if(e===i)break;i=e}for(let e of r.reverse()){try{s(e,{mode:t})}catch(n){if(n.code!==`EEXIST`)throw n;let r=o(e);if(!r.isDirectory()||r.isSymbolicLink()||t===448&&r.mode&63)throw Error(`Concurrent directory creation did not publish a safe directory.`)}Y_(w(e))}}function Y_(e){let n=c(e,`r`);try{i(n)}finally{t(n)}}function X_({directoryMode:e,mode:n,path:r,value:a}){let o=w(r);J_(o,e);let s=T(o,`.${String(process.pid)}.${le()}.tmp`),l,u,d;try{l=c(s,`wx`,n),t(l),l=void 0,y(s,`${JSON.stringify(a,null,2)}\n`,`utf8`),u=c(s,`r`),i(u),t(u),u=void 0,m(s,r),d=c(o,`r`),i(d),t(d),d=void 0}catch(e){l!==void 0&&t(l),u!==void 0&&t(u),d!==void 0&&t(d);try{v(s)}catch{}throw e}}var Z_=A().regex(/^[a-f0-9]{40}$/u),Q_=A().regex(/^sha256:[a-f0-9]{64}$/u),$_=P({artifactId:Q_,authorIdentity:A().min(1),checks:N(A().min(1)).min(1),diffScopeHash:Q_,deliveryMetrics:P({blockerTimeMs:j().int().nonnegative().nullable(),reviewRound:j().int().positive()}).strict().optional(),elapsedMs:j().int().nonnegative(),findings:N(A()),head:P({sha:Z_,tree:Z_}).strict(),issueNumber:j().int().positive(),prNumber:j().int().positive().nullable(),readOnly:L(!0),requestedEffort:A().min(1),requestedModel:A().min(1),effectiveEffort:A().min(1),effectiveModel:A().min(1),reviewerIdentity:A().min(1),schemaVersion:L(`ai-delivery.review-artifact@1`),summary:A().min(1),verdict:I([`approve`,`request-changes`])}).strict().superRefine((e,t)=>{let{artifactId:n,...r}=e;(n!==V(r)||e.authorIdentity===e.reviewerIdentity)&&t.addIssue({code:`custom`,message:`Review artifact identity or role separation is invalid.`})});P({artifact:$_,completedAt:mu(),githubReviewId:j().int().positive(),githubReviewUrl:tl(),headSha:Z_,login:A().min(1),prNumber:j().int().positive(),publicationEvidenceId:Q_,receiptId:Q_,schemaVersion:L(`ai-delivery.review-receipt@1`),state:L(`APPROVED`)}).strict().superRefine((e,t)=>{let{receiptId:n,...r}=e;(n!==V(r)||e.headSha!==e.artifact.head.sha||e.artifact.prNumber!==null&&e.artifact.prNumber!==e.prNumber)&&t.addIssue({code:`custom`,message:`Submitted review receipt is not bound to its artifact.`})});async function ev(e,t,n,r){let i;try{i=await e.clients.graphql(`query DeliveryReviewDecision($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid reviewDecision } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t})}catch{return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; review decision readback is unavailable.`}}let a=i.repository?.pullRequest;if(!a)return{reviewDecision:null,submittedReviewAuthorCanPushToRepository:null,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; PR decision readback is unavailable.`};if(a.headRefOid!==n)throw new R(`GitHub review decision does not match the exact PR head.`);let o=null;if(r)try{let i=await e.clients.graphql(`query DeliveryReviewAccess($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviews(last: 100) { nodes { fullDatabaseId author { login } authorCanPushToRepository commit { oid } state } } } } }`,{owner:e.repo.owner,name:e.repo.repo,number:t}),a=r.login.toLowerCase().replace(/\[bot\]$/u,``),s=i.repository?.pullRequest?.reviews.nodes.find(e=>e!==null&&String(e.fullDatabaseId)===String(r.id)&&e.author?.login.toLowerCase().replace(/\[bot\]$/u,``)===a&&e.commit?.oid===n&&e.state===`APPROVED`);typeof s?.authorCanPushToRepository==`boolean`&&(o=s.authorCanPushToRepository)}catch{}return a.reviewDecision===`APPROVED`?{reviewDecision:`APPROVED`,submittedReviewAuthorCanPushToRepository:o,status:`satisfied`,nextAction:`Continue only after required checks pass.`}:a.reviewDecision===`REVIEW_REQUIRED`?{reviewDecision:`REVIEW_REQUIRED`,submittedReviewAuthorCanPushToRepository:o,status:`still-required`,nextAction:o===!1?`GitHub still requires a qualifying approval; the submitted reviewer App review has no repository write access. Inspect the active rule and the App installation Contents grant, then obtain approval from an eligible independent reviewer.`:`GitHub still requires a qualifying approval. Inspect the active rule and obtain approval from an eligible independent reviewer; do not change actors or protections automatically.`}:a.reviewDecision===`CHANGES_REQUESTED`?{reviewDecision:`CHANGES_REQUESTED`,submittedReviewAuthorCanPushToRepository:o,status:`changes-requested`,nextAction:`Resolve the blocking review and obtain a fresh exact-head independent approval.`}:{reviewDecision:null,submittedReviewAuthorCanPushToRepository:o,status:`unknown`,nextAction:`Inspect the PR review requirement in GitHub before merge; no required-review decision was exposed.`}}function tv(e){let t=typeof e==`string`?JSON.parse(e):e;return $_.parse(t)}function nv(e){try{if(typeof e!=`string`||Buffer.byteLength(e,`utf8`)>65536)throw Error(`Invalid size.`);let t=e.match(/<!-- ai-delivery-review-artifact:[\s\S]*?-->/gu)??[],n=e.match(/<!-- ai-delivery-review-artifact-data:[\s\S]*?-->/gu)??[];if(t.length!==1||n.length!==1)throw Error(`Ambiguous binding.`);let r=t[0].match(/^<!-- ai-delivery-review-artifact: (sha256:[a-f0-9]{64}) -->$/u)?.[1],i=n[0].match(/^<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->$/u)?.[1];if(!r||!i)throw Error(`Invalid binding.`);let a=Buffer.from(i,`base64url`),o=a.toString(`utf8`);if(a.toString(`base64url`)!==i||!Buffer.from(o,`utf8`).equals(a))throw Error(`Invalid encoding.`);let s=tv(o);if(s.artifactId!==r)throw Error(`Artifact identity differs.`);return s}catch{throw new R(`GitHub review artifact binding is missing, invalid or ambiguous; obtain a fresh review.`)}}function rv(e){$_.parse(e);let t=`${e.summary}\n\n<!-- ai-delivery-review-artifact: ${e.artifactId} -->\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(e)).toString(`base64url`)} -->`;return nv(t),t}async function iv(e,t,n){let r=[];for(let n=1;n<=30;n++){let i=(await e.clients.rest.pulls.listFiles({...e.repo,pull_number:t,page:n,per_page:100})).data;if(r.push(...i.map(e=>e.filename)),i.length<100)break}if(!Number.isSafeInteger(n)||r.length!==n||new Set(r).size!==r.length)throw new R(`Independent review scope is incomplete or differs from the remote PR diff.`);return V(r.sort())}async function av(e,t){let n=[];for(let r=1;r<=20;r+=1){let i=await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,per_page:100,page:r});if(n.push(...i.data),i.data.length<100)return n}throw new R(`Review history exceeds the bounded readback window.`)}async function ov(e){let{artifact:t,context:n,issueNumber:r,prNumber:i}=e;if($_.parse(t),t.verdict!==`approve`||t.issueNumber!==r||t.authorIdentity!==n.config.roles.author.identity||t.reviewerIdentity!==n.config.roles.reviewer.identity||t.prNumber!==null&&t.prNumber!==i)throw new R(`Independent review artifact is foreign or rejected.`);if(n.clients.authSource!==`app`||n.clients.role!==`reviewer`||!n.clients.appActorLogin)throw new R(`Formal review requires the independent reviewer GitHub App role.`);let a=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(a.number!==i||a.head.sha!==t.head.sha||a.state!==`open`||a.base.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase()||a.head.repo?.full_name.toLowerCase()!==n.config.repository.toLowerCase())throw new R(`PR identity or head changed before formal review.`);let o=await n.clients.appActorLogin();if(!o||!a.user?.login||o.toLowerCase()===a.user.login.toLowerCase())throw new R(`Reviewer GitHub actor must differ from PR author.`);let s=(await n.clients.rest.git.getCommit({...n.repo,commit_sha:t.head.sha})).data;if(s.sha!==t.head.sha||s.tree.sha!==t.head.tree)throw new R(`Independent review tree differs from the remote commit.`);if(t.diffScopeHash!==await iv(n,i,a.changed_files))throw new R(`Independent review scope is incomplete or differs from the remote PR diff.`);let c=rv(t),l=`<!-- ai-delivery-review-artifact: ${t.artifactId} -->`,u=await av(n,i);if(u.some(e=>e.user?.login.toLowerCase()===o.toLowerCase()&&e.commit_id===t.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``)&&!e.body?.includes(l)))throw new R(`Another independent artifact conflicts with the existing exact-head App approval.`);let d=u.filter(e=>e.body?.includes(l));if(d.length>1)throw new R(`Conflicting GitHub reviews claim the same artifact identity.`);let f=d[0];if(f&&(f.state!==`APPROVED`||f.commit_id!==t.head.sha||f.user?.login.toLowerCase()!==o.toLowerCase()||!f.html_url||nv(f.body).artifactId!==t.artifactId))throw new R(`Prior GitHub review marker conflicts with exact-head approval.`);let p=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(p.head.sha!==t.head.sha||p.base.sha!==a.base.sha||p.state!==`open`)throw new R(`PR moved during independent review validation.`);if(e.dryRun)return{dryRun:!0,artifactId:t.artifactId,headSha:t.head.sha};let m=f??(await n.clients.rest.pulls.createReview({...n.repo,pull_number:i,commit_id:t.head.sha,body:c,event:`APPROVE`})).data;if(!m.id||m.state!==`APPROVED`||m.commit_id!==t.head.sha||m.user?.login.toLowerCase()!==o.toLowerCase()||!m.html_url)throw new R(`GitHub did not return complete exact-head independent approval.`);let h={artifact:t,repository:n.config.repository,baseSha:a.base.sha,headSha:t.head.sha,githubReviewId:m.id,githubReviewUrl:m.html_url,login:m.user.login,prNumber:i,schemaVersion:`ai-delivery.github-review@1`,state:`APPROVED`},g={...h,receiptId:V(h)},_=(await n.clients.rest.pulls.getReview({...n.repo,pull_number:i,review_id:m.id})).data;if(_.id!==g.githubReviewId||_.html_url!==g.githubReviewUrl||_.state!==`APPROVED`||_.commit_id!==g.headSha||_.user?.login!==g.login||nv(_.body).artifactId!==t.artifactId)throw new R(`GitHub exact-head App review readback disagrees.`);let v=(await n.clients.rest.pulls.get({...n.repo,pull_number:i})).data;if(v.head.sha!==t.head.sha||v.base.sha!==a.base.sha||v.state!==`open`)throw new R(`PR moved during independent review submission; approval is not current.`);return g}var sv=/^[a-f0-9]{40}$/u,cv=/^(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/u;function lv(e){if(typeof e!=`string`)throw new R(`Incomplete non-closing message readback.`);let t=e.replace(/[*_~`\\<>[\]]/gu,``);if(/\b(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\b(?:\s*:\s*|\s+)[^\n]*?(?:#[0-9]+|[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+#[0-9]+|https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9.-]+\/[A-Za-z0-9.-]+\/(?:issues|pull)\/[0-9]+)/iu.test(t))throw new R(`Non-closing delivery refuses closing directives in body, title or commit messages.`)}function uv(e,t){return`References ${e.config.repository}#${t}`}function dv(e,t,n){lv(n);let r=uv(e,t),i=n.startsWith(`${r}\n`)||n===r?n:`${r}\n\n${n}`;return fv(e,t,i),i}function fv(e,t,n){lv(n);let r=n.split(/\r?\n/u);if(r[0]!==uv(e,t)||r.filter(e=>/^References\s/iu.test(e)).length!==1)throw new R(`Non-closing PR body must retain one leading canonical References line.`)}function pv(e,t){let n=e.pageInfo;if(!n||typeof n.hasNextPage!=`boolean`||n.endCursor!==null&&typeof n.endCursor!=`string`)throw new R(`Incomplete non-closing native pagination.`);if(!n.hasNextPage)return null;if(!n.endCursor||t.has(n.endCursor))throw new R(`Non-closing native pagination did not advance.`);return t.add(n.endCursor),n.endCursor}async function mv(e,t){let n=(await e.clients.rest.issues.get({...e.repo,issue_number:t})).data;if(n.number!==t||`pull_request`in n||n.state!==`open`||typeof n.node_id!=`string`||!n.node_id||typeof n.title!=`string`||typeof n.body!=`string`||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/issues/${t}`.toLowerCase())throw new R(`Non-closing delivery requires the exact canonical OPEN issue and complete title/body.`);return n}function hv(e,t,n=!1){if(n?e.state!==`open`||e.draft||e.merged||t.state!==`closed`||t.draft||!t.merged:e.state!==t.state||e.draft!==t.draft||e.merged!==t.merged)throw new R(`Non-closing PR state/draft/merged readback drifted; reconcile read-only.`);if(e.node_id!==t.node_id||e.head.sha!==t.head.sha||e.head.ref!==t.head.ref||e.base.sha!==t.base.sha||e.base.ref!==t.base.ref||e.body!==t.body||e.title!==t.title||e.user.login.toLowerCase()!==t.user.login.toLowerCase())throw new R(`Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.`)}function gv(e,t){if(e.node_id!==t.node_id||e.title!==t.title||e.body!==t.body)throw new R(`Non-closing issue identity/title/criteria drifted; reconcile read-only.`)}function _v(e){if(e!==void 0&&typeof e!=`boolean`)throw new R(`nonClosing must be a boolean.`);return e===!0}async function vv(e,t){let n=await Nv(e.clients.role===`author`?e:{...e,clients:await _m({config:e.config,identity:e.config.roles.author.identity,role:`author`}),reviewerClients:e.clients},t);if(n.rules.visibility!==`complete`||n.approvalEligibility===`insufficient-permission`)throw new R(`Non-closing delivery requires complete native rule visibility and an independent reviewer route.`);return n}async function yv(e,t){let n=null,r=new Set,i=new Map,a;for(let o=0;o<20;o++){let o=await e.clients.graphql(`query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t.number,cursor:n}),s=o.repository?.pullRequest,c=s?.commits;if(o.repository?.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||s?.id!==t.node_id||s.number!==t.number||s.headRefOid!==t.head.sha||s.baseRefOid!==t.base.sha||s.baseRefName!==t.base.ref||!c||!Array.isArray(c.nodes)||c.nodes.length>100||!Number.isSafeInteger(c.totalCount)||c.totalCount<1||c.totalCount>2e3||a!==void 0&&a!==c.totalCount)throw new R(`Incomplete or moved introduced commit graph at the non-closing head/base.`);a=c.totalCount;for(let e of c.nodes){let t=e?.commit;if(!t||!Cv(t.oid)||i.has(t.oid)||!t.parents||!Array.isArray(t.parents.nodes)||t.parents.nodes.length>100||!Number.isSafeInteger(t.parents.totalCount)||t.parents.totalCount<1||t.parents.totalCount!==t.parents.nodes.length||t.parents.pageInfo?.hasNextPage!==!1||t.parents.nodes.some(e=>!Cv(e?.oid)))throw new R(`Incomplete, duplicate or truncated introduced commit identity/parents.`);lv(t.message),i.set(t.oid,t.message)}if(n=pv(c,r),n===null){if(i.size!==a||!i.has(t.head.sha))throw new R(`Introduced commit count/head is incomplete.`);return}}throw new R(`Non-closing commit graph exceeds the bounded readback window.`)}async function bv(e,t,n){let r=new Set,i;for(let a=1;a<=20;a++){let o=(await e.clients.rest.repos.compareCommitsWithBasehead({...e.repo,basehead:`${t}...${n}`,per_page:100,page:a})).data;if(o.base_commit?.sha!==t||!Cv(o.merge_base_commit?.sha)||![`ahead`,`diverged`].includes(o.status)||!Number.isSafeInteger(o.total_commits)||o.total_commits<1||o.total_commits>2e3||i!==void 0&&i!==o.total_commits||!Array.isArray(o.commits)||o.commits.length>100)throw new R(`Incomplete introduced commit range before non-closing publication.`);i=o.total_commits;for(let e of o.commits){if(!Cv(e.sha)||r.has(e.sha)||!Array.isArray(e.parents)||e.parents.length<1||e.parents.length>100||e.parents.some(e=>!Cv(e.sha)))throw new R(`Incomplete or duplicate introduced commit identity.`);lv(e.commit?.message),r.add(e.sha)}if(r.size===i&&r.has(n))return;if(o.commits.length<100)throw new R(`Truncated introduced commit range before publication.`)}throw new R(`Introduced commit range exceeds the bounded readback window.`)}async function xv(e,t,n){if(typeof n.node_id!=`string`||!n.node_id||n.html_url?.toLowerCase()!==`https://github.com/${e.config.repository}/pull/${n.number}`.toLowerCase())throw new R(`Incomplete non-closing PR node identity.`);fv(e,t,n.body),lv(n.title);let r=await mv(e,t),i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||n.base.ref!==i.default_branch||typeof i.node_id!=`string`||!i.node_id)throw new R(`Non-closing PR must target the canonical default repository/base.`);let a=await vv(e,n.base.ref);if(n.user.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new R(`Non-closing PR author differs from the configured author.`);let o=null,s=new Set,c=new Map,l=!1;for(let u=0;u<20;u++){let d=await e.clients.graphql(`query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:o}),f=d.repository?.issue,p=f?.timelineItems;if(d.repository?.id!==i.node_id||d.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||f?.id!==r.node_id||f.number!==t||f.state!==`OPEN`||!p||!Array.isArray(p.nodes)||p.nodes.length>100)throw new R(`Incomplete or conflicting native non-closing issue identity.`);for(let o of p.nodes){let s=o?.source,u=o?.target;if(!o||!Sv(o.id)||!s||!u||![`Issue`,`PullRequest`].includes(s.__typename)||!Sv(s.id)||!Number.isSafeInteger(s.number)||s.number<=0||!Sv(s.repository?.id)||typeof s.repository.nameWithOwner!=`string`||u.__typename!==`Issue`||u.id!==r.node_id||u.number!==t||u.repository?.id!==i.node_id||u.repository.nameWithOwner?.toLowerCase()!==e.config.repository.toLowerCase()||typeof o.isCrossRepository!=`boolean`||typeof o.willCloseTarget!=`boolean`||!Sv(o.actor?.login))throw new R(`Incomplete native cross-reference event identity/actor.`);let d=JSON.stringify([s.__typename,s.id,s.number,s.repository.id,s.repository.nameWithOwner.toLowerCase(),u.id,u.number,u.repository.id,u.repository.nameWithOwner.toLowerCase(),o.actor.login.toLowerCase(),o.isCrossRepository,o.willCloseTarget]);if(c.has(o.id)&&c.get(o.id)!==d)throw new R(`Conflicting duplicate native reference event.`);if(c.set(o.id,d),s.id===n.node_id||s.__typename===`PullRequest`&&s.number===n.number&&s.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()){if(s.__typename!==`PullRequest`||s.id!==n.node_id||s.number!==n.number||s.repository.id!==i.node_id||s.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||o.isCrossRepository||o.willCloseTarget!==!1||o.actor.login.toLowerCase()!==a.author.actorLogin.toLowerCase())throw new R(`Conflicting, closing or unauthorized native PR reference.`);l=!0}}if(o=pv(p,s),o===null)break;if(u===19)throw new R(`Native non-closing references exceed the bounded readback window.`)}if(!l)throw new R(`Missing authorized native non-closing PR-to-issue reference.`);if(await Ev(e,n.number,t,!0,n.node_id),await yv(e,n),!n.merged){let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${n.base.ref}`})).data;if(t.ref!==`refs/heads/${n.base.ref}`||t.object.type!==`commit`||t.object.sha!==n.base.sha)throw new R(`Non-closing default base has moved or is incomplete.`)}return gv(r,await mv(e,t)),hv(n,await Tv(e,n.number)),r}function Sv(e){return typeof e==`string`&&e.trim().length>0}function Cv(e){return typeof e==`string`&&sv.test(e)}function wv(e){if(typeof e!=`string`||!cv.test(e)||e.startsWith(`/`)||e.endsWith(`/`)||e.endsWith(`.lock`))throw new R(`Invalid GitHub branch name.`)}async function Tv(e,t){if(e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new R(`Configured and selected GitHub repository identities disagree.`);let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data;if(n.number!==t||typeof n.base.repo?.full_name!=`string`||typeof n.head.repo?.full_name!=`string`||n.base.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||n.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!Cv(n.head.sha)||!Cv(n.base.sha)||n.state!==`open`&&n.state!==`closed`||typeof n.merged!=`boolean`||typeof n.draft!=`boolean`||n.merged&&n.state!==`closed`)throw new R(`GitHub PR identity or exact head readback is invalid.`);return wv(n.head.ref),wv(n.base.ref),n}async function Ev(e,t,n,r=!1,i,a=!1,o,s){let c=null,l=new Set,u=0;for(let d=0;d<20;d++){let d=await e.clients.graphql(`query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,{...e.repo,number:t,cursor:c}),f=d.repository?.pullRequest?.closingIssuesReferences;if(typeof d.repository?.nameWithOwner!=`string`||d.repository.nameWithOwner.toLowerCase()!==e.config.repository.toLowerCase()||d.repository?.pullRequest?.number!==t||i!==void 0&&d.repository?.pullRequest?.id!==i||!f||!Array.isArray(f.nodes)||f.nodes.length>100||typeof f.pageInfo?.hasNextPage!=`boolean`||f.pageInfo.endCursor!==null&&typeof f.pageInfo.endCursor!=`string`)throw new R(`Incomplete or conflicting native GitHub PR issue association readback.`);for(let t of f.nodes){if(a&&(!t||t.__typename!==`Issue`||!Sv(o)||t.id!==o||!Sv(s)||t.repository?.id!==s))throw new R(`Incomplete or conflicting typed closing issue/repository identity before body transition.`);if(r)throw new R(`Non-closing PR has an unintended native closing association.`);if(!t||!Number.isSafeInteger(t.number)||t.number<=0||typeof t.repository?.nameWithOwner!=`string`||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(t.repository.nameWithOwner))throw new R(`Incomplete native PR closing-issue identity.`);if(t.number===n&&t.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase())u++;else if(a)throw new R(`Existing PR has conflicting closing associations; body transition refused.`)}if(!f.pageInfo.hasNextPage){if(!r&&u!==1)throw new R(`Native GitHub PR closing-issue association does not identify the intended issue.`);return}let p=f.pageInfo.endCursor;if(!p||l.has(p))throw new R(`Native PR issue pagination did not advance.`);l.add(p),c=p}throw new R(`Native PR issue association exceeds the bounded readback window.`)}async function Dv(e,t,n){let r=[];for(let i=1;i<=20;i++){let a=(await e.clients.rest.pulls.list({...e.repo,head:`${e.repo.owner}:${t}`,...n===void 0?{}:{base:n},state:`all`,page:i,per_page:100})).data;if(!Array.isArray(a)||a.some(e=>!e||!Number.isSafeInteger(e.number)||e.number<=0))throw new R(`Incomplete GitHub PR match readback.`);if(r.push(...a),a.length<100)return r}throw new R(`GitHub PR match history exceeds the bounded readback window.`)}async function Ov(e,t,n,r=!1){let i=await Tv(e,n);if(r?await xv(e,t,i):await Ev(e,n,t),!i.merged){let n=await H_(e,t);if(n.length>0){let e=n.filter(e=>e.name===i.head.ref);if(e.length!==1||e[0].sha!==i.head.sha)throw new R(`Native linked issue branches conflict with the exact PR head/ref.`)}let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.head.ref}`})).data;if(r.ref!==`refs/heads/${i.head.ref}`||r.object.type!==`commit`||r.object.sha!==i.head.sha)throw new R(`Current remote PR head/ref readback is incomplete or has moved.`)}return i}async function kv(e,t){let n=_v(t.nonClosing);if(n&&(t.issueNumber===void 0||t.prNumber===void 0))throw new R(`Non-closing inspection requires explicit canonical issue and PR numbers.`);let r=t.prNumber;if(r===void 0){if(t.issueNumber===void 0)throw new R(`prNumber or issueNumber is required.`);let n=await H_(e,t.issueNumber);if(n.length!==1)throw new R(`Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.`);let i=n[0].name,a=await Dv(e,i);if(a.length!==1)throw new R(`Select an explicit PR number when the remote issue branch has zero or multiple PRs.`);r=a[0].number}let i=t.issueNumber===void 0?await Tv(e,r):await Ov(e,t.issueNumber,r,n);return{prNumber:i.number,url:i.html_url,state:i.state,draft:i.draft,headSha:i.head.sha,headBranch:i.head.ref,baseBranch:i.base.ref,merged:i.merged}}async function Av(e,t=`open`){return{schemaVersion:`ai-delivery.pr-list@1`,pullRequests:(await e.clients.rest.paginate(e.clients.rest.pulls.list,{...e.repo,state:t,per_page:100})).map(e=>({number:e.number,state:e.state,draft:e.draft??!1,headSha:e.head.sha,baseSha:e.base.sha,url:e.html_url}))}}async function jv(e,t){let n=(await e.clients.rest.pulls.get({...e.repo,pull_number:t})).data,[r,i,a]=await Promise.all([e.clients.rest.checks.listForRef({...e.repo,ref:n.head.sha,per_page:100}),e.clients.rest.repos.getCombinedStatusForRef({...e.repo,ref:n.head.sha}),ev(e,t,n.head.sha)]);return{schemaVersion:`ai-delivery.pr-checks@1`,prNumber:n.number,headSha:n.head.sha,combinedStatus:i.data.state,reviewState:a,checkRuns:r.data.check_runs.map(e=>({name:e.name,status:e.status,conclusion:e.conclusion}))}}function Mv(e){if(typeof e!=`object`||!e)return null;let t=e.required_approving_review_count;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:null}async function Nv(e,t,n,r=`publication`,i){if(t===void 0)try{t=(await e.clients.rest.repos.get({...e.repo})).data.default_branch}catch{throw new R(`Author cannot read the selected GitHub repository; verify configured access.`)}let a=async()=>{await i?.checkResources(),i?.signal.throwIfAborted()};await a();let o=e.config.roles.author.authSource??`app`,s=r===`development`&&o===`app`&&e.clients.authSource===`personal`;if(e.clients.authSource!==o&&!s)throw new R(r===`publication`?`PR publication requires the configured author credential; configure the personal author role for personal publication.`:`Development access preflight requires the configured author credential or the explicit personal author override.`);if(e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new R(`Delivery access preflight requires authenticated author identity readback.`);let c=await e.clients.authenticatedAuthor(i?.signal);if(await a(),!c.actorLogin||!c.credentialIdentity)throw new R(`Author GitHub identity readback is incomplete.`);let l=n??e.reviewerClients??await _m({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients,...i===void 0?{}:{signal:i.signal}});if(await a(),l.role!==`reviewer`||l.authSource!==`app`||!l.appActorLogin)throw new R(`Configured reviewer GitHub App identity is unavailable.`);let u=await l.appActorLogin(i?.signal);if(await a(),!u)throw new R(`Reviewer GitHub App actor lookup is incomplete.`);if(c.actorLogin.toLowerCase()===u.toLowerCase())throw new R(`Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.`);try{let t=(await l.rest.repos.get({...e.repo,...i===void 0?{}:{request:{signal:i.signal}}})).data;if(await a(),t.full_name.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new R(`Reviewer GitHub App repository readback disagrees with the selected checkout.`)}catch(e){throw e instanceof R?e:new R(`Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.`)}let[d,f]=await Promise.allSettled([e.clients.rest.request(`GET /repos/{owner}/{repo}/rules/branches/{branch}`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}}),e.clients.rest.request(`GET /repos/{owner}/{repo}/branches/{branch}/protection`,{...e.repo,branch:t,...i===void 0?{}:{request:{signal:i.signal}}})]);await a();let p=[];if(d.status===`fulfilled`&&Array.isArray(d.value.data)){for(let e of d.value.data)if(e.type===`pull_request`){let t=Mv(e.parameters);t!==null&&p.push(t)}}if(f.status===`fulfilled`){let e=f.value.data,t=Mv(e.required_pull_request_reviews);t!==null&&p.push(t)}let m=Number(d.status===`fulfilled`)+Number(f.status===`fulfilled`),h=m===2?`complete`:m===1?`partial`:`unknown`,g=p.length>0?Math.max(...p):null,_=g!==null&&g>0&&l.effectiveContentsPermission===`read`;return{author:{actorLogin:c.actorLogin,authSource:e.clients.authSource,credentialSource:e.clients.credentialSource??`unreported`,identity:s?`personal`:e.config.roles.author.identity},reviewer:{actorLogin:u,credentialSource:l.credentialSource??`unreported`,effectiveContentsPermission:l.effectiveContentsPermission??`unknown`,identity:e.config.roles.reviewer.identity,repositoryAccess:`readable`},rules:{observedRequiredApprovals:g,visibility:h},approvalEligibility:_?`insufficient-permission`:`unknown`,nextAction:_?`The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.`:h===`complete`&&g===null?`No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.`:h===`complete`?`Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.`:`Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.`}}async function Pv(e,t){let n=_v(t.nonClosing);if(t.prNumber!==void 0&&(!Number.isSafeInteger(t.prNumber)||t.prNumber<=0))throw new R(`Existing PR selector must be a positive safe integer.`);let r=n?await mv(e,t.issueNumber):(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(`pull_request`in r||r.number!==t.issueNumber||r.state!==`open`)throw new R(`PR creation requires the requested open GitHub issue.`);let i=(await e.clients.rest.repos.get({...e.repo})).data;if(i.full_name?.toLowerCase()!==e.config.repository.toLowerCase()||e.config.repository.toLowerCase()!==`${e.repo.owner}/${e.repo.repo}`.toLowerCase())throw new R(`Configured and selected GitHub repository identities disagree.`);if(n&&!Sv(i.node_id))throw new R(`Incomplete canonical non-closing repository node identity.`);let a=t.baseBranch??i.default_branch;if(a!==i.default_branch)throw new R(`PR delivery requires the repository default branch for durable issue association.`);wv(a),t.headBranch!==void 0&&wv(t.headBranch);let o=t.prNumber===void 0?void 0:await Tv(e,t.prNumber),s=t.draft===!1&&t.headBranch!==void 0,c=o?await Dv(e,o.head.ref,a):s?await Dv(e,t.headBranch,a):void 0,l=o?o.head.ref:s&&c.length>0?t.headBranch:await U_(e,t.issueNumber,t.headBranch);if(t.headBranch!==void 0&&l!==t.headBranch)throw new R(`Explicit PR and head selectors disagree.`);wv(l);let u=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data;if(u.ref!==`refs/heads/${l}`||u.object.type!==`commit`||!Cv(u.object.sha))throw new R(`Remote issue branch head/ref readback is invalid.`);let d=c??await Dv(e,l,a);if(d.length>1||o&&(d.length!==1||d[0].number!==o.number))throw new R(`Remote issue branch has conflicting PR matches.`);let f=o??(d[0]===void 0?void 0:await Tv(e,d[0].number)),p=t.body??(n?f?.body??uv(e,t.issueNumber):`Closes #${t.issueNumber}`);if(!p.trim())throw new R(`PR body must contain text.`);let m=n?dv(e,t.issueNumber,p):RegExp(`(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\s+#${t.issueNumber}(?![0-9])`,`iu`).test(p)?p:`${p}\n\nCloses #${t.issueNumber}`,h=n&&f!==void 0&&f.body!==m;if(h&&(t.prNumber===void 0||t.body===void 0))throw new R(`Non-closing body transition requires an explicit existing PR number and body.`);if(f&&(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a||f.state!==`open`||f.merged||!h&&t.body!==void 0&&f.body!==m||t.title!==void 0&&f.title!==t.title))throw new R(`Existing remote PR conflicts with the requested branch, intent or state.`);let g=n?await vv(e,a):await Nv(e,a);if(f&&f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new R(`Existing PR author differs from the configured authenticated author.`);if(f&&(typeof f.node_id!=`string`||!f.node_id))throw new R(`Existing PR publication identity is incomplete.`);n&&lv(t.title??f?.title??r.title);let _=t.title??r.title,v,y=f,b=h,x=f?.body,S=f?.draft,C=!1,w=async()=>{n&&gv(r,await mv(e,t.issueNumber))},ee=async()=>{let o=await Ov(e,t.issueNumber,y.number,n&&!b);if(o.state!==`open`||o.merged||o.node_id!==y.node_id||o.head.sha!==u.object.sha||o.head.ref!==l||o.base.ref!==a||o.base.sha!==y.base.sha||o.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase()||h&&!C&&o.draft!==S||o.body!==x||o.title!==y.title)throw new R(`Existing PR publication head, identity, intent or author readback drifted.`);if(b){await Ev(e,o.number,t.issueNumber,!1,o.node_id,!0,r.node_id,i.node_id),lv(o.title),await yv(e,o);let n=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(n.ref!==`refs/heads/${a}`||n.object.type!==`commit`||n.object.sha!==o.base.sha)throw new R(`Non-closing transition default base drifted.`);hv(o,await Tv(e,o.number))}return await w(),o},T=async()=>{let t=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(t.ref!==`refs/heads/${a}`||t.object.type!==`commit`||!Cv(t.object.sha))throw new R(`Incomplete publication default base.`);if(v!==void 0&&v!==t.object.sha)throw new R(`Publication default base drifted before creation.`);v=t.object.sha,n&&await bv(e,t.object.sha,u.object.sha);let r=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${l}`})).data,i=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${a}`})).data;if(r.ref!==u.ref||r.object.type!==`commit`||r.object.sha!==u.object.sha||i.ref!==t.ref||i.object.type!==`commit`||i.object.sha!==t.object.sha)throw new R(`Non-closing publication head/base drifted.`);await w()};if(f?f=await ee():await T(),t.dryRun)return{dryRun:!0,...f===void 0?{}:{prNumber:f.number,draft:f.draft},...n?{nonClosing:!0,nonClosingVerified:f!==void 0&&!b,body:m,bodyTransition:b}:{},headSha:u.object.sha,headBranch:l,baseBranch:a,reviewRoute:g};let te=!1;if(f){if(b&&(f=await ee(),await e.clients.rest.pulls.update({...e.repo,pull_number:f.number,body:m}),b=!1,x=m,f=await ee()),t.draft===!1&&f.draft){if(f=await ee(),f.draft){let t=await e.clients.graphql(`mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}`,{id:f.node_id});if(t?.markPullRequestReadyForReview?.pullRequest?.id!==f.node_id||t.markPullRequestReadyForReview.pullRequest.isDraft!==!1)throw new R(`PR promotion mutation readback is incomplete or conflicting; reconcile this PR.`);C=!0}if(f=await ee(),f.draft)throw new R(`PR promotion readback is still draft.`)}}else{await T();let n;try{n=await e.clients.rest.pulls.create({...e.repo,head:l,base:a,title:_,body:m,draft:t.draft!==!1})}catch(e){throw new R(`PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${e instanceof Error?e.message:`Unknown failure`}`)}if(!Number.isSafeInteger(n.data.number)||n.data.number<=0)throw new R(`PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.`);te=!0;try{f=await Tv(e,n.data.number)}catch(e){throw new R(`GitHub returned created PR #${n.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`)}}try{if(te&&(f.body!==m||f.title!==_||f.draft!==(t.draft!==!1)||f.state!==`open`||f.merged||f.base.sha!==v))throw new R(`Created PR body, title, draft/open state or default base differs from publication intent.`);if(f.head.sha!==u.object.sha||f.head.ref!==l||f.base.ref!==a)throw new R(`GitHub PR creation readback drifted.`);if(f.user.login.toLowerCase()!==g.author.actorLogin.toLowerCase())throw new R(`Published PR author differs from the configured authenticated author.`);if(n){let n=await Ov(e,t.issueNumber,f.number,!0);hv(f,n),f=n,await w()}else await Ev(e,f.number,t.issueNumber);if(te){let t=await Tv(e,f.number);hv(f,t),f=t}}catch(e){throw te?new R(`GitHub created PR #${f.number} (${f.html_url}) at ${f.head.sha}; post-publication association/identity verification is unresolved. Reconcile this PR read-only; do not create again. ${e instanceof Error?e.message:`Unknown failure`}`):e}return{prNumber:f.number,url:f.html_url,headSha:f.head.sha,draft:f.draft,reviewRoute:g,...n?{nonClosing:!0}:{}}}async function Fv(e,t){let n=_v(t.nonClosing),r=await Ov(e,t.issueNumber,t.prNumber,n),i=n?await mv(e,t.issueNumber):void 0,a=await ov({context:e,artifact:tv(t.artifact),issueNumber:t.issueNumber,prNumber:t.prNumber,...t.dryRun===void 0?{}:{dryRun:t.dryRun}});return n&&(hv(r,await Ov(e,t.issueNumber,t.prNumber,!0)),gv(i,await mv(e,t.issueNumber))),a}async function Iv(e,t){let n=[];for(let r=1;r<=20;r++){let i=(await e.clients.rest.pulls.listReviews({...e.repo,pull_number:t,page:r,per_page:100})).data;if(n.push(...i),i.length<100)return n}throw new R(`GitHub review history exceeds the bounded readback window.`)}async function Lv(e,t){let n=_v(t.nonClosing);if(n&&t.strategy!==void 0&&t.strategy!==`squash`)throw new R(`Non-closing merge requires squash with explicit safe messages.`);if(e.clients.role!==`author`||e.clients.authSource!==(e.config.roles.author.authSource??`app`)||!e.clients.authenticatedAuthor)throw new R(`Merge and finish require the configured authenticated author role.`);let r=await e.clients.authenticatedAuthor();if(!r.actorLogin||!r.credentialIdentity)throw new R(`Author identity readback is incomplete.`);let i=await Ov(e,t.issueNumber,t.prNumber,n),a=i,o=n?await mv(e,t.issueNumber):void 0,s=n?{commit_title:i.title,commit_message:`${uv(e,t.issueNumber)}\n\nDelivered by PR #${i.number}.`}:void 0;if(s&&(lv(s.commit_title),lv(s.commit_message)),t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==i.head.sha)throw new R(`Requested reviewed head differs from the GitHub PR.`);if(i.merged&&i.state===`closed`&&Cv(i.merge_commit_sha))return{mergeSha:i.merge_commit_sha,headSha:i.head.sha,reused:!0};if((await Nv(e,i.base.ref)).approvalEligibility===`insufficient-permission`)throw new R(`Configured reviewer App is ineligible for the required approval.`);if(i.state!==`open`||i.draft)throw new R(`GitHub PR must be open and ready for merge.`);let c=e.reviewerClients??await _m({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(c.role!==`reviewer`||c.authSource!==`app`||!c.appActorLogin)throw new R(`Independent reviewer App route is unavailable.`);let l=await c.appActorLogin();if(!i.user?.login||l.toLowerCase()===i.user.login.toLowerCase())throw new R(`Reviewer App must differ from the PR author.`);let u=(await Iv(e,t.prNumber)).filter(e=>e.user?.login.toLowerCase()===l.toLowerCase()&&e.commit_id===i.head.sha&&e.state===`APPROVED`&&/<!-- ai-delivery-review-artifact: sha256:[a-f0-9]{64} -->/u.test(e.body??``));if(u.length!==1)throw new R(`GitHub requires one unambiguous exact-head independent App review.`);let d=u[0],f=(await e.clients.rest.pulls.getReview({...e.repo,pull_number:t.prNumber,review_id:d.id})).data;if(f.id!==d.id||f.state!==`APPROVED`||f.commit_id!==i.head.sha||f.user?.login.toLowerCase()!==l.toLowerCase()||f.body!==d.body)throw new R(`Independent GitHub review readback changed or was dismissed.`);let p=nv(f.body);if(p.verdict!==`approve`||p.issueNumber!==t.issueNumber||p.prNumber!==null&&p.prNumber!==t.prNumber||p.authorIdentity!==e.config.roles.author.identity||p.reviewerIdentity!==e.config.roles.reviewer.identity||p.head.sha!==i.head.sha)throw new R(`Independent review artifact binding is stale, foreign or rejected.`);let m=(await e.clients.rest.git.getCommit({...e.repo,commit_sha:i.head.sha})).data;if(m.sha!==p.head.sha||m.tree.sha!==p.head.tree)throw new R(`Independent review tree differs from the remote commit.`);if(p.diffScopeHash!==await iv(e,t.prNumber,i.changed_files))throw new R(`Independent review scope differs from the remote PR diff.`);let h=p.head.sha;if(t.reviewedHeadSha!==void 0&&t.reviewedHeadSha!==h)throw new R(`Requested reviewed head differs from the independent GitHub review.`);let g=await ev(e,t.prNumber,h,{id:d.id,login:l});if(g.submittedReviewAuthorCanPushToRepository!==!0)throw new R(`Specific reviewer App approval is not verifiably qualifying for required review.`);if(g.status!==`satisfied`)throw new R(`GitHub review eligibility is ${g.status}: ${g.nextAction}`);if((await Vg({graphql:e.clients.graphql,issueNumber:t.issueNumber,repo:e.repo})).blockers.some(e=>e.state===`OPEN`))throw new R(`GitHub issue has unresolved native blockers.`);if(i=await Ov(e,t.issueNumber,t.prNumber,n),n&&(hv(a,i),gv(o,await mv(e,t.issueNumber)),lv(s.commit_title),lv(s.commit_message)),i.head.sha!==h||i.state!==`open`||i.draft||i.mergeable!==!0||i.mergeable_state!==`clean`)throw new R(`GitHub merge eligibility is ${i.mergeable_state??`unknown`}; CLEAN at the reviewed head is required.`);let _=(await e.clients.rest.git.getRef({...e.repo,ref:`heads/${i.base.ref}`})).data.object.sha;if(!Cv(_)||_!==i.base.sha)throw new R(`GitHub base moved; refresh clean eligibility and independent review before merge.`);if(t.dryRun)return{dryRun:!0,headSha:h,prNumber:i.number,...s===void 0?{}:{nonClosing:!0,...s}};let v=(await e.clients.rest.pulls.merge({...e.repo,pull_number:t.prNumber,sha:h,merge_method:t.strategy??`squash`,...s})).data;if(!v.merged||!Cv(v.sha))throw new R(`GitHub refused the reviewed-head merge.`);let y=await Ov(e,t.issueNumber,t.prNumber,n);if(n&&(hv(a,y,!0),gv(o,await mv(e,t.issueNumber))),!y.merged||y.state!==`closed`||y.head.sha!==h||y.merge_commit_sha!==v.sha)throw new R(`GitHub merged PR readback disagrees with the reviewed-head mutation.`);return{mergeSha:v.sha,headSha:h,reused:!1}}async function Rv(e,t){if(_v(t.nonClosing))throw new R(`Non-closing delivery cannot finish or close its retained issue.`);let n=await Lv(e,t);if(t.dryRun)return n;let r=await Ov(e,t.issueNumber,t.prNumber);if(!r.merged||r.state!==`closed`||r.merge_commit_sha!==n.mergeSha)throw new R(`Intended GitHub PR is not verifiably merged; issue remains open.`);let i=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(i.number!==t.issueNumber||`pull_request`in i)throw new R(`Finish target is not the intended GitHub issue.`);i.state!==`closed`&&await e.clients.rest.issues.update({...e.repo,issue_number:t.issueNumber,state:`closed`,state_reason:`completed`});let a=(await e.clients.rest.issues.get({...e.repo,issue_number:t.issueNumber})).data;if(a.number!==t.issueNumber||a.state!==`closed`)throw new R(`GitHub issue closure readback disagrees.`);return{...n,issueClosed:!0}}var zv=A().regex(/^sha256:[a-f0-9]{64}$/u),Bv=2,Vv=P({admissionId:zv,capability:P({cli:j().int().positive(),mcp:j().int().positive()}).strict(),cliPath:A().min(1),cliSha256:zv,configDigest:zv,mcpLauncherPath:A().min(1),mcpLauncherSha256:zv,packageDistSha256:zv,packageManifestSha256:zv,packageVersion:A().min(1),pluginManifestPath:A().min(1),pluginManifestSha256:zv,repository:A().min(1),schemaVersion:L(`ai-delivery.runtime-admission@2`),sourceArchiveSha256:zv,sourceCommit:A().regex(/^[a-f0-9]{40}$/u)}).strict().superRefine((e,t)=>{let{admissionId:n,...r}=e;n!==V(r)&&t.addIssue({code:`custom`,message:`Runtime admission identity is invalid.`})});function Hv(e){return`sha256:${se(`sha256`).update(l(e)).digest(`hex`)}`}function Uv(e){let t=[],n=(e,r)=>{for(let i of d(e,{withFileTypes:!0}).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))){let a=T(e,i.name),o=r?`${r}/${i.name}`:i.name;if(i.isDirectory())n(a,o);else if(i.isFile())t.push({path:o,sha256:Hv(a)});else throw new R(`Runtime distribution contains an unsupported link or file type.`)}};if(n(e,``),t.length===0)throw new R(`Runtime distribution is empty.`);return V(t)}function Wv(e){let t=JSON.parse(l(e,`utf8`));if(typeof t!=`object`||!t||Array.isArray(t))throw new R(`Runtime package or plugin manifest is invalid.`);return t}async function Gv(e){let t=Eu(e.repoRoot),n=e.configuration??await sh(t,e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}),r=T(Du(t),`ai-delivery`,`runtime-admission.json`),i;try{i=Vv.parse(JSON.parse(U(r).toString(`utf8`)))}catch{throw new R(`Missing or invalid private ai-delivery runtime admission; refresh the installed binding before lifecycle mutation.`)}return Kv(i,n,e.runtimeEntryPath)}function Kv(e,t,n){let r=n??process.argv[1];if(!r)throw new R(`Running ai-delivery entry path is unavailable.`);try{let n=p(r),i=p(e.mcpLauncherPath),a=p(e.pluginManifestPath),o=w(n),s=T(w(o),`package.json`),c=Wv(s),l=Wv(a);if(n!==e.cliPath||i!==e.mcpLauncherPath||a!==e.pluginManifestPath||p(T(w(w(i)),`.claude-plugin`,`plugin.json`))!==a||Hv(n)!==e.cliSha256||Hv(i)!==e.mcpLauncherSha256||Hv(a)!==e.pluginManifestSha256||Hv(s)!==e.packageManifestSha256||Uv(o)!==e.packageDistSha256||e.configDigest!==t.configDigest||e.repository!==t.config.repository||e.capability.cli!==Bv||e.capability.mcp!==Bv||c.name!==`@aviaratech/ai-delivery`||c.version!==e.packageVersion||l.name!==`ai-delivery`||l.packageVersion!==e.packageVersion||l.deliveryCapabilityVersion!==Bv)throw new R(`Installed CLI/MCP source, capability or repository admission disagrees with the running delivery contract.`)}catch(e){throw e instanceof R?e:new R(`Installed CLI/MCP source or capability readback is unavailable.`)}return e}function qv(e){for(let t of[e.cliPath,e.mcpLauncherPath,e.pluginManifestPath])if(p(t)!==t)throw new R(`Installed runtime paths must be canonical regular files.`);let t=w(e.cliPath),n=T(w(t),`package.json`),r=Wv(n).bin;if(typeof r!=`object`||!r||!(`ai-delivery`in r)||r[`ai-delivery`]!==`./dist/cli.js`)throw new R(`Installed package CLI entry is not the supported ai-delivery executable.`);let i={capability:{cli:Bv,mcp:Bv},cliPath:e.cliPath,cliSha256:Hv(e.cliPath),configDigest:e.configuration.configDigest,mcpLauncherPath:e.mcpLauncherPath,mcpLauncherSha256:Hv(e.mcpLauncherPath),packageDistSha256:Uv(t),packageManifestSha256:Hv(n),packageVersion:e.packageVersion,pluginManifestPath:e.pluginManifestPath,pluginManifestSha256:Hv(e.pluginManifestPath),repository:e.configuration.config.repository,schemaVersion:`ai-delivery.runtime-admission@2`,sourceArchiveSha256:e.sourceArchiveSha256,sourceCommit:e.sourceCommit};return Kv(Vv.parse({...i,admissionId:V(i)}),e.configuration,e.cliPath)}var Jv=D(((e,t)=>{var n=De(`constants`),r=process.cwd,i=null,a=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return i||=r.call(process),i};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var o=process.chdir;process.chdir=function(e){i=null,o.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,o)}t.exports=s;function s(e){n.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),a===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,r,i){e.open(t,n.O_WRONLY|n.O_SYMLINK,r,function(t,n){if(t){i&&i(t);return}e.fchmod(n,r,function(t){e.close(n,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,r){var i=e.openSync(t,n.O_WRONLY|n.O_SYMLINK,r),a=!0,o;try{o=e.fchmodSync(i,r),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function r(e){n.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,r,i,a){e.open(t,n.O_SYMLINK,function(t,n){if(t){a&&a(t);return}e.futimes(n,r,i,function(t){e.close(n,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,r,i){var a=e.openSync(t,n.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,r,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function o(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!(e&&e.code!==`ENOSYS`&&(process.getuid&&process.getuid()===0||e.code!==`EINVAL`&&e.code!==`EPERM`))}}})),Yv=D(((e,t)=>{var n=De(`stream`).Stream;t.exports=r;function r(e){return{ReadStream:t,WriteStream:r};function t(r,i){if(!(this instanceof t))return new t(r,i);n.call(this);var a=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function r(t,i){if(!(this instanceof r))return new r(t,i);n.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),Xv=D(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),Zv=D(((e,t)=>{var n=De(`fs`),r=Jv(),i=Yv(),a=Xv(),o=De(`util`),s,c;typeof Symbol==`function`&&typeof Symbol.for==`function`?(s=Symbol.for(`graceful-fs.queue`),c=Symbol.for(`graceful-fs.previous`)):(s=`___graceful-fs.queue`,c=`___graceful-fs.previous`);function l(){}function u(e,t){Object.defineProperty(e,s,{get:function(){return t}})}var d=l;o.debuglog?d=o.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(d=function(){var e=o.format.apply(o,arguments);e=`GFS4: `+e.split(/\n/).join(`
|
|
254
|
+
GFS4: `),console.error(e)}),n[s]||(u(n,global[s]||[]),n.close=(function(e){function t(t,r){return e.call(n,t,function(e){e||h(),typeof r==`function`&&r.apply(this,arguments)})}return Object.defineProperty(t,c,{value:e}),t})(n.close),n.closeSync=(function(e){function t(t){e.apply(n,arguments),h()}return Object.defineProperty(t,c,{value:e}),t})(n.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){d(n[s]),De(`assert`).equal(n[s].length,0)})),global[s]||u(global,n[s]),t.exports=f(a(n)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!n.__patched&&(t.exports=f(n),n.__patched=!0);function f(e){r(e),e.gracefulify=f,e.createReadStream=ee,e.createWriteStream=T;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?p([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var a=e.writeFile;e.writeFile=o;function o(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,o){return a(e,t,n,function(a){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([i,[e,t,n,r],a,o||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var m=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=m.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?p([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=i(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;ne(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;ne(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ee(t,n){return new e.ReadStream(t,n)}function T(t,n){return new e.WriteStream(t,n)}var te=e.open;e.open=ne;function ne(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return te(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?p([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function p(e){d(`ENQUEUE`,e[0].name,e[1]),n[s].push(e),g()}var m;function h(){for(var e=Date.now(),t=0;t<n[s].length;++t)n[s][t].length>2&&(n[s][t][3]=e,n[s][t][4]=e);g()}function g(){if(clearTimeout(m),m=void 0,n[s].length!==0){var e=n[s].shift(),t=e[0],r=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)d(`RETRY`,t.name,r),t.apply(null,r);else if(Date.now()-a>=6e4){d(`TIMEOUT`,t.name,r);var c=r.pop();typeof c==`function`&&c.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(d(`RETRY`,t.name,r),t.apply(null,r.concat([a]))):n[s].push(e)}m===void 0&&(m=setTimeout(g,0))}}})),Qv=D(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),$v=D((e=>{var t=Qv();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),ey=D(((e,t)=>{t.exports=$v()})),ty=D(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),ny=D(((e,t)=>{var n=global.process,r=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!r(n))t.exports=function(){return function(){}};else{var i=De(`assert`),a=ty(),o=/^win/i.test(n.platform),s=De(`events`);typeof s!=`function`&&(s=s.EventEmitter);var c;n.__signal_exit_emitter__?c=n.__signal_exit_emitter__:(c=n.__signal_exit_emitter__=new s,c.count=0,c.emitted={}),c.infinite||(c.setMaxListeners(1/0),c.infinite=!0),t.exports=function(e,t){if(!r(global.process))return function(){};i.equal(typeof e,`function`,`a callback must be provided for exit handler`),f===!1&&p();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),c.on(n,e),function(){c.removeListener(n,e),c.listeners(`exit`).length===0&&c.listeners(`afterexit`).length===0&&l()}};var l=function(){f&&r(global.process)&&(f=!1,a.forEach(function(e){try{n.removeListener(e,d[e])}catch{}}),n.emit=g,n.reallyExit=m,--c.count)};t.exports.unload=l;var u=function(e,t,n){c.emitted[e]||(c.emitted[e]=!0,c.emit(e,t,n))},d={};a.forEach(function(e){d[e]=function(){r(global.process)&&n.listeners(e).length===c.count&&(l(),u(`exit`,null,e),u(`afterexit`,null,e),o&&e===`SIGHUP`&&(e=`SIGINT`),n.kill(n.pid,e))}}),t.exports.signals=function(){return a};var f=!1,p=function(){!f&&r(global.process)&&(f=!0,c.count+=1,a=a.filter(function(e){try{return n.on(e,d[e]),!0}catch{return!1}}),n.emit=_,n.reallyExit=h)};t.exports.load=p;var m=n.reallyExit,h=function(e){r(global.process)&&(n.exitCode=e||0,u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),m.call(n,n.exitCode))},g=n.emit,_=function(e,t){if(e===`exit`&&r(global.process)){t!==void 0&&(n.exitCode=t);var i=g.apply(this,arguments);return u(`exit`,n.exitCode,null),u(`afterexit`,n.exitCode,null),i}return g.apply(this,arguments)}}})),ry=D(((e,t)=>{var n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),iy=D(((e,t)=>{var n=De(`path`),r=Zv(),i=ey(),a=ny(),o=ry(),s={};function c(e,t){return t.lockfilePath||`${e}.lock`}function l(e,t,r){if(!t.realpath)return r(null,n.resolve(e));t.fs.realpath(e,r)}function u(e,t,n){let r=c(e,t);t.fs.mkdir(r,i=>{if(!i)return o.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?u(e,{...t,stale:0},n):n(r);if(!d(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));f(e,t,r=>{if(r)return n(r);u(e,{...t,stale:0},n)})})})}function d(e,t){return e.mtime.getTime()<Date.now()-t.stale}function f(e,t,n){t.fs.rmdir(c(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function p(e,t){let n=s[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return m(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let s=o.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,s,s,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?m(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,p(e,t));n.mtime=s,n.lastUpdate=Date.now(),n.updateDelay=null,p(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function m(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),s[e]===t&&delete s[e],t.options.onCompromised(n)}function h(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:r,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),l(e,t,(e,r)=>{if(e)return n(e);let a=i.operation(t.retries);a.attempt(()=>{u(r,t,(e,i,o)=>{if(a.retry(e))return;if(e)return n(a.mainError());let l=s[r]={lockfilePath:c(r,t),mtime:i,mtimePrecision:o,options:t,lastUpdate:Date.now()};p(r,t),n(null,e=>{if(l.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));g(r,{...t,realpath:!1},e)})})})})}function g(e,t,n){t={fs:r,realpath:!0,...t},l(e,t,(e,r)=>{if(e)return n(e);let i=s[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete s[r],f(r,t,n)})}function _(e,t,n){t={stale:1e4,realpath:!0,fs:r,...t},t.stale=Math.max(t.stale||0,2e3),l(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(c(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!d(r,t)))})}function v(){return s}a(()=>{for(let e in s){let t=s[e].options;try{t.fs.rmdirSync(c(e,t))}catch{}}}),t.exports.lock=h,t.exports.unlock=g,t.exports.check=_,t.exports.getLocks=v})),ay=D(((e,t)=>{var n=Zv();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),oy=Te(D(((e,t)=>{var n=iy(),{toPromise:r,toSync:i,toSyncOptions:a}=ay();async function o(e,t){return r(await r(n.lock)(e,t))}function s(e,t){return i(i(n.lock)(e,a(t)))}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1),sy={realpath:!1,retries:0,stale:1e4},cy=200;async function ly(e,{onCompromised:t,onReleaseError:n,onTimeout:r,operation:i,projectRoot:a,timeout:o}){let s=a??process.cwd(),c=E(s,e),l=null,u=typeof o==`number`&&o>0?o:null,d=u===null?null:Math.ceil(u/cy),f=0,p=u===null?null:Date.now()+u,m=!1;try{for(;;){if(d!==null&&f>=d)throw Error(`Lock acquisition timeout after ${u===null?`unknown`:String(u)}ms on ${c}. Another process may be holding the lock.`);f+=1,Pg(`Acquiring lock on ${c}... (attempt ${d===null?String(f):`${String(f)}/${String(d)}`})`);try{l=await oy.lock(c,{...sy,...t===void 0?{}:{onCompromised:t}}),Pg(`Lock acquired on ${c}`);break}catch(e){if(!dy(e))throw e;m||=(Ig(`Unable to acquire lock on ${c} - another agent is modifying it. Retrying...`),!0),p!==null&&u!==null&&Date.now()>=p&&(r?.(),p=Date.now()+u),await uy(cy)}}return await i()}finally{if(l!==null)try{await l(),Pg(`Lock released on ${c}`)}catch(e){n?.(e),Pg(`Failed to release lock on ${c}: ${e instanceof Error?e.message:String(e)}`)}}}function uy(e){return new Promise(t=>setTimeout(t,e))}function dy(e){return typeof e!=`object`||!e?!1:e.code===`ELOCKED`}var fy=F({bounds:F({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe().optional(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:N(A().min(1)).min(1).optional()}),maxSampledAggregateRssBytes:j().int().nonnegative().safe().nullable(),maxSampledNewOutputBytes:j().int().nonnegative().safe().nullable(),minSampledFreeDiskBytes:j().int().nonnegative().safe().nullable(),observation:L(`sampled`),outputBaselineId:A().regex(/^sha256:[a-f0-9]{64}$/u).optional(),processCoverage:L(`observed-processes-only`),sampleCount:j().int().nonnegative().safe()}).superRefine((e,t)=>{(e.maxSampledAggregateRssBytes!==null&&e.maxSampledAggregateRssBytes>e.bounds.maxAggregateRssBytes||e.maxSampledNewOutputBytes!==null&&e.bounds.maxNewOutputBytes!==void 0&&e.maxSampledNewOutputBytes>e.bounds.maxNewOutputBytes||e.minSampledFreeDiskBytes!==null&&e.minSampledFreeDiskBytes<e.bounds.minFreeDiskBytes||e.sampleCount>0&&(e.maxSampledAggregateRssBytes===null||e.minSampledFreeDiskBytes===null)||e.bounds.maxNewOutputBytes!==void 0&&e.sampleCount>0&&e.maxSampledNewOutputBytes===null||e.bounds.maxNewOutputBytes!==void 0!=(e.outputBaselineId!==void 0))&&t.addIssue({code:`custom`,message:`Resource samples do not satisfy their declared bounds.`})});function py(e){let t=[[`maxAggregateRssBytes`,e.maxAggregateRssBytes],[`minFreeDiskBytes`,e.minFreeDiskBytes]];e.maxNewOutputBytes!==void 0&&t.push([`maxNewOutputBytes`,e.maxNewOutputBytes]);for(let[e,n]of t)if(!Number.isSafeInteger(n)||n<=0)throw new R(`Invalid ${e} resource bound.`);if(e.maxNewOutputBytes===void 0!=(e.outputRoots===void 0))throw new R(`Filesystem output limit and output roots must be supplied together.`);if(e.outputRoots!==void 0&&(e.outputRoots.length===0||e.outputRoots.some(e=>!e)))throw new R(`Filesystem output roots must be nonempty paths.`);if(process.platform===`win32`)throw new R(`Resource observation requires POSIX process support.`)}var my=`AI_DELIVERY_OUTPUT_OBSERVATION_GATE`,hy=F({pid:j().int().positive(),identity:A().min(1)}),gy=F({directory:A().min(1),id:$c(),owner:hy}),_y=F({gateId:$c(),id:$c(),kind:I([`scan`,`fixture`]),owner:hy});function vy(){let e=Fy().get(process.pid);if(!e)throw new R(`Filesystem observation gate owner is unavailable.`);return{pid:e.pid,identity:e.identity}}function yy(e){let t=o(e);if(!t.isDirectory()||t.mode&63||p(e)!==e)throw new R(`Filesystem observation gate directory is invalid.`)}function by(e){try{let t=gy.parse(JSON.parse(e));return Sy(t),t}catch(e){throw new R(`Filesystem observation gate capability is invalid or stale: `+(e instanceof Error?e.message:String(e)))}}function xy(e,t=Fy()){let n=t.get(e.pid);return n?.identity===e.identity&&!n.status.startsWith(`Z`)}function Sy(e,t=!1){yy(e.directory);let n=gy.parse(JSON.parse(U(T(e.directory,`gate.json`)).toString(`utf8`))),r=Fy(),i=r.get(process.pid),a=new Set;for(;i&&i.pid!==e.owner.pid&&!a.has(i.pid);)a.add(i.pid),i=r.get(i.ppid);if(V(n)!==V(e)||(t?xy(e.owner,r):!xy(e.owner,r)||i?.identity!==e.owner.identity))throw new R(`Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor.`)}function Cy(e,t){let n=_y.parse(JSON.parse(U(t).toString(`utf8`)));if(n.gateId!==e.id)throw new R(`Filesystem observation gate claim belongs to another run.`);return n}function wy(e){let t=T(e.directory,`requests`);yy(t);let n=d(t);if(n.length>1024||n.some(e=>!/^[a-f0-9-]{36}\.json$/u.test(e)))throw new R(`Filesystem observation gate scan requests are invalid.`);let r=[],i=Fy();for(let a of n){let n;try{n=Cy(e,T(t,a))}catch(e){if(e.code===`ENOENT`)continue;throw e}if(n.kind!==`scan`||a!==n.id+`.json`||!xy(n.owner,i))throw new R(`Filesystem observation gate scan request was abandoned.`);r.push(a)}return r}function Ty(e,t,n){if(V(Cy(e,t))!==V(n))throw new R(`Filesystem observation gate claim changed before release.`);v(t)}async function Ey(e,t,r,i){if(!e)return r();Sy(e);let a={gateId:e.id,id:le(),kind:t,owner:vy()},c=t===`scan`?T(e.directory,`requests`,a.id+`.json`):void 0,l=T(e.directory,`held`),u=T(l,`owner.json`);if(c){let t=T(e.directory,a.id+`.pending`);q_(t,a),m(t,c)}let f,p,h,_=()=>{if(!f)return;let t=o(l);if(!t.isDirectory()||t.dev!==f.dev||t.ino!==f.ino)throw new R(`Filesystem observation gate lock changed before release.`);if(d(l).join(`,`)!==`owner.json`)throw new R(`Filesystem observation gate lock has unrelated metadata.`);Ty(e,u,a),g(l),f=void 0};try{for(;;){if(i?.aborted)throw new R(`Filesystem observation gate wait cancelled.`);Sy(e);let c=wy(e);if(t===`scan`||c.length===0){let n=!1;try{s(l,{mode:448}),n=!0}catch(e){if(e.code!==`EEXIST`)throw e}if(n){let n=o(l);if(f={dev:n.dev,ino:n.ino},q_(u,a),t===`scan`||wy(e).length===0)return await r();_()}}if(n(l))try{yy(l);let n=Cy(e,u);if(p=void 0,!xy(n.owner))throw new R(`Filesystem observation gate fixture or scanner was abandoned.`);if(t===`scan`&&n.kind===`fixture`){if(h?.claimId!==n.id&&(h={claimId:n.id,since:Date.now()}),Date.now()-h.since>5e3)throw new R(`Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled.`)}else h=void 0}catch(e){if(e.code!==`ENOENT`)throw e;if(p??=Date.now(),Date.now()-p>2e3)throw new R(`Filesystem observation gate owner publication is incomplete.`)}await new Promise(e=>setTimeout(e,100))}}finally{try{_()}finally{c&&Ty(e,c,a)}}}function Dy(e,t=!1){Sy(e,t);let r=T(e.directory,`requests`),i=T(e.directory,`held`);if(d(e.directory).some(e=>![`gate.json`,`requests`,`held`].includes(e)))throw new R(`Filesystem observation gate has unrelated or incomplete metadata.`);if(n(i)){if(yy(i),d(i).join(`,`)!==`owner.json`)throw new R(`Filesystem observation gate lock has unrelated metadata.`);let t=Cy(e,T(i,`owner.json`));if(xy(t.owner))throw new R(`Filesystem observation gate still has a live holder.`);Ty(e,T(i,`owner.json`),t),g(i)}for(let t of d(r)){if(!/^[a-f0-9-]{36}\.json$/u.test(t))throw new R(`Filesystem observation gate has unrelated metadata.`);let n=T(r,t),i=Cy(e,n);if(i.kind!==`scan`||t!==i.id+`.json`)throw new R(`Filesystem observation gate has unrelated scan metadata.`);if(xy(i.owner))throw new R(`Filesystem observation gate still has a live scan request.`);Ty(e,n,i)}if(g(r),V(JSON.parse(U(T(e.directory,`gate.json`)).toString(`utf8`)))!==V(e))throw new R(`Filesystem observation gate changed before retirement.`);v(T(e.directory,`gate.json`)),g(e.directory)}async function Oy(e,t,n){let r=process.env[my];if(r!==void 0)return n(by(r));if(!t)return n(void 0);let i=le(),a=T(Du(e),`ai-delivery`,`output-observation`,qy(e).slice(7));G_(a);for(let e of d(a)){$c().parse(e);let t=T(a,e);yy(t);let n=gy.parse(JSON.parse(U(T(t,`gate.json`)).toString(`utf8`)));if(n.id!==e||n.directory!==t||xy(n.owner))throw new R(`Prior filesystem observation gate is live or has conflicting ownership.`);Dy(n,!0)}let o=T(a,i);G_(T(o,`requests`));let s={directory:o,id:i,owner:vy()};q_(T(o,`gate.json`),s);try{return await n(s)}finally{Dy(s)}}var ky=class extends R{cause;code;constructor(e,t,n){let r=n.code;super(`${e} Path ${JSON.stringify(t)} (${r??`unknown errno`}): ${n instanceof Error?n.message:String(n)}`),this.code=r,this.cause=n}};function Ay(e,t,r=!1,i){let a=new Map,s=new Map,c=n=>{let l;try{l=o(n)}catch(e){if(e.code===`ENOENT`)return;throw new ky(`Filesystem output lstat failed.`,n,e)}if(l.isSymbolicLink()){let a;try{a=f(n)}catch(e){throw new ky(`Filesystem output readlink failed.`,n,e)}let c=V({device:l.dev,inode:l.ino,changed:l.ctimeMs,modified:l.mtimeMs,link:a}),u,d=!1;try{u=p(n)}catch(e){let s=new ky(`Filesystem output observation encountered a broken or cyclic symbolic link.`,n,e),l=t.get(n);if(l!==void 0&&l.identity!==c)throw new R(`Filesystem output alias identity changed. Path ${JSON.stringify(n)}.`);if(!r||s.code!==`ENOENT`||l?.identity!==c)throw s;let m=E(w(n),a),h=m,g=new Set([n]);for(;;)try{u=T(p(h),m.slice(h.length));break}catch(e){if(e.code!==`ENOENT`||w(h)===h)throw new ky(`Filesystem output ancestor resolution failed.`,h,e);let n;try{n=o(h)}catch(e){if(e.code!==`ENOENT`)throw new ky(`Filesystem output ancestor lstat failed.`,h,e)}if(n?.isSymbolicLink()){let e,r;try{e=f(h),r=o(h)}catch(e){throw new ky(`Filesystem output ancestor alias read failed.`,h,e)}let i=V({device:n.dev,inode:n.ino,changed:n.ctimeMs,modified:n.mtimeMs,link:e}),a=t.get(h);if(a===void 0)throw s;if(g.has(h)||a.identity!==i||!r.isSymbolicLink()||r.dev!==n.dev||r.ino!==n.ino||r.ctimeMs!==n.ctimeMs||r.mtimeMs!==n.mtimeMs)throw new R(`Filesystem output ancestor alias identity changed. Path ${JSON.stringify(h)}.`);g.add(h),m=T(E(w(h),e),m.slice(h.length)),h=m;continue}h=w(h)}if(u!==l.target)throw new R(`Filesystem output alias target identity changed. Path ${JSON.stringify(n)}.`);d=!0,i?.(s.message)}let m=t.get(n);if(m?.missing&&(m.identity!==c||m.target!==u))throw new R(`Filesystem output alias identity changed after target absence. Path ${JSON.stringify(n)}.`);if(!e.some(e=>u===e||u.startsWith(`${e}${re}`)))throw new R(`Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(n)} resolves to ${JSON.stringify(u)}.`);let h;try{h=o(n)}catch(e){if(r&&e.code===`ENOENT`&&m?.identity===c)return;throw new ky(`Filesystem output alias identity readback failed.`,n,e)}if(!h.isSymbolicLink()||h.dev!==l.dev||h.ino!==l.ino||h.ctimeMs!==l.ctimeMs||h.mtimeMs!==l.mtimeMs)throw new R(`Filesystem output alias identity changed during observation. Path ${JSON.stringify(n)}.`);s.set(n,{identity:c,target:u,missing:d});return}if(l.isDirectory()){let e;try{e=d(n)}catch(e){if(e.code===`ENOENT`)return;throw new ky(`Filesystem output readdir failed.`,n,e)}for(let t of e)c(T(n,t));return}if(!l.isFile()&&!l.isSocket()||!Number.isSafeInteger(l.size))throw new R(`Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(n)}.`);if(a.set(n,l.isSocket()?0:l.size),a.size>1e6)throw new R(`Filesystem output observation exceeded its file limit.`)};for(let t of e){if(n(t)&&p(t)!==t)throw new R(`Filesystem output roots must not be symbolic links.`);c(t)}t.clear();for(let[e,n]of s)t.set(e,n);return a}async function jy(e,t,n=!1,r){let i,a,o,s,c=()=>{if(s!==void 0&&Date.now()-s>=1e3)throw new R(`Filesystem output observation remained unavailable for 1 second. First observation: ${a.message} Last observation: ${o.message}`)};for(;;){if(t?.aborted)throw new R(`Filesystem output observation cancelled.`);c();try{i=await Ey(e.gate,`scan`,()=>Ay(e.roots,e.links,n,r),t),c();break}catch(e){if(!n||!(e instanceof ky)||e.code!==`ENOENT`)throw e;o=e,a===void 0&&(s=Date.now(),a=e,r?.(e.message)),c(),await new Promise(e=>setTimeout(e,25))}}let l=0;for(let[t,n]of i)if(l+=Math.max(0,n-(e.files.get(t)??0)),!Number.isSafeInteger(l))throw new R(`Filesystem output observation overflowed.`);return l}function My(e){let t=e;for(;;)try{let e=_(t,{bigint:!0});return e.bavail*e.bsize}catch(e){if(e.code!==`ENOENT`||w(t)===t)throw e;t=w(t)}}function Ny(e,t){let n=(t===void 0?[e]:[e,...t.roots]).reduce((e,t)=>{let n=My(t);return n<e?n:e},BigInt(2**53-1));if(n>BigInt(2**53-1))throw new R(`Free disk observation overflowed.`);return Number(n)}function Py(e,t,n){if(Ny(e,n)<t.minFreeDiskBytes)throw new R(`Free disk fell below limit ${t.minFreeDiskBytes}.`)}function Fy(){let e=n(`/usr/bin/ps`)?`/usr/bin/ps`:`/bin/ps`,t=S(e,[`-A`,`-o`,`pid=,ppid=,pgid=,rss=,stat=,lstart=`],{encoding:`utf8`,env:{...process.env,LC_ALL:`C`},maxBuffer:4194304,timeout:1e3});if(t.status!==0||t.error||t.signal||!t.stdout.endsWith(`
|
|
255
|
+
`))throw new R(`Owned process resource observation failed.`);let r=new Map;for(let e of t.stdout.trim().split(`
|
|
256
|
+
`)){let t=/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(e.trim());if(!t)throw new R(`Owned process resource observation is ambiguous.`);let n={pid:Number(t[1]),ppid:Number(t[2]),pgid:Number(t[3]),rssBytes:Number(t[4])*1024,status:t[5],identity:t[6]};if(!Number.isSafeInteger(n.pid)||n.pid<=0||!Number.isSafeInteger(n.ppid)||!Number.isSafeInteger(n.pgid)||!Number.isSafeInteger(n.rssBytes)||r.has(n.pid))throw new R(`Owned process resource observation is ambiguous.`);r.set(n.pid,n)}return r}function Iy(e,t){let n=t.get(e.rootPid);if(e.rootIdentity===void 0){if(n===void 0||n.status.startsWith(`Z`)||n.pgid!==e.rootPid)throw new R(`Owned process identity could not be established before the command exited.`);e.rootIdentity=n.identity,e.tracked.set(n.pid,n)}else if(n!==void 0&&n.identity!==e.rootIdentity)throw new R(`Owned process identity changed during verification.`);let r=new Map;for(let[n,i]of e.tracked){let a=t.get(n);if(a===void 0||a.status.startsWith(`Z`))e.tracked.delete(n);else if(a.identity!==i.identity)throw new R(`Tracked process identity changed during verification.`);else r.set(n,a)}for(let n of t.values())!n.status.startsWith(`Z`)&&n.pgid===e.rootPid&&r.set(n.pid,n);let i=new Map;for(let e of t.values()){let t=i.get(e.ppid)??[];t.push(e),i.set(e.ppid,t)}let a=[...r.values()];for(let e of a)for(let t of i.get(e.pid)??[])!t.status.startsWith(`Z`)&&!r.has(t.pid)&&(r.set(t.pid,t),a.push(t));for(let t of r.values())e.tracked.set(t.pid,t);return e.sampled=!0,[...r.values()]}function Ly(e,t,n,r,i,a=0,o=!1){let s=Fy(),c=Iy(e,s),l=o?Ry(s,new Set(c.map(e=>e.pid))):a,u=c.reduce((e,t)=>e+t.rssBytes,l);if(!Number.isSafeInteger(u))throw new R(`Owned aggregate RSS is outside the safe integer range.`);if(u>n.maxAggregateRssBytes)throw new R(`Owned aggregate RSS ${u} exceeded limit ${n.maxAggregateRssBytes}.`);let d=Ny(t,r);if(d<n.minFreeDiskBytes)throw new R(`Free disk fell below limit ${n.minFreeDiskBytes}.`);if(i!==void 0&&!Number.isSafeInteger(i))throw new R(`Filesystem output observation overflowed.`);if(r!==void 0&&n.maxNewOutputBytes!==void 0&&i!==void 0&&i>n.maxNewOutputBytes)throw new R(`Positive new filesystem output ${i} exceeded limit ${n.maxNewOutputBytes}.`);return{aggregateRssBytes:u,freeDiskBytes:d,...i===void 0?{}:{newOutputBytes:i},ownedProcessCount:c.length}}function Ry(e=Fy(),t=new Set){let n=e.get(process.pid);if(n===void 0||n.status.startsWith(`Z`))throw new R(`Runtime setup controller resource observation is unavailable.`);let r=new Set([process.pid]),i=process.memoryUsage().rss;for(let n of r)for(let a of e.values())a.ppid===n&&!a.status.startsWith(`Z`)&&!r.has(a.pid)&&(r.add(a.pid),t.has(a.pid)||(i+=a.rssBytes));if(!Number.isSafeInteger(i))throw new R(`Controller aggregate RSS observation overflowed.`);return i}async function zy(e){if(!e.sampled||e.rootIdentity===void 0)throw new R(`Owned process cleanup cannot be verified without a root identity.`);let t=Date.now()+2e3;for(;;){let n=Fy(),r=n.get(e.rootPid);if(r!==void 0&&r.identity!==e.rootIdentity)throw new R(`Owned process group identity changed before cleanup readback.`);let i=[...n.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)),a=[...e.tracked.values()].some(e=>{let t=n.get(e.pid);if(t===void 0||t.status.startsWith(`Z`))return!1;if(t.identity!==e.identity)throw new R(`Tracked process identity changed before cleanup readback.`);return!0});if(!i&&!a)return;if(Date.now()>=t)throw new R(`Owned process cleanup did not release every sampled process.`);await new Promise(e=>setTimeout(e,100))}}function By(e){if(!e.sampled||e.rootIdentity===void 0)throw new R(`Owned process identity is unknown.`);let t=Fy(),n=t.get(e.rootPid);if(n!==void 0&&n.identity!==e.rootIdentity)throw new R(`Owned process group identity changed before cleanup.`);let r=[...e.tracked.values()].flatMap(e=>{let n=t.get(e.pid);if(n===void 0||n.status.startsWith(`Z`))return[];if(n.identity!==e.identity)throw new R(`Tracked process identity changed before cleanup.`);return[n]}),i=[...t.values()].filter(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`));if(i.length>0&&!r.some(t=>t.pgid===e.rootPid))throw new R(`Owned process group has no surviving recorded identity; cleanup is ambiguous.`);let a=t=>{try{process.kill(t,`SIGKILL`)}catch(n){let r=n.code;if(r===`ESRCH`)return;if(r!==`EPERM`)throw n;let i=Fy();if(t<0){let t=i.get(e.rootPid);if(t!==void 0&&t.identity!==e.rootIdentity)throw new R(`Owned process group identity changed during cleanup signal readback.`);if([...i.values()].some(t=>t.pgid===e.rootPid&&!t.status.startsWith(`Z`)))throw n}else{let r=i.get(t);if(r!==void 0&&r.identity!==e.tracked.get(t)?.identity)throw new R(`Tracked process identity changed during cleanup signal readback.`);if(r!==void 0&&!r.status.startsWith(`Z`))throw n}}};i.length>0&&a(-e.rootPid);for(let e of r.reverse())a(e.pid)}var Vy=F({pid:j().int().positive(),identity:A().min(1)}),Hy=F({schemaVersion:L(`ai-delivery.verification-writer@1`),writerId:$c(),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),owner:Vy,command:jl([F({phase:L(`idle`)}),F({phase:L(`starting`)}),F({phase:L(`running`),root:Vy,tracked:N(F({...Vy.shape,pgid:j().int().positive()}))})]),stateId:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{stateId:n,...r}=e;n!==V(r)&&t.addIssue({code:`custom`,message:`Writer state is corrupt.`})});function Uy(e,t){if(t===void 0)return;let n=Hy.parse(JSON.parse(t.toString(`utf8`)));if(n.worktreeDigest!==qy(e))throw new R(`Verification writer belongs to another worktree.`);let r=Fy(),i=r.get(n.owner.pid);if(i?.identity===n.owner.identity&&!i.status.startsWith(`Z`))throw new R(`A live verification writer still owns this worktree.`);if(n.command.phase===`starting`)throw new R(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(n.command.phase===`running`){let e=[n.command.root,...n.command.tracked],t=new Set([n.command.root.pid,...n.command.tracked.map(e=>e.pgid)]);if(e.some(e=>r.has(e.pid))||[...r.values()].some(e=>t.has(e.pgid)))throw new R(`Transition requires identity-bound command and process-group absence.`)}}async function Wy(e,r,a,s,l=!1){let u=qy(e),d=T(s??Du(e),`ai-delivery`,`writers@1`,`${u.slice(7)}.json`);return G_(w(d)),ly(d,{projectRoot:e,timeout:200,...a?.onLockReleaseError===void 0?{}:{onReleaseError:a.onLockReleaseError},...a?.onLockCompromised===void 0?{}:{onCompromised:a.onLockCompromised},operation:async()=>{await hb(s??Du(e),u,l);let f=Fy(),p=f.get(process.pid);if(p===void 0||p.status.startsWith(`Z`))throw new R(`Verification writer identity is unknown.`);let m;if(a)try{o(d),m=U(d)}catch(e){if(e.code!==`ENOENT`)throw e}else n(d)&&(m=U(d));if(a&&Uy(e,m),m!==void 0&&!a){let e=Hy.parse(JSON.parse(m.toString(`utf8`)));if(e.worktreeDigest!==u)throw new R(`Verification writer belongs to another worktree.`);let t=f.get(e.owner.pid);if(t?.identity===e.owner.identity&&!t.status.startsWith(`Z`))throw new R(`A live verification writer still owns this worktree.`);if(e.command.phase===`starting`)throw new R(`Interrupted writer has unknown command ownership; reconcile before retrying.`);if(e.command.phase===`running`){let t={rootPid:e.command.root.pid,rootIdentity:e.command.root.identity,sampled:!0,tracked:new Map(e.command.tracked.map(e=>[e.pid,{...e,ppid:0,rssBytes:0,status:``}]))};By(t),await zy(t),eb({state:`recovered`,stageId:`writer`,completedStages:0,reusedStages:0,remainingStages:0,elapsedMs:0,reason:`Recorded interrupted command cleanup confirmed; compatible completed stages remain available.`})}}a&&await a.beforeClaim({previousBytes:m===void 0?void 0:Buffer.from(m),owner:{pid:p.pid,identity:p.identity}});let h={schemaVersion:`ai-delivery.verification-writer@1`,writerId:a?.writerId??le(),worktreeDigest:u,owner:{pid:p.pid,identity:p.identity},command:{phase:`idle`}},g=e=>{h={...h,command:e},q_(d,{...h,stateId:V(h)})};if(a){let e=Buffer.from(`${JSON.stringify({...h,stateId:V(h)},null,2)}\n`);await a.recordClaim(Buffer.from(e));let t;try{o(d),t=U(d)}catch(e){if(e.code!==`ENOENT`)throw e}if(t===void 0!=(m===void 0)||t!==void 0&&m!==void 0&&!t.equals(m))throw new R(`Writer changed after transition intent preservation.`)}g({phase:`idle`});let _={starting:()=>g({phase:`starting`}),observed:e=>{if(e.rootIdentity===void 0)throw new R(`Cannot persist an unknown command owner.`);g({phase:`running`,root:{pid:e.rootPid,identity:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,identity:t,pgid:n}))})},idle:()=>g({phase:`idle`}),assertQuiescent:()=>{let e=Hy.parse(JSON.parse(U(d).toString(`utf8`)));if(e.writerId!==h.writerId||e.command.phase!==`idle`)throw new R(`Verification writer command quiescence is not confirmed.`)}},y=async()=>{let e=U(d),n=Hy.parse(JSON.parse(e.toString(`utf8`)));if(n.writerId!==h.writerId)throw new R(`Verification writer ownership changed.`);if(n.command.phase===`idle`){if(a&&(await a.recordRelease(Buffer.from(e)),!U(d).equals(e)))throw new R(`Writer changed before recorded release.`);if(v(d),a){let e=c(w(d),`r`);try{i(e)}finally{t(e)}try{o(d)}catch(e){if(e.code!==`ENOENT`)throw e;await a.afterRelease?.();return}throw new R(`Writer absence is not confirmed after recorded release.`)}}};try{return await a?.afterClaim?.(Buffer.from(U(d))),await r(_)}finally{await y()}}})}async function Gy(e,t,n){let r=T(Du(e),`ai-delivery`,`writers@1`,`${qy(t).slice(7)}.json`);return ly(r,{projectRoot:e,timeout:200,operation:async()=>{await hb(Du(e),qy(t));try{o(r)}catch(e){if(e.code!==`ENOENT`)throw e;return n()}throw new R(`Sealed transition writer absence postcondition drifted.`)}})}async function Ky(e,t){$c().parse(e.writerId);let n=Eu(e.repoRoot);return Wy(e.worktreePath===void 0?n:E(e.worktreePath),async e=>{e.assertQuiescent();let n=await t();return e.assertQuiescent(),n},e,Du(n))}function qy(e){return V(E(e))}function Jy(t){let r=[],i=e=>{for(let n of d(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=T(e,n.name);n.isDirectory()?i(a):n.isFile()&&n.name.endsWith(`.js`)&&!n.name.endsWith(`.test.js`)&&r.push({path:a.slice(t.length+1),digest:H(l(a))})}};i(t);let a=new Map,o=t=>{if(a.has(t))return;let r=l(t),i=P({dependencies:zl(A(),A()).optional()}).parse(JSON.parse(r.toString(`utf8`)));a.set(t,H(r));let s=e(t);for(let e of Object.keys(i.dependencies??{}).sort()){let t;try{t=s.resolve(`${e}/package.json`)}catch{t=s.resolve(e)}let r=w(t);for(;;){let t=T(r,`package.json`);if(n(t)&&P({name:A().optional()}).parse(JSON.parse(l(t,`utf8`))).name===e){o(t);break}let i=w(r);if(i===r)throw new R(`Producer dependency identity is unavailable for ${e}.`);r=i}}};return o(T(w(t),`package.json`)),{code:r,dependencies:[...a].sort(([e],[t])=>e.localeCompare(t))}}function Yy(e=w(me(import.meta.url))){return V(Jy(e))}function Xy(e){return Yy(p(e))}function Zy(e){return Jy(p(e)).dependencies.map(([e,t])=>({source:e,digest:t}))}function Qy(e){return $y(JSON.parse(e.toString(`utf8`)))}function $y(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new R(`Invalid run manifest.`);let t=e,n=gh.parse(t.classification),r=Ch.parse(t.aggregate),i=Sh.array().parse(t.stageReceipts);if(![`ai-delivery.run@1`,`ai-delivery.run@2`,`ai-delivery.run@3`].includes(String(t.schemaVersion)))throw new R(`Run manifest schema version is unsupported.`);if(t.schemaVersion===`ai-delivery.run@1`&&t.resources!==void 0)throw new R(`Historical run manifest has unexpected resource evidence.`);let a=t.resources===void 0?void 0:fy.parse(t.resources);if(t.schemaVersion===`ai-delivery.run@2`&&a===void 0)throw new R(`Historical bounded run lacks resource evidence.`);let o=t.schemaVersion===`ai-delivery.run@3`?F({worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).parse(t.writer):void 0,s={aggregate:r,classification:n,completedAt:t.completedAt,...a===void 0?{}:{resources:a},...o===void 0?{}:{writer:o},schemaVersion:t.schemaVersion,stageReceipts:i};if(typeof t.completedAt!=`string`||t.manifestId!==V(s)||Eh({classification:n,receipts:i}).aggregateId!==r.aggregateId)throw new R(`Run manifest identity or aggregate is invalid.`);return{...s,completedAt:t.completedAt,manifestId:t.manifestId}}function eb(e){process.stderr.write(`ai-delivery.verify ${JSON.stringify(e)}\n`)}function tb(e,t,n,r,i,a,o,s,c){let[l,...u]=t;if(!l)throw new R(`Policy selected an empty stage command.`);if(n?.aborted)throw new R(`Selected policy stage command cancelled.`);return s?.starting(),new Promise((t,d)=>{let f=x(`/bin/sh`,[`-c`,`IFS= read -r ready || exit 125; [ "$ready" = run ] || exit 125; exec "$@" </dev/null`,`ai-delivery-command`,l,...u],{cwd:c?.cwd??e,detached:process.platform!==`win32`,stdio:[`pipe`,`pipe`,`pipe`],...a?.gate===void 0&&c===void 0?{}:{env:{...c?.environment??process.env,...a?.gate===void 0?{}:{[my]:JSON.stringify(a.gate)}}}}),p=[],m=[],h=process.platform===`win32`||f.pid===void 0?void 0:{rootPid:f.pid,sampled:!1,tracked:new Map},g=0,_=0,v=c?.maxCapturedOutputBytes??8388608,y=0,b,S,C,w=!1,ee=!1,T=!1,te,ne,E,re=new AbortController,ie=()=>{let t=te===void 0?``:` First filesystem observation: ${te} Last filesystem observation: ${ne}`;try{let n=Buffer.concat([...p,...m]);return c?.failedOutput?c.failedOutput(n):` Command output ${kh({bytes:n,gitCommonDir:Du(e)})}.${t}`}catch(e){return` Command output persistence failed (${e instanceof Error?e.message:String(e)}).${t}`}},ae,oe,se,ce=()=>{clearInterval(fe),se!==void 0&&clearInterval(se),ae!==void 0&&clearTimeout(ae),oe!==void 0&&clearTimeout(oe),n?.removeEventListener(`abort`,pe),process.removeListener(`SIGINT`,me),process.removeListener(`SIGTERM`,he)},le=()=>{if(f.pid!==void 0){if(h?.sampled){try{Iy(h,Fy())}catch(e){S??=e instanceof Error?e.message:String(e)}try{s?.observed(h)}catch(e){C??=e instanceof Error?e.message:String(e)}try{By(h)}catch(e){S??=e instanceof Error?e.message:String(e)}}else try{f.exitCode===null&&f.signalCode===null&&f.kill(`SIGKILL`),T&&(S??=`owned process identity was not observed before cleanup`)}catch(e){S??=e instanceof Error?e.message:String(e)}}},ue=e=>{b===void 0&&(b=e,re.abort(),le(),w||(ae=setTimeout(()=>{ee||w||(ee=!0,ce(),f.stdout.destroy(),f.stderr.destroy(),f.unref(),c?.onCleanupFailure?.(`Owned command pipes did not close; descendant cleanup could not be verified.`),d(new R(`Selected policy stage command failed (${b}).${ie()}${C===void 0?``:` Writer state persistence failed (${C}).`} Owned process cleanup failed (owned command pipes did not close; descendant cleanup could not be verified).`)))},2e3)))},de=(e,t)=>{if(g+=t.length,c?.onCaptured?.(g),c!==void 0&&i?.maxNewOutputBytes!==void 0&&g+y>i.maxNewOutputBytes){ue(`source-phase captured output exceeded remaining cumulative allowance`);return}if(g>v){let n=v-_;n>0&&(e.push(Buffer.from(t.subarray(0,n))),_+=Math.min(n,t.length)),ue(c?.maxCapturedOutputBytes===void 0?`captured output exceeded 8 MiB`:`captured output exceeded ${v} bytes`);return}e.push(t),_+=t.length};f.stdout.on(`data`,e=>de(p,e)),f.stderr.on(`data`,e=>de(m,e)),f.stdout.once(`error`,e=>ue(e.message)),f.stderr.once(`error`,e=>ue(e.message)),f.stdin.once(`error`,e=>ue(e.message)),f.once(`error`,e=>{f.pid===void 0&&s?.idle(),ue(e.message)}),f.once(`exit`,(e,t)=>{e!==0||t!==null?ue(`exit ${String(e)}${t===null?``:` signal ${t}`}`):w||(oe=setTimeout(()=>{w||ue(`owned command pipes did not close after direct child exit`)},1e3))}),f.once(`spawn`,()=>{let t=()=>{if(b===void 0&&f.pid!==void 0)try{if(h===void 0)throw new R(`Owned process identity is unavailable on this platform.`);if(Iy(h,Fy()),s?.observed(h),i!==void 0){let t=Ly(h,e,i,a,void 0,c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(w||E!==void 0)return;E=(async()=>{if(i!==void 0&&a!==void 0){let t=await jy(a,re.signal,T,e=>{te??=e,ne=e,r?.(g,void 0,e)});if(b!==void 0)return;y=t;let n=Ly(h,e,i,a,t+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(n),r?.(g,n)}b===void 0&&!T&&(T=!0,f.stdin.end(`run
|
|
257
|
+
`))})().catch(e=>ue(e instanceof Error?e.message:String(e))).finally(()=>{E=void 0})}catch(e){ue(e instanceof Error?e.message:String(e))}};t(),se=setInterval(t,1e3),se.unref()});let fe=setInterval(()=>r?.(g),5e3);fe.unref();let pe=()=>ue(`cancelled`),me=()=>ue(`cancelled by SIGINT`),he=()=>ue(`cancelled by SIGTERM`);n?.addEventListener(`abort`,pe,{once:!0}),process.once(`SIGINT`,me),process.once(`SIGTERM`,he),n?.aborted&&pe();let ge=async(n,l)=>{if(w=!0,!ee){if(await E,b===void 0&&h!==void 0)try{if(i!==void 0){let t=Ly(h,e,i,a,a===void 0?void 0:await jy(a,re.signal)+(c===void 0?0:g),c===void 0?0:process.memoryUsage().rss,c?.includeControllerTree);o?.(t),r?.(g,t)}if(!h.sampled)throw new R(`Owned process resource observation was unavailable.`);if(Iy(h,Fy()).length>0)throw new R(`A sampled owned descendant survived command exit.`)}catch(e){ue(e instanceof Error?e.message:String(e))}if(b!==void 0||n!==0||l!==null){let e=b??`exit ${String(n)}${l===null?``:` signal ${l}`}`,t=f.pid===void 0||!T;if(h!==void 0&&h.sampled)try{await zy(h),t=!0}catch(e){S??=e instanceof Error?e.message:String(e)}if(t)try{s?.idle()}catch(e){C??=e instanceof Error?e.message:String(e)}ee=!0,S!==void 0&&c?.onCleanupFailure?.(S),d(new R(`Selected policy stage command failed (${e}). Command exit ${String(n)}${l===null?``:` signal ${l}`}.${ie()}${C===void 0?``:` Writer state persistence failed (${C}).`}${S===void 0?``:` Owned process cleanup failed (${S}).`}`));return}s?.idle(),ee=!0,t(c?.stdoutOnly?Buffer.concat(p):Buffer.concat([...p,...m],g))}};f.once(`close`,(e,t)=>{ge(e,t).catch(e=>{ee=!0,d(e)}).finally(ce)})})}var nb=A().regex(/^sha256:[a-f0-9]{64}$/u),rb=A().regex(/^[a-f0-9]{40}$/u),ib=F({path:A().min(1),digest:nb}),ab=ib.extend({device:j().int().nonnegative().safe(),inode:j().int().nonnegative().safe(),uid:j().int().nonnegative().safe(),mode:j().int().nonnegative().safe()}),ob=F({argv:N(A()).min(1),cwd:A().min(1),executable:ab}),sb=F({head:rb,indexTree:rb,branch:A().min(1),configDigest:nb,dirty:N(F({path:A().min(1),digest:nb.nullable()}))}),cb=F({maxAggregateRssBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),outputRoots:N(A().min(1)).min(1)}),lb=F({phaseId:nb,recordId:nb,baselineId:nb.optional(),authorizationDigest:nb}),ub=F({repoRoot:A().min(1),issueNumber:j().int().positive().safe(),identity:A().min(1),rowDigest:nb,controller:F({head:rb,configDigest:nb,admissionId:nb,runtimeEntryPath:A().min(1),packageVersion:A().min(1),archiveDigest:nb}),source:sb.extend({path:A().min(1),effect:Nl(`kind`,[F({kind:L(`preserve`)}),F({kind:L(`commitOnce`),parent:rb,tree:rb,configDigest:nb.optional()})])}),caller:ib,authorization:ib,inputs:N(ib),commands:N(ob).min(1),commandGraphDigest:nb,environment:F({digest:nb,overrides:zl(A(),A().nullable())}),bounds:cb,completionArtifacts:N(A().min(1)),reconciliation:lb.optional()}).omit({environment:!0}).extend({environmentDigest:nb}),db=F({roots:N(A().min(1)).min(1),files:N(Ll([A(),j().int().nonnegative().safe()])),links:N(Ll([A(),F({identity:A(),target:A(),missing:M()})])),baselineId:nb}),fb=F({index:j().int().nonnegative().safe(),outputDigest:nb.nullable(),outputBytes:j().int().nonnegative().safe(),status:I([`complete`,`failed`])}),pb=F({source:sb,artifacts:N(ab),newOutputBytes:j().int().nonnegative().safe(),writerReleased:L(!0),lockReleased:L(!0)}),mb=F({schemaVersion:L(`ai-delivery.source-phase@1`),phaseId:nb,recordId:nb,worktreeDigest:nb,bindingDigest:nb,authorizationDigest:nb,status:I([`preparing`,`intent`,`complete`,`failed-quiescent`,`rejected-before-work`,`unresolved`]),writerId:$c(),binding:ub.optional(),baseline:db.optional(),allocation:cb.optional(),owner:F({pid:j().int().positive().safe(),identity:A().min(1)}),bootstrapFiles:N(Ll([A(),j().int().nonnegative().safe()])),bootstrapBytes:j().int().nonnegative().safe(),capturedBytes:j().int().nonnegative().safe(),nextCommandIndex:j().int().nonnegative().safe(),commands:N(fb),claimDigest:nb.optional(),releaseDigest:nb.optional(),preparationArtifact:ab.optional(),writerArtifact:ab.optional(),producerDigest:nb.optional(),actor:F({identity:A().min(1),actorLogin:A().min(1),credentialIdentity:A().min(1)}).optional(),retainedArtifacts:N(ab).optional(),retainedPredecessors:N(F({phaseId:nb,recordId:nb})),reconciliation:lb.optional(),result:pb.optional(),failure:F({operation:A().optional(),accounting:A().optional(),cleanup:A().optional(),writerRelease:A().optional(),lockRelease:A().optional()}).optional()}).superRefine((e,t)=>{let{recordId:n,...r}=e;if((n!==V(r)||e.phaseId!==e.bindingDigest)&&t.addIssue({code:`custom`,message:`Source-phase record identity is invalid.`}),e.binding!==void 0&&V(e.binding)!==e.bindingDigest&&t.addIssue({code:`custom`,message:`Source-phase input binding is invalid.`}),e.baseline!==void 0){let{baselineId:n,...r}=e.baseline;n!==V(r)&&t.addIssue({code:`custom`,message:`Source-phase baseline is invalid.`})}e.status===`rejected-before-work`&&(e.commands.length!==0||e.nextCommandIndex!==0||e.capturedBytes!==0)&&t.addIssue({code:`custom`,message:`Rejected source-phase input cannot contain executed work.`}),e.status===`complete`&&(e.result===void 0||e.baseline===void 0||e.binding===void 0||e.failure!==void 0)&&t.addIssue({code:`custom`,message:`Source-phase completion is incomplete.`}),e.status===`complete`&&(e.commands.length!==e.binding?.commands.length||e.nextCommandIndex!==e.commands.length||e.commands.some((e,t)=>e.index!==t||e.status!==`complete`))&&t.addIssue({code:`custom`,message:`Source-phase completion does not contain its exact successful command graph.`})});async function hb(e,t,n=!1){let r=T(e,`ai-delivery`,`receipts`,`source-phase@1`,t.slice(7)),i;try{let e=o(r);if(!e.isDirectory()||e.isSymbolicLink())throw new R(`Source-phase admission metadata is not a canonical directory.`);i=d(r)}catch(e){if(e.code===`ENOENT`)return;throw e}if(i.length>1e5)throw new R(`Source-phase admission exceeded its entry bound.`);for(let e of i){let i=mb.parse(JSON.parse(U(T(r,e)).toString(`utf8`)));if(i.worktreeDigest!==t||e!==`${i.phaseId.slice(7)}.json`)throw new R(`Source-phase admission record belongs to another input or worktree.`);if(i.status===`preparing`||i.status===`intent`)throw new R(`An unsealed source phase still excludes another worktree writer.`);if(n&&i.status===`unresolved`)throw new R(`Unresolved source phase requires owning reconciliation before another attempt.`);await new Promise(e=>setImmediate(e))}}F({status:L(`complete`),phaseId:nb,recordId:nb,source:sb,commands:N(fb)});var gb=F({schemaVersion:L(`ai-delivery.runtime-output@1`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),worktreeDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),limit:j().int().positive().safe().max(8*1024**2),outputs:N(F({digest:A().regex(/^sha256:[a-f0-9]{64}$/u),bytes:j().int().nonnegative().safe().max(8*1024**2),status:I([`reserved`,`complete`])})).max(4096),contentDigest:A().regex(/^sha256:[a-f0-9]{64}$/u)}).superRefine((e,t)=>{let{contentDigest:n,...r}=e;(n!==V(r)||new Set(e.outputs.map(e=>e.digest)).size!==e.outputs.length||e.outputs.reduce((e,t)=>e+t.bytes,0)>e.limit)&&t.addIssue({code:`custom`,message:`Runtime retained-output ledger is corrupt.`})});async function _b(e,t,n){let r=new AbortController,i=n?.signal===void 0?r.signal:AbortSignal.any([n.signal,r.signal]),a,o,s=0,c=Date.now(),l=()=>{if(a!==void 0)throw a;if(i.aborted)throw new R(`Runtime setup cancelled.`);let t=n===void 0?0:Ry();if(n!==void 0){if(t>n.bounds.maxAggregateRssBytes)throw new R(`Controller aggregate RSS ${t} exceeded limit ${n.bounds.maxAggregateRssBytes}.`);Py(e,n.bounds,o)}return t};if(n!==void 0){if(py(n.bounds),!Number.isSafeInteger(n.maxCapturedOutputBytes)||n.maxCapturedOutputBytes<=0||n.maxCapturedOutputBytes>8*1024**2)throw new R(`Invalid runtime setup captured-output bound; maximum is 8 MiB.`);l()}return e=Eu(e),Wy(e,async u=>Oy(e,n!==void 0,async d=>{let f,p,m=Du(e),h=()=>{if(f===void 0||p===void 0)throw new R(`Runtime output allowance is unbound.`);let{contentDigest:e,...t}=f;if(f=gb.parse({...t,contentDigest:V(t)}),Buffer.byteLength(JSON.stringify(f,null,2))>1024**2)throw new R(`Runtime retained-output ledger exceeds its evidence bound.`);q_(p,f)},g=e=>{try{if(Ah({gitCommonDir:m,digest:e.digest,expectedBytes:e.bytes}).length!==e.bytes)throw new R(`Runtime retained-output evidence size changed.`);return!0}catch(t){if(e.status===`reserved`&&t.code===`ENOENT`)return!1;throw t}},_=t=>{if(n===void 0)return;if(f!==void 0)throw new R(`Runtime output allowance is already bound.`);let r={stageId:t,worktreeDigest:qy(e),producerDigest:Yy(),limit:n.maxCapturedOutputBytes};p=T(m,`ai-delivery`,`verification@1`,`runtime-output`,r.worktreeDigest.slice(7),`${t.slice(7)}.json`);let i;try{i=U(p,{maxBytes:1024**2})}catch(e){if(e.code!==`ENOENT`)throw e}if(i!==void 0){if(f=gb.parse(JSON.parse(i.toString(`utf8`))),f.stageId!==r.stageId||f.worktreeDigest!==r.worktreeDigest||f.producerDigest!==r.producerDigest||f.limit!==r.limit)throw new R(`Runtime retained-output ledger belongs to an incompatible stage or controller.`);let e=!1;for(let t of f.outputs)g(t)&&t.status===`reserved`&&(t.status=`complete`,e=!0);e&&h()}else{let e={schemaVersion:`ai-delivery.runtime-output@1`,...r,outputs:[]};f=gb.parse({...e,contentDigest:V(e)}),h()}},v=()=>{if(n===void 0)return 8*1024**2;if(f===void 0)throw new R(`Runtime output allowance is unbound.`);return f.limit-f.outputs.reduce((e,t)=>e+t.bytes,0)},y=e=>{if(f===void 0)throw new R(`Runtime output allowance is unbound.`);let t=H(e),n=f.outputs.find(e=>e.digest===t);if(n!==void 0){if(n.bytes!==e.length||!g(n))throw new R(`Runtime retained-output reservation is unresolved; identical output cannot be rewritten.`);return` Command output ${t}.`}if(e.length>v())throw new R(`Runtime retained-output allowance exceeded.`);let r={digest:t,bytes:e.length,status:`reserved`};if(f.outputs.push(r),h(),kh({bytes:e,gitCommonDir:m}),!g(r))throw new R(`Runtime retained-output publication is unresolved.`);return f.outputs[f.outputs.length-1].status=`complete`,h(),` Command output ${t}.`};if(n!==void 0){let t=[...n.bounds.outputRoots??[],T(Du(e),`ai-delivery`)].map(t=>E(e,t)).sort(),r=t.filter((e,n)=>!t.slice(0,n).some(t=>e===t||e.startsWith(`${t}${re}`))),a=new Map,s=await Ey(d,`scan`,()=>Ay(r,a),i);o={roots:r,links:a,files:s,baselineId:V([...s]),...d===void 0?{}:{gate:d}}}let b=async()=>{let t=l();if(n===void 0||o===void 0)return;let r=s+await jy(o,i);if(l(),r>n.bounds.maxNewOutputBytes)throw new R(`Runtime setup output ${r} exceeded limit ${n.bounds.maxNewOutputBytes}.`);eb({state:`running`,stageId:`runtime-setup`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:s,sampledAggregateRssBytes:t,sampledFreeDiskBytes:Ny(e,o),sampledNewOutputBytes:r})};await b();let x=n===void 0?void 0:setInterval(()=>{try{l()}catch(e){a??=e instanceof Error?e:new R(String(e)),r.abort()}},1e3);x?.unref();try{let r=await t({assertQuiescent:()=>u.assertQuiescent(),bindCapturedOutput:_,checkResources:b,signal:i,run:async(t,r,a,o,l)=>{await b(),py(r);let f=r.outputRoots?.map(t=>E(e,t)).sort();if(f!==void 0){for(let e=1;e<f.length;e++)if(f[e]===f[e-1]||f[e].startsWith(`${f[e-1]}${re}`))throw new R(`Filesystem output roots must not overlap.`)}let p=async d=>{let p=v();if(p<=0)throw new R(`Runtime retained-output allowance is exhausted; installer was not started.`);let m=new Map,h=f===void 0?void 0:await Ey(d,`scan`,()=>Ay(f,m),i),g=f===void 0||h===void 0?void 0:{roots:f,files:h,links:m,baselineId:V([...h]),...d===void 0?{}:{gate:d}};Py(e,r,g);let _=0,x=await tb(e,t,a===void 0?i:AbortSignal.any([i,a]),(e,t,n)=>eb({state:`running`,stageId:`runtime-setup:install`,completedStages:0,reusedStages:0,remainingStages:1,elapsedMs:Date.now()-c,capturedOutputBytes:e,...n===void 0?{}:{reason:n},...t===void 0?{}:{sampledAggregateRssBytes:t.aggregateRssBytes,sampledFreeDiskBytes:t.freeDiskBytes,sampledNewOutputBytes:t.newOutputBytes}}),r,g,void 0,u,n===void 0&&o===void 0&&l===void 0?void 0:{environment:o??process.env,...l===void 0?{}:{cwd:l},...n===void 0?{}:{maxCapturedOutputBytes:p,includeControllerTree:!0,failedOutput:y},onCaptured:e=>{s+=e-_,_=e}});return await b(),x};return n===void 0?Oy(e,f!==void 0,p):p(d)}});return await b(),eb({state:`completed`,stageId:`runtime-setup`,completedStages:1,reusedStages:0,remainingStages:0,elapsedMs:Date.now()-c}),r}catch(e){throw a===void 0?i.aborted?new R(`Runtime setup cancelled. ${e instanceof Error?e.message:String(e)}`):e:new R(`${a.message} Runtime setup operation failed (${e instanceof Error?e.message:String(e)}).`)}finally{x!==void 0&&clearInterval(x)}}))}var vb=`.issue-cli`;function yb(e){let t=e??process.cwd(),r=E(t,vb);return n(r)||s(r,{recursive:!0}),r}var bb=`${vb}/worktrees.json`,xb=F({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:I([`active`,`error`,`merged`,`pr-published`,`stale`]),type:L(`issue`),updatedAt:A().min(1)}).transform(({prNumber:e,...t})=>({...t,...e===void 0?{}:{prNumber:e}})),Sb=F({schemaVersion:L(`ai-delivery.committed-continuation-plan@1`),planId:z,repository:A().min(1),repoRoot:A().min(1),configDigest:z,currentRuntime:Vv,row:xb,replacement:xb,head:Fu,terminalHead:Fu,terminalMergeId:z,operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1),preserved:N(F({path:A().min(1),digest:z})).min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e,{prNumber:i,identity:a,status:o,updatedAt:s,...c}=e.row,{identity:l,status:u,updatedAt:d,...f}=e.replacement;(n!==V(r)||e.row.status!==`merged`||!e.row.prNumber||e.replacement.status!==`active`||e.replacement.prNumber!==void 0||B(c)!==B(f)||e.head.sha===e.terminalHead.sha||new Set(e.preserved.map(e=>e.path)).size!==e.preserved.length)&&t.addIssue({code:`custom`,message:`Committed continuation plan identity or disposition is invalid.`})}),Cb=F({schemaVersion:L(`ai-delivery.committed-continuation-intent@1`),intentId:z,plan:Sb,authorityCommentId:j().int().positive(),acceptanceCommentId:j().int().positive()}).superRefine(({intentId:e,...t},n)=>{e!==V(t)&&n.addIssue({code:`custom`,message:`Continuation intent identity is invalid.`})}),wb=F({schemaVersion:L(`ai-delivery.committed-continuation-completion@1`),completionId:z,intentId:z,planId:z,row:xb,head:Fu,completed:L(!0)}).superRefine(({completionId:e,...t},n)=>{e!==V(t)&&n.addIssue({code:`custom`,message:`Continuation completion identity is invalid.`})});function Tb(e,t,n){return T(Du(e),`ai-delivery`,`continuations`,String(t),`${n}.plan.json`)}function Eb(e){return Tb(e.repoRoot,e.row.issueNumber,e.head.sha).replace(/\.plan\.json$/u,`.intent.json`)}function Db(e){return Eb(e).replace(/\.intent\.json$/u,`.completion.json`)}function Ob(e,t){return T(Du(e.repoRoot),`ai-delivery`,`continuations`,`evidence`,`${t.slice(7)}.bin`)}function kb(e,t=!1){for(let n of e.preserved)if(H(U(n.path))!==n.digest||t&&H(U(Ob(e,n.digest)))!==n.digest)throw Error(`Committed continuation original evidence changed.`);if(t){let t=Buffer.from(B(e.row));if(!U(Ob(e,H(t))).equals(t))throw Error(`Committed continuation original row beforeimage changed.`)}}function Ab(e,t){let r=T(Du(t),`ai-delivery`,`continuations`,String(e));if(!n(r))return;let i;for(let a of d(r).filter(e=>e.endsWith(`.intent.json`)).sort()){let o=Cb.parse(JSON.parse(U(T(r,a)).toString(`utf8`))),s=o.plan;if(s.repoRoot!==E(t)||s.row.issueNumber!==e||T(r,a)!==Eb(s))throw Error(`Committed continuation checkpoint identity disagrees.`);kb(s,!0);let c=Db(s);if(n(c)){let e=wb.parse(JSON.parse(U(c).toString(`utf8`)));if(e.intentId!==o.intentId||e.planId!==s.planId||B(e.row)!==B(s.replacement)||B(e.head)!==B(s.head))throw Error(`Committed continuation completion disagrees with its intent.`);Fb(s.replacement,t),Rb(t,r,!1),Rb(t,w(Ob(s,s.preserved[0].digest)),!1),Lb(c)}else{if(i)throw Error(`Issue has multiple incomplete committed continuations.`);i=o}}return i}function jb(e){if(!e.identity)throw Error(`ai-delivery worktree ownership requires the preparing identity.`);return{branch:e.branch,identity:e.identity,...e.issueNumber===void 0?{}:{issueNumber:e.issueNumber},path:e.path,...e.prNumber===void 0||e.type===`issue`?{}:{prNumber:e.prNumber},schemaVersion:`ai-delivery.worktree-owner@1`,type:e.type}}function Mb(e,t){let n=V(jb(t)).slice(7);return T(Du(e),`ai-delivery`,`worktree-owners`,`${n}.json`)}function Nb(e,t){if(e.type!==`issue`||e.issueNumber===void 0)return;let n=T(Du(t),`ai-delivery`,`worktree-owners`,`issue-${String(e.issueNumber)}.transition.json`);try{o(n)}catch(e){if(e.code===`ENOENT`)return;throw Error(`Worktree transition is incomplete or unreadable.`)}try{let r=JSON.parse(U(n).toString(`utf8`)),{intentId:i,...a}=r,{planId:o,...s}=r.plan;if(r.schemaVersion!==`ai-delivery.worktree-transition-intent@1`||i!==V(a)||o!==V(s)||r.plan.repoRoot!==E(t)||r.plan.row.issueNumber!==e.issueNumber)throw Error(`Invalid transition intent.`);if(r.plan.purpose===`merged-cleanup`)throw Error(`Worktree transition is terminal and cannot authorize ordinary source operations.`);let c=T(`${n}.evidence`,`completion.json`),l=JSON.parse(U(c).toString(`utf8`)),{completionId:u,...d}=l;if(l.schemaVersion!==`ai-delivery.worktree-transition-completion@1`||l.planId!==o||l.intentId!==i||l.completed!==!0||u!==V(d)||JSON.stringify(jb(e))!==JSON.stringify(jb(r.plan.row)))throw Error(`Invalid transition completion.`);return}catch(e){throw e instanceof Error&&e.message.includes(`transition is terminal`)?e:Error(`Worktree transition is incomplete or unreadable; resume its exact approved plan.`)}}function Pb(e,t){if(Nb(e,t),e.issueNumber!==void 0&&Ab(e.issueNumber,t))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);Fb(e,t)}function Fb(e,t){let n=jb(e),r=Mb(t,e),i;try{i=JSON.parse(U(r).toString(`utf8`))}catch{throw Error(`Worktree lacks its exact ai-delivery ownership witness.`)}if(JSON.stringify(i)!==JSON.stringify({...n,ownerId:V(n)}))throw Error(`Worktree ownership witness disagrees with the canonical registry identity.`)}function Ib(e,t,n=!1){let r=jb(e);Ru(Mb(t,e),Buffer.from(JSON.stringify({...r,ownerId:V(r)}))),n||Pb(e,t)}function Lb(e){let n=c(w(e),`r`);try{i(n)}finally{t(n)}}function Rb(e,t,n=!0){let r=T(Du(e),`ai-delivery`),i=[r,T(r,`continuations`),t],a=(e,t)=>{let n;try{n=o(e)}catch(e){if(t&&e.code===`ENOENT`)return;throw e}if(!n.isDirectory()||n.isSymbolicLink()||e!==r&&n.mode&63)throw Error(`Committed continuation evidence requires a private directory.`)};for(let e of i)a(e,n&&e!==r);n&&G_(t);for(let e of i)a(e,!1),Lb(e)}async function zb(e,t){let n=e.repoRoot;if(Ab(e.row.issueNumber,n))throw Error(`Committed continuation is pending or incomplete; resume supported develop.`);return Hb(n),ly(bb,{projectRoot:n,timeout:5e3,operation:async()=>{let r=Wb(n),i=r.worktrees.filter(t=>t.type===`issue`&&t.issueNumber===e.row.issueNumber);if(i.length>1)throw Error(`Transition has duplicate canonical issue rows.`);if(r.worktrees.some(t=>!i.includes(t)&&Jb(t,e.row)))throw Error(`Transition conflicts with another canonical registry path, branch or PR identity.`);let a=i[0],o={...e.row,...e.row.prNumber===void 0?{}:{prNumber:e.row.prNumber}},s=e.purpose===`active-resume`?o:{...o,prNumber:e.terminalPrNumber,status:`merged`};if(a!==void 0&&![o,s].some(e=>B(a)===B(e)))throw Error(`Transition canonical row drifted.`);let c=T(Du(n),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`),l=()=>{if(JSON.parse(U(c).toString(`utf8`)).plan?.planId!==e.planId)throw Error(`Transition lacks its exact durable intent.`)};return t({current:a,writeOwner:()=>{l(),Ib(s,n,!0)},commitRow:()=>{if(l(),a===void 0)throw Error(`Transition cannot recreate a removed canonical row.`);return r.worktrees.splice(r.worktrees.indexOf(a),1,s),a=s,Qb(n,r),s},removeRow:()=>{if(l(),e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw Error(`Transition lacks explicit unheld terminal source disposition.`);a!==void 0&&(r.worktrees.splice(r.worktrees.indexOf(a),1),Qb(n,r),a=void 0)}})}})}function Bb(e){let t=e.row,n=jb(t);if(B(JSON.parse(U(Mb(e.repoRoot,t)).toString(`utf8`)))!==B({...n,ownerId:V(n)}))throw Error(`Sealed transition owner witness drifted.`)}function Vb(e){return Wb(e??process.cwd()).worktrees}function Hb(e){yb(e)}function Ub(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wb(e){let t=E(e,bb);if(!n(t))return{worktrees:[]};try{let e=l(t,`utf8`),n=JSON.parse(e);if(!Ub(n)||Object.keys(n).length!==1||!Array.isArray(n.worktrees))throw Error(`Registry must be an object with a worktrees array.`);return{worktrees:n.worktrees.map((e,t)=>Gb(e,t))}}catch(e){throw Error(`Unable to read worktree registry: ${e instanceof Error?e.message:String(e)}`)}}function Gb(e,t){if(!Ub(e))throw Error(`worktrees[${String(t)}] must be an object.`);let n=new Set([`branch`,`createdAt`,`identity`,`issueNumber`,`path`,`prNumber`,`status`,`type`,`updatedAt`]),r=Object.keys(e).filter(e=>!n.has(e));if(r.length>0)throw Error(`worktrees[${String(t)}] has unsupported fields: ${r.join(`, `)}.`);let i=Yb(e.branch,`worktrees[${String(t)}].branch`),a=Yb(e.createdAt,`worktrees[${String(t)}].createdAt`),o=Yb(e.path,`worktrees[${String(t)}].path`),s=Zb(e.type,`worktrees[${String(t)}].type`),c=Xb(e.status,`worktrees[${String(t)}].status`),l=qb(e.identity,`worktrees[${String(t)}].identity`),u=Kb(e.issueNumber,`worktrees[${String(t)}].issueNumber`),d=Kb(e.prNumber,`worktrees[${String(t)}].prNumber`),f=Yb(e.updatedAt,`worktrees[${String(t)}].updatedAt`);if(s===`issue`&&u===void 0)throw Error(`worktrees[${String(t)}].issueNumber is required for issue worktrees.`);return{branch:i,createdAt:a,...l===void 0?{}:{identity:l},...u===void 0?{}:{issueNumber:u},path:o,...d===void 0?{}:{prNumber:d},status:c,type:s,updatedAt:f}}function Kb(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer.`);return e}}function qb(e,t){if(e!==void 0)return Yb(e,t)}function Jb(e,t){return e.path===t.path||e.branch===t.branch||e.issueNumber!==void 0&&t.issueNumber!==void 0&&e.issueNumber===t.issueNumber||e.prNumber!==void 0&&t.prNumber!==void 0&&e.prNumber===t.prNumber}function Yb(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string.`);return e}function Xb(e,t){if(e===`merged`||e===`pr-published`||e===`active`||e===`error`||e===`stale`)return e;throw Error(`${t} is invalid.`)}function Zb(e,t){if(e===`issue`||e===`pr`||e===`standalone`)return e;throw Error(`${t} is invalid.`)}function Qb(e,t){Hb(e);let n=E(e,bb);try{K_(n,t)}catch(e){throw Error(`Unable to save worktree registry: ${e instanceof Error?e.message:String(e)}`)}}function $b(e,t){let n=ne(T(e,`.worktrees`),t);if(n===``||n.startsWith(`..`)||n.startsWith(`/`))throw new R(`Worktree path must be inside the repository .worktrees directory.`)}function ex(e,t,r,i,a){if($b(t,e.path),e.status!==`merged`||e.path!==T(t,`.worktrees`,`issue-${String(e.issueNumber)}`))throw new R(`Only the exact registered merged issue worktree can be cleaned.`);let o=n(e.path);if(o&&Eu(e.path)!==p(e.path))throw new R(`Registered worktree points elsewhere.`);if(!o&&!a)throw new R(`Registered worktree is missing.`);o&&Au(e.path);let s=ju(t,r),c=Tu(t,`merge-base`,`--is-ancestor`,e.branch,s)===0;if(i){if(i.headBranch!==e.branch||i.headSha!==wu(o?e.path:t,`rev-parse`,o?`HEAD`:e.branch)||i.remoteHeadSha!==null&&i.remoteHeadSha!==i.headSha||i.baseBranch!==s.slice(`refs/remotes/${xu(t,r)}/`.length)||i.remoteBaseSha!==wu(t,`rev-parse`,s)||Tu(t,`merge-base`,`--is-ancestor`,i.baseSha,i.mergeSha)!==0||Tu(t,`merge-base`,`--is-ancestor`,i.mergeSha,s)!==0||wu(t,`rev-parse`,`${i.mergeSha}^{tree}`)!==i.mergeTree||!c&&i.strategy===`merge`)throw new R(`Exact merged-result cleanup attestation disagrees with Git or remote readback.`)}else if(!c)throw new R(`Branch is not included in the current base and exact merged-result attestation is absent.`);o&&wu(t,`worktree`,`remove`,e.path)}function tx(e,t){if(e.purpose!==`merged-cleanup`||e.disposition!==`remove`||e.retainedHoldCommentIds.length!==0)throw new R(`Transition cannot remove held or nonterminal source.`);let n=e.lineage.find(t=>t.prNumber===e.terminalPrNumber);if(!n?.merged||!n.mergeSha)throw new R(`Transition lacks exact native terminal merge lineage.`);let r=wu(e.repoRoot,`rev-parse`,`${n.mergeSha}^{tree}`),i=Tu(e.repoRoot,`merge-base`,`--is-ancestor`,e.head.sha,n.mergeSha)===0?`merge`:`squash`;if(i===`squash`&&r!==e.head.tree)throw new R(`Transition lacks exact retained tree proof for non-merge source removal.`);if(!e.remoteRefs||e.remoteRefs.headSha!==null&&e.remoteRefs.headSha!==e.head.sha)throw new R(`Transition lacks exact authenticated remote branch readback.`);ex({...e.row,status:`merged`,prNumber:n.prNumber},e.repoRoot,t,{baseBranch:n.baseBranch,baseSha:n.baseSha,headBranch:e.row.branch,headSha:e.head.sha,mergeSha:n.mergeSha,mergeTree:r,remoteBaseSha:e.remoteRefs.baseSha,remoteHeadSha:e.remoteRefs.headSha,strategy:i},!0)}var nx=F({path:A().min(1),source:A().min(1),digest:z,size:j().int().nonnegative().safe()}),rx=F({branch:A().min(1),createdAt:A().min(1),identity:A().min(1),issueNumber:j().int().positive(),path:A().min(1),prNumber:j().int().positive().optional(),status:I([`active`,`error`,`merged`,`pr-published`,`stale`]),type:L(`issue`),updatedAt:A().min(1)}),ix=F({prNumber:j().int().positive(),headSha:Mu,headBranch:A().min(1),baseSha:Mu,baseBranch:A().min(1),mergeSha:Mu.nullable(),merged:M(),authorLogin:A().min(1)}),ax=F({schemaVersion:L(`ai-delivery.worktree-transition-plan@1`),planId:z,repository:A().min(1),repoRoot:A().min(1),row:rx,purpose:I([`active-resume`,`merged-cleanup`]),disposition:I([`retain`,`remove`]),head:F({sha:Mu,tree:Mu}),terminalPrNumber:j().int().positive().nullable(),lineage:N(ix),retainedHoldCommentIds:N(j().int().positive()),remoteRefs:F({headSha:Mu.nullable(),baseSha:Mu}).nullable(),holdEvidence:N(F({commentId:j().int().positive(),digest:z})),inventory:N(nx),inventoryId:z,historicalProducer:L(`UNKNOWN`),closure:F({family:L(`public-ai-delivery-0.3.5-posix@1`),admissionPath:A().min(1),archivePath:A().min(1),admission:Vv,admissionBytesDigest:z,producerDigest:z,runManifestIds:N(z).min(1)}),currentRuntime:Vv,policyDigest:z,operator:F({actorLogin:A().min(1),credentialIdentity:A().regex(/^user:[1-9]\d*$/u)}),reviewerActor:A().min(1)}).superRefine((e,t)=>{let{planId:n,...r}=e;(n!==V(r)||e.inventoryId!==V(e.inventory)||e.disposition===`remove`&&(e.purpose!==`merged-cleanup`||e.retainedHoldCommentIds.length!==0)||e.purpose===`active-resume`&&e.terminalPrNumber!==null||e.purpose===`merged-cleanup`&&e.terminalPrNumber===null||e.disposition===`remove`&&e.remoteRefs===null)&&t.addIssue({code:`custom`,message:`Transition plan identity or disposition is invalid.`})}),ox=`sha256:c561a94b7727ad5dfc520cbdcad803b9eaddfd49d334ccbc9253edeede26994e`;function sx(e,t,n){if(!e.configuration)throw new R(`Transition requires the current repository configuration.`);let r=U(t),i=Vv.parse(JSON.parse(r.toString(`utf8`)));if(i.packageVersion!==`0.3.5`||i.sourceArchiveSha256!==ox)throw new R(`Retained operational producer is outside the supported public 0.3.5 family.`);Kv(i,{...e.configuration,configDigest:i.configDigest},i.cliPath);let a=ux(n);if(H(a)!==ox)throw new R(`Retained official public archive bytes disagree.`);let o=pe(a,{maxOutputLength:8388608}),s=w(w(i.cliPath)),c=[],l=(e,t)=>{let n=ux(e);c.push({source:e,path:t,digest:H(n),size:n.length})},u=0;for(let e=0;e+512<=o.length;){let t=o.subarray(e,e+512);if(t.every(e=>e===0))break;let n=t.subarray(0,100).toString(`utf8`).replace(/\0.*$/su,``),r=Number.parseInt(t.subarray(124,136).toString(`ascii`).replace(/\0.*$/su,``).trim(),8);if(t[156]!==48||!/^package\/(?!.*(?:^|\/)\.\.\/)[A-Za-z0-9_./-]+$/u.test(n)||!Number.isSafeInteger(r)||r<0)throw new R(`Retained public archive inventory is unsupported.`);let i=o.subarray(e+512,e+512+r),a=E(s,n.slice(8)),c=ux(a);if(i.length!==r||!c.equals(i))throw new R(`Retained producer bytes drifted: ${n}`);u+=1,l(a,`retained/${n}`),e+=512+Math.ceil(r/512)*512}if(u!==155)throw new R(`Retained public producer inventory is incomplete.`);l(t,`retained/admission.json`),l(n,`retained/public-archive.tar.gz`);let d=Zy(w(i.cliPath));for(let e of d)l(e.source,`retained/dependency-manifests/${V(e.source).slice(7)}.json`);return c.sort((e,t)=>e.path.localeCompare(t.path)),{admissionPath:t,archivePath:n,admission:i,admissionBytesDigest:H(r),producerDigest:Xy(w(i.cliPath)),inventory:c}}function cx(e,t,n,r,i){let a=n.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).map(e=>Qy(ux(e.source)));if(a.length===0||!a.some(e=>e.classification.head.sha===i.sha&&e.classification.head.tree===i.tree)||a.some(e=>e.schemaVersion!==`ai-delivery.run@3`||e.writer?.worktreeDigest!==V(t.path)||e.writer.producerDigest!==r||e.classification.repository===``||e.classification.requiredStages.some(e=>![`source_only`,`focused_node`,`canonical_verify`].includes(e.resourceClass))||e.classification.requiredStages.some(e=>e.commands.length>0)&&e.resources===void 0))throw new R(`Complete operational run inventory lacks supported producer-bound closure for the exact retained source head/tree.`);for(let t of a)for(let n of t.stageReceipts){let t=n.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,r=T(Du(e),`ai-delivery`,`verification@${String(t)}`,`stages`,n.input.stageId,`${n.input.inputId.slice(7)}.json`);if(B(JSON.parse(U(r).toString(`utf8`)))!==B(n))throw new R(`Operational run inventory has a missing or conflicting stage checkpoint.`)}return a.map(e=>e.manifestId).sort()}function lx(e){try{return o(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ux(e){let t=o(e);if(!t.isFile()||t.isSymbolicLink()||t.nlink!==1||p(e)!==e)throw new R(`Historical evidence requires canonical regular files without links.`);return l(e)}function dx(e,t,n=!1){let r=Du(e),i=new Map,a=new Set;lx(t.path)?a.add(wu(t.path,`rev-parse`,`HEAD`)):n&&a.add(wu(e,`rev-parse`,t.branch));let s=(e,c)=>{if(!lx(e))return;let l=o(e);if(l.isSymbolicLink()||p(e)!==e)throw new R(`Historical evidence inventory contains a noncanonical path.`);if(l.isDirectory()){for(let t of d(e).sort())s(T(e,t),`${c}/${t}`);return}let u=ux(e);if(i.set(c,{path:c,source:e,digest:H(u),size:u.length}),c.endsWith(`.json`)){let i;try{i=JSON.parse(u.toString(`utf8`))}catch{return}if(i&&typeof i.headSha==`string`&&/^[a-f0-9]{40}$/u.test(i.headSha)&&a.add(i.headSha),i?.schemaVersion===`issue-cli.terminal-evidence@1`){if(!Array.isArray(i.files))throw new R(`Historical terminal evidence manifest is incomplete.`);for(let t of i.files){if(typeof t.name!=`string`||!/^[A-Za-z0-9_.-]+$/u.test(t.name)||typeof t.sha256!=`string`)throw new R(`Historical terminal evidence inventory is invalid.`);let n=ux(T(w(e),t.name));if(n.length!==t.size||H(n)!==`sha256:${t.sha256}`)throw new R(`Historical terminal evidence manifest disagrees with original bytes.`)}}if(c.startsWith(`git/ai-delivery/runs@2/`)&&i?.schemaVersion===`ai-delivery.run@3`){let e=Qy(u),i=e.classification.head.sha;a.add(i);for(let i of e.stageReceipts){let e=i.input.schemaVersion===`ai-delivery.stage-input@2`?2:1,a=`ai-delivery/verification@${String(e)}/stages/${i.input.stageId}/${i.input.inputId.slice(7)}.json`;s(T(r,a),`git/${a}`);let o=`ai-delivery/resource-stages@1/${i.input.inputId.slice(7)}.json`;s(T(r,o),`git/${o}`);for(let e of i.commands){let t=`ai-delivery/verification@1/command-output/${e.outputDigest.slice(7)}.bin`;if(H(ux(T(r,t)))!==e.outputDigest)throw new R(`Historical command output is corrupt.`);s(T(r,t),`git/${t}`)}for(let e of i.artifacts){if(n)continue;let r=E(t.path,e.path);if(ne(t.path,r).startsWith(`..`)||H(ux(r))!==e.digest)throw new R(`Historical stage artifact is missing or corrupt.`);s(r,`worktree/${e.path}`)}}if(e.resources?.outputBaselineId){let t=`ai-delivery/output-baselines@1/${e.resources.outputBaselineId.slice(7)}`;s(T(r,`${t}.json`),`git/${t}.json`),s(T(r,`${t}.state.json`),`git/${t}.state.json`)}}}};s(T(e,`.issue-cli`,`issues`,String(t.issueNumber)),`repository/.issue-cli/issues/${String(t.issueNumber)}`),n||s(T(t.path,`.issue-cli`),`worktree/.issue-cli`);let c=V(E(t.path)).slice(7);s(T(r,`ai-delivery`,`runs@2`,c),`git/ai-delivery/runs@2/${c}`),s(T(r,`ai-delivery`,`writers@1`,`${c}.json`),`git/ai-delivery/writers@1/${c}.json`);let l=T(e,`.issue-cli`,`receipts`),u=t=>{if(!lx(t))return;let n=o(t);if(n.isSymbolicLink())throw new R(`Historical receipt inventory contains a link.`);if(n.isDirectory())for(let e of d(t).sort())u(T(t,e));else[...a].some(e=>t.includes(e))&&s(t,`repository/${ne(e,t)}`)};u(l);for(let e of[`publications`,`reviews`,`merges`,`merge-intents`,`merge-attempts`,`merge-results`])s(T(r,`ai-delivery`,e,String(t.issueNumber)),`git/ai-delivery/${e}/${String(t.issueNumber)}`);for(let e of[...a].sort())s(T(r,`ai-delivery`,`runs`,`${e}.json`),`git/ai-delivery/runs/${e}.json`);return[...i.values()].sort((e,t)=>e.path.localeCompare(t.path))}var fx=F({schemaVersion:L(`ai-delivery.worktree-transition-intent@1`),intentId:z,plan:ax,relinquishmentCommentId:j().int().positive(),acceptanceCommentId:j().int().positive(),originalRegistryDigest:z,originalWriterDigest:z.nullable()}).superRefine((e,t)=>{let{intentId:n,...r}=e;n!==V(r)&&t.addIssue({code:`custom`,message:`Transition intent is corrupt.`})}),px=F({schemaVersion:L(`ai-delivery.worktree-transition-step@1`),planId:z,intentId:z,attemptId:$c(),event:I([`authority`,`claim`,`claimed`,`release`,`released`,`row`,`owner`,`removal-intent`,`removed`]),sequence:j().int().positive().safe(),predecessorId:z.nullable(),data:zl(A(),wl()),stepId:z}),mx=F({schemaVersion:L(`ai-delivery.worktree-transition-completion@1`),completionId:z,planId:z,intentId:z,completed:L(!0),writerReleased:L(!0),result:I([`active-resumed`,`retained`,`removed`]),rowAfter:rx.nullable(),inventoryId:z,attempts:N(z).min(1),completedAt:mu()}).superRefine((e,t)=>{let{completionId:n,...r}=e;n!==V(r)&&t.addIssue({code:`custom`,message:`Transition completion is corrupt.`})});function hx(e){let t=T(Du(e.repoRoot),`ai-delivery`,`worktree-owners`,`issue-${String(e.row.issueNumber)}.transition.json`);return{intent:t,directory:`${t}.evidence`,blobs:T(`${t}.evidence`,`bytes`)}}function gx(e,t){Ru(e,Buffer.from(B(t)))}function _x(e,t){let n=H(t);return Ru(T(e,`${n.slice(7)}.bin`),t,n),n}function vx(e,t){let n=U(T(e,`${z.parse(t).slice(7)}.bin`));if(H(n)!==t)throw new R(`Preserved transition evidence is corrupt.`);return n}function yx(e){let t=V({planId:e.planId,purpose:`transition-writer`}).slice(7);return`${t.slice(0,8)}-${t.slice(8,12)}-5${t.slice(13,16)}-8${t.slice(17,20)}-${t.slice(20,32)}`}function bx(e,t){if(!lx(e))return[];let n=null;return d(e).sort((e,t)=>Number(e.split(`.`)[0])-Number(t.split(`.`)[0])).map((r,i)=>{if(!/^[1-9]\d*\.[a-f0-9-]{36}\.(?:authority|claim|claimed|release|released|row|owner|removal-intent|removed)\.json$/u.test(r))throw new R(`Transition attempt inventory contains an unsupported record.`);let a=px.parse(JSON.parse(U(T(e,r)).toString(`utf8`))),{stepId:o,...s}=a;if(o!==V(s)||a.intentId!==t.intentId||a.planId!==t.plan.planId||a.sequence!==i+1||a.predecessorId!==n||r!==`${String(a.sequence)}.${a.attemptId}.${a.event}.json`)throw new R(`Transition attempt record is corrupt or belongs to another intent.`);return n=o,a})}function xx(e,t){let n=[e.originalWriterDigest],r,i;for(let e of t)if(e.event===`claim`){let t=z.parse(e.data.bytesDigest),a=e.data.previousBytesDigest===null?null:z.parse(e.data.previousBytesDigest);if(!n.includes(a))throw new R(`Transition claim predecessor is outside its exact writer lineage.`);n=[a,t],r={attemptId:e.attemptId,bytesDigest:t},i=void 0}else if(e.event===`claimed`||e.event===`release`){if(!r||e.attemptId!==r.attemptId||e.data.bytesDigest!==r.bytesDigest)throw new R(`Transition claim/release acknowledgement belongs to another writer lineage.`);n=e.event===`claimed`?[r.bytesDigest]:[r.bytesDigest,null],e.event===`release`&&(i=e.attemptId)}else if(e.event===`released`){if(i!==e.attemptId||e.data.absent!==!0)throw new R(`Transition absence lacks its exact latest release intent.`);n=[null]}return n}function Sx(e,t,n){t.originalWriterDigest!==null&&vx(e,t.originalWriterDigest);for(let t of n)[`authority`,`claim`,`claimed`,`release`].includes(t.event)&&vx(e,z.parse(t.data.bytesDigest))}async function Cx(e,t,n,r,i){if(!e.configuration||e.root!==t.repoRoot||e.config.repository!==t.repository)throw new R(`Transition repository or current configuration drifted.`);if(B(await Gv({repoRoot:t.repoRoot,configuration:e.configuration,...i===void 0?{}:{runtimeEntryPath:i}}))!==B(t.currentRuntime)||H(ux(Lx(e).policyModulePath))!==t.policyDigest)throw new R(`Transition current runtime/configuration/policy drifted.`);let{inventory:a,...o}=sx(e,t.closure.admissionPath,t.closure.archivePath),{family:s,runManifestIds:c,...l}=t.closure;if(B(o)!==B(l))throw new R(`Retained operational producer drifted.`);for(let e of[`v1`,`v2`])if(lx(T(Du(t.repoRoot),`issue-cli`,`verification-stages`,e)))throw new R(`Unsupported operative issue-cli verification-stages/${e}; supported closure is missing.`);let u=!lx(t.row.path);if(u&&(!r||t.disposition!==`remove`))throw new R(`Transition source disappeared without recorded removal intent.`);if(!u){if(Eu(t.row.path)!==t.row.path||Du(t.row.path)!==Du(t.repoRoot)||wu(t.row.path,`branch`,`--show-current`)!==t.row.branch)throw new R(`Transition worktree ownership or branch drifted.`);Au(t.row.path)}let d=u?t.repoRoot:t.row.path,f=u?t.row.branch:`HEAD`;if(wu(d,`rev-parse`,f)!==t.head.sha||wu(d,`rev-parse`,`${f}^{tree}`)!==t.head.tree)throw new R(`Transition exact source coordinates drifted.`);let p=await Mx(e,t.row,t.terminalPrNumber);if(B(p)!==B(t.lineage))throw new R(`Transition authenticated native PR lineage or complete PR set drifted.`);if(t.disposition===`remove`){let n=t.lineage.find(e=>e.prNumber===t.terminalPrNumber);if(!n||B(await Px(e,t.row.branch,n.baseBranch))!==B(t.remoteRefs)||wu(t.repoRoot,`rev-parse`,ju(t.repoRoot,Lx(e).remote))!==t.remoteRefs?.baseSha)throw new R(`Transition native remote branch readback or local retaining ref drifted.`);if(a.some(e=>{let n=ne(t.row.path,e.source);return n===``||!n.startsWith(`..`)&&!n.startsWith(`/`)}))throw new R(`Retained operational producer must remain outside the source selected for removal.`)}let m=(await e.clients.rest.issues.get({...e.repo,issue_number:t.row.issueNumber})).data;if(m.state!==(t.purpose===`merged-cleanup`?`closed`:`open`))throw new R(`Transition native issue state drifted.`);for(let n of t.holdEvidence){let t=(await e.clients.rest.issues.getComment({...e.repo,comment_id:n.commentId})).data;if(H(Buffer.from(B(t)))!==n.digest)throw new R(`Retained native hold evidence drifted.`)}let h=[...dx(t.repoRoot,t.row,u),...a].sort((e,t)=>e.path.localeCompare(t.path));if(Nx(t.repoRoot,t.row,t.purpose,t.terminalPrNumber,t.head,p,m.state,h),B(cx(t.repoRoot,t.row,h,o.producerDigest,t.head))!==B(t.closure.runManifestIds))throw new R(`Operational run inventory IDs drifted.`);if(h.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(e=>Qy(ux(e.source)).classification.repository!==t.repository))throw new R(`Operational run inventory belongs to another repository.`);let g=e=>e.filter(e=>!e.path.startsWith(`git/ai-delivery/writers@1/`)&&!(u&&e.path.startsWith(`worktree/`)));if(B(g(h))!==B(g(t.inventory)))throw new R(`Transition complete historical writer/run/stage inventory drifted.`);if(n&&h.some(e=>e.path.startsWith(`git/ai-delivery/writers@1/`)&&!t.inventory.some(t=>B(t)===B(e))))throw new R(`Original transition writer evidence drifted.`)}async function wx(e,t){if(t.authority!==`worktree:transition`)throw new R(`Explicit exact-plan worktree transition authority is required.`);let n=ax.parse(JSON.parse(ux(p(t.planPath)).toString(`utf8`)));if(n.planId!==t.expectedPlanId)throw new R(`Transition expected plan identity disagrees.`);let r=hx(n),i=T(r.directory,`completion.json`),a=T(r.directory,`attempts`),o;if(lx(r.intent)&&(o=fx.parse(JSON.parse(U(r.intent).toString(`utf8`))),B(o.plan)!==B(n)||o.relinquishmentCommentId!==t.relinquishmentCommentId||o.acceptanceCommentId!==t.acceptanceCommentId))throw new R(`Pending transition requires its original exact plan and native authority IDs.`);let s=n.purpose===`active-resume`?`active-resumed`:n.disposition===`retain`?`retained`:`removed`;if(lx(i)){if(!o)throw new R(`Transition completion lacks its durable intent.`);let c=mx.parse(JSON.parse(U(i).toString(`utf8`))),l=bx(a,o);if(c.planId!==n.planId||c.intentId!==o.intentId||c.result!==s||c.inventoryId!==n.inventoryId||B(c.attempts)!==B(l.map(e=>e.stepId))||B(xx(o,l))!==B([null]))throw new R(`Transition completion is corrupt.`);for(let e of n.inventory)vx(r.blobs,e.digest);vx(r.blobs,o.originalRegistryDigest),Sx(r.blobs,o,l);for(let e of n.holdEvidence)vx(r.blobs,e.digest);return await Cx(e,n,!1,bx(a,o).some(e=>e.event===`removal-intent`),t.runtimeEntryPath),await kx(e,n,t),await Gy(n.repoRoot,n.row.path,()=>zb(n,async({current:e})=>{if(B(e??null)!==B(c.rowAfter))throw new R(`Sealed transition registry postcondition drifted.`);if(Bb(n),s===`removed`){if(lx(n.row.path)||e!==void 0)throw new R(`Removed transition source was recreated; terminal absence postcondition drifted.`)}else if(!e||!lx(n.row.path))throw new R(`Sealed transition source or owner witness disappeared.`)})),{planId:n.planId,result:s,replayed:!0,receiptPath:i}}let c=le(),l=o===void 0?[]:bx(a,o),u=(e,t)=>{if(!o)throw new R(`Transition step lacks durable intent.`);let r={schemaVersion:`ai-delivery.worktree-transition-step@1`,planId:n.planId,intentId:o.intentId,attemptId:c,event:e,data:t,sequence:l.length+1,predecessorId:l.at(-1)?.stepId??null},i=px.parse({...r,stepId:V(r)});xx(o,[...l,i]),gx(T(a,`${String(i.sequence)}.${c}.${e}.json`),i),l.push(i)},d=[...l],f=null,m,h=!1,g=null;return await Ky({repoRoot:n.repoRoot,worktreePath:n.row.path,writerId:yx(n),beforeClaim:async({previousBytes:i})=>{await zb(n,async({current:s})=>{o!==void 0&&(l=bx(a,o));let c=d.some(e=>e.event===`removal-intent`);if(s===void 0&&!c)throw new R(`Transition row disappeared without recorded removal intent.`);await Cx(e,n,o===void 0,c,t.runtimeEntryPath);let p=await kx(e,n,t);if(o===void 0){let e=n.inventory.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));if(i===void 0!=(e===void 0)||i!==void 0&&H(i)!==e?.digest)throw new R(`Original transition writer bytes or absence drifted.`);let a=_x(r.blobs,ux(T(n.repoRoot,`.issue-cli`,`worktrees.json`))),s={schemaVersion:`ai-delivery.worktree-transition-intent@1`,plan:n,relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId,originalRegistryDigest:a,originalWriterDigest:i===void 0?null:H(i)};o=fx.parse({...s,intentId:V(s)}),gx(r.intent,o),Ix(r.blobs,n.inventory)}else{for(let e of n.inventory){if(!lx(T(r.blobs,`${e.digest.slice(7)}.bin`))){if(e.path.startsWith(`git/ai-delivery/writers@1/`)){if(i===void 0||H(i)!==e.digest)throw new R(`Original writer was lost before preservation.`);_x(r.blobs,i)}else Ix(r.blobs,[e])}vx(r.blobs,e.digest)}let e=i===void 0?null:H(i);if(!xx(o,l).includes(e))throw new R(`Writer bytes/absence are outside the latest exact transition claim/release lineage.`);e!==null&&vx(r.blobs,e)}f=i===void 0?null:H(i),vx(r.blobs,o.originalRegistryDigest),Sx(r.blobs,o,l),u(`authority`,{bytesDigest:_x(r.blobs,Buffer.from(B(p))),relinquishmentCommentId:t.relinquishmentCommentId,acceptanceCommentId:t.acceptanceCommentId});for(let t of n.holdEvidence){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.commentId})).data;if(_x(r.blobs,Buffer.from(B(n)))!==t.digest)throw new R(`Retained hold changed during preservation.`)}})},recordClaim:e=>{m=_x(r.blobs,e),u(`claim`,{bytesDigest:m,previousBytesDigest:f})},afterClaim:e=>{if(H(e)!==m)throw new R(`Actual writer claim bytes disagree with their recorded intent.`);u(`claimed`,{bytesDigest:m})},recordRelease:e=>{if(H(e)!==m)throw new R(`Writer changed before its exact recorded release.`);u(`release`,{bytesDigest:_x(r.blobs,e)})},afterRelease:async()=>{u(`released`,{absent:!0}),h&&o&&await zb(n,async({current:e})=>{if(B(e??null)!==B(g))throw new R(`Transition row changed before completion sealing.`);for(let e of n.inventory)vx(r.blobs,e.digest);let t=bx(a,o);Sx(r.blobs,o,t);let c={schemaVersion:`ai-delivery.worktree-transition-completion@1`,planId:n.planId,intentId:o.intentId,completed:!0,writerReleased:!0,result:s,rowAfter:g,inventoryId:n.inventoryId,attempts:t.map(e=>e.stepId),completedAt:new Date().toISOString()};gx(i,{...c,completionId:V(c)})})}},async()=>{await zb(n,async({current:r,writeOwner:i,commitRow:a,removeRow:o})=>{let s=d.some(e=>e.event===`removal-intent`);if(await Cx(e,n,!1,s,t.runtimeEntryPath),await kx(e,n,t),r!==void 0&&(i(),u(`owner`,{exactWitness:!0}),g=a(),u(`row`,{rowDigest:V(g)})),n.disposition===`remove`){if(u(`removal-intent`,{head:n.head,path:n.row.path}),tx(n,Lx(e).remote),lx(n.row.path))throw new R(`Terminal source removal readback is not absent.`);u(`removed`,{absent:!0}),o(),g=null}h=!0})}),{planId:n.planId,result:s,replayed:d.length>0,receiptPath:i}}async function Tx(e){if(e.clients.authSource!==`personal`||e.clients.role!==`author`||!e.clients.authenticatedAuthor)throw new R(`Worktree relinquishment requires the configured authenticated personal operator.`);let t=await e.clients.authenticatedAuthor();if(!/^user:[1-9]\d*$/u.test(t.credentialIdentity))throw new R(`Operator user identity is unavailable.`);let n=await _m({config:e.config,identity:e.config.roles.reviewer.identity,role:`reviewer`,selectedAuthor:e.clients});if(n.authSource!==`app`||!n.appActorLogin)throw new R(`Configured reviewer App identity is unavailable.`);let r=await n.appActorLogin();if(r.toLowerCase()===t.actorLogin.toLowerCase())throw new R(`Transition acceptance requires a distinct configured reviewer App.`);return{operator:t,reviewerActor:r,reviewer:n}}function Ex(e){return B({schemaVersion:`ai-delivery.worktree-relinquishment@1`,plan:Ox(e),acceptedScope:`the-complete-content-addressed-plan-and-every-original-in-its-inventory`,authority:`relinquish-only-the-inventoried-public-posix-writers`,operationalClosure:`the-inventory-is-the-complete-remaining-launcher-writer-and-managed-process-set-all-are-quiescent-no-unknown-resources`,maintainedExclusion:`all-old-launchers-and-writers-remain-excluded-through-apply-including-interruption-and-exact-plan-replay`,historicalAuthority:`preservation-only-no-current-verification-review-or-retirement-authority`,sourceDisposition:e.disposition===`remove`?`no-outstanding-holds-remove-only-clean-merged-source`:`retain-source-and-all-outstanding-holds`,exclusions:[`private-adoption`,`hold-release`,`launcher-changes`,`shared-runtime-admission`,`legacy-protocol-retirement`]})}function Dx(e,t){return B({schemaVersion:`ai-delivery.worktree-transition-acceptance@1`,plan:Ox(e),acceptedScope:`independent-acceptance-of-the-complete-content-addressed-plan-and-inventory-including-complete-launcher-set-and-maintained-exclusion`,relinquishmentCommentId:t,relinquishmentDigest:H(Buffer.from(Ex(e))),result:`approved`})}function Ox(e){let t=ax.parse(e);return{planId:t.planId,inventoryId:t.inventoryId,repository:t.repository,repoRoot:t.repoRoot,row:t.row,head:t.head,purpose:t.purpose,disposition:t.disposition,terminalPrNumber:t.terminalPrNumber,lineage:t.lineage,remoteRefs:t.remoteRefs,holdEvidence:t.holdEvidence,closure:t.closure,currentRuntimeId:t.currentRuntime.admissionId,currentConfigDigest:t.currentRuntime.configDigest,policyDigest:t.policyDigest,operator:t.operator,reviewerActor:t.reviewerActor,historicalProducer:t.historicalProducer}}async function kx(e,t,n){let r=await Tx(e);if(B(r.operator)!==B(t.operator)||r.reviewerActor!==t.reviewerActor)throw new R(`Configured transition authority identities drifted.`);if(t.lineage.some(e=>e.authorLogin.toLowerCase()===r.reviewerActor.toLowerCase()))throw new R(`Configured transition reviewer App is also the native PR author.`);let i=t.terminalPrNumber??t.row.issueNumber;return Ax(e,{repository:t.repository,subject:i,operator:t.operator,reviewerActor:t.reviewerActor,authorityCommentId:n.relinquishmentCommentId,acceptanceCommentId:n.acceptanceCommentId,operatorBody:Ex(t),reviewerBody:Dx(t,n.relinquishmentCommentId),revokedBody:B({schemaVersion:`ai-delivery.worktree-relinquishment-revocation@1`,planId:t.planId,relinquishmentCommentId:n.relinquishmentCommentId})})}async function Ax(e,t){let n=await Tx(e);if(B(n.operator)!==B(t.operator)||n.reviewerActor!==t.reviewerActor)throw new R(`Configured transition authority identities drifted.`);let r=t.subject,i=`https://api.github.com/repos/${t.repository}/issues/${String(r)}`,a=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t.authorityCommentId})).data,o=(await n.reviewer.rest.issues.getComment({...e.repo,comment_id:t.acceptanceCommentId})).data;if(a?.id!==t.authorityCommentId||a.issue_url?.toLowerCase()!==i.toLowerCase()||a.user?.type!==`User`||a.user?.login.toLowerCase()!==n.operator.actorLogin.toLowerCase()||`user:${String(a.user?.id)}`!==n.operator.credentialIdentity||a.body!==t.operatorBody)throw new R(`Native operator relinquishment is missing, changed or belongs to another subject.`);if(o?.id!==t.acceptanceCommentId||o.issue_url?.toLowerCase()!==i.toLowerCase()||o.user?.type!==`Bot`||o.user.login.toLowerCase()!==n.reviewerActor.toLowerCase()||o.body!==t.reviewerBody)throw new R(`Native configured reviewer-App exact-plan acceptance is missing or changed.`);for(let i=1;;i+=1){let a=(await e.clients.rest.issues.listComments({...e.repo,issue_number:r,per_page:100,page:i})).data;if(a.some(e=>e.body===t.revokedBody&&e.user?.login.toLowerCase()===n.operator.actorLogin.toLowerCase()&&`user:${String(e.user.id)}`===n.operator.credentialIdentity))throw new R(`Native operator relinquishment has been revoked.`);if(a.length<100)break}return{relinquishment:a,acceptance:o}}async function jx(e,t,n){let r=(await e.clients.rest.pulls.get({...e.repo,pull_number:n})).data,i=(await e.clients.graphql(`query WorktreeTransitionLineage($owner: String!, $repo: String!, $number: Int!) {
|
|
258
258
|
repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
|
|
259
259
|
closingIssuesReferences(first: 100) { nodes { number repository { nameWithOwner } } pageInfo { hasNextPage } }
|
|
260
260
|
} }
|
|
261
|
-
}`,{...e.repo,number:n})).repository.pullRequest?.closingIssuesReferences;if(r.number!==n||r.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||r.base.repo.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!i||i.pageInfo.hasNextPage||!i.nodes.some(n=>n.number===t&&n.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()))throw new L(`Native PR lineage does not establish the exact repository and closing issue.`);return Gb.parse({prNumber:n,headSha:r.head.sha,headBranch:r.head.ref,baseSha:r.base.sha,baseBranch:r.base.ref,mergeSha:r.merge_commit_sha,merged:r.merged,authorLogin:r.user?.login})}async function yx(e,t,n){let r=[...new Set([t.prNumber,n].filter(e=>e!=null))];return Promise.all(r.map(n=>vx(e,t.issueNumber,n)))}function bx(e,t,n,r,i,a,o,s){if(n===`active-resume`){if(![`active`,`pr-published`].includes(t.status)||o!==`open`||a.some(e=>e.merged||e.headSha!==i.sha||e.headBranch!==t.branch))throw new L(`Active resume requires the exact open issue and unmerged source lineage.`);if(s.some(e=>/^git\/ai-delivery\/(?:publications|reviews|merges|merge-intents|merge-attempts|merge-results)\//u.test(e.path)))throw new L(`Existing current publication/review/merge slots require separate authority reconciliation; active resume cannot overwrite them.`)}else{let n=a.find(e=>e.prNumber===r);if(!n||o!==`closed`||!n.merged||n.headSha!==i.sha||n.headBranch!==t.branch||a.some(r=>!r.merged||!r.mergeSha||r.headBranch!==t.branch||r.baseBranch!==n.baseBranch||Eu(e,`merge-base`,`--is-ancestor`,r.mergeSha,r.prNumber===n.prNumber?n.mergeSha:i.sha)!==0))throw new L(`Terminal native PR lineage or merged-result ancestry does not bind the retained exact source.`)}}async function xx(e,t,n){let r=async t=>{try{let n=(await e.clients.rest.repos.getBranch({...e.repo,branch:t})).data;if(n.name!==t)throw new L(`Native branch readback belongs to another ref.`);return Nu.parse(n.commit.sha)}catch(e){if(e.status===404)return null;throw e}},i=await r(t),a=await r(n);if(a===null)throw new L(`Native retaining base branch is missing.`);return{headSha:i,baseSha:a}}async function Sx(e,t){let n=[],r=ku(e.root),i=Ob(r).filter(e=>e.type===`issue`&&e.issueNumber===t.issueNumber);if(i.length!==1)return{ready:!1,blockers:[`Expected one canonical legacy issue row.`],plan:null,inventory:[]};let a=[];try{let o=Wb.parse(i[0]);if(a.push(...Qb(r,o)),!e.configuration||e.config.repository!==`${e.repo.owner}/${e.repo.repo}`)throw new L(`Transition requires exact current repository configuration.`);if(o.path!==T(r,`.worktrees`,`issue-${String(o.issueNumber)}`)||o.branch!==`issue/${String(o.issueNumber)}`||Du(o.path)!==p(o.path)||Ou(o.path)!==Ou(r)||Tu(o.path,`branch`,`--show-current`)!==o.branch)throw new L(`Legacy row path, branch or Git ownership disagrees.`);ju(o.path);for(let e of[`v1`,`v2`])Xb(T(Ou(r),`issue-cli`,`verification-stages`,e))&&n.push(`Unsupported operative issue-cli verification-stages/${e}; no authenticated supported operational closure is available.`);if((!t.retainedAdmissionPath||!t.retainedArchivePath)&&n.push(`Missing retained supported public producer admission/archive and operational closure. Historical UNKNOWN is preservation-only.`),n.length>0)return{ready:!1,blockers:n,plan:null,inventory:a};let s=await Mv({repoRoot:r,configuration:e.configuration,...t.runtimeEntryPath===void 0?{}:{runtimeEntryPath:t.runtimeEntryPath}}),{inventory:c,...l}=Jb(e,p(t.retainedAdmissionPath),p(t.retainedArchivePath));a.push(...c);let u={sha:Tu(o.path,`rev-parse`,`HEAD`),tree:Tu(o.path,`rev-parse`,`HEAD^{tree}`)},d=Yb(r,o,a,l.producerDigest,u);if(a.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(t=>zy(Zb(t.source)).classification.repository!==e.config.repository))throw new L(`Operational run inventory belongs to another repository.`);if(t.disposition===`remove`&&c.some(e=>{let t=ne(o.path,e.source);return t===``||!t.startsWith(`..`)&&!t.startsWith(`/`)}))throw new L(`Retained operational producer must remain outside the source selected for removal.`);let f=a.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));Ay(o.path,f===void 0?void 0:Zb(f.source));let m=t.purpose===`merged-cleanup`?t.terminalPrNumber??o.prNumber??null:null,h=await yx(e,o,m),g=(await e.clients.rest.issues.get({...e.repo,issue_number:o.issueNumber})).data;bx(r,o,t.purpose,m,u,h,g.state,a);let _=await fx(e);if(h.some(e=>e.authorLogin.toLowerCase()===_.reviewerActor.toLowerCase()))throw new L(`Configured transition reviewer App is also the native PR author.`);let v=t.disposition===`remove`?await xx(e,o.branch,h.find(e=>e.prNumber===m).baseBranch):null;if(v&&(v.headSha!==null&&v.headSha!==u.sha||Tu(r,`rev-parse`,Mu(r,wx(e).remote))!==v.baseSha))throw new L(`Native remote branch readback disagrees with exact source or local retaining ref.`);let y=[...t.retainedHoldCommentIds??[]].sort((e,t)=>e-t);if(new Set(y).size!==y.length)throw new L(`Retained hold inventory has duplicates.`);let b=[];for(let t of y){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t})).data;if(!n.body||n.issue_url?.toLowerCase()!==`https://api.github.com/repos/${e.config.repository}/issues/${String(m??o.issueNumber)}`.toLowerCase())throw new L(`Retained hold comment belongs to another subject or is unavailable.`);let r=Buffer.from(z(n));b.push({commentId:t,digest:V(r)})}a.sort((e,t)=>e.path.localeCompare(t.path));let x={schemaVersion:`ai-delivery.worktree-transition-plan@1`,repository:e.config.repository,repoRoot:r,row:o,purpose:t.purpose,disposition:t.disposition??`retain`,head:u,terminalPrNumber:m,lineage:h,remoteRefs:v,retainedHoldCommentIds:y,holdEvidence:b,inventory:a,inventoryId:B(a),historicalProducer:`UNKNOWN`,closure:{family:`public-ai-delivery-0.3.5-posix@1`,...l,runManifestIds:d},currentRuntime:s,policyDigest:V(Zb(wx(e).policyModulePath)),operator:_.operator,reviewerActor:_.reviewerActor},S=Kb.parse({...x,planId:B(x)});return{ready:!0,blockers:n,plan:S,inventory:a,relinquishmentBody:px(S)}}catch(e){return n.push(e instanceof Error?e.message:String(e)),{ready:!1,blockers:n,plan:null,inventory:a}}}function Cx(e,t){for(let n of t){let t=Zb(n.source);if(t.length!==n.size||V(t)!==n.digest)throw new L(`Historical evidence drifted: ${n.path}`);zu(T(e,`${n.digest.slice(7)}.bin`),t,n.digest)}}function wx(e){if(!e.configuration||!(`policyModulePath`in e.configuration))throw new L(`Historical repository configuration binding is unsupported by this runtime; preserve its original controller and records. No policy module was loaded.`);return e.configuration}var Tx=A().regex(/^sha256:[a-f0-9]{64}$/u),Ex=P({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2)}),Dx=P({archivePath:A().min(1),archiveSha256:Tx,configDigest:Tx,packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),repoRoot:A().min(1),repository:A().min(1),reviewRouteDigest:Tx,runtimeDirectory:A().min(1),nativePluginRoot:A().min(1).optional(),sourceCommit:A().regex(/^[a-f0-9]{40}$/u),resourceBounds:Ex.optional()}),Ox=P({schemaVersion:I(`ai-delivery.runtime-stage@1`),stageId:Tx,intent:Dx,directory:P({device:j().int(),inode:j().int()}),admission:Ov.optional(),status:F([`incomplete`,`complete`]),recordId:Tx}).superRefine((e,t)=>{let{recordId:n,...r}=e;(n!==B(r)||e.stageId!==B(e.intent)||e.status===`complete`!=(e.admission!==void 0)||e.admission!==void 0&&(e.admission.sourceCommit!==e.intent.sourceCommit||e.admission.sourceArchiveSha256!==e.intent.archiveSha256||e.admission.packageVersion!==e.intent.packageVersion||e.admission.configDigest!==e.intent.configDigest||e.admission.repository!==e.intent.repository||e.admission.cliPath!==Ax(e.intent.runtimeDirectory,e.intent.nativePluginRoot).cliPath||e.admission.mcpLauncherPath!==Ax(e.intent.runtimeDirectory,e.intent.nativePluginRoot).mcpLauncherPath||e.admission.pluginManifestPath!==Ax(e.intent.runtimeDirectory,e.intent.nativePluginRoot).pluginManifestPath))&&t.addIssue({code:`custom`,message:`Runtime stage identity or completion is corrupt.`})});function kx(e){if(!ee(e)||E(e)!==e)throw new L(`Runtime setup paths must be absolute and canonical.`);let t=e.split(re).filter(Boolean),n=re;for(let e of t){n=T(n,e);try{if(o(n).isSymbolicLink())throw new L(`Runtime setup path contains a symbolic link.`)}catch(e){if(e.code!==`ENOENT`)throw e}}return e}function Ax(e,t){let n=T(e,`node_modules`,`@aviaratech`,`ai-delivery`),r=t??T(n,`plugins`,`ai-delivery`);return{cliPath:t?T(r,`runtime`,`dist`,`cli.js`):T(n,`dist`,`cli.js`),mcpLauncherPath:T(r,`dist`,`mcp-launcher.js`),pluginManifestPath:T(r,`.claude-plugin`,`plugin.json`)}}function jx(e,t){if(t!==void 0&&(kx(t),t===e||t.startsWith(`${e}${re}`)||e.startsWith(`${t}${re}`)))throw new L(`Native plugin cache and owned runtime stage paths must not overlap.`)}function Mx(e){if(e.nativePluginRoot===void 0)return;jx(e.runtimeDirectory,e.nativePluginRoot);let t=kx(T(e.runtimeDirectory,`node_modules/@aviaratech/ai-delivery/plugins/ai-delivery`)),n=0,r=(e,t,i)=>{if(i>16||++n>4096)throw new L(`Native plugin inventory exceeds the reviewed layout bound.`);let a=o(e),s=o(t);if(a.isDirectory()&&s.isDirectory()){let n=d(e).sort();if(JSON.stringify(n)!==JSON.stringify(d(t).sort()))throw new L(`Selected native plugin inventory disagrees with reviewed archive bytes.`);for(let a of n)r(T(e,a),T(t,a),i+1)}else if(!a.isFile()||!s.isFile()||a.nlink!==1||s.nlink!==1||a.size!==s.size||!l(e).equals(l(t)))throw new L(`Selected native plugin files disagree with reviewed archive bytes.`)};try{r(t,e.nativePluginRoot,0)}catch(e){throw e instanceof L?e:new L(`Selected native plugin cannot be matched to reviewed archive bytes.`)}}function Nx(e,t){kx(e),Tx.parse(t);let n=o(e);if(!n.isFile()||n.nlink!==1)throw new L(`Reviewed runtime archive bytes do not match the expected digest.`);let r=l(e);if(V(r)!==t)throw new L(`Reviewed runtime archive bytes do not match the expected digest.`);return r}function Px(e){let t=kx(T(e.runtimeDirectory,`reviewed-archive.tgz`));if(V(H(t))!==e.archiveSha256)throw new L(`Runtime stage archive snapshot bytes changed.`);return t}async function Fx(e,t,n,r){if(await n?.(),typeof e.identity!=`string`||!e.identity.trim())throw new L(`Runtime setup requires an explicit configured author identity.`);let i=Du(e.repoRoot);if(i!==ku(i))throw new L(`Runtime setup requires the primary consumer controller checkout.`);if(ju(i),Au(i).sha!==e.expectedSourceCommit)throw new L(`Primary controller source commit changed.`);kx(e.runtimeDirectory);let a=await D_({identity:e.identity,repoRoot:i,role:`author`,...r===void 0?{}:{signal:r},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});await n?.();let o=fh({commandName:t,deliveryConfig:a.config,identity:e.identity,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(o.error)throw new L(o.error);if(!a.configuration||a.configuration.configDigest!==e.expectedConfigDigest)throw new L(`Primary controller resolver config digest changed.`);let s=await bv(a,void 0,void 0,`publication`,n===void 0||r===void 0?void 0:{signal:r,checkResources:n});if(await n?.(),ju(i),Au(i).sha!==e.expectedSourceCommit)throw new L(`Primary controller source commit changed during preflight.`);return{root:i,configuration:a.configuration,reviewRoute:s}}function Ix(e){kx(e);let t=o(e);if(!t.isDirectory()||(t.mode&511)!=448)throw new L(`Runtime stage directory must be private and owned.`);let n;try{n=Ox.parse(JSON.parse(H(T(e,`runtime-stage.json`)).toString(`utf8`)))}catch{throw new L(`Runtime stage is unowned, incompatible or corrupt.`)}if(n.intent.runtimeDirectory!==e||t.dev!==n.directory.device||t.ino!==n.directory.inode)throw new L(`Runtime stage directory ownership changed.`);return n.status===`complete`&&(Px(n.intent),Mx(n.intent)),n}function Lx(e,t){let n=Ox.parse({...t,recordId:B(t)});J_(T(e,`runtime-stage.json`),n);let r=Ix(e);if(r.recordId!==n.recordId)throw new L(`Runtime stage completion readback changed.`);return r}function Rx(e){let n=c(e,`r`);try{i(n)}finally{t(n)}}function zx(e){let n=H(e),r=c(e,`r`);try{i(r)}finally{t(r)}if(Rx(w(e)),!H(e).equals(n))throw new L(`Runtime admission third-party replacement conflict.`)}function Bx(e,t,n){if(!e.admission)throw new L(`Runtime stage completion is missing.`);return{stageId:e.stageId,admission:e.admission,reused:n,reviewRoute:t,launch:{cli:{command:process.execPath,args:[e.admission.cliPath]},mcp:{command:process.execPath,args:[e.admission.mcpLauncherPath]}}}}function Vx(e,t,n){if(e.intent.repoRoot!==t.root||e.intent.repository!==t.configuration.config.repository||e.intent.sourceCommit!==n.expectedSourceCommit||e.intent.configDigest!==n.expectedConfigDigest)throw new L(`Runtime stage primary controller source or configuration changed.`);if(e.intent.reviewRouteDigest!==B(t.reviewRoute))throw new L(`Runtime stage configured actors or review route changed.`)}async function Hx(e){if(e.authority!==`runtime:stage`)throw new L(`Explicit runtime:stage authority is required.`);let t=Ex.parse({maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2,maxCapturedOutputBytes:1024**2,...e.resourceBounds});return kx(e.runtimeDirectory),jx(e.runtimeDirectory,e.nativePluginRoot),ib(e.repoRoot,async r=>{let i=await Fx(e,`runtime:stage`,r.checkResources,r.signal);Nx(e.archivePath,e.expectedArchiveSha256);let a=Dx.parse({archivePath:e.archivePath,archiveSha256:e.expectedArchiveSha256,configDigest:e.expectedConfigDigest,sourceCommit:e.expectedSourceCommit,packageVersion:e.packageVersion,repoRoot:i.root,repository:i.configuration.config.repository,reviewRouteDigest:B(i.reviewRoute),runtimeDirectory:e.runtimeDirectory,resourceBounds:t,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot}}),c=B(a);if(r.bindCapturedOutput(c),n(e.runtimeDirectory)){let t=Ix(e.runtimeDirectory);if(t.stageId!==c)throw new L(`Runtime stage belongs to an incompatible setup intent.`);if(t.status===`complete`){let n=await Fx(e,`runtime:stage`,r.checkResources,r.signal);return Vx(t,n,e),Nx(a.archivePath,a.archiveSha256),zx(T(e.runtimeDirectory,`reviewed-archive.tgz`)),Px(a),Nv(t.admission,n.configuration,t.admission.cliPath),zx(T(e.runtimeDirectory,`runtime-stage.json`)),Rx(w(e.runtimeDirectory)),await r.checkResources(),Bx(t,n.reviewRoute,!0)}r.assertQuiescent(),h(e.runtimeDirectory,{recursive:!0})}K_(w(e.runtimeDirectory)),s(e.runtimeDirectory,{mode:448});let l=o(e.runtimeDirectory),u={schemaVersion:`ai-delivery.runtime-stage@1`,stageId:c,intent:a,directory:{device:l.dev,inode:l.ino},status:`incomplete`},d=!1;try{if(Rx(w(e.runtimeDirectory)),Lx(e.runtimeDirectory,u),d=!0,e.signal?.aborted)throw new L(`Runtime stage cancelled.`);let n=Nx(e.archivePath,e.expectedArchiveSha256);if(!Number.isSafeInteger(t.maxNewOutputBytes)||n.length>=t.maxNewOutputBytes)throw new L(`Reviewed archive snapshot exceeds the stage output limit.`);zu(T(e.runtimeDirectory,`reviewed-archive.tgz`),n);let i=Px(a),o=T(e.runtimeDirectory,`.npm`),s=T(o,`cache`),c=T(o,`logs`),l=T(o,`tmp`);for(let e of[s,c,l])K_(e);let f=T(o,`user.npmrc`),p=T(o,`global.npmrc`);zu(f,Buffer.alloc(0)),zu(p,Buffer.alloc(0)),await r.checkResources(),await r.run([`npm`,`install`,`--prefix`,e.runtimeDirectory,`--omit=dev`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--package-lock=false`,`--cache`,s,`--logs-dir`,c,`--logs-max`,`0`,`--userconfig`,f,`--globalconfig`,p,i],{...t,maxNewOutputBytes:t.maxNewOutputBytes-n.length,outputRoots:[e.runtimeDirectory]},e.signal,{...process.env,TMPDIR:l,TMP:l,TEMP:l},e.runtimeDirectory);let m=await Fx(e,`runtime:stage`,r.checkResources,r.signal);Vx({...u,recordId:B(u)},m,e),Nx(e.archivePath,e.expectedArchiveSha256),Px(a),Mx(a);let h=Pv({...Ax(e.runtimeDirectory,e.nativePluginRoot),packageVersion:e.packageVersion,sourceArchiveSha256:e.expectedArchiveSha256,sourceCommit:e.expectedSourceCommit,configuration:m.configuration});if(Mx(a),e.signal?.aborted)throw new L(`Runtime stage cancelled.`);r.assertQuiescent(),Nv(h,m.configuration,h.cliPath),await r.checkResources();let g=Lx(e.runtimeDirectory,{...u,status:`complete`,admission:h});return Nv(g.admission,m.configuration,g.admission.cliPath),Bx(g,m.reviewRoute,!1)}catch(t){if(d){r.assertQuiescent();let t=Ix(e.runtimeDirectory);if(t.stageId!==c)throw new L(`Runtime stage cleanup ownership changed.`);if(t.status===`incomplete`)h(e.runtimeDirectory,{recursive:!0});else{let n=await Fx(e,`runtime:stage`,r.checkResources,r.signal);return Vx(t,n,e),Nx(a.archivePath,a.archiveSha256),zx(T(e.runtimeDirectory,`reviewed-archive.tgz`)),Px(a),Nv(t.admission,n.configuration,t.admission.cliPath),zx(T(e.runtimeDirectory,`runtime-stage.json`)),Rx(w(e.runtimeDirectory)),Bx(t,n.reviewRoute,!0)}}else{r.assertQuiescent();let t=o(e.runtimeDirectory);if(t.dev!==l.dev||t.ino!==l.ino||t.isSymbolicLink())throw new L(`Runtime stage cleanup ownership changed.`);h(e.runtimeDirectory,{recursive:!0})}throw t}},{bounds:{...t,outputRoots:[e.runtimeDirectory]},maxCapturedOutputBytes:t.maxCapturedOutputBytes,...e.signal===void 0?{}:{signal:e.signal}})}var Ux=class extends L{admissionId;stageId;status=`commit-status-unknown`;constructor(e,t){super(`Runtime admission commit-status-unknown for ${e}; retry runtime:admit with the same stage ${t} to reconcile durability.`),this.admissionId=e,this.stageId=t}};async function Wx(e){if(e.authority!==`runtime:admit`)throw new L(`Explicit runtime:admit authority is required.`);Tx.parse(e.stageId),e.expectedPriorAdmissionSha256!==null&&Tx.parse(e.expectedPriorAdmissionSha256);let t=await Fx(e,`runtime:admit`),r=T(Ou(t.root),`ai-delivery`,`runtime-admission.json`);return kx(r),K_(w(r)),Xv(r,{projectRoot:t.root,timeout:200,operation:async()=>{let t=Ix(e.runtimeDirectory);if(t.stageId!==e.stageId||t.status!==`complete`||!t.admission)throw new L(`Exact completed runtime stage identity is required.`);let i=await Fx(e,`runtime:admit`);Vx(t,i,e),Nx(t.intent.archivePath,t.intent.archiveSha256),Px(t.intent),Nv(t.admission,i.configuration,t.admission.cliPath);let a=Buffer.from(`${JSON.stringify(t.admission,null,2)}\n`);kx(r);let o=n(r)?H(r):void 0,s=()=>{if(kx(r),Px(t.intent),Nv(t.admission,i.configuration,t.admission.cliPath),!n(r)||!H(r).equals(a))throw new L(`Runtime admission third-party replacement conflict; current bytes preserved.`);try{zx(r)}catch{throw!n(r)||!H(r).equals(a)?new L(`Runtime admission third-party replacement conflict; current bytes preserved.`):new Ux(t.admission.admissionId,t.stageId)}return{admission:t.admission,reused:!0}};if(o?.equals(a))return s();if((o===void 0?null:V(o))!==e.expectedPriorAdmissionSha256)throw new L(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);let c=await Fx(e,`runtime:admit`);Vx(t,c,e),Nx(t.intent.archivePath,t.intent.archiveSha256),Px(t.intent),Nv(t.admission,c.configuration,t.admission.cliPath),kx(r);let l=n(r)?H(r):void 0;if((l===void 0?null:V(l))!==e.expectedPriorAdmissionSha256)throw new L(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);try{J_(r,t.admission)}catch(t){let i=n(r)?H(r):void 0;if(i?.equals(a))return s();throw(i===void 0?null:V(i))===e.expectedPriorAdmissionSha256?t:new L(`Runtime admission third-party replacement conflict; current bytes preserved.`)}return s(),{admission:t.admission,reused:!1}}})}var Gx=j().int().positive(),Kx=M(A().trim().min(1)),qx=A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),Jx={blockedBy:M(Gx).optional(),body:A().optional(),issueType:A().min(1).optional(),labels:Kx.optional(),milestone:Gx.optional(),parentIssueNumber:Gx.optional(),points:Gx.optional(),priority:A().min(1).optional(),repo:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),title:A().trim().min(1).max(256)},Yx={repo:qx,state:F([`open`,`closed`,`all`]).optional(),labels:M(A().min(1).regex(/^[^"\\\r\n]+$/u)).optional(),parentIssueNumber:Gx.nullable().optional(),issueType:A().min(1).optional(),projectStatus:F([`Todo`,`In Progress`,`Blocked`,`Done`]).nullable().optional(),updatedSince:hu({offset:!0}).optional(),page:Gx.optional(),perPage:Gx.max(100).optional()},Xx=A().trim().min(1).max(256).regex(/^[^"\\\r\n]+$/u),Zx={repo:qx,identity:A().min(1).optional(),expectedSourceCommit:A().regex(/^[a-f0-9]{40}$/u),expectedConfigDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),runtimeDirectory:A().min(1)},Qx=[{name:`issue_comment`,commandName:`comment`,description:`Post a typed issue journal with authoritative comment readback`,inputSchema:x_.extend({repo:qx})},{name:`runtime_stage`,commandName:`runtime:stage`,description:`Explicitly stage a reviewed local public archive without host activation or admission`,inputSchema:P({...Zx,authority:I(`runtime:stage`),archivePath:A().min(1),expectedArchiveSha256:A().regex(/^sha256:[a-f0-9]{64}$/u),packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),nativePluginRoot:A().min(1).optional(),resourceBounds:P({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2).optional()}).optional()})},{name:`runtime_admit`,commandName:`runtime:admit`,description:`Explicitly admit an exact completed stage with prior-byte compare-and-swap and reconciliation`,inputSchema:P({...Zx,authority:I(`runtime:admit`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),expectedPriorAdmissionSha256:A().regex(/^sha256:[a-f0-9]{64}$/u).nullable()})},{name:`issue_create`,commandName:`create`,description:`Create a native GitHub tracking issue with configured metadata and relationships`,inputSchema:P(Jx)},{name:`issue_start`,commandName:`start`,description:`Create or resume a tracked issue and its GitHub-linked branch`,inputSchema:P({...Jx,body:Jx.body.optional(),issueType:Jx.issueType.optional(),points:Jx.points.optional(),priority:Jx.priority.optional(),title:Jx.title.optional(),issueNumber:Gx.optional(),request:A().min(1).optional(),requestId:A().trim().min(1).max(256).optional(),resumeCreated:xl().optional(),branch:A().min(1).optional()})},{name:`issue_list`,commandName:`list`,description:`List repository issues with native filters, named organization fields and pagination`,inputSchema:P({...Yx,query:Xx.optional()})},{name:`issue_search`,commandName:`search`,description:`Search literal issue text in the selected repository with native filters and pagination`,inputSchema:P({...Yx,query:Xx})},{name:`issue_update`,commandName:`update`,description:`Update native issue fields and exact relationship sets with readback`,inputSchema:P({repo:qx,blockedBy:M(Gx).optional(),body:A().optional(),issueNumber:Gx,issueType:A().min(1).optional(),labels:Kx.optional(),milestone:Gx.nullable().optional(),parentIssueNumber:Gx.nullable().optional(),park:I(!0).optional(),points:Gx.optional(),priority:A().min(1).optional(),state:F([`open`,`closed`]).optional(),preserveHistory:xl().optional(),closeReason:F([`completed`,`not_planned`,`duplicate`]).optional(),supersededBy:Gx.optional(),title:A().trim().min(1).max(256).optional()}).refine(e=>e.closeReason===void 0&&e.supersededBy===void 0||e.state===`closed`,`Closure details require state closed`)},{name:`issue_info`,commandName:`info`,description:`Read live issue metadata, relationships and Project status`,inputSchema:P({issueNumber:Gx,repo:qx})},{name:`issue_ready_check`,commandName:`ready:check`,description:`Evaluate deterministic readiness from live native issue state`,inputSchema:P({issueNumber:Gx,repo:Jx.repo})},{name:`issue_pr_create`,commandName:`pr:create`,description:`Create or reuse a PR from its GitHub-linked issue branch`,inputSchema:P({repo:qx,issueNumber:Gx,body:A().min(1).optional(),draft:xl().optional(),dryRun:xl().optional(),title:A().min(1).optional(),headBranch:A().min(1).optional()})},{name:`issue_pr_info`,commandName:`pr:info`,description:`Inspect a PR by number or its GitHub-linked issue branch`,inputSchema:P({repo:qx,issueNumber:Gx.optional(),prNumber:Gx.optional()})},{name:`issue_pr_review`,commandName:`pr:review`,description:`Submit one existing exact-head independent review with the reviewer App role`,inputSchema:P({repo:qx,issueNumber:Gx,prNumber:Gx,artifact:A().min(1),identity:A().min(1).optional(),dryRun:xl().optional()})},{name:`issue_pr_merge`,commandName:`pr:merge`,description:`Guarded exact-head merge with live blocker, check and review readback`,inputSchema:P({repo:qx,issueNumber:Gx,prNumber:Gx,reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:F([`merge`,`squash`,`rebase`]).optional(),dryRun:xl().optional()})},{name:`issue_finish`,commandName:`finish`,description:`Resume a guarded merge and close its issue after merged-PR readback`,inputSchema:P({repo:qx,issueNumber:Gx,prNumber:Gx,reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:F([`merge`,`squash`,`rebase`]).optional(),dryRun:xl().optional()})},{name:`issue_worktree_transition_inspect`,commandName:`worktree:transition:inspect`,description:`Read a legacy issue row, original evidence and exact closure gaps without changing ownership`,inputSchema:P({repo:qx,issueNumber:Gx,purpose:F([`active-resume`,`merged-cleanup`]),disposition:F([`retain`,`remove`]).optional(),terminalPrNumber:Gx.optional(),retainedHoldCommentIds:M(Gx).optional(),retainedAdmissionPath:A().min(1).optional(),retainedArchivePath:A().min(1).optional()})},{name:`issue_worktree_transition_apply`,commandName:`worktree:transition:apply`,description:`Apply or resume one exact independently accepted transition with immutable preservation and closure proof`,inputSchema:P({repo:qx,authority:I(`worktree:transition`),planPath:A().min(1),expectedPlanId:A().regex(/^sha256:[a-f0-9]{64}$/u),relinquishmentCommentId:Gx,acceptanceCommentId:Gx})}];function $x(e){return Qx.find(t=>t.name===e)??null}function eS(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw new L(`${t} must be positive.`);return n}function tS(e,t){return typeof e[t]==`string`?e[t]:void 0}function nS(e,t){let n=tS(e,t);if(!n?.trim())throw new L(`${t} is required.`);return n}function rS(e){let{issueNumber:t,request:n,requestId:r,repo:i,resumeCreated:a,branch:o,...s}=e;return{...s,issueNumber:eS({issueNumber:t},`issueNumber`)}}async function iS(e,t,n=`author`){let r=await sh(),i=e.identity??r.roles[n].identity,a=fh({commandName:t,deliveryConfig:r,identity:i,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(a.error)throw new L(a.error);return D_({identity:i,repoRoot:e.repoRoot,role:n,...e.repo===void 0?{}:{repository:e.repo},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}})}async function aS(e,t){let n=t.issueNumber===void 0?void 0:eS(t,`issueNumber`),r,i=(i,a)=>({status:`created-not-started`,repository:e.config.repository,createdIssue:r,failure:{phase:i,message:a instanceof Error?a.message:String(a)},safeResume:{tool:`issue_start`,arguments:{...t,repo:e.config.repository,issueNumber:n,resumeCreated:!0}}});if(n===void 0){let a=tS(t,`title`)??nS(t,`request`),o={...t,title:a,body:tS(t,`body`)??tS(t,`request`)??a},s=B(Object.fromEntries(Object.entries({title:a,body:o.body,issueType:o.issueType,points:o.points,priority:o.priority,labels:o.labels,blockedBy:o.blockedBy,parentIssueNumber:o.parentIssueNumber,milestone:o.milestone,branch:t.branch}).filter(([,e])=>e!==void 0))),c=tS(t,`requestId`)??s,l=`<!-- ai-delivery-start: ${B({repository:e.config.repository.toLowerCase(),requestKey:c})} -->`;o.body=`${o.body}\n\n<!-- ai-delivery-start-intent: ${s} -->\n${l}`;let u=!1,d=[];for(let t=1;t<=20;t++){let n=(await e.clients.rest.issues.listForRepo({...e.repo,state:`all`,page:t,per_page:100})).data;if(d.push(...n.filter(e=>!(`pull_request`in e)&&e.body?.includes(l))),n.length<100){u=!0;break}}if(!u)throw new L(`Issue-start retry search exceeds the bounded readback window; select a known issue number.`);if(d.length>1)throw new L(`Conflicting issues claim the same start request.`);let f=d[0];if(f&&(f.title!==a||f.body!==o.body||f.state!==`open`))throw new L(`Prior issue-start request conflicts with the requested intent or state.`);try{f?(r={number:f.number,title:f.title,url:f.html_url},n=f.number,await z_(e,{...o,issueNumber:n})):(r=(await A_(e,o)).created,n=r.number)}catch(e){if(e instanceof k_)r=e.created,n=r.number;else if(!r)throw e;return i(`tracking`,e)}}else if(t.resumeCreated===!0){let a=(await e.clients.rest.issues.get({...e.repo,issue_number:n})).data;if(a.number!==n||`pull_request`in a)throw new L(`Known-created issue readback disagrees.`);r={number:n,title:a.title,url:a.html_url};try{await z_(e,rS(t))}catch(e){return i(`tracking`,e)}}try{let r=await G_(e,n,tS(t,`branch`));return await E_(e,n),{issueNumber:n,repository:e.config.repository,branch:r.branch,headSha:r.headSha,reused:r.reused}}catch(e){if(r)return i(`branch-or-journal`,e);throw e}}async function oS(e,t,n){let r=$x(e);if(!r)throw new L(`Unknown ai-delivery tool ${e}.`);let{repo:i,...a}=r.inputSchema.parse(t);if(i!==void 0&&n.repo!==void 0&&i!==n.repo)throw new L(`Tool and execution repository selectors disagree.`);let o=typeof i==`string`?i:n.repo,s={...n,...o===void 0?{}:{repo:o}},c=e===`runtime_stage`||e===`runtime_admit`||e.startsWith(`issue_worktree_transition_`),l=n.repoRoot;if(c){let t=await sh();if(l=wu({repository:o??(()=>{let e=Cu(l,`origin`);return`${e.owner}/${e.repo}`})(),launchDirectory:l,checkoutRoots:t.checkoutRoots}),e===`runtime_stage`||e===`runtime_admit`){let r={...a,repoRoot:l,identity:tS(a,`identity`)??n.identity??t.roles.author.identity,...n.personalAuth===void 0?{}:{personalAuth:n.personalAuth},...n.signal===void 0?{}:{signal:n.signal}};return e===`runtime_stage`?Hx(r):Wx(r)}}let u=e===`issue_pr_review`?tS(a,`identity`):void 0,d=await iS({...s,...u===void 0?{}:{identity:u}},r.commandName,e===`issue_pr_review`?`reviewer`:`author`);switch(c&&(d.root=l),e){case`issue_comment`:return T_(d,a);case`issue_create`:return A_(d,a);case`issue_start`:return aS(d,a);case`issue_update`:return R_(d,a);case`issue_list`:case`issue_search`:return F_(d,a);case`issue_info`:return B_(d,eS(a,`issueNumber`));case`issue_ready_check`:return H_(d,eS(a,`issueNumber`));case`issue_pr_create`:return xv(d,{issueNumber:eS(a,`issueNumber`),...a.body===void 0?{}:{body:nS(a,`body`)},...a.title===void 0?{}:{title:nS(a,`title`)},...a.headBranch===void 0?{}:{headBranch:nS(a,`headBranch`)},draft:a.draft!==!1,dryRun:a.dryRun===!0});case`issue_pr_info`:return gv(d,a);case`issue_pr_review`:return Sv(d,{artifact:nS(a,`artifact`),issueNumber:eS(a,`issueNumber`),prNumber:eS(a,`prNumber`),dryRun:a.dryRun===!0});case`issue_pr_merge`:case`issue_finish`:{let t={issueNumber:eS(a,`issueNumber`),prNumber:eS(a,`prNumber`),...a.strategy===void 0?{}:{strategy:a.strategy},...a.reviewedHeadSha===void 0?{}:{reviewedHeadSha:nS(a,`reviewedHeadSha`)},dryRun:a.dryRun===!0};return e===`issue_finish`?Tv(d,t):wv(d,t)}case`issue_worktree_transition_inspect`:return Sx(d,{...a,...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}});case`issue_worktree_transition_apply`:return dx(d,{authority:`worktree:transition`,planPath:nS(a,`planPath`),expectedPlanId:nS(a,`expectedPlanId`),relinquishmentCommentId:eS(a,`relinquishmentCommentId`),acceptanceCommentId:eS(a,`acceptanceCommentId`),...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}})}}var sS;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(sS||={});var cS;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(cS||={});var U=sS.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),lS=e=>{switch(typeof e){case`undefined`:return U.undefined;case`string`:return U.string;case`number`:return Number.isNaN(e)?U.nan:U.number;case`boolean`:return U.boolean;case`function`:return U.function;case`bigint`:return U.bigint;case`symbol`:return U.symbol;case`object`:return Array.isArray(e)?U.array:e===null?U.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?U.promise:typeof Map<`u`&&e instanceof Map?U.map:typeof Set<`u`&&e instanceof Set?U.set:typeof Date<`u`&&e instanceof Date?U.date:U.object;default:return U.unknown}},W=sS.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),uS=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;if(n===`_errors`){a&&e._errors.push(t(i)),r++;continue}Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,sS.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};uS.create=e=>new uS(e);var dS=(e,t)=>{let n;switch(e.code){case W.invalid_type:n=e.received===U.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case W.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,sS.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:n=`Unrecognized key(s) in object: ${sS.joinValues(e.keys,`, `)}`;break;case W.invalid_union:n=`Invalid input`;break;case W.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${sS.joinValues(e.options)}`;break;case W.invalid_enum_value:n=`Invalid enum value. Expected ${sS.joinValues(e.options)}, received '${e.received}'`;break;case W.invalid_arguments:n=`Invalid function arguments`;break;case W.invalid_return_type:n=`Invalid function return type`;break;case W.invalid_date:n=`Invalid date`;break;case W.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:sS.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case W.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case W.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case W.custom:n=`Invalid input`;break;case W.invalid_intersection_types:n=`Intersection results could not be merged`;break;case W.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case W.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,sS.assertNever(e)}return{message:n}},fS=dS;function pS(){return fS}var mS=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function G(e,t){let n=pS(),r=mS({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===dS?void 0:dS].filter(e=>!!e)});e.common.issues.push(r)}var hS=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return K;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return K;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},K=Object.freeze({status:`aborted`}),gS=e=>({status:`dirty`,value:e}),_S=e=>({status:`valid`,value:e}),vS=e=>e.status===`aborted`,yS=e=>e.status===`dirty`,bS=e=>e.status===`valid`,xS=e=>typeof Promise<`u`&&e instanceof Promise,q;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(q||={});var SS=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},CS=(e,t)=>{if(bS(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new uS(e.common.issues);return this._error=t,this._error}}};function J(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var Y=class{get description(){return this._def.description}_getType(e){return lS(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:lS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hS,ctx:{common:e.parent.common,data:e.data,parsedType:lS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(xS(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lS(e)};return CS(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lS(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return bS(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>bS(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lS(e)},r=this._parse({data:e,path:n.path,parent:n});return CS(n,await(xS(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:W.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new EC({schema:this,typeName:X.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return DC.create(this,this._def)}nullable(){return OC.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sC.create(this)}promise(){return TC.create(this,this._def)}or(e){return uC.create([this,e],this._def)}and(e){return mC.create(this,e,this._def)}transform(e){return new EC({...J(this._def),schema:this,typeName:X.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new kC({...J(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new MC({typeName:X.ZodBranded,type:this,...J(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new AC({...J(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return NC.create(this,e)}readonly(){return PC.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wS=/^c[^\s-]{8,}$/i,TS=/^[0-9a-z]+$/,ES=/^[0-9A-HJKMNP-TV-Z]{26}$/i,DS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,OS=/^[a-z0-9_-]{21}$/i,kS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,AS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,jS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,MS=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,NS,PS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,FS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,IS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,LS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,RS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,BS=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,VS=RegExp(`^${BS}$`);function HS(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function US(e){return RegExp(`^${HS(e)}$`)}function WS(e){let t=`${BS}T${HS(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function GS(e,t){return!((t!==`v4`&&t||!PS.test(e))&&(t!==`v6`&&t||!IS.test(e)))}function KS(e,t){if(!kS.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function qS(e,t){return!((t!==`v4`&&t||!FS.test(e))&&(t!==`v6`&&t||!LS.test(e)))}var JS=class e extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.string,received:t.parsedType}),K}let t=new hS,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)jS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`email`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)NS||=new RegExp(MS,`u`),NS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`emoji`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)DS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`uuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)OS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`nanoid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)wS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)TS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid2`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ES.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ulid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),G(n,{validation:`url`,code:W.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`regex`,code:W.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?WS(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?VS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?US(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?AS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`duration`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?GS(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ip`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?KS(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`jwt`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?qS(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cidr`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?RS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?zS.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64url`,code:W.invalid_string,message:r.message}),t.dirty()):sS.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:W.invalid_string,...q.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...q.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...q.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...q.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...q.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...q.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...q.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...q.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...q.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...q.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...q.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...q.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...q.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...q.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...q.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...q.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...q.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...q.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...q.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...q.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...q.errToObj(t)})}nonempty(e){return this.min(1,q.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};JS.create=e=>new JS({checks:[],typeName:X.ZodString,coerce:e?.coerce??!1,...J(e)});function YS(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var XS=class e extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==U.number){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.number,received:t.parsedType}),K}let t,n=new hS;for(let r of this._def.checks)r.kind===`int`?sS.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?YS(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_finite,message:r.message}),n.dirty()):sS.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:q.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:q.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:q.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:q.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:q.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&sS.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};XS.create=e=>new XS({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...J(e)});var ZS=class e extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==U.bigint)return this._getInvalidInput(e);let t,n=new hS;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):sS.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.bigint,received:t.parsedType}),K}gte(e,t){return this.setLimit(`min`,e,!0,q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:q.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZS.create=e=>new ZS({checks:[],typeName:X.ZodBigInt,coerce:e?.coerce??!1,...J(e)});var QS=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.boolean,received:t.parsedType}),K}return _S(e.data)}};QS.create=e=>new QS({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...J(e)});var $S=class e extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.date,received:t.parsedType}),K}if(Number.isNaN(e.data.getTime()))return G(this._getOrReturnCtx(e),{code:W.invalid_date}),K;let t=new hS,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):sS.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:q.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:q.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};$S.create=e=>new $S({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...J(e)});var eC=class extends Y{_parse(e){if(this._getType(e)!==U.symbol){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.symbol,received:t.parsedType}),K}return _S(e.data)}};eC.create=e=>new eC({typeName:X.ZodSymbol,...J(e)});var tC=class extends Y{_parse(e){if(this._getType(e)!==U.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.undefined,received:t.parsedType}),K}return _S(e.data)}};tC.create=e=>new tC({typeName:X.ZodUndefined,...J(e)});var nC=class extends Y{_parse(e){if(this._getType(e)!==U.null){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.null,received:t.parsedType}),K}return _S(e.data)}};nC.create=e=>new nC({typeName:X.ZodNull,...J(e)});var rC=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return _S(e.data)}};rC.create=e=>new rC({typeName:X.ZodAny,...J(e)});var iC=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _S(e.data)}};iC.create=e=>new iC({typeName:X.ZodUnknown,...J(e)});var aC=class extends Y{_parse(e){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.never,received:t.parsedType}),K}};aC.create=e=>new aC({typeName:X.ZodNever,...J(e)});var oC=class extends Y{_parse(e){if(this._getType(e)!==U.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.void,received:t.parsedType}),K}return _S(e.data)}};oC.create=e=>new oC({typeName:X.ZodVoid,...J(e)});var sC=class e extends Y{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return G(t,{code:W.invalid_type,expected:U.array,received:t.parsedType}),K;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(G(t,{code:e?W.too_big:W.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(G(t,{code:W.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(G(t,{code:W.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new SS(t,e,t.path,n)))).then(e=>hS.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new SS(t,e,t.path,n)));return hS.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:q.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:q.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:q.toString(n)}})}nonempty(e){return this.min(1,e)}};sC.create=(e,t)=>new sC({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...J(t)});function cC(e){if(e instanceof lC){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=DC.create(cC(r))}return new lC({...e._def,shape:()=>t})}return e instanceof sC?new sC({...e._def,type:cC(e.element)}):e instanceof DC?DC.create(cC(e.unwrap())):e instanceof OC?OC.create(cC(e.unwrap())):e instanceof hC?hC.create(e.items.map(e=>cC(e))):e}var lC=class e extends Y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=sS.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==U.object){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.object,received:t.parsedType}),K}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof aC&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new SS(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof aC){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(G(n,{code:W.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new SS(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>hS.mergeObjectSync(t,e)):hS.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return q.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:q.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of sS.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of sS.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return cC(this)}partial(t){let n={};for(let e of sS.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of sS.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof DC;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return SC(sS.objectKeys(this.shape))}};lC.create=(e,t)=>new lC({shape:()=>e,unknownKeys:`strip`,catchall:aC.create(),typeName:X.ZodObject,...J(t)}),lC.strictCreate=(e,t)=>new lC({shape:()=>e,unknownKeys:`strict`,catchall:aC.create(),typeName:X.ZodObject,...J(t)}),lC.lazycreate=(e,t)=>new lC({shape:e,unknownKeys:`strip`,catchall:aC.create(),typeName:X.ZodObject,...J(t)});var uC=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new uS(e.ctx.common.issues));return G(t,{code:W.invalid_union,unionErrors:n}),K}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new uS(e));return G(t,{code:W.invalid_union,unionErrors:i}),K}}get options(){return this._def.options}};uC.create=(e,t)=>new uC({options:e,typeName:X.ZodUnion,...J(t)});var dC=e=>e instanceof bC?dC(e.schema):e instanceof EC?dC(e.innerType()):e instanceof xC?[e.value]:e instanceof CC?e.options:e instanceof wC?sS.objectValues(e.enum):e instanceof kC?dC(e._def.innerType):e instanceof tC?[void 0]:e instanceof nC?[null]:e instanceof DC?[void 0,...dC(e.unwrap())]:e instanceof OC?[null,...dC(e.unwrap())]:e instanceof MC||e instanceof PC?dC(e.unwrap()):e instanceof AC?dC(e._def.innerType):[],fC=class e extends Y{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.object)return G(t,{code:W.invalid_type,expected:U.object,received:t.parsedType}),K;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(G(t,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=dC(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...J(r)})}};function pC(e,t){let n=lS(e),r=lS(t);if(e===t)return{valid:!0,data:e};if(n===U.object&&r===U.object){let n=sS.objectKeys(t),r=sS.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=pC(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===U.array&&r===U.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=pC(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===U.date&&r===U.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var mC=class extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(vS(e)||vS(r))return K;let i=pC(e.value,r.value);return i.valid?((yS(e)||yS(r))&&t.dirty(),{status:t.value,value:i.data}):(G(n,{code:W.invalid_intersection_types}),K)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};mC.create=(e,t,n)=>new mC({left:e,right:t,typeName:X.ZodIntersection,...J(n)});var hC=class e extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.array)return G(n,{code:W.invalid_type,expected:U.array,received:n.parsedType}),K;if(n.data.length<this._def.items.length)return G(n,{code:W.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),K;!this._def.rest&&n.data.length>this._def.items.length&&(G(n,{code:W.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new SS(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>hS.mergeArray(t,e)):hS.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};hC.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new hC({items:e,typeName:X.ZodTuple,rest:null,...J(t)})};var gC=class e extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.object)return G(n,{code:W.invalid_type,expected:U.object,received:n.parsedType}),K;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new SS(n,e,n.path,e)),value:a._parse(new SS(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?hS.mergeObjectAsync(t,r):hS.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Y?new e({keyType:t,valueType:n,typeName:X.ZodRecord,...J(r)}):new e({keyType:JS.create(),valueType:t,typeName:X.ZodRecord,...J(n)})}},_C=class extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.map)return G(n,{code:W.invalid_type,expected:U.map,received:n.parsedType}),K;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new SS(n,e,n.path,[a,`key`])),value:i._parse(new SS(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return K;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return K;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};_C.create=(e,t,n)=>new _C({valueType:t,keyType:e,typeName:X.ZodMap,...J(n)});var vC=class e extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==U.set)return G(n,{code:W.invalid_type,expected:U.set,received:n.parsedType}),K;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(G(n,{code:W.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(G(n,{code:W.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return K;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new SS(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:q.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:q.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};vC.create=(e,t)=>new vC({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...J(t)});var yC=class e extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.function)return G(t,{code:W.invalid_type,expected:U.function,received:t.parsedType}),K;function n(e,n){return mS({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pS(),dS].filter(e=>!!e),issueData:{code:W.invalid_arguments,argumentsError:n}})}function r(e,n){return mS({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pS(),dS].filter(e=>!!e),issueData:{code:W.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof TC){let e=this;return _S(async function(...t){let o=new uS([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return _S(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new uS([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new uS([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:hC.create(t).rest(iC.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||hC.create([]).rest(iC.create()),returns:n||iC.create(),typeName:X.ZodFunction,...J(r)})}},bC=class extends Y{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};bC.create=(e,t)=>new bC({getter:e,typeName:X.ZodLazy,...J(t)});var xC=class extends Y{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:W.invalid_literal,expected:this._def.value}),K}return{status:`valid`,value:e.data}}get value(){return this._def.value}};xC.create=(e,t)=>new xC({value:e,typeName:X.ZodLiteral,...J(t)});function SC(e,t){return new CC({values:e,typeName:X.ZodEnum,...J(t)})}var CC=class e extends Y{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{expected:sS.joinValues(n),received:t.parsedType,code:W.invalid_type}),K}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{received:t.data,code:W.invalid_enum_value,options:n}),K}return _S(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};CC.create=SC;var wC=class extends Y{_parse(e){let t=sS.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==U.string&&n.parsedType!==U.number){let e=sS.objectValues(t);return G(n,{expected:sS.joinValues(e),received:n.parsedType,code:W.invalid_type}),K}if(this._cache||=new Set(sS.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=sS.objectValues(t);return G(n,{received:n.data,code:W.invalid_enum_value,options:e}),K}return _S(e.data)}get enum(){return this._def.values}};wC.create=(e,t)=>new wC({values:e,typeName:X.ZodNativeEnum,...J(t)});var TC=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==U.promise&&t.common.async===!1?(G(t,{code:W.invalid_type,expected:U.promise,received:t.parsedType}),K):_S((t.parsedType===U.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};TC.create=(e,t)=>new TC({type:e,typeName:X.ZodPromise,...J(t)});var EC=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{G(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return K;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?K:r.status===`dirty`||t.value===`dirty`?gS(r.value):r});{if(t.value===`aborted`)return K;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?K:r.status===`dirty`||t.value===`dirty`?gS(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?K:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?K:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!bS(e))return K;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>bS(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):K)}sS.assertNever(r)}};EC.create=(e,t,n)=>new EC({schema:e,typeName:X.ZodEffects,effect:t,...J(n)}),EC.createWithPreprocess=(e,t,n)=>new EC({schema:t,effect:{type:`preprocess`,transform:e},typeName:X.ZodEffects,...J(n)});var DC=class extends Y{_parse(e){return this._getType(e)===U.undefined?_S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};DC.create=(e,t)=>new DC({innerType:e,typeName:X.ZodOptional,...J(t)});var OC=class extends Y{_parse(e){return this._getType(e)===U.null?_S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};OC.create=(e,t)=>new OC({innerType:e,typeName:X.ZodNullable,...J(t)});var kC=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===U.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};kC.create=(e,t)=>new kC({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...J(t)});var AC=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xS(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new uS(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new uS(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};AC.create=(e,t)=>new AC({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...J(t)});var jC=class extends Y{_parse(e){if(this._getType(e)!==U.nan){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:U.nan,received:t.parsedType}),K}return{status:`valid`,value:e.data}}};jC.create=e=>new jC({typeName:X.ZodNaN,...J(e)});var MC=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},NC=class e extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?K:e.status===`dirty`?(t.dirty(),gS(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?K:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:X.ZodPipeline})}},PC=class extends Y{_parse(e){let t=this._def.innerType._parse(e),n=e=>(bS(e)&&(e.value=Object.freeze(e.value)),e);return xS(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};PC.create=(e,t)=>new PC({innerType:e,typeName:X.ZodReadonly,...J(t)}),lC.lazycreate;var X;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(X||={}),JS.create,XS.create,jC.create,ZS.create,QS.create,$S.create,eC.create,tC.create,nC.create,rC.create,iC.create,aC.create,oC.create,sC.create;var FC=lC.create;lC.strictCreate,uC.create,fC.create,mC.create,hC.create,gC.create,_C.create,vC.create,yC.create,bC.create,xC.create,CC.create,wC.create,TC.create,EC.create,DC.create,OC.create,EC.createWithPreprocess,NC.create;var IC=k(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Wr.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){Ut(this,`with`,e)},parse(e,t){return Cn(this,e,t,{callee:this.parse})},parseAsync(e,t){return Tn(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Dn(this,e,t)},safeParseAsync(e,t){return An(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return _t(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),LC=k(`ZodMiniObject`,(e,t)=>{Ki.init(e,t),IC.init(e,t),Qt(e,`shape`,e=>e._zod.def.shape,!1)});function RC(e,t){return new LC({type:`object`,shape:e??{},...O(t)})}function zC(e){return!!e._zod}function BC(e){let t=Object.values(e);if(t.length===0)return RC({});let n=t.every(zC),r=t.every(e=>!zC(e));if(n)return RC(e);if(r)return FC(e);throw Error(`Mixed Zod versions detected in object shape.`)}function VC(e,t){return zC(e)?Dn(e,t):e.safeParse(t)}async function HC(e,t){return zC(e)?await An(e,t):await e.safeParseAsync(t)}function UC(e){if(!e)return;let t;if(t=zC(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function WC(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return BC(e)}}if(zC(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function GC(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function KC(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${GC(e.path)}`:e.message).join(`
|
|
262
|
-
`);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function qC(e){return e.description}function JC(e){if(zC(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function YC(e){if(zC(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}var XC=`2025-11-25`,ZC=[XC,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],QC=`io.modelcontextprotocol/related-task`,$C=du(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ew=Ml([A(),j().int()]),tw=A();Al({ttl:j().optional(),pollInterval:j().optional()});var nw=N({ttl:j().optional()}),rw=N({taskId:A()}),iw=Al({progressToken:ew.optional(),[QC]:rw.optional()}),aw=N({_meta:iw.optional()}),ow=aw.extend({task:nw.optional()}),sw=e=>ow.safeParse(e).success,cw=N({method:A(),params:aw.loose().optional()}),lw=N({_meta:iw.optional()}),uw=N({method:A(),params:lw.loose().optional()}),dw=Al({_meta:iw.optional()}),fw=Ml([A(),j().int()]),pw=N({jsonrpc:I(`2.0`),id:fw,...cw.shape}).strict(),mw=e=>pw.safeParse(e).success,hw=N({jsonrpc:I(`2.0`),...uw.shape}).strict(),gw=e=>hw.safeParse(e).success,_w=N({jsonrpc:I(`2.0`),id:fw,result:dw}).strict(),vw=e=>_w.safeParse(e).success,Z;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Z||={});var yw=N({jsonrpc:I(`2.0`),id:fw.optional(),error:N({code:j().int(),message:A(),data:Tl().optional()})}).strict(),bw=e=>yw.safeParse(e).success,xw=Ml([pw,hw,_w,yw]);Ml([_w,yw]);var Sw=dw.strict(),Cw=lw.extend({requestId:fw.optional(),reason:A().optional()}),ww=uw.extend({method:I(`notifications/cancelled`),params:Cw}),Tw=N({icons:M(N({src:A(),mimeType:A().optional(),sizes:M(A()).optional(),theme:F([`light`,`dark`]).optional()})).optional()}),Ew=N({name:A(),title:A().optional()}),Dw=Ew.extend({...Ew.shape,...Tw.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),Ow=mu(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Il(N({form:Il(N({applyDefaults:xl().optional()}),Bl(A(),Tl())).optional(),url:$C.optional()}),Bl(A(),Tl()).optional())),kw=Al({list:$C.optional(),cancel:$C.optional(),requests:Al({sampling:Al({createMessage:$C.optional()}).optional(),elicitation:Al({create:$C.optional()}).optional()}).optional()}),Aw=Al({list:$C.optional(),cancel:$C.optional(),requests:Al({tools:Al({call:$C.optional()}).optional()}).optional()}),jw=N({experimental:Bl(A(),$C).optional(),sampling:N({context:$C.optional(),tools:$C.optional()}).optional(),elicitation:Ow.optional(),roots:N({listChanged:xl().optional()}).optional(),tasks:kw.optional(),extensions:Bl(A(),$C).optional()}),Mw=aw.extend({protocolVersion:A(),capabilities:jw,clientInfo:Dw}),Nw=cw.extend({method:I(`initialize`),params:Mw}),Pw=N({experimental:Bl(A(),$C).optional(),logging:$C.optional(),completions:$C.optional(),prompts:N({listChanged:xl().optional()}).optional(),resources:N({subscribe:xl().optional(),listChanged:xl().optional()}).optional(),tools:N({listChanged:xl().optional()}).optional(),tasks:Aw.optional(),extensions:Bl(A(),$C).optional()}),Fw=dw.extend({protocolVersion:A(),capabilities:Pw,serverInfo:Dw,instructions:A().optional()}),Iw=uw.extend({method:I(`notifications/initialized`),params:lw.optional()}),Lw=cw.extend({method:I(`ping`),params:aw.optional()}),Rw=N({progress:j(),total:Kl(j()),message:Kl(A())}),zw=N({...lw.shape,...Rw.shape,progressToken:ew}),Bw=uw.extend({method:I(`notifications/progress`),params:zw}),Vw=aw.extend({cursor:tw.optional()}),Hw=cw.extend({params:Vw.optional()}),Uw=dw.extend({nextCursor:tw.optional()}),Ww=F([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Gw=N({taskId:A(),status:Ww,ttl:Ml([j(),Cl()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Kl(j()),statusMessage:Kl(A())}),Kw=dw.extend({task:Gw}),qw=lw.merge(Gw),Jw=uw.extend({method:I(`notifications/tasks/status`),params:qw}),Yw=cw.extend({method:I(`tasks/get`),params:aw.extend({taskId:A()})}),Xw=dw.merge(Gw),Zw=cw.extend({method:I(`tasks/result`),params:aw.extend({taskId:A()})});dw.loose();var Qw=Hw.extend({method:I(`tasks/list`)}),$w=Uw.extend({tasks:M(Gw)}),eT=cw.extend({method:I(`tasks/cancel`),params:aw.extend({taskId:A()})}),tT=dw.merge(Gw),nT=N({uri:A(),mimeType:Kl(A()),_meta:Bl(A(),Tl()).optional()}),rT=nT.extend({text:A()}),iT=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),aT=nT.extend({blob:iT}),oT=F([`user`,`assistant`]),sT=N({audience:M(oT).optional(),priority:j().min(0).max(1).optional(),lastModified:hu({offset:!0}).optional()}),cT=N({...Ew.shape,...Tw.shape,uri:A(),description:Kl(A()),mimeType:Kl(A()),size:Kl(j()),annotations:sT.optional(),_meta:Kl(Al({}))}),lT=N({...Ew.shape,...Tw.shape,uriTemplate:A(),description:Kl(A()),mimeType:Kl(A()),annotations:sT.optional(),_meta:Kl(Al({}))}),uT=Hw.extend({method:I(`resources/list`)}),dT=Uw.extend({resources:M(cT)}),fT=Hw.extend({method:I(`resources/templates/list`)}),pT=Uw.extend({resourceTemplates:M(lT)}),mT=aw.extend({uri:A()}),hT=mT,gT=cw.extend({method:I(`resources/read`),params:hT}),_T=dw.extend({contents:M(Ml([rT,aT]))}),vT=uw.extend({method:I(`notifications/resources/list_changed`),params:lw.optional()}),yT=mT,bT=cw.extend({method:I(`resources/subscribe`),params:yT}),xT=mT,ST=cw.extend({method:I(`resources/unsubscribe`),params:xT}),CT=lw.extend({uri:A()}),wT=uw.extend({method:I(`notifications/resources/updated`),params:CT}),TT=N({name:A(),description:Kl(A()),required:Kl(xl())}),ET=N({...Ew.shape,...Tw.shape,description:Kl(A()),arguments:Kl(M(TT)),_meta:Kl(Al({}))}),DT=Hw.extend({method:I(`prompts/list`)}),OT=Uw.extend({prompts:M(ET)}),kT=aw.extend({name:A(),arguments:Bl(A(),A()).optional()}),AT=cw.extend({method:I(`prompts/get`),params:kT}),jT=N({type:I(`text`),text:A(),annotations:sT.optional(),_meta:Bl(A(),Tl()).optional()}),MT=N({type:I(`image`),data:iT,mimeType:A(),annotations:sT.optional(),_meta:Bl(A(),Tl()).optional()}),NT=N({type:I(`audio`),data:iT,mimeType:A(),annotations:sT.optional(),_meta:Bl(A(),Tl()).optional()}),PT=N({type:I(`tool_use`),name:A(),id:A(),input:Bl(A(),Tl()),_meta:Bl(A(),Tl()).optional()}),FT=N({type:I(`resource`),resource:Ml([rT,aT]),annotations:sT.optional(),_meta:Bl(A(),Tl()).optional()}),IT=Ml([jT,MT,NT,cT.extend({type:I(`resource_link`)}),FT]),LT=N({role:oT,content:IT}),RT=dw.extend({description:A().optional(),messages:M(LT)}),zT=uw.extend({method:I(`notifications/prompts/list_changed`),params:lw.optional()}),BT=N({title:A().optional(),readOnlyHint:xl().optional(),destructiveHint:xl().optional(),idempotentHint:xl().optional(),openWorldHint:xl().optional()}),VT=N({taskSupport:F([`required`,`optional`,`forbidden`]).optional()}),HT=N({...Ew.shape,...Tw.shape,description:A().optional(),inputSchema:N({type:I(`object`),properties:Bl(A(),$C).optional(),required:M(A()).optional()}).catchall(Tl()),outputSchema:N({type:I(`object`),properties:Bl(A(),$C).optional(),required:M(A()).optional()}).catchall(Tl()).optional(),annotations:BT.optional(),execution:VT.optional(),_meta:Bl(A(),Tl()).optional()}),UT=Hw.extend({method:I(`tools/list`)}),WT=Uw.extend({tools:M(HT)}),GT=dw.extend({content:M(IT).default([]),structuredContent:Bl(A(),Tl()).optional(),isError:xl().optional()});GT.or(dw.extend({toolResult:Tl()}));var KT=ow.extend({name:A(),arguments:Bl(A(),Tl()).optional()}),qT=cw.extend({method:I(`tools/call`),params:KT}),JT=uw.extend({method:I(`notifications/tools/list_changed`),params:lw.optional()}),YT=N({autoRefresh:xl().default(!0),debounceMs:j().int().nonnegative().default(300)}),XT=F([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),ZT=aw.extend({level:XT}),QT=cw.extend({method:I(`logging/setLevel`),params:ZT}),$T=lw.extend({level:XT,logger:A().optional(),data:Tl()}),eE=uw.extend({method:I(`notifications/message`),params:$T}),tE=N({hints:M(N({name:A().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),nE=N({mode:F([`auto`,`required`,`none`]).optional()}),rE=N({type:I(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:M(IT).default([]),structuredContent:N({}).loose().optional(),isError:xl().optional(),_meta:Bl(A(),Tl()).optional()}),iE=Pl(`type`,[jT,MT,NT]),aE=Pl(`type`,[jT,MT,NT,PT,rE]),oE=N({role:oT,content:Ml([aE,M(aE)]),_meta:Bl(A(),Tl()).optional()}),sE=ow.extend({messages:M(oE),modelPreferences:tE.optional(),systemPrompt:A().optional(),includeContext:F([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:M(A()).optional(),metadata:$C.optional(),tools:M(HT).optional(),toolChoice:nE.optional()}),cE=cw.extend({method:I(`sampling/createMessage`),params:sE}),lE=dw.extend({model:A(),stopReason:Kl(F([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:oT,content:iE}),uE=dw.extend({model:A(),stopReason:Kl(F([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:oT,content:Ml([aE,M(aE)])}),dE=N({type:I(`boolean`),title:A().optional(),description:A().optional(),default:xl().optional()}),fE=N({type:I(`string`),title:A().optional(),description:A().optional(),minLength:j().optional(),maxLength:j().optional(),format:F([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),pE=N({type:F([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),mE=N({type:I(`string`),title:A().optional(),description:A().optional(),enum:M(A()),default:A().optional()}),hE=N({type:I(`string`),title:A().optional(),description:A().optional(),oneOf:M(N({const:A(),title:A()})),default:A().optional()}),gE=Ml([Ml([N({type:I(`string`),title:A().optional(),description:A().optional(),enum:M(A()),enumNames:M(A()).optional(),default:A().optional()}),Ml([mE,hE]),Ml([N({type:I(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:N({type:I(`string`),enum:M(A())}),default:M(A()).optional()}),N({type:I(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:N({anyOf:M(N({const:A(),title:A()}))}),default:M(A()).optional()})])]),dE,fE,pE]),_E=Ml([ow.extend({mode:I(`form`).optional(),message:A(),requestedSchema:N({type:I(`object`),properties:Bl(A(),gE),required:M(A()).optional()})}),ow.extend({mode:I(`url`),message:A(),elicitationId:A(),url:A().url()})]),vE=cw.extend({method:I(`elicitation/create`),params:_E}),yE=lw.extend({elicitationId:A()}),bE=uw.extend({method:I(`notifications/elicitation/complete`),params:yE}),xE=dw.extend({action:F([`accept`,`decline`,`cancel`]),content:mu(e=>e===null?void 0:e,Bl(A(),Ml([A(),j(),xl(),M(A())])).optional())}),SE=N({type:I(`ref/resource`),uri:A()}),CE=N({type:I(`ref/prompt`),name:A()}),wE=aw.extend({ref:Ml([CE,SE]),argument:N({name:A(),value:A()}),context:N({arguments:Bl(A(),A()).optional()}).optional()}),TE=cw.extend({method:I(`completion/complete`),params:wE});function EE(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function DE(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var OE=dw.extend({completion:Al({values:M(A()).max(100),total:Kl(j().int()),hasMore:Kl(xl())})}),kE=N({uri:A().startsWith(`file://`),name:A().optional(),_meta:Bl(A(),Tl()).optional()}),AE=cw.extend({method:I(`roots/list`),params:aw.optional()}),jE=dw.extend({roots:M(kE)}),ME=uw.extend({method:I(`notifications/roots/list_changed`),params:lw.optional()});Ml([Lw,Nw,TE,QT,AT,DT,uT,fT,gT,bT,ST,qT,UT,Yw,Zw,Qw,eT]),Ml([ww,Bw,Iw,ME,Jw]),Ml([Sw,lE,uE,xE,jE,Xw,$w,Kw]),Ml([Lw,cE,vE,AE,Yw,Zw,Qw,eT]),Ml([ww,Bw,eE,wT,vT,JT,zT,Jw,bE]),Ml([Sw,Fw,OE,RT,OT,dT,pT,_T,GT,WT,Xw,$w,Kw]);var Q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new NE(e.elicitations,n)}return new e(t,n,r)}},NE=class extends Q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function PE(e){return e===`completed`||e===`failed`||e===`cancelled`}var FE=Symbol(`Let zodToJsonSchema decide on which parser to use`),IE={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},LE=e=>typeof e==`string`?{...IE,name:e}:{...IE,...e},RE=e=>{let t=LE(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function zE(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function BE(e,t,n,r,i){e[t]=n,zE(e,t,r,i)}var VE=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function HE(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?VE(t,e.currentPath):t.join(`/`)}}function UE(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==X.ZodAny&&(n.items=ND(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&BE(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&BE(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(BE(n,`minItems`,e.exactLength.value,e.exactLength.message,t),BE(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function WE(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?BE(n,`minimum`,r.value,r.message,t):BE(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),BE(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?BE(n,`maximum`,r.value,r.message,t):BE(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),BE(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:BE(n,`multipleOf`,r.value,r.message,t)}return n}function GE(){return{type:`boolean`}}function KE(e,t){return ND(e.type._def,t)}var qE=(e,t)=>ND(e.innerType._def,t);function JE(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>JE(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return YE(e,t)}}var YE=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:BE(n,`minimum`,r.value,r.message,t);break;case`max`:BE(n,`maximum`,r.value,r.message,t)}return n};function XE(e,t){return{...ND(e.innerType._def,t),default:e.defaultValue()}}function ZE(e,t){return t.effectStrategy===`input`?ND(e.schema._def,t):HE(t)}function QE(e){return{type:`string`,enum:Array.from(e.values)}}var $E=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function eD(e,t){let n=[ND(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),ND(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if($E(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function tD(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var nD=void 0,rD={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(nD===void 0&&(nD=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),nD),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function iD(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:BE(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:BE(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:cD(n,`email`,r.message,t);break;case`format:idn-email`:cD(n,`idn-email`,r.message,t);break;case`pattern:zod`:lD(n,rD.email,r.message,t)}break;case`url`:cD(n,`uri`,r.message,t);break;case`uuid`:cD(n,`uuid`,r.message,t);break;case`regex`:lD(n,r.regex,r.message,t);break;case`cuid`:lD(n,rD.cuid,r.message,t);break;case`cuid2`:lD(n,rD.cuid2,r.message,t);break;case`startsWith`:lD(n,RegExp(`^${aD(r.value,t)}`),r.message,t);break;case`endsWith`:lD(n,RegExp(`${aD(r.value,t)}$`),r.message,t);break;case`datetime`:cD(n,`date-time`,r.message,t);break;case`date`:cD(n,`date`,r.message,t);break;case`time`:cD(n,`time`,r.message,t);break;case`duration`:cD(n,`duration`,r.message,t);break;case`length`:BE(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),BE(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:lD(n,RegExp(aD(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&cD(n,`ipv4`,r.message,t),r.version!==`v4`&&cD(n,`ipv6`,r.message,t);break;case`base64url`:lD(n,rD.base64url,r.message,t);break;case`jwt`:lD(n,rD.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&lD(n,rD.ipv4Cidr,r.message,t),r.version!==`v4`&&lD(n,rD.ipv6Cidr,r.message,t);break;case`emoji`:lD(n,rD.emoji(),r.message,t);break;case`ulid`:lD(n,rD.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:cD(n,`binary`,r.message,t);break;case`contentEncoding:base64`:BE(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:lD(n,rD.base64,r.message,t)}break;case`nanoid`:lD(n,rD.nanoid,r.message,t)}return n}function aD(e,t){return t.patternStrategy===`escape`?sD(e):e}var oD=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function sD(e){let t=``;for(let n=0;n<e.length;n++)oD.has(e[n])||(t+=`\\`),t+=e[n];return t}function cD(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):BE(e,`format`,t,n,r)}function lD(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:uD(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):BE(e,`pattern`,uD(t,r),n,r)}function uD(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
261
|
+
}`,{...e.repo,number:n})).repository.pullRequest?.closingIssuesReferences;if(r.number!==n||r.head.repo?.full_name.toLowerCase()!==e.config.repository.toLowerCase()||r.base.repo.full_name.toLowerCase()!==e.config.repository.toLowerCase()||!i||i.pageInfo.hasNextPage||!i.nodes.some(n=>n.number===t&&n.repository.nameWithOwner.toLowerCase()===e.config.repository.toLowerCase()))throw new R(`Native PR lineage does not establish the exact repository and closing issue.`);return ix.parse({prNumber:n,headSha:r.head.sha,headBranch:r.head.ref,baseSha:r.base.sha,baseBranch:r.base.ref,mergeSha:r.merge_commit_sha,merged:r.merged,authorLogin:r.user?.login})}async function Mx(e,t,n){let r=[...new Set([t.prNumber,n].filter(e=>e!=null))];return Promise.all(r.map(n=>jx(e,t.issueNumber,n)))}function Nx(e,t,n,r,i,a,o,s){if(n===`active-resume`){if(![`active`,`pr-published`].includes(t.status)||o!==`open`||a.some(e=>e.merged||e.headSha!==i.sha||e.headBranch!==t.branch))throw new R(`Active resume requires the exact open issue and unmerged source lineage.`);if(s.some(e=>/^git\/ai-delivery\/(?:publications|reviews|merges|merge-intents|merge-attempts|merge-results)\//u.test(e.path)))throw new R(`Existing current publication/review/merge slots require separate authority reconciliation; active resume cannot overwrite them.`)}else{let n=a.find(e=>e.prNumber===r);if(!n||o!==`closed`||!n.merged||n.headSha!==i.sha||n.headBranch!==t.branch||a.some(r=>!r.merged||!r.mergeSha||r.headBranch!==t.branch||r.baseBranch!==n.baseBranch||Tu(e,`merge-base`,`--is-ancestor`,r.mergeSha,r.prNumber===n.prNumber?n.mergeSha:i.sha)!==0))throw new R(`Terminal native PR lineage or merged-result ancestry does not bind the retained exact source.`)}}async function Px(e,t,n){let r=async t=>{try{let n=(await e.clients.rest.repos.getBranch({...e.repo,branch:t})).data;if(n.name!==t)throw new R(`Native branch readback belongs to another ref.`);return Mu.parse(n.commit.sha)}catch(e){if(e.status===404)return null;throw e}},i=await r(t),a=await r(n);if(a===null)throw new R(`Native retaining base branch is missing.`);return{headSha:i,baseSha:a}}async function Fx(e,t){let n=[],r=Ou(e.root),i=Vb(r).filter(e=>e.type===`issue`&&e.issueNumber===t.issueNumber);if(i.length!==1)return{ready:!1,blockers:[`Expected one canonical legacy issue row.`],plan:null,inventory:[]};let a=[];try{let o=rx.parse(i[0]);if(a.push(...dx(r,o)),!e.configuration||e.config.repository!==`${e.repo.owner}/${e.repo.repo}`)throw new R(`Transition requires exact current repository configuration.`);if(o.path!==T(r,`.worktrees`,`issue-${String(o.issueNumber)}`)||o.branch!==`issue/${String(o.issueNumber)}`||Eu(o.path)!==p(o.path)||Du(o.path)!==Du(r)||wu(o.path,`branch`,`--show-current`)!==o.branch)throw new R(`Legacy row path, branch or Git ownership disagrees.`);Au(o.path);for(let e of[`v1`,`v2`])lx(T(Du(r),`issue-cli`,`verification-stages`,e))&&n.push(`Unsupported operative issue-cli verification-stages/${e}; no authenticated supported operational closure is available.`);if((!t.retainedAdmissionPath||!t.retainedArchivePath)&&n.push(`Missing retained supported public producer admission/archive and operational closure. Historical UNKNOWN is preservation-only.`),n.length>0)return{ready:!1,blockers:n,plan:null,inventory:a};let s=await Gv({repoRoot:r,configuration:e.configuration,...t.runtimeEntryPath===void 0?{}:{runtimeEntryPath:t.runtimeEntryPath}}),{inventory:c,...l}=sx(e,p(t.retainedAdmissionPath),p(t.retainedArchivePath));a.push(...c);let u={sha:wu(o.path,`rev-parse`,`HEAD`),tree:wu(o.path,`rev-parse`,`HEAD^{tree}`)},d=cx(r,o,a,l.producerDigest,u);if(a.filter(e=>e.path.startsWith(`git/ai-delivery/runs@2/`)).some(t=>Qy(ux(t.source)).classification.repository!==e.config.repository))throw new R(`Operational run inventory belongs to another repository.`);if(t.disposition===`remove`&&c.some(e=>{let t=ne(o.path,e.source);return t===``||!t.startsWith(`..`)&&!t.startsWith(`/`)}))throw new R(`Retained operational producer must remain outside the source selected for removal.`);let f=a.find(e=>e.path.startsWith(`git/ai-delivery/writers@1/`));Uy(o.path,f===void 0?void 0:ux(f.source));let m=t.purpose===`merged-cleanup`?t.terminalPrNumber??o.prNumber??null:null,h=await Mx(e,o,m),g=(await e.clients.rest.issues.get({...e.repo,issue_number:o.issueNumber})).data;Nx(r,o,t.purpose,m,u,h,g.state,a);let _=await Tx(e);if(h.some(e=>e.authorLogin.toLowerCase()===_.reviewerActor.toLowerCase()))throw new R(`Configured transition reviewer App is also the native PR author.`);let v=t.disposition===`remove`?await Px(e,o.branch,h.find(e=>e.prNumber===m).baseBranch):null;if(v&&(v.headSha!==null&&v.headSha!==u.sha||wu(r,`rev-parse`,ju(r,Lx(e).remote))!==v.baseSha))throw new R(`Native remote branch readback disagrees with exact source or local retaining ref.`);let y=[...t.retainedHoldCommentIds??[]].sort((e,t)=>e-t);if(new Set(y).size!==y.length)throw new R(`Retained hold inventory has duplicates.`);let b=[];for(let t of y){let n=(await e.clients.rest.issues.getComment({...e.repo,comment_id:t})).data;if(!n.body||n.issue_url?.toLowerCase()!==`https://api.github.com/repos/${e.config.repository}/issues/${String(m??o.issueNumber)}`.toLowerCase())throw new R(`Retained hold comment belongs to another subject or is unavailable.`);let r=Buffer.from(B(n));b.push({commentId:t,digest:H(r)})}a.sort((e,t)=>e.path.localeCompare(t.path));let x={schemaVersion:`ai-delivery.worktree-transition-plan@1`,repository:e.config.repository,repoRoot:r,row:o,purpose:t.purpose,disposition:t.disposition??`retain`,head:u,terminalPrNumber:m,lineage:h,remoteRefs:v,retainedHoldCommentIds:y,holdEvidence:b,inventory:a,inventoryId:V(a),historicalProducer:`UNKNOWN`,closure:{family:`public-ai-delivery-0.3.5-posix@1`,...l,runManifestIds:d},currentRuntime:s,policyDigest:H(ux(Lx(e).policyModulePath)),operator:_.operator,reviewerActor:_.reviewerActor},S=ax.parse({...x,planId:V(x)});return{ready:!0,blockers:n,plan:S,inventory:a,relinquishmentBody:Ex(S)}}catch(e){return n.push(e instanceof Error?e.message:String(e)),{ready:!1,blockers:n,plan:null,inventory:a}}}function Ix(e,t){for(let n of t){let t=ux(n.source);if(t.length!==n.size||H(t)!==n.digest)throw new R(`Historical evidence drifted: ${n.path}`);Ru(T(e,`${n.digest.slice(7)}.bin`),t,n.digest)}}function Lx(e){if(!e.configuration||!(`policyModulePath`in e.configuration))throw new R(`Historical repository configuration binding is unsupported by this runtime; preserve its original controller and records. No policy module was loaded.`);return e.configuration}var Rx=A().regex(/^sha256:[a-f0-9]{64}$/u),zx=F({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2)}),Bx=F({archivePath:A().min(1),archiveSha256:Rx,configDigest:Rx,packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),repoRoot:A().min(1),repository:A().min(1),reviewRouteDigest:Rx,runtimeDirectory:A().min(1),nativePluginRoot:A().min(1).optional(),sourceCommit:A().regex(/^[a-f0-9]{40}$/u),resourceBounds:zx.optional()}),Vx=F({schemaVersion:L(`ai-delivery.runtime-stage@1`),stageId:Rx,intent:Bx,directory:F({device:j().int(),inode:j().int()}),admission:Vv.optional(),status:I([`incomplete`,`complete`]),recordId:Rx}).superRefine((e,t)=>{let{recordId:n,...r}=e;(n!==V(r)||e.stageId!==V(e.intent)||e.status===`complete`!=(e.admission!==void 0)||e.admission!==void 0&&(e.admission.sourceCommit!==e.intent.sourceCommit||e.admission.sourceArchiveSha256!==e.intent.archiveSha256||e.admission.packageVersion!==e.intent.packageVersion||e.admission.configDigest!==e.intent.configDigest||e.admission.repository!==e.intent.repository||e.admission.cliPath!==Ux(e.intent.runtimeDirectory,e.intent.nativePluginRoot).cliPath||e.admission.mcpLauncherPath!==Ux(e.intent.runtimeDirectory,e.intent.nativePluginRoot).mcpLauncherPath||e.admission.pluginManifestPath!==Ux(e.intent.runtimeDirectory,e.intent.nativePluginRoot).pluginManifestPath))&&t.addIssue({code:`custom`,message:`Runtime stage identity or completion is corrupt.`})});function Hx(e){if(!ee(e)||E(e)!==e)throw new R(`Runtime setup paths must be absolute and canonical.`);let t=e.split(re).filter(Boolean),n=re;for(let e of t){n=T(n,e);try{if(o(n).isSymbolicLink())throw new R(`Runtime setup path contains a symbolic link.`)}catch(e){if(e.code!==`ENOENT`)throw e}}return e}function Ux(e,t){let n=T(e,`node_modules`,`@aviaratech`,`ai-delivery`),r=t??T(n,`plugins`,`ai-delivery`);return{cliPath:t?T(r,`runtime`,`dist`,`cli.js`):T(n,`dist`,`cli.js`),mcpLauncherPath:T(r,`dist`,`mcp-launcher.js`),pluginManifestPath:T(r,`.claude-plugin`,`plugin.json`)}}function Wx(e,t){if(t!==void 0&&(Hx(t),t===e||t.startsWith(`${e}${re}`)||e.startsWith(`${t}${re}`)))throw new R(`Native plugin cache and owned runtime stage paths must not overlap.`)}function Gx(e){if(e.nativePluginRoot===void 0)return;Wx(e.runtimeDirectory,e.nativePluginRoot);let t=Hx(T(e.runtimeDirectory,`node_modules/@aviaratech/ai-delivery/plugins/ai-delivery`)),n=0,r=(e,t,i)=>{if(i>16||++n>4096)throw new R(`Native plugin inventory exceeds the reviewed layout bound.`);let a=o(e),s=o(t);if(a.isDirectory()&&s.isDirectory()){let n=d(e).sort();if(JSON.stringify(n)!==JSON.stringify(d(t).sort()))throw new R(`Selected native plugin inventory disagrees with reviewed archive bytes.`);for(let a of n)r(T(e,a),T(t,a),i+1)}else if(!a.isFile()||!s.isFile()||a.nlink!==1||s.nlink!==1||a.size!==s.size||!l(e).equals(l(t)))throw new R(`Selected native plugin files disagree with reviewed archive bytes.`)};try{r(t,e.nativePluginRoot,0)}catch(e){throw e instanceof R?e:new R(`Selected native plugin cannot be matched to reviewed archive bytes.`)}}function Kx(e,t){Hx(e),Rx.parse(t);let n=o(e);if(!n.isFile()||n.nlink!==1)throw new R(`Reviewed runtime archive bytes do not match the expected digest.`);let r=l(e);if(H(r)!==t)throw new R(`Reviewed runtime archive bytes do not match the expected digest.`);return r}function qx(e){let t=Hx(T(e.runtimeDirectory,`reviewed-archive.tgz`));if(H(U(t))!==e.archiveSha256)throw new R(`Runtime stage archive snapshot bytes changed.`);return t}async function Jx(e,t,n,r){if(await n?.(),typeof e.identity!=`string`||!e.identity.trim())throw new R(`Runtime setup requires an explicit configured author identity.`);let i=Eu(e.repoRoot);if(i!==Ou(i))throw new R(`Runtime setup requires the primary consumer controller checkout.`);if(Au(i),ku(i).sha!==e.expectedSourceCommit)throw new R(`Primary controller source commit changed.`);Hx(e.runtimeDirectory);let a=await E_({identity:e.identity,repoRoot:i,role:`author`,...r===void 0?{}:{signal:r},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});await n?.();let o=dh({commandName:t,deliveryConfig:a.config,identity:e.identity,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(o.error)throw new R(o.error);if(!a.configuration||a.configuration.configDigest!==e.expectedConfigDigest)throw new R(`Primary controller resolver config digest changed.`);let s=await Nv(a,void 0,void 0,`publication`,n===void 0||r===void 0?void 0:{signal:r,checkResources:n});if(await n?.(),Au(i),ku(i).sha!==e.expectedSourceCommit)throw new R(`Primary controller source commit changed during preflight.`);return{root:i,configuration:a.configuration,reviewRoute:s}}function Yx(e){Hx(e);let t=o(e);if(!t.isDirectory()||(t.mode&511)!=448)throw new R(`Runtime stage directory must be private and owned.`);let n;try{n=Vx.parse(JSON.parse(U(T(e,`runtime-stage.json`)).toString(`utf8`)))}catch{throw new R(`Runtime stage is unowned, incompatible or corrupt.`)}if(n.intent.runtimeDirectory!==e||t.dev!==n.directory.device||t.ino!==n.directory.inode)throw new R(`Runtime stage directory ownership changed.`);return n.status===`complete`&&(qx(n.intent),Gx(n.intent)),n}function Xx(e,t){let n=Vx.parse({...t,recordId:V(t)});q_(T(e,`runtime-stage.json`),n);let r=Yx(e);if(r.recordId!==n.recordId)throw new R(`Runtime stage completion readback changed.`);return r}function Zx(e){let n=c(e,`r`);try{i(n)}finally{t(n)}}function Qx(e){let n=U(e),r=c(e,`r`);try{i(r)}finally{t(r)}if(Zx(w(e)),!U(e).equals(n))throw new R(`Runtime admission third-party replacement conflict.`)}function $x(e,t,n){if(!e.admission)throw new R(`Runtime stage completion is missing.`);return{stageId:e.stageId,admission:e.admission,reused:n,reviewRoute:t,launch:{cli:{command:process.execPath,args:[e.admission.cliPath]},mcp:{command:process.execPath,args:[e.admission.mcpLauncherPath]}}}}function eS(e,t,n){if(e.intent.repoRoot!==t.root||e.intent.repository!==t.configuration.config.repository||e.intent.sourceCommit!==n.expectedSourceCommit||e.intent.configDigest!==n.expectedConfigDigest)throw new R(`Runtime stage primary controller source or configuration changed.`);if(e.intent.reviewRouteDigest!==V(t.reviewRoute))throw new R(`Runtime stage configured actors or review route changed.`)}async function tS(e){if(e.authority!==`runtime:stage`)throw new R(`Explicit runtime:stage authority is required.`);let t=zx.parse({maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2,maxCapturedOutputBytes:1024**2,...e.resourceBounds});return Hx(e.runtimeDirectory),Wx(e.runtimeDirectory,e.nativePluginRoot),_b(e.repoRoot,async r=>{let i=await Jx(e,`runtime:stage`,r.checkResources,r.signal);Kx(e.archivePath,e.expectedArchiveSha256);let a=Bx.parse({archivePath:e.archivePath,archiveSha256:e.expectedArchiveSha256,configDigest:e.expectedConfigDigest,sourceCommit:e.expectedSourceCommit,packageVersion:e.packageVersion,repoRoot:i.root,repository:i.configuration.config.repository,reviewRouteDigest:V(i.reviewRoute),runtimeDirectory:e.runtimeDirectory,resourceBounds:t,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot}}),c=V(a);if(r.bindCapturedOutput(c),n(e.runtimeDirectory)){let t=Yx(e.runtimeDirectory);if(t.stageId!==c)throw new R(`Runtime stage belongs to an incompatible setup intent.`);if(t.status===`complete`){let n=await Jx(e,`runtime:stage`,r.checkResources,r.signal);return eS(t,n,e),Kx(a.archivePath,a.archiveSha256),Qx(T(e.runtimeDirectory,`reviewed-archive.tgz`)),qx(a),Kv(t.admission,n.configuration,t.admission.cliPath),Qx(T(e.runtimeDirectory,`runtime-stage.json`)),Zx(w(e.runtimeDirectory)),await r.checkResources(),$x(t,n.reviewRoute,!0)}r.assertQuiescent(),h(e.runtimeDirectory,{recursive:!0})}G_(w(e.runtimeDirectory)),s(e.runtimeDirectory,{mode:448});let l=o(e.runtimeDirectory),u={schemaVersion:`ai-delivery.runtime-stage@1`,stageId:c,intent:a,directory:{device:l.dev,inode:l.ino},status:`incomplete`},d=!1;try{if(Zx(w(e.runtimeDirectory)),Xx(e.runtimeDirectory,u),d=!0,e.signal?.aborted)throw new R(`Runtime stage cancelled.`);let n=Kx(e.archivePath,e.expectedArchiveSha256);if(!Number.isSafeInteger(t.maxNewOutputBytes)||n.length>=t.maxNewOutputBytes)throw new R(`Reviewed archive snapshot exceeds the stage output limit.`);Ru(T(e.runtimeDirectory,`reviewed-archive.tgz`),n);let i=qx(a),o=T(e.runtimeDirectory,`.npm`),s=T(o,`cache`),c=T(o,`logs`),l=T(o,`tmp`);for(let e of[s,c,l])G_(e);let f=T(o,`user.npmrc`),p=T(o,`global.npmrc`);Ru(f,Buffer.alloc(0)),Ru(p,Buffer.alloc(0)),await r.checkResources(),await r.run([`npm`,`install`,`--prefix`,e.runtimeDirectory,`--omit=dev`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--package-lock=false`,`--cache`,s,`--logs-dir`,c,`--logs-max`,`0`,`--userconfig`,f,`--globalconfig`,p,i],{...t,maxNewOutputBytes:t.maxNewOutputBytes-n.length,outputRoots:[e.runtimeDirectory]},e.signal,{...process.env,TMPDIR:l,TMP:l,TEMP:l},e.runtimeDirectory);let m=await Jx(e,`runtime:stage`,r.checkResources,r.signal);eS({...u,recordId:V(u)},m,e),Kx(e.archivePath,e.expectedArchiveSha256),qx(a),Gx(a);let h=qv({...Ux(e.runtimeDirectory,e.nativePluginRoot),packageVersion:e.packageVersion,sourceArchiveSha256:e.expectedArchiveSha256,sourceCommit:e.expectedSourceCommit,configuration:m.configuration});if(Gx(a),e.signal?.aborted)throw new R(`Runtime stage cancelled.`);r.assertQuiescent(),Kv(h,m.configuration,h.cliPath),await r.checkResources();let g=Xx(e.runtimeDirectory,{...u,status:`complete`,admission:h});return Kv(g.admission,m.configuration,g.admission.cliPath),$x(g,m.reviewRoute,!1)}catch(t){if(d){r.assertQuiescent();let t=Yx(e.runtimeDirectory);if(t.stageId!==c)throw new R(`Runtime stage cleanup ownership changed.`);if(t.status===`incomplete`)h(e.runtimeDirectory,{recursive:!0});else{let n=await Jx(e,`runtime:stage`,r.checkResources,r.signal);return eS(t,n,e),Kx(a.archivePath,a.archiveSha256),Qx(T(e.runtimeDirectory,`reviewed-archive.tgz`)),qx(a),Kv(t.admission,n.configuration,t.admission.cliPath),Qx(T(e.runtimeDirectory,`runtime-stage.json`)),Zx(w(e.runtimeDirectory)),$x(t,n.reviewRoute,!0)}}else{r.assertQuiescent();let t=o(e.runtimeDirectory);if(t.dev!==l.dev||t.ino!==l.ino||t.isSymbolicLink())throw new R(`Runtime stage cleanup ownership changed.`);h(e.runtimeDirectory,{recursive:!0})}throw t}},{bounds:{...t,outputRoots:[e.runtimeDirectory]},maxCapturedOutputBytes:t.maxCapturedOutputBytes,...e.signal===void 0?{}:{signal:e.signal}})}var nS=class extends R{admissionId;stageId;status=`commit-status-unknown`;constructor(e,t){super(`Runtime admission commit-status-unknown for ${e}; retry runtime:admit with the same stage ${t} to reconcile durability.`),this.admissionId=e,this.stageId=t}};async function rS(e){if(e.authority!==`runtime:admit`)throw new R(`Explicit runtime:admit authority is required.`);Rx.parse(e.stageId),e.expectedPriorAdmissionSha256!==null&&Rx.parse(e.expectedPriorAdmissionSha256);let t=await Jx(e,`runtime:admit`),r=T(Du(t.root),`ai-delivery`,`runtime-admission.json`);return Hx(r),G_(w(r)),ly(r,{projectRoot:t.root,timeout:200,operation:async()=>{let t=Yx(e.runtimeDirectory);if(t.stageId!==e.stageId||t.status!==`complete`||!t.admission)throw new R(`Exact completed runtime stage identity is required.`);let i=await Jx(e,`runtime:admit`);eS(t,i,e),Kx(t.intent.archivePath,t.intent.archiveSha256),qx(t.intent),Kv(t.admission,i.configuration,t.admission.cliPath);let a=Buffer.from(`${JSON.stringify(t.admission,null,2)}\n`);Hx(r);let o=n(r)?U(r):void 0,s=()=>{if(Hx(r),qx(t.intent),Kv(t.admission,i.configuration,t.admission.cliPath),!n(r)||!U(r).equals(a))throw new R(`Runtime admission third-party replacement conflict; current bytes preserved.`);try{Qx(r)}catch{throw!n(r)||!U(r).equals(a)?new R(`Runtime admission third-party replacement conflict; current bytes preserved.`):new nS(t.admission.admissionId,t.stageId)}return{admission:t.admission,reused:!0}};if(o?.equals(a))return s();if((o===void 0?null:H(o))!==e.expectedPriorAdmissionSha256)throw new R(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);let c=await Jx(e,`runtime:admit`);eS(t,c,e),Kx(t.intent.archivePath,t.intent.archiveSha256),qx(t.intent),Kv(t.admission,c.configuration,t.admission.cliPath),Hx(r);let l=n(r)?U(r):void 0;if((l===void 0?null:H(l))!==e.expectedPriorAdmissionSha256)throw new R(`Runtime admission prior-byte compare-and-swap conflict; current bytes preserved.`);try{q_(r,t.admission)}catch(t){let i=n(r)?U(r):void 0;if(i?.equals(a))return s();throw(i===void 0?null:H(i))===e.expectedPriorAdmissionSha256?t:new R(`Runtime admission third-party replacement conflict; current bytes preserved.`)}return s(),{admission:t.admission,reused:!1}}})}var iS=j().int().positive(),aS=N(A().trim().min(1)),oS=A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),sS={blockedBy:N(iS).optional(),body:A().optional(),issueType:A().min(1).optional(),labels:aS.optional(),milestone:iS.optional(),parentIssueNumber:iS.optional(),points:iS.optional(),priority:A().min(1).optional(),repo:A().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u).optional(),title:A().trim().min(1).max(256)},cS={repo:oS,state:I([`open`,`closed`,`all`]).optional(),labels:N(A().min(1).regex(/^[^"\\\r\n]+$/u)).optional(),parentIssueNumber:iS.nullable().optional(),issueType:A().min(1).optional(),projectStatus:I([`Todo`,`In Progress`,`Blocked`,`Done`]).nullable().optional(),updatedSince:mu({offset:!0}).optional(),page:iS.optional(),perPage:iS.max(100).optional()},lS=A().trim().min(1).max(256).regex(/^[^"\\\r\n]+$/u),uS={repo:oS,identity:A().min(1).optional(),expectedSourceCommit:A().regex(/^[a-f0-9]{40}$/u),expectedConfigDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),runtimeDirectory:A().min(1)},dS=[{name:`issue_comment`,commandName:`comment`,description:`Post a typed issue journal with authoritative comment readback`,inputSchema:F({...b_.shape,repo:oS}).superRefine(({repo:e,...t},n)=>{let r=b_.safeParse(t);if(!r.success)for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message})})},{name:`runtime_stage`,commandName:`runtime:stage`,description:`Explicitly stage a reviewed local public archive without host activation or admission`,inputSchema:F({...uS,authority:L(`runtime:stage`),archivePath:A().min(1),expectedArchiveSha256:A().regex(/^sha256:[a-f0-9]{64}$/u),packageVersion:A().regex(/^\d+\.\d+\.\d+$/u),nativePluginRoot:A().min(1).optional(),resourceBounds:F({maxAggregateRssBytes:j().int().positive().safe(),minFreeDiskBytes:j().int().positive().safe(),maxNewOutputBytes:j().int().positive().safe(),maxCapturedOutputBytes:j().int().positive().safe().max(8*1024**2).optional()}).optional()})},{name:`runtime_admit`,commandName:`runtime:admit`,description:`Explicitly admit an exact completed stage with prior-byte compare-and-swap and reconciliation`,inputSchema:F({...uS,authority:L(`runtime:admit`),stageId:A().regex(/^sha256:[a-f0-9]{64}$/u),expectedPriorAdmissionSha256:A().regex(/^sha256:[a-f0-9]{64}$/u).nullable()})},{name:`issue_create`,commandName:`create`,description:`Create a native GitHub tracking issue with configured metadata and relationships`,inputSchema:F(sS)},{name:`issue_start`,commandName:`start`,description:`Create or resume a tracked issue and its GitHub-linked branch`,inputSchema:F({...sS,body:sS.body.optional(),issueType:sS.issueType.optional(),points:sS.points.optional(),priority:sS.priority.optional(),title:sS.title.optional(),issueNumber:iS.optional(),request:A().min(1).optional(),requestId:A().trim().min(1).max(256).optional(),resumeCreated:M().optional(),branch:A().min(1).optional()})},{name:`issue_list`,commandName:`list`,description:`List repository issues with native filters, named organization fields and pagination`,inputSchema:F({...cS,query:lS.optional()})},{name:`issue_search`,commandName:`search`,description:`Search literal issue text in the selected repository with native filters and pagination`,inputSchema:F({...cS,query:lS})},{name:`issue_update`,commandName:`update`,description:`Update native issue fields and exact relationship sets with readback`,inputSchema:F({repo:oS,blockedBy:N(iS).optional(),body:A().optional(),issueNumber:iS,issueType:A().min(1).optional(),labels:aS.optional(),milestone:iS.nullable().optional(),parentIssueNumber:iS.nullable().optional(),park:L(!0).optional(),points:iS.optional(),priority:A().min(1).optional(),state:I([`open`,`closed`]).optional(),preserveHistory:M().optional(),closeReason:I([`completed`,`not_planned`,`duplicate`]).optional(),supersededBy:iS.optional(),title:A().trim().min(1).max(256).optional()}).refine(e=>e.closeReason===void 0&&e.supersededBy===void 0||e.state===`closed`,`Closure details require state closed`)},{name:`issue_info`,commandName:`info`,description:`Read live issue metadata, relationships and Project status`,inputSchema:F({issueNumber:iS,repo:oS})},{name:`issue_ready_check`,commandName:`ready:check`,description:`Evaluate deterministic readiness from live native issue state`,inputSchema:F({issueNumber:iS,repo:sS.repo})},{name:`issue_pr_create`,commandName:`pr:create`,description:`Create or reuse a PR from its GitHub-linked issue branch`,inputSchema:F({repo:oS,issueNumber:iS,prNumber:iS.optional(),nonClosing:M().optional(),body:A().min(1).optional(),draft:M().optional(),dryRun:M().optional(),title:A().min(1).optional(),headBranch:A().min(1).optional()})},{name:`issue_pr_info`,commandName:`pr:info`,description:`Inspect a PR by number or its GitHub-linked issue branch`,inputSchema:F({repo:oS,issueNumber:iS.optional(),prNumber:iS.optional(),nonClosing:M().optional()})},{name:`issue_pr_review`,commandName:`pr:review`,description:`Submit one existing exact-head independent review with the reviewer App role`,inputSchema:F({repo:oS,issueNumber:iS,prNumber:iS,nonClosing:M().optional(),artifact:A().min(1),identity:A().min(1).optional(),dryRun:M().optional()})},{name:`issue_pr_merge`,commandName:`pr:merge`,description:`Guarded exact-head merge with live blocker, check and review readback`,inputSchema:F({repo:oS,issueNumber:iS,prNumber:iS,nonClosing:M().optional(),reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:I([`merge`,`squash`,`rebase`]).optional(),dryRun:M().optional()})},{name:`issue_finish`,commandName:`finish`,description:`Resume a guarded merge and close its issue after merged-PR readback`,inputSchema:F({repo:oS,issueNumber:iS,prNumber:iS,nonClosing:M().optional(),reviewedHeadSha:A().regex(/^[a-f0-9]{40}$/u).optional(),strategy:I([`merge`,`squash`,`rebase`]).optional(),dryRun:M().optional()})},{name:`issue_worktree_transition_inspect`,commandName:`worktree:transition:inspect`,description:`Read a legacy issue row, original evidence and exact closure gaps without changing ownership`,inputSchema:F({repo:oS,issueNumber:iS,purpose:I([`active-resume`,`merged-cleanup`]),disposition:I([`retain`,`remove`]).optional(),terminalPrNumber:iS.optional(),retainedHoldCommentIds:N(iS).optional(),retainedAdmissionPath:A().min(1).optional(),retainedArchivePath:A().min(1).optional()})},{name:`issue_worktree_transition_apply`,commandName:`worktree:transition:apply`,description:`Apply or resume one exact independently accepted transition with immutable preservation and closure proof`,inputSchema:F({repo:oS,authority:L(`worktree:transition`),planPath:A().min(1),expectedPlanId:A().regex(/^sha256:[a-f0-9]{64}$/u),relinquishmentCommentId:iS,acceptanceCommentId:iS})}];function fS(e){return dS.find(t=>t.name===e)??null}function pS(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw new R(`${t} must be positive.`);return n}function mS(e,t){return typeof e[t]==`string`?e[t]:void 0}function hS(e,t){let n=mS(e,t);if(!n?.trim())throw new R(`${t} is required.`);return n}function gS(e){let{issueNumber:t,request:n,requestId:r,repo:i,resumeCreated:a,branch:o,...s}=e;return{...s,issueNumber:pS({issueNumber:t},`issueNumber`)}}async function _S(e,t,n=`author`){let r=await oh(),i=e.identity??r.roles[n].identity,a=dh({commandName:t,deliveryConfig:r,identity:i,...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth}});if(a.error)throw new R(a.error);return E_({identity:i,repoRoot:e.repoRoot,role:n,...e.repo===void 0?{}:{repository:e.repo},...e.personalAuth===void 0?{}:{personalAuth:e.personalAuth},...e.signal===void 0?{}:{signal:e.signal}})}async function vS(e,t){let n=t.issueNumber===void 0?void 0:pS(t,`issueNumber`),r,i=(i,a)=>({status:`created-not-started`,repository:e.config.repository,createdIssue:r,failure:{phase:i,message:a instanceof Error?a.message:String(a)},safeResume:{tool:`issue_start`,arguments:{...t,repo:e.config.repository,issueNumber:n,resumeCreated:!0}}});if(n===void 0){let a=mS(t,`title`)??hS(t,`request`),o={...t,title:a,body:mS(t,`body`)??mS(t,`request`)??a},s=V(Object.fromEntries(Object.entries({title:a,body:o.body,issueType:o.issueType,points:o.points,priority:o.priority,labels:o.labels,blockedBy:o.blockedBy,parentIssueNumber:o.parentIssueNumber,milestone:o.milestone,branch:t.branch}).filter(([,e])=>e!==void 0))),c=mS(t,`requestId`)??s,l=`<!-- ai-delivery-start: ${V({repository:e.config.repository.toLowerCase(),requestKey:c})} -->`;o.body=`${o.body}\n\n<!-- ai-delivery-start-intent: ${s} -->\n${l}`;let u=!1,d=[];for(let t=1;t<=20;t++){let n=(await e.clients.rest.issues.listForRepo({...e.repo,state:`all`,page:t,per_page:100})).data;if(d.push(...n.filter(e=>!(`pull_request`in e)&&e.body?.includes(l))),n.length<100){u=!0;break}}if(!u)throw new R(`Issue-start retry search exceeds the bounded readback window; select a known issue number.`);if(d.length>1)throw new R(`Conflicting issues claim the same start request.`);let f=d[0];if(f&&(f.title!==a||f.body!==o.body||f.state!==`open`))throw new R(`Prior issue-start request conflicts with the requested intent or state.`);try{f?(r={number:f.number,title:f.title,url:f.html_url},n=f.number,await R_(e,{...o,issueNumber:n})):(r=(await k_(e,o)).created,n=r.number)}catch(e){if(e instanceof O_)r=e.created,n=r.number;else if(!r)throw e;return i(`tracking`,e)}}else if(t.resumeCreated===!0){let a=(await e.clients.rest.issues.get({...e.repo,issue_number:n})).data;if(a.number!==n||`pull_request`in a)throw new R(`Known-created issue readback disagrees.`);r={number:n,title:a.title,url:a.html_url};try{await R_(e,gS(t))}catch(e){return i(`tracking`,e)}}try{let r=await W_(e,n,mS(t,`branch`));return await T_(e,n),{issueNumber:n,repository:e.config.repository,branch:r.branch,headSha:r.headSha,reused:r.reused}}catch(e){if(r)return i(`branch-or-journal`,e);throw e}}async function yS(e,t,n){let r=fS(e);if(!r)throw new R(`Unknown ai-delivery tool ${e}.`);let{repo:i,...a}=r.inputSchema.parse(t);if(e===`issue_finish`&&a.nonClosing===!0)throw new R(`Non-closing delivery cannot finish or close its retained issue.`);if(i!==void 0&&n.repo!==void 0&&i!==n.repo)throw new R(`Tool and execution repository selectors disagree.`);let o=typeof i==`string`?i:n.repo,s={...n,...o===void 0?{}:{repo:o}},c=e===`runtime_stage`||e===`runtime_admit`||e.startsWith(`issue_worktree_transition_`),l=n.repoRoot;if(c){let t=await oh();if(l=Cu({repository:o??(()=>{let e=Su(l,`origin`);return`${e.owner}/${e.repo}`})(),launchDirectory:l,checkoutRoots:t.checkoutRoots}),e===`runtime_stage`||e===`runtime_admit`){let r={...a,repoRoot:l,identity:mS(a,`identity`)??n.identity??t.roles.author.identity,...n.personalAuth===void 0?{}:{personalAuth:n.personalAuth},...n.signal===void 0?{}:{signal:n.signal}};return e===`runtime_stage`?tS(r):rS(r)}}let u=e===`issue_pr_review`?mS(a,`identity`):void 0,d=await _S({...s,...u===void 0?{}:{identity:u}},r.commandName,e===`issue_pr_review`?`reviewer`:`author`);switch(c&&(d.root=l),e){case`issue_comment`:return w_(d,a);case`issue_create`:return k_(d,a);case`issue_start`:return vS(d,a);case`issue_update`:return L_(d,a);case`issue_list`:case`issue_search`:return P_(d,a);case`issue_info`:return z_(d,pS(a,`issueNumber`));case`issue_ready_check`:return V_(d,pS(a,`issueNumber`));case`issue_pr_create`:return Pv(d,{...a.prNumber===void 0?{}:{prNumber:pS(a,`prNumber`)},issueNumber:pS(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},...a.body===void 0?{}:{body:hS(a,`body`)},...a.title===void 0?{}:{title:hS(a,`title`)},...a.headBranch===void 0?{}:{headBranch:hS(a,`headBranch`)},draft:a.draft!==!1,dryRun:a.dryRun===!0});case`issue_pr_info`:return kv(d,a);case`issue_pr_review`:return Fv(d,{artifact:hS(a,`artifact`),issueNumber:pS(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:pS(a,`prNumber`),dryRun:a.dryRun===!0});case`issue_pr_merge`:case`issue_finish`:{let t={issueNumber:pS(a,`issueNumber`),...a.nonClosing===void 0?{}:{nonClosing:a.nonClosing===!0},prNumber:pS(a,`prNumber`),...a.strategy===void 0?{}:{strategy:a.strategy},...a.reviewedHeadSha===void 0?{}:{reviewedHeadSha:hS(a,`reviewedHeadSha`)},dryRun:a.dryRun===!0};return e===`issue_finish`?Rv(d,t):Lv(d,t)}case`issue_worktree_transition_inspect`:return Fx(d,{...a,...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}});case`issue_worktree_transition_apply`:return wx(d,{authority:`worktree:transition`,planPath:hS(a,`planPath`),expectedPlanId:hS(a,`expectedPlanId`),relinquishmentCommentId:pS(a,`relinquishmentCommentId`),acceptanceCommentId:pS(a,`acceptanceCommentId`),...n.runtimeEntryPath===void 0?{}:{runtimeEntryPath:n.runtimeEntryPath}})}}var bS;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(bS||={});var xS;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(xS||={});var W=bS.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),SS=e=>{switch(typeof e){case`undefined`:return W.undefined;case`string`:return W.string;case`number`:return Number.isNaN(e)?W.nan:W.number;case`boolean`:return W.boolean;case`function`:return W.function;case`bigint`:return W.bigint;case`symbol`:return W.symbol;case`object`:return Array.isArray(e)?W.array:e===null?W.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?W.promise:typeof Map<`u`&&e instanceof Map?W.map:typeof Set<`u`&&e instanceof Set?W.set:typeof Date<`u`&&e instanceof Date?W.date:W.object;default:return W.unknown}},G=bS.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),CS=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;if(n===`_errors`){a&&e._errors.push(t(i)),r++;continue}Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,bS.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};CS.create=e=>new CS(e);var wS=(e,t)=>{let n;switch(e.code){case G.invalid_type:n=e.received===W.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case G.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,bS.jsonStringifyReplacer)}`;break;case G.unrecognized_keys:n=`Unrecognized key(s) in object: ${bS.joinValues(e.keys,`, `)}`;break;case G.invalid_union:n=`Invalid input`;break;case G.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${bS.joinValues(e.options)}`;break;case G.invalid_enum_value:n=`Invalid enum value. Expected ${bS.joinValues(e.options)}, received '${e.received}'`;break;case G.invalid_arguments:n=`Invalid function arguments`;break;case G.invalid_return_type:n=`Invalid function return type`;break;case G.invalid_date:n=`Invalid date`;break;case G.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:bS.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case G.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case G.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case G.custom:n=`Invalid input`;break;case G.invalid_intersection_types:n=`Intersection results could not be merged`;break;case G.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case G.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,bS.assertNever(e)}return{message:n}},TS=wS;function ES(){return TS}var DS=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function K(e,t){let n=ES(),r=DS({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===wS?void 0:wS].filter(e=>!!e)});e.common.issues.push(r)}var OS=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return q;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return q;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},q=Object.freeze({status:`aborted`}),kS=e=>({status:`dirty`,value:e}),AS=e=>({status:`valid`,value:e}),jS=e=>e.status===`aborted`,MS=e=>e.status===`dirty`,NS=e=>e.status===`valid`,PS=e=>typeof Promise<`u`&&e instanceof Promise,J;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(J||={});var FS=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},IS=(e,t)=>{if(NS(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new CS(e.common.issues);return this._error=t,this._error}}};function Y(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var LS=class{get description(){return this._def.description}_getType(e){return SS(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:SS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new OS,ctx:{common:e.parent.common,data:e.data,parsedType:SS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(PS(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:SS(e)};return IS(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:SS(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return NS(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>NS(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:SS(e)},r=this._parse({data:e,path:n.path,parent:n});return IS(n,await(PS(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:G.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new BC({schema:this,typeName:X.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return VC.create(this,this._def)}nullable(){return HC.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xC.create(this)}promise(){return zC.create(this,this._def)}or(e){return wC.create([this,e],this._def)}and(e){return OC.create(this,e,this._def)}transform(e){return new BC({...Y(this._def),schema:this,typeName:X.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new UC({...Y(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new KC({typeName:X.ZodBranded,type:this,...Y(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new WC({...Y(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return qC.create(this,e)}readonly(){return JC.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},RS=/^c[^\s-]{8,}$/i,zS=/^[0-9a-z]+$/,BS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,VS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,HS=/^[a-z0-9_-]{21}$/i,US=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,WS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,GS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,KS=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,qS,JS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,YS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,XS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ZS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,QS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$S=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eC=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,tC=RegExp(`^${eC}$`);function nC(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function rC(e){return RegExp(`^${nC(e)}$`)}function iC(e){let t=`${eC}T${nC(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function aC(e,t){return!((t!==`v4`&&t||!JS.test(e))&&(t!==`v6`&&t||!XS.test(e)))}function oC(e,t){if(!US.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function sC(e,t){return!((t!==`v4`&&t||!YS.test(e))&&(t!==`v6`&&t||!ZS.test(e)))}var cC=class e extends LS{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.string,received:t.parsedType}),q}let t=new OS,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?K(n,{code:G.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&K(n,{code:G.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)GS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`email`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)qS||=new RegExp(KS,`u`),qS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`emoji`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)VS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`uuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)HS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`nanoid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)RS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)zS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cuid2`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)BS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ulid`,code:G.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),K(n,{validation:`url`,code:G.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`regex`,code:G.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?iC(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?tC.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?rC(r).test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:G.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?WS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`duration`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?aC(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`ip`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?oC(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`jwt`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?sC(e.data,r.version)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`cidr`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?QS.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64`,code:G.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?$S.test(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{validation:`base64url`,code:G.invalid_string,message:r.message}),t.dirty()):bS.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:G.invalid_string,...J.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...J.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...J.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...J.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...J.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...J.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...J.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...J.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...J.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...J.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...J.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...J.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};cC.create=e=>new cC({checks:[],typeName:X.ZodString,coerce:e?.coerce??!1,...Y(e)});function lC(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var uC=class e extends LS{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==W.number){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.number,received:t.parsedType}),q}let t,n=new OS;for(let r of this._def.checks)r.kind===`int`?bS.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?lC(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_finite,message:r.message}),n.dirty()):bS.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:J.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:J.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:J.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&bS.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};uC.create=e=>new uC({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...Y(e)});var dC=class e extends LS{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==W.bigint)return this._getInvalidInput(e);let t,n=new OS;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),K(t,{code:G.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):bS.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:J.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};dC.create=e=>new dC({checks:[],typeName:X.ZodBigInt,coerce:e?.coerce??!1,...Y(e)});var fC=class extends LS{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.boolean,received:t.parsedType}),q}return AS(e.data)}};fC.create=e=>new fC({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...Y(e)});var pC=class e extends LS{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.date,received:t.parsedType}),q}if(Number.isNaN(e.data.getTime()))return K(this._getOrReturnCtx(e),{code:G.invalid_date}),q;let t=new OS,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),K(n,{code:G.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):bS.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};pC.create=e=>new pC({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...Y(e)});var mC=class extends LS{_parse(e){if(this._getType(e)!==W.symbol){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.symbol,received:t.parsedType}),q}return AS(e.data)}};mC.create=e=>new mC({typeName:X.ZodSymbol,...Y(e)});var hC=class extends LS{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.undefined,received:t.parsedType}),q}return AS(e.data)}};hC.create=e=>new hC({typeName:X.ZodUndefined,...Y(e)});var gC=class extends LS{_parse(e){if(this._getType(e)!==W.null){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.null,received:t.parsedType}),q}return AS(e.data)}};gC.create=e=>new gC({typeName:X.ZodNull,...Y(e)});var _C=class extends LS{constructor(){super(...arguments),this._any=!0}_parse(e){return AS(e.data)}};_C.create=e=>new _C({typeName:X.ZodAny,...Y(e)});var vC=class extends LS{constructor(){super(...arguments),this._unknown=!0}_parse(e){return AS(e.data)}};vC.create=e=>new vC({typeName:X.ZodUnknown,...Y(e)});var yC=class extends LS{_parse(e){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.never,received:t.parsedType}),q}};yC.create=e=>new yC({typeName:X.ZodNever,...Y(e)});var bC=class extends LS{_parse(e){if(this._getType(e)!==W.undefined){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.void,received:t.parsedType}),q}return AS(e.data)}};bC.create=e=>new bC({typeName:X.ZodVoid,...Y(e)});var xC=class e extends LS{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==W.array)return K(t,{code:G.invalid_type,expected:W.array,received:t.parsedType}),q;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(K(t,{code:e?G.too_big:G.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(K(t,{code:G.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(K(t,{code:G.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new FS(t,e,t.path,n)))).then(e=>OS.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new FS(t,e,t.path,n)));return OS.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:J.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:J.toString(n)}})}nonempty(e){return this.min(1,e)}};xC.create=(e,t)=>new xC({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...Y(t)});function SC(e){if(e instanceof CC){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=VC.create(SC(r))}return new CC({...e._def,shape:()=>t})}return e instanceof xC?new xC({...e._def,type:SC(e.element)}):e instanceof VC?VC.create(SC(e.unwrap())):e instanceof HC?HC.create(SC(e.unwrap())):e instanceof kC?kC.create(e.items.map(e=>SC(e))):e}var CC=class e extends LS{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=bS.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==W.object){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof yC&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new FS(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof yC){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(K(n,{code:G.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new FS(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>OS.mergeObjectSync(t,e)):OS.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return J.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:J.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of bS.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of bS.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return SC(this)}partial(t){let n={};for(let e of bS.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of bS.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof VC;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return IC(bS.objectKeys(this.shape))}};CC.create=(e,t)=>new CC({shape:()=>e,unknownKeys:`strip`,catchall:yC.create(),typeName:X.ZodObject,...Y(t)}),CC.strictCreate=(e,t)=>new CC({shape:()=>e,unknownKeys:`strict`,catchall:yC.create(),typeName:X.ZodObject,...Y(t)}),CC.lazycreate=(e,t)=>new CC({shape:e,unknownKeys:`strip`,catchall:yC.create(),typeName:X.ZodObject,...Y(t)});var wC=class extends LS{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new CS(e.ctx.common.issues));return K(t,{code:G.invalid_union,unionErrors:n}),q}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new CS(e));return K(t,{code:G.invalid_union,unionErrors:i}),q}}get options(){return this._def.options}};wC.create=(e,t)=>new wC({options:e,typeName:X.ZodUnion,...Y(t)});var TC=e=>e instanceof PC?TC(e.schema):e instanceof BC?TC(e.innerType()):e instanceof FC?[e.value]:e instanceof LC?e.options:e instanceof RC?bS.objectValues(e.enum):e instanceof UC?TC(e._def.innerType):e instanceof hC?[void 0]:e instanceof gC?[null]:e instanceof VC?[void 0,...TC(e.unwrap())]:e instanceof HC?[null,...TC(e.unwrap())]:e instanceof KC||e instanceof JC?TC(e.unwrap()):e instanceof WC?TC(e._def.innerType):[],EC=class e extends LS{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.object)return K(t,{code:G.invalid_type,expected:W.object,received:t.parsedType}),q;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(K(t,{code:G.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=TC(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Y(r)})}};function DC(e,t){let n=SS(e),r=SS(t);if(e===t)return{valid:!0,data:e};if(n===W.object&&r===W.object){let n=bS.objectKeys(t),r=bS.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=DC(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===W.array&&r===W.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=DC(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===W.date&&r===W.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var OC=class extends LS{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(jS(e)||jS(r))return q;let i=DC(e.value,r.value);return i.valid?((MS(e)||MS(r))&&t.dirty(),{status:t.value,value:i.data}):(K(n,{code:G.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};OC.create=(e,t,n)=>new OC({left:e,right:t,typeName:X.ZodIntersection,...Y(n)});var kC=class e extends LS{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.array)return K(n,{code:G.invalid_type,expected:W.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return K(n,{code:G.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),q;!this._def.rest&&n.data.length>this._def.items.length&&(K(n,{code:G.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new FS(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>OS.mergeArray(t,e)):OS.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};kC.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new kC({items:e,typeName:X.ZodTuple,rest:null,...Y(t)})};var AC=class e extends LS{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.object)return K(n,{code:G.invalid_type,expected:W.object,received:n.parsedType}),q;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new FS(n,e,n.path,e)),value:a._parse(new FS(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?OS.mergeObjectAsync(t,r):OS.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof LS?new e({keyType:t,valueType:n,typeName:X.ZodRecord,...Y(r)}):new e({keyType:cC.create(),valueType:t,typeName:X.ZodRecord,...Y(n)})}},jC=class extends LS{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.map)return K(n,{code:G.invalid_type,expected:W.map,received:n.parsedType}),q;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new FS(n,e,n.path,[a,`key`])),value:i._parse(new FS(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};jC.create=(e,t,n)=>new jC({valueType:t,keyType:e,typeName:X.ZodMap,...Y(n)});var MC=class e extends LS{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==W.set)return K(n,{code:G.invalid_type,expected:W.set,received:n.parsedType}),q;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(K(n,{code:G.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(K(n,{code:G.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return q;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new FS(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:J.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:J.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};MC.create=(e,t)=>new MC({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...Y(t)});var NC=class e extends LS{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==W.function)return K(t,{code:G.invalid_type,expected:W.function,received:t.parsedType}),q;function n(e,n){return DS({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ES(),wS].filter(e=>!!e),issueData:{code:G.invalid_arguments,argumentsError:n}})}function r(e,n){return DS({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ES(),wS].filter(e=>!!e),issueData:{code:G.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof zC){let e=this;return AS(async function(...t){let o=new CS([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return AS(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new CS([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new CS([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:kC.create(t).rest(vC.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||kC.create([]).rest(vC.create()),returns:n||vC.create(),typeName:X.ZodFunction,...Y(r)})}},PC=class extends LS{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};PC.create=(e,t)=>new PC({getter:e,typeName:X.ZodLazy,...Y(t)});var FC=class extends LS{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return K(t,{received:t.data,code:G.invalid_literal,expected:this._def.value}),q}return{status:`valid`,value:e.data}}get value(){return this._def.value}};FC.create=(e,t)=>new FC({value:e,typeName:X.ZodLiteral,...Y(t)});function IC(e,t){return new LC({values:e,typeName:X.ZodEnum,...Y(t)})}var LC=class e extends LS{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{expected:bS.joinValues(n),received:t.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{received:t.data,code:G.invalid_enum_value,options:n}),q}return AS(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};LC.create=IC;var RC=class extends LS{_parse(e){let t=bS.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==W.string&&n.parsedType!==W.number){let e=bS.objectValues(t);return K(n,{expected:bS.joinValues(e),received:n.parsedType,code:G.invalid_type}),q}if(this._cache||=new Set(bS.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=bS.objectValues(t);return K(n,{received:n.data,code:G.invalid_enum_value,options:e}),q}return AS(e.data)}get enum(){return this._def.values}};RC.create=(e,t)=>new RC({values:e,typeName:X.ZodNativeEnum,...Y(t)});var zC=class extends LS{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==W.promise&&t.common.async===!1?(K(t,{code:G.invalid_type,expected:W.promise,received:t.parsedType}),q):AS((t.parsedType===W.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};zC.create=(e,t)=>new zC({type:e,typeName:X.ZodPromise,...Y(t)});var BC=class extends LS{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{K(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return q;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?kS(r.value):r});{if(t.value===`aborted`)return q;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?kS(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?q:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?q:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!NS(e))return q;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>NS(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):q)}bS.assertNever(r)}};BC.create=(e,t,n)=>new BC({schema:e,typeName:X.ZodEffects,effect:t,...Y(n)}),BC.createWithPreprocess=(e,t,n)=>new BC({schema:t,effect:{type:`preprocess`,transform:e},typeName:X.ZodEffects,...Y(n)});var VC=class extends LS{_parse(e){return this._getType(e)===W.undefined?AS(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};VC.create=(e,t)=>new VC({innerType:e,typeName:X.ZodOptional,...Y(t)});var HC=class extends LS{_parse(e){return this._getType(e)===W.null?AS(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};HC.create=(e,t)=>new HC({innerType:e,typeName:X.ZodNullable,...Y(t)});var UC=class extends LS{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===W.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};UC.create=(e,t)=>new UC({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...Y(t)});var WC=class extends LS{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return PS(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new CS(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new CS(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};WC.create=(e,t)=>new WC({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...Y(t)});var GC=class extends LS{_parse(e){if(this._getType(e)!==W.nan){let t=this._getOrReturnCtx(e);return K(t,{code:G.invalid_type,expected:W.nan,received:t.parsedType}),q}return{status:`valid`,value:e.data}}};GC.create=e=>new GC({typeName:X.ZodNaN,...Y(e)});var KC=class extends LS{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},qC=class e extends LS{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),kS(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:X.ZodPipeline})}},JC=class extends LS{_parse(e){let t=this._def.innerType._parse(e),n=e=>(NS(e)&&(e.value=Object.freeze(e.value)),e);return PS(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};JC.create=(e,t)=>new JC({innerType:e,typeName:X.ZodReadonly,...Y(t)}),CC.lazycreate;var X;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(X||={}),cC.create,uC.create,GC.create,dC.create,fC.create,pC.create,mC.create,hC.create,gC.create,_C.create,vC.create,yC.create,bC.create,xC.create;var YC=CC.create;CC.strictCreate,wC.create,EC.create,OC.create,kC.create,AC.create,jC.create,MC.create,NC.create,PC.create,FC.create,LC.create,RC.create,zC.create,BC.create,VC.create,HC.create,BC.createWithPreprocess,qC.create;var XC=k(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Wr.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){Ut(this,`with`,e)},parse(e,t){return Cn(this,e,t,{callee:this.parse})},parseAsync(e,t){return Tn(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Dn(this,e,t)},safeParseAsync(e,t){return An(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return _t(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),ZC=k(`ZodMiniObject`,(e,t)=>{Ki.init(e,t),XC.init(e,t),Qt(e,`shape`,e=>e._zod.def.shape,!1)});function QC(e,t){return new ZC({type:`object`,shape:e??{},...O(t)})}function $C(e){return!!e._zod}function ew(e){let t=Object.values(e);if(t.length===0)return QC({});let n=t.every($C),r=t.every(e=>!$C(e));if(n)return QC(e);if(r)return YC(e);throw Error(`Mixed Zod versions detected in object shape.`)}function tw(e,t){return $C(e)?Dn(e,t):e.safeParse(t)}async function nw(e,t){return $C(e)?await An(e,t):await e.safeParseAsync(t)}function rw(e){if(!e)return;let t;if(t=$C(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function iw(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return ew(e)}}if($C(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function aw(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function ow(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${aw(e.path)}`:e.message).join(`
|
|
262
|
+
`);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function sw(e){return e.description}function cw(e){if($C(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function lw(e){if($C(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}var uw=`2025-11-25`,dw=[uw,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],fw=`io.modelcontextprotocol/related-task`,pw=uu(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),mw=jl([A(),j().int()]),hw=A();kl({ttl:j().optional(),pollInterval:j().optional()});var gw=P({ttl:j().optional()}),_w=P({taskId:A()}),vw=kl({progressToken:mw.optional(),[fw]:_w.optional()}),yw=P({_meta:vw.optional()}),bw=yw.extend({task:gw.optional()}),xw=e=>bw.safeParse(e).success,Sw=P({method:A(),params:yw.loose().optional()}),Cw=P({_meta:vw.optional()}),ww=P({method:A(),params:Cw.loose().optional()}),Tw=kl({_meta:vw.optional()}),Ew=jl([A(),j().int()]),Dw=P({jsonrpc:L(`2.0`),id:Ew,...Sw.shape}).strict(),Ow=e=>Dw.safeParse(e).success,kw=P({jsonrpc:L(`2.0`),...ww.shape}).strict(),Aw=e=>kw.safeParse(e).success,jw=P({jsonrpc:L(`2.0`),id:Ew,result:Tw}).strict(),Mw=e=>jw.safeParse(e).success,Z;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Z||={});var Nw=P({jsonrpc:L(`2.0`),id:Ew.optional(),error:P({code:j().int(),message:A(),data:wl().optional()})}).strict(),Pw=e=>Nw.safeParse(e).success,Fw=jl([Dw,kw,jw,Nw]);jl([jw,Nw]);var Iw=Tw.strict(),Lw=Cw.extend({requestId:Ew.optional(),reason:A().optional()}),Rw=ww.extend({method:L(`notifications/cancelled`),params:Lw}),zw=P({icons:N(P({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:I([`light`,`dark`]).optional()})).optional()}),Bw=P({name:A(),title:A().optional()}),Vw=Bw.extend({...Bw.shape,...zw.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),Hw=pu(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Fl(P({form:Fl(P({applyDefaults:M().optional()}),zl(A(),wl())).optional(),url:pw.optional()}),zl(A(),wl()).optional())),Uw=kl({list:pw.optional(),cancel:pw.optional(),requests:kl({sampling:kl({createMessage:pw.optional()}).optional(),elicitation:kl({create:pw.optional()}).optional()}).optional()}),Ww=kl({list:pw.optional(),cancel:pw.optional(),requests:kl({tools:kl({call:pw.optional()}).optional()}).optional()}),Gw=P({experimental:zl(A(),pw).optional(),sampling:P({context:pw.optional(),tools:pw.optional()}).optional(),elicitation:Hw.optional(),roots:P({listChanged:M().optional()}).optional(),tasks:Uw.optional(),extensions:zl(A(),pw).optional()}),Kw=yw.extend({protocolVersion:A(),capabilities:Gw,clientInfo:Vw}),qw=Sw.extend({method:L(`initialize`),params:Kw}),Jw=P({experimental:zl(A(),pw).optional(),logging:pw.optional(),completions:pw.optional(),prompts:P({listChanged:M().optional()}).optional(),resources:P({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:P({listChanged:M().optional()}).optional(),tasks:Ww.optional(),extensions:zl(A(),pw).optional()}),Yw=Tw.extend({protocolVersion:A(),capabilities:Jw,serverInfo:Vw,instructions:A().optional()}),Xw=ww.extend({method:L(`notifications/initialized`),params:Cw.optional()}),Zw=Sw.extend({method:L(`ping`),params:yw.optional()}),Qw=P({progress:j(),total:Gl(j()),message:Gl(A())}),$w=P({...Cw.shape,...Qw.shape,progressToken:mw}),eT=ww.extend({method:L(`notifications/progress`),params:$w}),tT=yw.extend({cursor:hw.optional()}),nT=Sw.extend({params:tT.optional()}),rT=Tw.extend({nextCursor:hw.optional()}),iT=I([`working`,`input_required`,`completed`,`failed`,`cancelled`]),aT=P({taskId:A(),status:iT,ttl:jl([j(),Sl()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Gl(j()),statusMessage:Gl(A())}),oT=Tw.extend({task:aT}),sT=Cw.merge(aT),cT=ww.extend({method:L(`notifications/tasks/status`),params:sT}),lT=Sw.extend({method:L(`tasks/get`),params:yw.extend({taskId:A()})}),uT=Tw.merge(aT),dT=Sw.extend({method:L(`tasks/result`),params:yw.extend({taskId:A()})});Tw.loose();var fT=nT.extend({method:L(`tasks/list`)}),pT=rT.extend({tasks:N(aT)}),mT=Sw.extend({method:L(`tasks/cancel`),params:yw.extend({taskId:A()})}),hT=Tw.merge(aT),gT=P({uri:A(),mimeType:Gl(A()),_meta:zl(A(),wl()).optional()}),_T=gT.extend({text:A()}),vT=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),yT=gT.extend({blob:vT}),bT=I([`user`,`assistant`]),xT=P({audience:N(bT).optional(),priority:j().min(0).max(1).optional(),lastModified:mu({offset:!0}).optional()}),ST=P({...Bw.shape,...zw.shape,uri:A(),description:Gl(A()),mimeType:Gl(A()),size:Gl(j()),annotations:xT.optional(),_meta:Gl(kl({}))}),CT=P({...Bw.shape,...zw.shape,uriTemplate:A(),description:Gl(A()),mimeType:Gl(A()),annotations:xT.optional(),_meta:Gl(kl({}))}),wT=nT.extend({method:L(`resources/list`)}),TT=rT.extend({resources:N(ST)}),ET=nT.extend({method:L(`resources/templates/list`)}),DT=rT.extend({resourceTemplates:N(CT)}),OT=yw.extend({uri:A()}),kT=OT,AT=Sw.extend({method:L(`resources/read`),params:kT}),jT=Tw.extend({contents:N(jl([_T,yT]))}),MT=ww.extend({method:L(`notifications/resources/list_changed`),params:Cw.optional()}),NT=OT,PT=Sw.extend({method:L(`resources/subscribe`),params:NT}),FT=OT,IT=Sw.extend({method:L(`resources/unsubscribe`),params:FT}),LT=Cw.extend({uri:A()}),RT=ww.extend({method:L(`notifications/resources/updated`),params:LT}),zT=P({name:A(),description:Gl(A()),required:Gl(M())}),BT=P({...Bw.shape,...zw.shape,description:Gl(A()),arguments:Gl(N(zT)),_meta:Gl(kl({}))}),VT=nT.extend({method:L(`prompts/list`)}),HT=rT.extend({prompts:N(BT)}),UT=yw.extend({name:A(),arguments:zl(A(),A()).optional()}),WT=Sw.extend({method:L(`prompts/get`),params:UT}),GT=P({type:L(`text`),text:A(),annotations:xT.optional(),_meta:zl(A(),wl()).optional()}),KT=P({type:L(`image`),data:vT,mimeType:A(),annotations:xT.optional(),_meta:zl(A(),wl()).optional()}),qT=P({type:L(`audio`),data:vT,mimeType:A(),annotations:xT.optional(),_meta:zl(A(),wl()).optional()}),JT=P({type:L(`tool_use`),name:A(),id:A(),input:zl(A(),wl()),_meta:zl(A(),wl()).optional()}),YT=P({type:L(`resource`),resource:jl([_T,yT]),annotations:xT.optional(),_meta:zl(A(),wl()).optional()}),XT=jl([GT,KT,qT,ST.extend({type:L(`resource_link`)}),YT]),ZT=P({role:bT,content:XT}),QT=Tw.extend({description:A().optional(),messages:N(ZT)}),$T=ww.extend({method:L(`notifications/prompts/list_changed`),params:Cw.optional()}),eE=P({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),tE=P({taskSupport:I([`required`,`optional`,`forbidden`]).optional()}),nE=P({...Bw.shape,...zw.shape,description:A().optional(),inputSchema:P({type:L(`object`),properties:zl(A(),pw).optional(),required:N(A()).optional()}).catchall(wl()),outputSchema:P({type:L(`object`),properties:zl(A(),pw).optional(),required:N(A()).optional()}).catchall(wl()).optional(),annotations:eE.optional(),execution:tE.optional(),_meta:zl(A(),wl()).optional()}),rE=nT.extend({method:L(`tools/list`)}),iE=rT.extend({tools:N(nE)}),aE=Tw.extend({content:N(XT).default([]),structuredContent:zl(A(),wl()).optional(),isError:M().optional()});aE.or(Tw.extend({toolResult:wl()}));var oE=bw.extend({name:A(),arguments:zl(A(),wl()).optional()}),sE=Sw.extend({method:L(`tools/call`),params:oE}),cE=ww.extend({method:L(`notifications/tools/list_changed`),params:Cw.optional()}),lE=P({autoRefresh:M().default(!0),debounceMs:j().int().nonnegative().default(300)}),uE=I([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),dE=yw.extend({level:uE}),fE=Sw.extend({method:L(`logging/setLevel`),params:dE}),pE=Cw.extend({level:uE,logger:A().optional(),data:wl()}),mE=ww.extend({method:L(`notifications/message`),params:pE}),hE=P({hints:N(P({name:A().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),gE=P({mode:I([`auto`,`required`,`none`]).optional()}),_E=P({type:L(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(XT).default([]),structuredContent:P({}).loose().optional(),isError:M().optional(),_meta:zl(A(),wl()).optional()}),vE=Nl(`type`,[GT,KT,qT]),yE=Nl(`type`,[GT,KT,qT,JT,_E]),bE=P({role:bT,content:jl([yE,N(yE)]),_meta:zl(A(),wl()).optional()}),xE=bw.extend({messages:N(bE),modelPreferences:hE.optional(),systemPrompt:A().optional(),includeContext:I([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:N(A()).optional(),metadata:pw.optional(),tools:N(nE).optional(),toolChoice:gE.optional()}),SE=Sw.extend({method:L(`sampling/createMessage`),params:xE}),CE=Tw.extend({model:A(),stopReason:Gl(I([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:bT,content:vE}),wE=Tw.extend({model:A(),stopReason:Gl(I([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:bT,content:jl([yE,N(yE)])}),TE=P({type:L(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),EE=P({type:L(`string`),title:A().optional(),description:A().optional(),minLength:j().optional(),maxLength:j().optional(),format:I([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),DE=P({type:I([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),OE=P({type:L(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),kE=P({type:L(`string`),title:A().optional(),description:A().optional(),oneOf:N(P({const:A(),title:A()})),default:A().optional()}),AE=jl([jl([P({type:L(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),jl([OE,kE]),jl([P({type:L(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:P({type:L(`string`),enum:N(A())}),default:N(A()).optional()}),P({type:L(`array`),title:A().optional(),description:A().optional(),minItems:j().optional(),maxItems:j().optional(),items:P({anyOf:N(P({const:A(),title:A()}))}),default:N(A()).optional()})])]),TE,EE,DE]),jE=jl([bw.extend({mode:L(`form`).optional(),message:A(),requestedSchema:P({type:L(`object`),properties:zl(A(),AE),required:N(A()).optional()})}),bw.extend({mode:L(`url`),message:A(),elicitationId:A(),url:A().url()})]),ME=Sw.extend({method:L(`elicitation/create`),params:jE}),NE=Cw.extend({elicitationId:A()}),PE=ww.extend({method:L(`notifications/elicitation/complete`),params:NE}),FE=Tw.extend({action:I([`accept`,`decline`,`cancel`]),content:pu(e=>e===null?void 0:e,zl(A(),jl([A(),j(),M(),N(A())])).optional())}),IE=P({type:L(`ref/resource`),uri:A()}),LE=P({type:L(`ref/prompt`),name:A()}),RE=yw.extend({ref:jl([LE,IE]),argument:P({name:A(),value:A()}),context:P({arguments:zl(A(),A()).optional()}).optional()}),zE=Sw.extend({method:L(`completion/complete`),params:RE});function BE(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function VE(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var HE=Tw.extend({completion:kl({values:N(A()).max(100),total:Gl(j().int()),hasMore:Gl(M())})}),UE=P({uri:A().startsWith(`file://`),name:A().optional(),_meta:zl(A(),wl()).optional()}),WE=Sw.extend({method:L(`roots/list`),params:yw.optional()}),GE=Tw.extend({roots:N(UE)}),KE=ww.extend({method:L(`notifications/roots/list_changed`),params:Cw.optional()});jl([Zw,qw,zE,fE,WT,VT,wT,ET,AT,PT,IT,sE,rE,lT,dT,fT,mT]),jl([Rw,eT,Xw,KE,cT]),jl([Iw,CE,wE,FE,GE,uT,pT,oT]),jl([Zw,SE,ME,WE,lT,dT,fT,mT]),jl([Rw,eT,mE,RT,MT,cE,$T,cT,PE]),jl([Iw,Yw,HE,QT,HT,TT,DT,jT,aE,iE,uT,pT,oT]);var Q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new qE(e.elicitations,n)}return new e(t,n,r)}},qE=class extends Q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function JE(e){return e===`completed`||e===`failed`||e===`cancelled`}var YE=Symbol(`Let zodToJsonSchema decide on which parser to use`),XE={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},ZE=e=>typeof e==`string`?{...XE,name:e}:{...XE,...e},QE=e=>{let t=ZE(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function $E(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function eD(e,t,n,r,i){e[t]=n,$E(e,t,r,i)}var tD=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function nD(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?tD(t,e.currentPath):t.join(`/`)}}function rD(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==X.ZodAny&&(n.items=qD(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&eD(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&eD(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(eD(n,`minItems`,e.exactLength.value,e.exactLength.message,t),eD(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function iD(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?eD(n,`minimum`,r.value,r.message,t):eD(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),eD(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?eD(n,`maximum`,r.value,r.message,t):eD(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),eD(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:eD(n,`multipleOf`,r.value,r.message,t)}return n}function aD(){return{type:`boolean`}}function oD(e,t){return qD(e.type._def,t)}var sD=(e,t)=>qD(e.innerType._def,t);function cD(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>cD(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return lD(e,t)}}var lD=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:eD(n,`minimum`,r.value,r.message,t);break;case`max`:eD(n,`maximum`,r.value,r.message,t)}return n};function uD(e,t){return{...qD(e.innerType._def,t),default:e.defaultValue()}}function dD(e,t){return t.effectStrategy===`input`?qD(e.schema._def,t):nD(t)}function fD(e){return{type:`string`,enum:Array.from(e.values)}}var pD=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function mD(e,t){let n=[qD(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),qD(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(pD(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function hD(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var gD=void 0,_D={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(gD===void 0&&(gD=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),gD),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function vD(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:eD(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:eD(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:SD(n,`email`,r.message,t);break;case`format:idn-email`:SD(n,`idn-email`,r.message,t);break;case`pattern:zod`:CD(n,_D.email,r.message,t)}break;case`url`:SD(n,`uri`,r.message,t);break;case`uuid`:SD(n,`uuid`,r.message,t);break;case`regex`:CD(n,r.regex,r.message,t);break;case`cuid`:CD(n,_D.cuid,r.message,t);break;case`cuid2`:CD(n,_D.cuid2,r.message,t);break;case`startsWith`:CD(n,RegExp(`^${yD(r.value,t)}`),r.message,t);break;case`endsWith`:CD(n,RegExp(`${yD(r.value,t)}$`),r.message,t);break;case`datetime`:SD(n,`date-time`,r.message,t);break;case`date`:SD(n,`date`,r.message,t);break;case`time`:SD(n,`time`,r.message,t);break;case`duration`:SD(n,`duration`,r.message,t);break;case`length`:eD(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),eD(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:CD(n,RegExp(yD(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&SD(n,`ipv4`,r.message,t),r.version!==`v4`&&SD(n,`ipv6`,r.message,t);break;case`base64url`:CD(n,_D.base64url,r.message,t);break;case`jwt`:CD(n,_D.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&CD(n,_D.ipv4Cidr,r.message,t),r.version!==`v4`&&CD(n,_D.ipv6Cidr,r.message,t);break;case`emoji`:CD(n,_D.emoji(),r.message,t);break;case`ulid`:CD(n,_D.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:SD(n,`binary`,r.message,t);break;case`contentEncoding:base64`:eD(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:CD(n,_D.base64,r.message,t)}break;case`nanoid`:CD(n,_D.nanoid,r.message,t)}return n}function yD(e,t){return t.patternStrategy===`escape`?xD(e):e}var bD=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function xD(e){let t=``;for(let n=0;n<e.length;n++)bD.has(e[n])||(t+=`\\`),t+=e[n];return t}function SD(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):eD(e,`format`,t,n,r)}function CD(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:wD(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):eD(e,`pattern`,wD(t,r),n,r)}function wD(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
263
263
|
]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
|
|
264
|
-
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function dD(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===X.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:ND(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??HE(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:ND(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===X.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=iD(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===X.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===X.ZodBranded&&e.keyType._def.type._def.typeName===X.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=KE(e.keyType._def,t);return{...n,propertyNames:i}}return n}function fD(e,t){return t.mapStrategy===`record`?dD(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[ND(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||HE(t),ND(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||HE(t)],minItems:2,maxItems:2}}}function pD(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function mD(e){return e.target===`openAi`?void 0:{not:HE({...e,currentPath:[...e.currentPath,`not`]})}}function hD(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var gD={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function _D(e,t){if(t.target===`openApi3`)return vD(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in gD&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=gD[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return vD(e,t)}var vD=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>ND(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function yD(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:gD[e.innerType._def.typeName],nullable:!0}:{type:[gD[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=ND(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=ND(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function bD(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,zE(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?BE(n,`minimum`,r.value,r.message,t):BE(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),BE(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?BE(n,`maximum`,r.value,r.message,t):BE(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),BE(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:BE(n,`multipleOf`,r.value,r.message,t)}return n}function xD(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=CD(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=ND(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=SD(e,t);return o!==void 0&&(r.additionalProperties=o),r}function SD(e,t){if(e.catchall._def.typeName!==`ZodNever`)return ND(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function CD(e){try{return e.isOptional()}catch{return!0}}var wD=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ND(e.innerType._def,t);let n=ND(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:HE(t)},n]}:HE(t)},TD=(e,t)=>{if(t.pipeStrategy===`input`)return ND(e.in._def,t);if(t.pipeStrategy===`output`)return ND(e.out._def,t);let n=ND(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,ND(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function ED(e,t){return ND(e.type._def,t)}function DD(e,t){let n={type:`array`,uniqueItems:!0,items:ND(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&BE(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&BE(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function OD(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>ND(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:ND(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>ND(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function kD(e){return{not:HE(e)}}function AD(e){return HE(e)}var jD=(e,t)=>ND(e.innerType._def,t),MD=(e,t,n)=>{switch(t){case X.ZodString:return iD(e,n);case X.ZodNumber:return bD(e,n);case X.ZodObject:return xD(e,n);case X.ZodBigInt:return WE(e,n);case X.ZodBoolean:return GE();case X.ZodDate:return JE(e,n);case X.ZodUndefined:return kD(n);case X.ZodNull:return hD(n);case X.ZodArray:return UE(e,n);case X.ZodUnion:case X.ZodDiscriminatedUnion:return _D(e,n);case X.ZodIntersection:return eD(e,n);case X.ZodTuple:return OD(e,n);case X.ZodRecord:return dD(e,n);case X.ZodLiteral:return tD(e,n);case X.ZodEnum:return QE(e);case X.ZodNativeEnum:return pD(e);case X.ZodNullable:return yD(e,n);case X.ZodOptional:return wD(e,n);case X.ZodMap:return fD(e,n);case X.ZodSet:return DD(e,n);case X.ZodLazy:return()=>e.getter()._def;case X.ZodPromise:return ED(e,n);case X.ZodNaN:case X.ZodNever:return mD(n);case X.ZodEffects:return ZE(e,n);case X.ZodAny:return HE(n);case X.ZodUnknown:return AD(n);case X.ZodDefault:return XE(e,n);case X.ZodBranded:return KE(e,n);case X.ZodReadonly:return jD(e,n);case X.ZodCatch:return qE(e,n);case X.ZodPipeline:return TD(e,n);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(e=>void 0)(t)}};function ND(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==FE)return i}if(r&&!n){let e=PD(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=MD(e,e.typeName,t),o=typeof a==`function`?ND(a(),t):a;if(o&&FD(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var PD=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:VE(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),HE(t)):t.$refStrategy===`seen`?HE(t):void 0}},FD=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),ID=(e,t)=>{let n=RE(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:ND(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??HE(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=ND(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??HE(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function LD(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function RD(e,t){return zC(e)?wc(e,{target:LD(t?.target),io:t?.pipeStrategy??`input`}):ID(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function zD(e){let t=UC(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=YC(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function BD(e,t){let n=VC(e,t);if(!n.success)throw n.error;return n.data}var VD=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ww,e=>{this._oncancel(e)}),this.setNotificationHandler(Bw,e=>{this._onprogress(e)}),this.setRequestHandler(Lw,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Yw,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Zw,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Q(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Q(Z.InvalidParams,`Task not found: ${r}`);if(!PE(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(PE(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[QC]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Qw,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Q(Z.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(eT,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Task not found: ${e.params.taskId}`);if(PE(n.status))throw new Q(Z.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Q(Z.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Q?e:new Q(Z.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Q.fromError(Z.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),vw(e)||bw(e)?this._onresponse(e):mw(e)?this._onrequest(e,t):gw(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Q.fromError(Z.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[QC]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Z.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=sw(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new Q(Z.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Z.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),vw(e)?n(e):n(new Q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(vw(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),vw(e)?r(e):r(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Kw,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Q(Z.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},PE(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[QC]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Q?e:new Q(Z.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=VC(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Q.fromError(Z.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Xw,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},$w,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},tT,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[QC]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[QC]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[QC]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=zD(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=BD(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=zD(e);this._notificationHandlers.set(n,n=>{let r=BD(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&mw(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Q(Z.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new Q(Z.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new Q(Z.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Jw.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),PE(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Q(Z.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(PE(a.status))throw new Q(Z.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Jw.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),PE(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function HD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function UD(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=HD(a)&&HD(i)?{...a,...i}:i}return n}var WD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),GD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=WD(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),$=D((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;var t=WD(),n=GD(),r=WD();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=GD();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=E(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=E(this.rhs,e,n),this}get names(){return ne(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=E(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(re(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>te(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ie(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=E(this.condition,e,t),this}get names(){let e=super.names;return ne(e,this.condition),this.else&&te(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=E(this.iteration,e,t),this}get names(){return te(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return ne(ne(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=E(this.iterable,e,t),this}get names(){return te(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&te(e,this.catch.names),this.finally&&te(e,this.finally.names),e}},ee=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ee.kind=`catch`;var T=class extends m{render(e){return`finally`+super.render(e)}};T.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
265
|
-
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ee(e),t(e)}return n&&(this._currNode=r.finally=new T,this.code(n)),this._endBlockNode(ee,T)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function te(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ne(e,n){return n instanceof t._CodeOrName?te(e,n.names):e}function E(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function re(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ie(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ue(e)}`}e.not=ie;var ae=le(e.operators.AND);function oe(...e){return e.reduce(ae)}e.and=oe;var se=le(e.operators.OR);function ce(...e){return e.reduce(se)}e.or=ce;function le(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ue(n)} ${e} ${ue(r)}`}function ue(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),KD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=$(),n=WD();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;var _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),qD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),JD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=$(),n=KD(),r=qD();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}var u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),YD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=JD(),n=$(),r=qD(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),XD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),ZD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),QD=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=XD(),n=ZD(),r=JD(),i=$(),a=KD(),o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;var u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
264
|
+
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function TD(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===X.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:qD(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??nD(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:qD(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===X.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=vD(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===X.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===X.ZodBranded&&e.keyType._def.type._def.typeName===X.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=oD(e.keyType._def,t);return{...n,propertyNames:i}}return n}function ED(e,t){return t.mapStrategy===`record`?TD(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[qD(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||nD(t),qD(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||nD(t)],minItems:2,maxItems:2}}}function DD(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function OD(e){return e.target===`openAi`?void 0:{not:nD({...e,currentPath:[...e.currentPath,`not`]})}}function kD(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var AD={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function jD(e,t){if(t.target===`openApi3`)return MD(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in AD&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=AD[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return MD(e,t)}var MD=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>qD(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function ND(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:AD[e.innerType._def.typeName],nullable:!0}:{type:[AD[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=qD(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=qD(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function PD(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,$E(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?eD(n,`minimum`,r.value,r.message,t):eD(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),eD(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?eD(n,`maximum`,r.value,r.message,t):eD(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),eD(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:eD(n,`multipleOf`,r.value,r.message,t)}return n}function FD(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=LD(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=qD(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=ID(e,t);return o!==void 0&&(r.additionalProperties=o),r}function ID(e,t){if(e.catchall._def.typeName!==`ZodNever`)return qD(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function LD(e){try{return e.isOptional()}catch{return!0}}var RD=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return qD(e.innerType._def,t);let n=qD(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:nD(t)},n]}:nD(t)},zD=(e,t)=>{if(t.pipeStrategy===`input`)return qD(e.in._def,t);if(t.pipeStrategy===`output`)return qD(e.out._def,t);let n=qD(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,qD(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function BD(e,t){return qD(e.type._def,t)}function VD(e,t){let n={type:`array`,uniqueItems:!0,items:qD(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&eD(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&eD(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function HD(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>qD(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:qD(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>qD(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function UD(e){return{not:nD(e)}}function WD(e){return nD(e)}var GD=(e,t)=>qD(e.innerType._def,t),KD=(e,t,n)=>{switch(t){case X.ZodString:return vD(e,n);case X.ZodNumber:return PD(e,n);case X.ZodObject:return FD(e,n);case X.ZodBigInt:return iD(e,n);case X.ZodBoolean:return aD();case X.ZodDate:return cD(e,n);case X.ZodUndefined:return UD(n);case X.ZodNull:return kD(n);case X.ZodArray:return rD(e,n);case X.ZodUnion:case X.ZodDiscriminatedUnion:return jD(e,n);case X.ZodIntersection:return mD(e,n);case X.ZodTuple:return HD(e,n);case X.ZodRecord:return TD(e,n);case X.ZodLiteral:return hD(e,n);case X.ZodEnum:return fD(e);case X.ZodNativeEnum:return DD(e);case X.ZodNullable:return ND(e,n);case X.ZodOptional:return RD(e,n);case X.ZodMap:return ED(e,n);case X.ZodSet:return VD(e,n);case X.ZodLazy:return()=>e.getter()._def;case X.ZodPromise:return BD(e,n);case X.ZodNaN:case X.ZodNever:return OD(n);case X.ZodEffects:return dD(e,n);case X.ZodAny:return nD(n);case X.ZodUnknown:return WD(n);case X.ZodDefault:return uD(e,n);case X.ZodBranded:return oD(e,n);case X.ZodReadonly:return GD(e,n);case X.ZodCatch:return sD(e,n);case X.ZodPipeline:return zD(e,n);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(e=>void 0)(t)}};function qD(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==YE)return i}if(r&&!n){let e=JD(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=KD(e,e.typeName,t),o=typeof a==`function`?qD(a(),t):a;if(o&&YD(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var JD=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:tD(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),nD(t)):t.$refStrategy===`seen`?nD(t):void 0}},YD=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),XD=(e,t)=>{let n=QE(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:qD(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??nD(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=qD(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??nD(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function ZD(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function QD(e,t){return $C(e)?wc(e,{target:ZD(t?.target),io:t?.pipeStrategy??`input`}):XD(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function $D(e){let t=rw(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=lw(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function eO(e,t){let n=tw(e,t);if(!n.success)throw n.error;return n.data}var tO=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Rw,e=>{this._oncancel(e)}),this.setNotificationHandler(eT,e=>{this._onprogress(e)}),this.setRequestHandler(Zw,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(lT,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(dT,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Q(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Q(Z.InvalidParams,`Task not found: ${r}`);if(!JE(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(JE(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[fw]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(fT,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Q(Z.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(mT,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Q(Z.InvalidParams,`Task not found: ${e.params.taskId}`);if(JE(n.status))throw new Q(Z.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Q(Z.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Q?e:new Q(Z.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Q.fromError(Z.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Mw(e)||Pw(e)?this._onresponse(e):Ow(e)?this._onrequest(e,t):Aw(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Q.fromError(Z.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[fw]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Z.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=xw(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new Q(Z.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Z.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),Mw(e)?n(e):n(new Q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(Mw(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),Mw(e)?r(e):r(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}return}let i;try{let r=await this.request(e,oT,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Q(Z.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},JE(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Q(Z.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Q?e:new Q(Z.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[fw]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Q?e:new Q(Z.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=tw(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Q.fromError(Z.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},uT,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},pT,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},hT,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[fw]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[fw]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[fw]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=$D(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=eO(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=$D(e);this._notificationHandlers.set(n,n=>{let r=eO(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&Ow(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Q(Z.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new Q(Z.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new Q(Z.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Q(Z.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=cT.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),JE(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Q(Z.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(JE(a.status))throw new Q(Z.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=cT.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),JE(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function nO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rO(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=nO(a)&&nO(i)?{...a,...i}:i}return n}var iO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),aO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=iO(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),$=D((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;var t=iO(),n=aO(),r=iO();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=aO();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=E(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=E(this.rhs,e,n),this}get names(){return ne(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=E(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(re(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>te(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ie(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=E(this.condition,e,t),this}get names(){let e=super.names;return ne(e,this.condition),this.else&&te(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=E(this.iteration,e,t),this}get names(){return te(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return ne(ne(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=E(this.iterable,e,t),this}get names(){return te(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&te(e,this.catch.names),this.finally&&te(e,this.finally.names),e}},ee=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ee.kind=`catch`;var T=class extends m{render(e){return`finally`+super.render(e)}};T.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
265
|
+
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ee(e),t(e)}return n&&(this._currNode=r.finally=new T,this.code(n)),this._endBlockNode(ee,T)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function te(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ne(e,n){return n instanceof t._CodeOrName?te(e,n.names):e}function E(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function re(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ie(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ue(e)}`}e.not=ie;var ae=le(e.operators.AND);function oe(...e){return e.reduce(ae)}e.and=oe;var se=le(e.operators.OR);function ce(...e){return e.reduce(se)}e.or=ce;function le(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ue(n)} ${e} ${ue(r)}`}function ue(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),oO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=$(),n=iO();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;var _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),sO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),cO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=$(),n=oO(),r=sO();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}var u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),lO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=cO(),n=$(),r=sO(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),uO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),dO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),fO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=uO(),n=dO(),r=cO(),i=$(),a=oO(),o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;var u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
266
266
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
|
|
267
267
|
|| (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
|
|
268
|
-
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;var g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),$D=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=$(),n=KD();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),eO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=$(),n=KD(),r=qD(),i=KD();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;var h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),tO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=$(),n=qD(),r=eO(),i=JD();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),nO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=$(),n=KD();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),rO=D(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),iO=D(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),aO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=KD(),n=rO(),r=iO(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;var o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;var d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),oO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=YD(),n=QD(),r=ZD(),i=QD(),a=$D(),o=tO(),s=nO(),c=$(),l=qD(),u=aO(),d=KD(),f=JD();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&re(e),te(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ee(e),ie(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&re(e),ne(e),E(e);let a=r.const(`_errs`,l.default.errors);ee(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),T(e)}function ee(e,t){if(e.opts.jtd)return oe(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);oe(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function T(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function te(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function ne(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function E(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function re({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ie(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ae(e),t.return((0,c._)`${l.default.errors} === 0`))}function ae({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function oe(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>_e(e,`$ref`,h.all.$ref.definition));return}p.jtd||ce(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),se(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):se(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function se(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&_e(e,n.keyword,n.definition,t.type)})}function ce(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(le(e,t),e.opts.allowUnionTypes||ue(e,t),de(e,e.dataTypes))}function le(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{pe(e.dataTypes,t)||he(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),me(e,t)}}function ue(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&he(e,`use allowUnionTypes to allow union type keyword`)}function de(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>fe(t,e))&&he(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function fe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function pe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function me(e,t){let n=[];for(let r of e.dataTypes)pe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function he(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ge=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,be(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=ge;function _e(e,t,n,r){let i=new ge(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}var ve=/^\/(?:[^~]|~0|~1)*$/,ye=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function be(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ve.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ye.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=be})),sO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),cO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=aO();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),lO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=$(),n=sO(),r=qD(),i=aO(),a=KD(),o=oO(),s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;var h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),uO=Ce({$id:()=>dO,additionalProperties:()=>!1,default:()=>gO,description:()=>fO,properties:()=>hO,required:()=>mO,type:()=>pO}),dO,fO,pO,mO,hO,gO,_O=Se((()=>{dO=`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,fO=`Meta-schema for $data reference (JSON AnySchema extension proposal)`,pO=`object`,mO=[`$data`],hO={$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},gO={$id:dO,description:fO,type:pO,required:mO,properties:hO,additionalProperties:!1}})),vO=D(((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(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}var p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function S(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}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}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}var C={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},w=/[@/?#:]/g,ee=/[@/?#]/g;function T(e,t){let n=t?ee:w;return n.lastIndex=0,e.replace(n,e=>C[e])}function te(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){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ne(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=se(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function E(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function re(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function ie(e){return re(e,l)}function ae(e){return re(e,c)}function oe(e){return re(e,c)}function se(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function ce(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=se(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function le(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ue(e){let t=[];if(e.userinfo!==void 0&&(t.push(ie(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=te(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:T(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:ue,reescapeHostDelimiters:T,normalizePercentEncoding:te,normalizePathEncoding:ne,serializePathEncoding:E,normalizeQueryFragmentEncoding:ce,encodeUserinfo:ie,encodeQuery:ae,encodeFragment:oe,escapePreservingEscapes:le,removeDotSegments:S,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),yO=D(((e,t)=>{var{isUUID:n}=vO(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}var h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),bO=D(((e,t)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=vO(),{SCHEMES:m,getSchemeHandler:h}=yO(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=se(e,t):typeof e==`object`&&(e=oe(C(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=ae(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=ae(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),S=y.host,w=S!==void 0&&S!==``&&(f(S)||n(S).isIPV6);ie(y,r||{},b,w);let ee=S&&S.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(S);if(y.error&&!ee)throw Error(y.error);return i.skipEscape=!0,C(y,i)}function x(e,t,n,i){let a={};return i||(e=oe(C(e,n),n),t=oe(C(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function S(e,t,n){let r=le(e,n),i=le(t,n);return r!==void 0&&i!==void 0&&r===i}function C(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(n.path=o.skipEscape?a(n.path):s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}var w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ee=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,T=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function te(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 ne(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function E(e){return e[0]===`[`&&e[e.length-1]===`]`}function re(e){let t=e[4];return ne(e[3])||t!==void 0&&!E(t)&&ne(t)||ne(e[6])||ne(e[7])||ne(e[8])}function ie(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!E(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function ae(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(ee);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let S=e.match(T);if(S!==null){let e=S[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let C=e.match(w);if(C){if(i.scheme=C[1],i.userinfo=C[3],i.host=C[4],i.port=parseInt(C[5],10),i.path=C[6]||``,i.query=C[7],i.fragment=C[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=re(C),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=C[5]);let t=te(i,C);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host){if(f(i.host)===!1){let e=E(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=ie(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function oe(e,t){return ae(e,t).parsed}function se(e,t){return ce(e,t).normalized}function ce(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=ae(e,t);return{normalized:r||i||a||o||s?e:C(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function le(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:C(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=ce(n,t);return i||a||o||s||c?void 0:r}var ue={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:S,serialize:C,parse:oe};t.exports=ue,t.exports.default=ue,t.exports.fastUri=ue})),xO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=bO();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),SO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=oO();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=$();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}});var r=sO(),i=cO(),a=XD(),o=lO(),s=$(),c=aO(),l=QD(),u=KD(),d=(_O(),Ee(uO).default),f=xO(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;var m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},v=200;function y(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??v,loopEnum:e.loopEnum??v,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var b=class{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,...y(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ne(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,g,e,`NOT SUPPORTED`),x.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&w.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ee.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),C.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=S.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=S.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(re.call(this,n,t),!t)return(0,u.eachItem)(n,e=>ie.call(this,e)),this;oe.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>ie.call(this,e,r):e=>r.type.forEach(t=>ie.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=ce(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};b.ValidationError=r.default,b.MissingRefError=i.default,e.default=b;function x(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function S(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function C(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function w(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ee(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}var te={log(){},warn(){},error(){}};function ne(e){if(e===!1)return te;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}var E=/^[a-z_$][a-z0-9_$:-]*$/i;function re(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!E.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function ie(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ae.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ae(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function oe(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=ce(t)),e.validateSchema=this.compile(t,!0))}var se={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function ce(e){return{anyOf:[e,se]}}})),CO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),wO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=cO(),n=eO(),r=$(),i=qD(),a=lO(),o=KD(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),TO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=CO(),n=wO();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),EO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),DO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),OO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),kO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD(),r=OO();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),AO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=eO(),n=KD(),r=$();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),jO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),MO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=eO(),n=$(),r=KD();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),NO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),PO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=rO();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),FO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=QD(),n=$(),r=KD(),i=PO();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),IO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD(),r=PO();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),LO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD(),r=PO();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),RO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=EO(),n=DO(),r=kO(),i=AO(),a=jO(),o=MO(),s=NO(),c=FO(),l=IO(),u=LO();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),zO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=$(),n=KD(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),BO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=$(),n=KD(),r=eO(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),VO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=BO();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),HO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD(),r=eO(),i=zO();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),UO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),WO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=$(),n=KD(),r=eO();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
268
|
+
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;var g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),pO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=$(),n=oO();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),mO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=$(),n=oO(),r=sO(),i=oO();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;var h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),hO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=$(),n=sO(),r=mO(),i=cO();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),gO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=$(),n=oO();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),_O=D(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),vO=D(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),yO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=oO(),n=_O(),r=vO(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;var o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;var d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),bO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=lO(),n=fO(),r=dO(),i=fO(),a=pO(),o=hO(),s=gO(),c=$(),l=sO(),u=yO(),d=oO(),f=cO();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&re(e),te(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ee(e),ie(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&re(e),ne(e),E(e);let a=r.const(`_errs`,l.default.errors);ee(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),T(e)}function ee(e,t){if(e.opts.jtd)return oe(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);oe(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function T(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function te(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function ne(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function E(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function re({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ie(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ae(e),t.return((0,c._)`${l.default.errors} === 0`))}function ae({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function oe(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>_e(e,`$ref`,h.all.$ref.definition));return}p.jtd||ce(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),se(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):se(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function se(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&_e(e,n.keyword,n.definition,t.type)})}function ce(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(le(e,t),e.opts.allowUnionTypes||ue(e,t),de(e,e.dataTypes))}function le(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{pe(e.dataTypes,t)||he(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),me(e,t)}}function ue(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&he(e,`use allowUnionTypes to allow union type keyword`)}function de(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>fe(t,e))&&he(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function fe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function pe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function me(e,t){let n=[];for(let r of e.dataTypes)pe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function he(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ge=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,be(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=ge;function _e(e,t,n,r){let i=new ge(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}var ve=/^\/(?:[^~]|~0|~1)*$/,ye=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function be(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ve.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ye.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=be})),xO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),SO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=yO();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),CO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=$(),n=xO(),r=sO(),i=yO(),a=oO(),o=bO(),s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;var h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),wO=Ce({$id:()=>TO,additionalProperties:()=>!1,default:()=>AO,description:()=>EO,properties:()=>kO,required:()=>OO,type:()=>DO}),TO,EO,DO,OO,kO,AO,jO=Se((()=>{TO=`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,EO=`Meta-schema for $data reference (JSON AnySchema extension proposal)`,DO=`object`,OO=[`$data`],kO={$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},AO={$id:TO,description:EO,type:DO,required:OO,properties:kO,additionalProperties:!1}})),MO=D(((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(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}var p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function S(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}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}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}var C={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},w=/[@/?#:]/g,ee=/[@/?#]/g;function T(e,t){let n=t?ee:w;return n.lastIndex=0,e.replace(n,e=>C[e])}function te(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){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ne(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=se(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function E(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function re(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function ie(e){return re(e,l)}function ae(e){return re(e,c)}function oe(e){return re(e,c)}function se(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function ce(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=se(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function le(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ue(e){let t=[];if(e.userinfo!==void 0&&(t.push(ie(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=te(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:T(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:ue,reescapeHostDelimiters:T,normalizePercentEncoding:te,normalizePathEncoding:ne,serializePathEncoding:E,normalizeQueryFragmentEncoding:ce,encodeUserinfo:ie,encodeQuery:ae,encodeFragment:oe,escapePreservingEscapes:le,removeDotSegments:S,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),NO=D(((e,t)=>{var{isUUID:n}=MO(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}var h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),PO=D(((e,t)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=MO(),{SCHEMES:m,getSchemeHandler:h}=NO(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=se(e,t):typeof e==`object`&&(e=oe(C(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=ae(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=ae(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),S=y.host,w=S!==void 0&&S!==``&&(f(S)||n(S).isIPV6);ie(y,r||{},b,w);let ee=S&&S.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(S);if(y.error&&!ee)throw Error(y.error);return i.skipEscape=!0,C(y,i)}function x(e,t,n,i){let a={};return i||(e=oe(C(e,n),n),t=oe(C(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function S(e,t,n){let r=le(e,n),i=le(t,n);return r!==void 0&&i!==void 0&&r===i}function C(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(n.path=o.skipEscape?a(n.path):s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}var w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ee=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,T=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function te(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 ne(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function E(e){return e[0]===`[`&&e[e.length-1]===`]`}function re(e){let t=e[4];return ne(e[3])||t!==void 0&&!E(t)&&ne(t)||ne(e[6])||ne(e[7])||ne(e[8])}function ie(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!E(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function ae(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(ee);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let S=e.match(T);if(S!==null){let e=S[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let C=e.match(w);if(C){if(i.scheme=C[1],i.userinfo=C[3],i.host=C[4],i.port=parseInt(C[5],10),i.path=C[6]||``,i.query=C[7],i.fragment=C[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=re(C),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=C[5]);let t=te(i,C);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host){if(f(i.host)===!1){let e=E(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=ie(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function oe(e,t){return ae(e,t).parsed}function se(e,t){return ce(e,t).normalized}function ce(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=ae(e,t);return{normalized:r||i||a||o||s?e:C(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function le(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:C(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=ce(n,t);return i||a||o||s||c?void 0:r}var ue={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:S,serialize:C,parse:oe};t.exports=ue,t.exports.default=ue,t.exports.fastUri=ue})),FO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=PO();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),IO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=bO();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=$();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}});var r=xO(),i=SO(),a=uO(),o=CO(),s=$(),c=yO(),l=fO(),u=oO(),d=(jO(),Ee(wO).default),f=FO(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;var m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},v=200;function y(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??v,loopEnum:e.loopEnum??v,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var b=class{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,...y(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ne(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),x.call(this,g,e,`NOT SUPPORTED`),x.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&w.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ee.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),C.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=S.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=S.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(re.call(this,n,t),!t)return(0,u.eachItem)(n,e=>ie.call(this,e)),this;oe.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>ie.call(this,e,r):e=>r.type.forEach(t=>ie.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=ce(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};b.ValidationError=r.default,b.MissingRefError=i.default,e.default=b;function x(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function S(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function C(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function w(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ee(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}var te={log(){},warn(){},error(){}};function ne(e){if(e===!1)return te;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}var E=/^[a-z_$][a-z0-9_$:-]*$/i;function re(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!E.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function ie(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ae.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ae(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function oe(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=ce(t)),e.validateSchema=this.compile(t,!0))}var se={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function ce(e){return{anyOf:[e,se]}}})),LO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),RO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=SO(),n=mO(),r=$(),i=sO(),a=CO(),o=oO(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),zO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=LO(),n=RO();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),BO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),VO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),HO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),UO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO(),r=HO();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),WO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mO(),n=oO(),r=$();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),GO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),KO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mO(),n=$(),r=oO();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),qO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),JO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=_O();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),YO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=fO(),n=$(),r=oO(),i=JO();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),XO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO(),r=JO();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),ZO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO(),r=JO();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),QO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=BO(),n=VO(),r=UO(),i=WO(),a=GO(),o=KO(),s=qO(),c=YO(),l=XO(),u=ZO();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),$O=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=$(),n=oO(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),ek=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=$(),n=oO(),r=mO(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),tk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ek();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),nk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO(),r=mO(),i=$O();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),rk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),ik=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=$(),n=oO(),r=mO();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
269
269
|
missingProperty: ${i},
|
|
270
270
|
depsCount: ${n},
|
|
271
|
-
deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),GO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),KO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=eO(),n=$(),r=qD(),i=KD();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),qO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=oO(),n=eO(),r=KD(),i=KO();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),JO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=eO(),n=$(),r=KD(),i=KD();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),YO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=KD();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),XO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:eO().validateUnion,error:{message:`must match a schema in anyOf`}}})),ZO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),QO=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=KD();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),$O=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=KD(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),ek=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=KD();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),tk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=zO(),n=VO(),r=BO(),i=HO(),a=UO(),o=WO(),s=GO(),c=KO(),l=qO(),u=JO(),d=YO(),f=XO(),p=ZO(),m=QO(),h=$O(),g=ek();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),nk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),rk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[nk().default]})),ik=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),ak=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=TO(),n=RO(),r=tk(),i=rk(),a=ik();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),ok=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),sk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=ok(),r=lO(),i=cO(),a=KD();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),ck=Ce({$id:()=>uk,$schema:()=>lk,default:()=>hk,definitions:()=>fk,properties:()=>mk,title:()=>dk,type:()=>pk}),lk,uk,dk,fk,pk,mk,hk,gk=Se((()=>{lk=`http://json-schema.org/draft-07/schema#`,uk=`http://json-schema.org/draft-07/schema#`,dk=`Core schema meta-schema`,fk={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:[]}},pk=[`object`,`boolean`],mk={$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:`#`}},hk={$schema:lk,$id:uk,title:dk,definitions:fk,type:pk,properties:mk,default:!0}})),_k=D(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var n=SO(),r=ak(),i=sk(),a=(gk(),Ee(ck).default),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`,c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=oO();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=sO();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=cO();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),vk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:T,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}var ee=/[^\\]\\Z/;function T(e){if(ee.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),yk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=_k(),n=$(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),bk=D(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=vk(),r=yk(),i=$(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),xk=Te(_k(),1),Sk=Te(bk(),1);function Ck(){let e=new xk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Sk.default)(e),e}var wk=class{constructor(e){this._ajv=e??Ck()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},Tk=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},lE,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},xE,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function Ek(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function Dk(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var Ok=class extends VD{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(XT.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new wk,this.setRequestHandler(Nw,e=>this._oninitialize(e)),this.setNotificationHandler(Iw,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(QT,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=XT.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Tk(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=UD(this._capabilities,e)}setRequestHandler(e,t){let n=UC(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=YC(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=VC(qT,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=VC(Kw,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=VC(GT,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Dk(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Ek(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:ZC.includes(t)?t:XC,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},Sw)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},uE,t):this.request({method:`sampling/createMessage`,params:e},lE,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},xE,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},xE,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},jE,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},kk=Symbol.for(`mcp.completable`);function Ak(e){return!!e&&typeof e==`object`&&kk in e}function jk(e){return e[kk]?.complete}var Mk;(function(e){e.Completable=`McpCompletable`})(Mk||={});var Nk=/^[A-Za-z0-9._-]{1,128}$/;function Pk(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Nk.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Fk(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Ik(e){let t=Pk(e);return Fk(e,t.warnings),t.isValid}var Lk=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Rk=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ok(e,t)}get experimental(){return this._experimental||={tasks:new Lk(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Gk(UT)),this.server.assertCanSetRequestHandler(Gk(qT)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(UT,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=WC(t.inputSchema);return e?RD(e,{strictUnions:!0,pipeStrategy:`input`}):zk})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=WC(t.outputSchema);e&&(n.outputSchema=RD(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(qT,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Q(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Q(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await HC(WC(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=KC(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await HC(WC(e.outputSchema),t.structuredContent);if(!r.success){let e=KC(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Q(Z.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Gk(TE)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(TE,async e=>{switch(e.params.ref.type){case`ref/prompt`:return EE(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return DE(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return qk;let r=UC(n.argsSchema)?.[e.params.argument.name];if(!Ak(r))return qk;let i=jk(r);return i?Kk(await i(e.params.argument.value,e.params.context)):qk}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return qk;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Kk(await r(e.params.argument.value,e.params.context)):qk}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Gk(uT)),this.server.assertCanSetRequestHandler(Gk(fT)),this.server.assertCanSetRequestHandler(Gk(gT)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(uT,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(fT,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(gT,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Q(Z.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Gk(DT)),this.server.assertCanSetRequestHandler(Gk(AT)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(DT,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Wk(t.argsSchema):void 0}))})),this.server.setRequestHandler(AT,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await HC(WC(n.argsSchema),e.params.arguments);if(!r.success){let t=KC(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:BC(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=BC(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Ak(e instanceof Gl?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Ik(e);let l={title:t,description:n,inputSchema:Uk(r),outputSchema:Uk(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Ik(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=BC(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=BC(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(Hk(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Hk(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},zk={type:`object`,properties:{}};function Bk(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Vk(e){return`_def`in e||`_zod`in e||Bk(e)}function Hk(e){return typeof e!=`object`||!e||Vk(e)?!1:Object.keys(e).length===0||Object.values(e).some(Bk)}function Uk(e){if(e){if(Hk(e))return BC(e);if(!Vk(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Wk(e){let t=UC(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:qC(t),required:!JC(t)})):[]}function Gk(e){let t=UC(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=YC(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Kk(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var qk={completion:{values:[],hasMore:!1}},Jk=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
272
|
-
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),
|
|
273
|
-
`}var
|
|
274
|
-
`),await new Promise(()=>{})}var
|
|
275
|
-
`),points:Number(a[0])}}function fA(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function pA(e){let t=new Map;for(let n of e){if(!fA(n.number))throw new L(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new L(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function mA(e){if(fA(e))return e;if(typeof e!=`string`)return;let t=/^#?([1-9]\d*)$/u.exec(e.trim()),n=t?.[1]===void 0?NaN:Number(t[1]);return fA(n)?n:void 0}function hA(e,t){let n=RegExp(`<!--\\s*${t}:\\s*([\\s\\S]*?)\\s*-->`,`u`).exec(e)?.[1];if(n!==void 0)try{let e=JSON.parse(n);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`not an object`);return e}catch{throw new L(`Invalid legacy ${t} payload.`)}}function gA(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function _A({dependencyDeclaration:e,executionContract:t,related:n}){let r=[],i=t?.dependencies;if(Array.isArray(i))for(let e of i){if(typeof e!=`object`||!e)continue;let t=e,n=mA(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...vA(e?.blockedBy)),r.push(...vA(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function vA(e){return Array.isArray(e)?e.map(mA).filter(e=>e!==void 0):[]}function yA(e){if(e.unresolvedBlockers.size>0)return`Blocked`;let t=e.labels.some(e=>[`status:in-progress`,`status:review`].includes(e.toLowerCase()));return e.existing===`In Progress`||t?`In Progress`:`Todo`}function bA(e){let t=[];for(let n of e.labels){let e=oA.get(n.toLowerCase());e!==void 0&&t.push(e);let r=/^points:(1|2|3|5|8|13)$/u.exec(n.toLowerCase());r?.[1]!==void 0&&t.push(Number(r[1]))}let n=e.executionContract?.effort;if(typeof n==`string`){let e=n.startsWith(`effort:`)?n:`effort:${n}`,r=oA.get(e.toLowerCase());r!==void 0&&t.push(r)}e.bodyPoint!==void 0&&t.push(e.bodyPoint);let r=[...new Set(t)];if(r.length>1)throw new L(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new L(`Issue has no canonical Fibonacci sizing value; assign native Points before migration.`);return i}function xA({label:e,labels:t,mapping:n}){let r=t.flatMap(e=>{let t=n.get(e.toLowerCase());return t===void 0?[]:[t]}),i=[...new Set(r)];if(i.length>1)throw new L(`Found conflicting legacy ${e} values.`);return i[0]}var SA=class{constructor(e){this._client=e}async*callToolStream(e,t=GT,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof Q){yield{type:`error`,error:e};return}yield{type:`error`,error:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function CA(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&CA(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&CA(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&CA(n,t)}}function wA(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var TA=class extends VD{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new wk,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,JT,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,zT,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,vT,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new SA(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=UD(this._capabilities,e)}setRequestHandler(e,t){let n=UC(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=YC(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=VC(vE,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=wA(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new Q(Z.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new Q(Z.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=VC(Kw,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=VC(xE,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new Q(Z.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{CA(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=VC(cE,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=VC(Kw,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=VC(i.tools||i.toolChoice?uE:lE,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:XC,capabilities:this._capabilities,clientInfo:this._clientInfo}},Fw,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!ZC.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Ek(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&Dk(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},Sw,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},OE,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},Sw,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},RT,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},OT,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},dT,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},pT,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},_T,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},Sw,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},Sw,t)}async callTool(e,t=GT,n){if(this.isToolTaskRequired(e.name))throw new Q(Z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},WT,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=YT.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},EA=D(((e,t)=>{t.exports=a,a.sync=o;var n=De(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function i(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:r(t,n)}function a(e,t,r){n.stat(e,function(n,a){r(n,!n&&i(a,e,t))})}function o(e,t){return i(n.statSync(e),e,t)}})),DA=D(((e,t)=>{t.exports=r,r.sync=i;var n=De(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),OA=D(((e,t)=>{De(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?EA():DA();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),kA=D(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=De(`path`),i=n?`;`:`:`,a=OA(),o=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),s=(e,t)=>{let r=t.colon||i,a=e.match(/\//)||n&&e.match(/\\/)?[``]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(r)],o=n?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=n?o.split(r):[``];return n&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:a,pathExt:s,pathExtExe:o}},c=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:i,pathExt:c,pathExtExe:l}=s(e,t),u=[],d=n=>new Promise((a,s)=>{if(n===i.length)return t.all&&u.length?a(u):s(o(e));let c=i[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=r.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(f(p,n,0))}),f=(e,n,r)=>new Promise((i,o)=>{if(r===c.length)return i(d(n+1));let s=c[r];a(e+s,{pathExt:l},(a,o)=>{if(!a&&o){if(t.all)u.push(e+s);else return i(e+s)}return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};t.exports=c,c.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:i,pathExtExe:c}=s(e,t),l=[];for(let o=0;o<n.length;o++){let s=n[o],u=/^".*"$/.test(s)?s.slice(1,-1):s,d=r.join(u,e),f=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<i.length;e++){let n=f+i[e];try{if(a.sync(n,{pathExt:c})){if(t.all)l.push(n);else return n}}catch{}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw o(e)}})),AA=D(((e,t)=>{var n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),jA=D(((e,t)=>{var n=De(`path`),r=kA(),i=AA();function a(e,t){let a=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=r.sync(e.command,{path:a[i({env:a})],pathExt:t?n.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=n.resolve(s?e.options.cwd:``,l),l}function o(e){return a(e)||a(e,!0)}t.exports=o})),MA=D(((e,t)=>{var n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),NA=D(((e,t)=>{t.exports=/^#!(.*)/})),PA=D(((e,t)=>{var n=NA();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),FA=D(((e,t)=>{var n=De(`fs`),r=PA();function i(e){let t=Buffer.alloc(150),i;try{i=n.openSync(e,`r`),n.readSync(i,t,0,150,0),n.closeSync(i)}catch{}return r(t.toString())}t.exports=i})),IA=D(((e,t)=>{var n=De(`path`),r=jA(),i=MA(),a=FA(),o=process.platform===`win32`,s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){e.file=r(e);let t=e.file&&a(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}function u(e){if(!o)return e;let t=l(e),r=!s.test(t);if(e.options.forceShell||r){let r=c.test(t);e.command=n.normalize(e.command),e.command=i.command(e.command),e.args=e.args.map(e=>i.argument(e,r)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function d(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:u(r)}t.exports=d})),LA=D(((e,t)=>{var n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),RA=Te(D(((e,t)=>{var n=De(`child_process`),r=IA(),i=LA();function a(e,t,a){let o=r(e,t,a),s=n.spawn(o.command,o.args,o.options);return i.hookChildProcess(s,o),s}function o(e,t,a){let o=r(e,t,a),s=n.spawnSync(o.command,o.args,o.options);return s.error=s.error||i.verifyENOENTSync(s.status,o),s}t.exports=a,t.exports.spawn=a,t.exports.sync=o,t.exports._parse=r,t.exports._enoent=i}))(),1),zA=ie.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function BA(){let e={};for(let t of zA){let n=ie.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var VA=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Jk({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new he)}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=(0,RA.default)(this._serverParams.command,this._serverParams.args??[],{env:{...BA(),...this._serverParams.env},stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`],shell:!1,windowsHide:ie.platform===`win32`,cwd:this._serverParams.cwd}),this._process.on(`error`,e=>{t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{e()}),this._process.on(`close`,e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{this.onerror?.(e)}),this._process.stdout?.on(`data`,e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on(`error`,e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once(`close`,()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),e.exitCode===null){try{e.kill(`SIGTERM`)}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(e.exitCode===null)try{e.kill(`SIGKILL`)}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=Xk(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}},HA=A().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),UA=P({action:F([`install`,`doctor`,`update`,`rollback`,`remove`]),host:F([`codex`,`claude-code`]),scope:F([`user`,`project`,`local`]),version:HA.optional(),dryRun:xl().default(!1),repoRoot:A().min(1)}),WA=P({pid:j().int().positive(),birth:A().min(1)}),GA=P({action:UA.shape.action,targetVersion:HA.nullable(),owner:WA,producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),staging:P({path:A(),device:j().int().nonnegative().optional(),inode:j().int().nonnegative().optional()}).optional(),command:Pl(`phase`,[P({phase:I(`idle`)}),P({phase:I(`starting`)}),P({phase:I(`running`),process:WA,tracked:M(WA.extend({pgid:j().int().positive()})).max(256)})])}),KA=P({owner:I(`@aviaratech/ai-delivery.plugin@1`),host:UA.shape.host,scope:UA.shape.scope,projectRoot:A().nullable(),nativeHome:A().min(1),marketplace:A(),currentVersion:HA.nullable(),previousVersion:HA.nullable(),installedPath:A().nullable(),nativeVersion:A().optional(),pending:GA.optional()}),qA=P({owner:I(`@aviaratech/ai-delivery.plugin-version@1`),version:HA,archiveSha256:A().regex(/^[a-f0-9]{64}$/u),files:Bl(A(),A().regex(/^[a-f0-9]{64}$/u))}),JA=e=>se(`sha256`).update(e).digest(`hex`);function YA(e){let t=E(e);for(;;){if(n(t)&&o(t).isSymbolicLink())throw Error(`Managed plugin paths must not use symlinks.`);let e=w(t);if(e===t)break;t=e}}function XA(e){let t=p(E(e.repoRoot)),r=E(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??T(oe(),e.host===`codex`?`.codex`:`.claude`)),i=[];for(;!n(r);)i.unshift(C(r)),r=w(r);let a=T(p(r),...i),s=e.scope===`user`?`user`:`${e.scope}-${se(`sha256`).update(t).digest(`hex`).slice(0,16)}`,c=T(oe(),`.cache`,`ai-delivery`,`plugins`,e.host,s);if(YA(c),n(c)&&(!o(c).isDirectory()||o(c).mode&63))throw Error(`Managed plugin directory is not private.`);return{directory:c,projectRoot:t,nativeHome:a,marketplace:`ai-delivery-${s}`,catalog:T(c,`marketplace`),statePath:T(c,`state.json`),tool:e.host===`codex`?`codex`:`claude`}}function ZA(e,t){if(!n(t.statePath))return;let r=o(t.statePath);if(!r.isFile()||r.nlink!==1||r.mode&63||r.size>65536)throw Error(`Managed plugin state is unsafe.`);let i=KA.parse(JSON.parse(l(t.statePath,`utf8`)));if(i.nativeHome!==t.nativeHome)throw Error(`Managed plugin state belongs to a different native profile.`);if(i.host!==e.host||i.scope!==e.scope||i.marketplace!==t.marketplace||i.projectRoot!==(e.scope===`user`?null:t.projectRoot))throw Error(`Managed plugin state belongs to a different target.`);return i}function QA(e){let t=Sy().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function $A(e){if(QA(e.owner.pid)===e.owner.birth)throw Error(`A live plugin installer still owns this target.`);if(e.command.phase===`starting`)throw Error(`Interrupted installer command ownership is unknown; preserve its state before recovery.`);if(e.command.phase!==`running`)return;let t={rootPid:e.command.process.pid,rootIdentity:e.command.process.birth,sampled:!0,tracked:new Map(e.command.tracked.map(({pid:e,birth:t,pgid:n})=>[e,{pid:e,identity:t,pgid:n,ppid:0,rssBytes:0,status:``}]))};Dy(t),await Ey(t)}async function ej(e,t,n,r,i){return(await Hy(n,[e,...t],r,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2},void 0,void 0,{starting:()=>i?.({phase:`starting`}),observed:e=>i?.({phase:`running`,process:{pid:e.rootPid,birth:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,birth:t,pgid:n}))}),idle:()=>i?.({phase:`idle`}),assertQuiescent:()=>{}},{environment:{...process.env,DISABLE_AUTOUPDATER:`1`},cwd:n,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>` Native command output: ${e.toString(`utf8`).slice(-2e3)}`})).toString(`utf8`)}function tj(e){let n=c(e,`r`);try{i(n)}finally{t(n)}}function nj(e,t){return T(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function rj(e,t){return T(e.catalog,`versions`,t)}function ij(e){let t={},n=0,r=(e,i,a)=>{if(a>16)throw Error(`Plugin tree exceeds the depth bound.`);for(let s of d(e).sort()){if(++n>4096)throw Error(`Plugin tree exceeds the entry bound.`);let c=T(e,s),u=`${i}${s}`,d=o(c);if(d.isSymbolicLink()||!d.isDirectory()&&(!d.isFile()||d.nlink!==1))throw Error(`Plugin tree contains links or special files.`);if(d.isDirectory())r(c,`${u}/`,a+1);else{if(d.size>32*1024**2)throw Error(`Plugin file exceeds the size bound.`);t[u]=JA(l(c))}}};return r(e,``,0),t}function aj(e,t){let r=rj(e,t);YA(r);let i=T(r,`version.json`);if(!n(i))throw Error(`No completed immutable plugin unit for ${t}.`);let a=o(i),s=T(r,`archive.tgz`),c=o(s);if(!a.isFile()||a.nlink!==1||a.size>1048576||!c.isFile()||c.nlink!==1||c.size>32*1024**2)throw Error(`Immutable plugin unit metadata is unsafe.`);let u=qA.parse(JSON.parse(l(i,`utf8`)));if(u.version!==t||JSON.stringify(ij(nj(e,t)))!==JSON.stringify(u.files)||JA(l(s))!==u.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return u}function oj(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=pe(e,{maxOutputLength:128*1024**2}),n=new Map;for(let e=0;e+512<=t.length;){let r=t.subarray(e,e+512);if(r.every(e=>e===0))break;let i=(e,t)=>r.subarray(e,e+t).toString().replace(/\0.*$/su,``).trim(),a=(e,t)=>{let n=i(e,t);if(!/^[0-7]+$/u.test(n))throw Error(`Unsupported tar numeric header.`);return Number.parseInt(n,8)};if([...r].reduce((e,t,n)=>e+(n>=148&&n<156?32:t),0)!==a(148,8))throw Error(`Plugin archive header checksum mismatch.`);let o=`${i(345,155)?`${i(345,155)}/`:``}${i(0,100)}`,s=a(124,12),c=i(156,1);if(!/^package\/[A-Za-z0-9_./-]+$/u.test(o)||o.split(`/`).some(e=>e===`..`||e===`.`)||o.split(`/`).length>16||![``,`0`,`5`].includes(c)||e+512+s>t.length||n.has(o)||n.size>=4096)throw Error(`Unsafe or unsupported plugin archive member.`);c!==`5`&&n.set(o,t.subarray(e+512,e+512+s)),e+=512+Math.ceil(s/512)*512}return n}async function sj(e,t,r,i,a){let c=rj(e,t);if(n(c)){aj(e,t);return}let u=w(c);K_(u);let d=T(u,`.stage-${le()}`);a({path:d}),s(d,{mode:448});let f=o(d);tj(u),a({path:d,device:f.dev,inode:f.ino});let p=!0,g=!1,_,v=e=>{p=e.phase===`idle`,i(e)};try{let n=JSON.parse(await ej(`npm`,[`pack`,`@aviaratech/ai-delivery@${t}`,`--ignore-scripts`,`--json`,`--logs-max`,`0`,`--cache`,T(e.directory,`npm-cache`),`--pack-destination`,d],d,r,v))[0]?.filename;if(typeof n!=`string`||!/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(n))throw Error(`npm returned an unsafe archive path.`);let i=l(T(d,n)),o=oj(i),s=JSON.parse(o.get(`package/package.json`)?.toString()??`null`);if(s?.name!==`@aviaratech/ai-delivery`||s.version!==t)throw Error(`Archive package identity does not match the explicit version.`);let f=T(d,`plugins`,`ai-delivery`);for(let[e,t]of o)if(e.startsWith(`package/plugins/ai-delivery/`)){let n=T(f,e.slice(28));K_(w(n)),y(n,t,{mode:384,flag:`wx`}),tj(n)}let p=JSON.parse(l(T(f,`plugin.json`),`utf8`)),h=JSON.parse(l(T(f,`.claude-plugin/plugin.json`),`utf8`)),g=JSON.parse(l(T(f,`runtime/package.json`),`utf8`));if(p.name!==`ai-delivery`||p.version!==t||h.name!==p.name||h.version!==t||h.packageVersion!==t||h.deliveryCapabilityVersion!==2||g.name!==s.name||g.version!==t)throw Error(`Archive does not contain a coherent self-contained native plugin.`);if((await ej(process.execPath,[T(f,`runtime/dist/cli.js`),`--version`],d,r,v)).trim()!==t)throw Error(`Built native CLI version does not match its archive.`);m(T(d,n),T(d,`archive.tgz`)),tj(T(d,`archive.tgz`)),J_(T(d,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:JA(i),files:ij(f)}),m(d,c),tj(u),a(void 0),aj(e,t)}catch(e){g=!0,_=e}try{if(p&&n(d)){let e=o(d);if(e.dev!==f.dev||e.ino!==f.ino||!e.isDirectory()||e.isSymbolicLink())throw Error(`Owned staging directory identity changed.`);h(d,{recursive:!0}),tj(u)}p&&a(void 0)}catch(e){_=g?AggregateError([_,e],`Plugin preparation failed and staging cleanup also failed.`):e,g=!0}if(g)throw _}function cj(e,t){aj(e,t);let n=`./versions/${t}/plugins/ai-delivery`;J_(T(e.catalog,`.agents/plugins/marketplace.json`),{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}),J_(T(e.catalog,`.claude-plugin/marketplace.json`),{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]})}async function lj(e,t,n,r){let i=JSON.parse(await ej(t.tool,[`plugin`,`list`,...e.host===`codex`?[`--available`]:[],`--json`],t.projectRoot,n,r));if(e.host===`claude-code`)return M(Bl(A(),Tl())).parse(i);let a=N({installed:M(Bl(A(),Tl())),available:M(Bl(A(),Tl()))}).parse(i);return[...a.installed.map(e=>({...e,installed:!0})),...a.available.map(e=>({...e,installed:!1}))]}function uj(e,t,r){if(e.host===`claude-code`){let e=T(t.nativeHome,`plugins/known_marketplaces.json`);if(!n(e))return!1;if(!o(e).isFile()||o(e).size>1048576)throw Error(`Native marketplace registry is unsafe.`);let r=Bl(A(),Tl()).parse(JSON.parse(l(e,`utf8`)));if(r[t.marketplace]===void 0)return!1;let i=N({source:N({source:I(`directory`),path:A()}),installLocation:A()}).parse(r[t.marketplace]);if(E(i.source.path)!==t.catalog||E(i.installLocation)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`);return!0}let i=r.filter(e=>e.marketplaceName===t.marketplace);for(let e of i){let n=N({sourceType:I(`local`),source:A()}).parse(e.marketplaceSource);if(E(n.source)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`)}return i.length>0}function dj(e,t,n){let r=n.filter(n=>(n.pluginId??n.id)===`ai-delivery@${t.marketplace}`&&(e.host===`codex`?n.installed===!0:n.scope===e.scope)&&(e.scope===`user`||n.projectPath===t.projectRoot));if(r.length>1)throw Error(`Native plugin readback is ambiguous.`);let i=r[0];if(!i)return;let a=e.host===`codex`?N({source:I(`local`),path:A()}).parse(i.source).path:void 0;return{version:HA.parse(i.version),enabled:xl().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:Bl(A(),Tl()).parse(i.mcpServers)}:{}}}function fj(e){let t=T(e.catalog,`.claude-plugin/marketplace.json`);if(YA(t),!o(t).isFile()||o(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=N({name:I(e.marketplace),plugins:M(N({name:A(),version:HA,source:A()}))}).parse(JSON.parse(l(t,`utf8`))).plugins.filter(e=>e.name===`ai-delivery`);if(n.length!==1)throw Error(`Managed Claude catalog selection is ambiguous.`);let r=n[0];if(!r.source.startsWith(`./`)||E(e.catalog,r.source)!==nj(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function pj(e,t,n,r,i=n.version){let a=aj(t,e.host===`claude-code`?i:n.version),o=nj(t,e.host===`claude-code`?i:n.version);if(e.host===`claude-code`&&fj(t).version!==i)throw Error(`Claude catalog version differs from its native selection.`);if(e.host===`codex`&&E(n.sourceRoot)!==o)throw Error(`Native plugin source differs from the managed version.`);let s=e.host===`codex`?r:o;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`codex`&&E(s)!==T(t.nativeHome,`plugins/cache`,t.marketplace,`ai-delivery`,n.version))throw Error(`Native cache path is outside the managed native selection.`);if(YA(s),JSON.stringify(ij(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!N({command:I(`node`),args:Rl([I("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function mj(e,t,n){let r=new VA({command:process.execPath,args:[T(e,`dist/mcp-launcher.js`)],cwd:n,env:{PATH:process.env.PATH??``,NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new TA({name:`ai-delivery-plugin-doctor`,version:`1.0.0`});try{if(await i.connect(r,{timeout:3e4}),i.getServerVersion()?.version!==t)throw Error(`MCP server version differs from the selected archive.`);return await i.listTools({},{timeout:3e4}),{configuration:`native_manifest_present`,startup:`ready`,version:t}}catch(e){return{configuration:`native_manifest_present`,startup:`failed`,error:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}finally{await i.close(),await r.close()}}async function hj(e){let t=UA.parse(e);if(t.host===`codex`&&t.scope!==`user`)throw Error(`Codex currently supports user plugin installation; select --scope user.`);if((t.action===`install`||t.action===`update`)&&t.version===void 0)throw Error(`An explicit --version is required for install and update.`);if(t.version!==void 0&&t.action!==`install`&&t.action!==`update`)throw Error(`--version is supported only for install and update; rollback selects the recorded previous version.`);if(![`darwin`,`linux`].includes(process.platform))throw Error(`Plugin management requires the supported POSIX runtime environment.`);let r=XA(t),i=ZA(t,r),a={action:t.action,host:t.host,scope:t.scope,version:t.action===`remove`?null:t.version??(t.action===`rollback`?i?.previousVersion:i?.currentVersion)??null,changed:!1,dryRun:t.dryRun,installed:!1,marketplace:r.marketplace,managedDirectory:r.directory,repositoryAdmission:`explicit_stage_and_admit_required`};if(t.dryRun)return a;if(t.action===`doctor`){if(!i||(a.recoveryRequired=i.pending!==void 0,i.pending||!i.currentVersion))return a;aj(r,i.currentVersion);let e=await lj(t,r,new AbortController().signal),n=uj(t,r,e),o=dj(t,r,e);if(a.installed=o?.version===i.currentVersion,a.enabled=o?.enabled??!1,i.installedPath&&(a.nativeCachePath=i.installedPath),i.nativeVersion&&(a.nativeVersion=i.nativeVersion),!n||!a.installed)return a.mcp={configuration:`missing`,startup:`not_checked`},a;try{a.nativePluginRoot=pj(t,r,o,i.installedPath),a.sourceIntegrity=!0,a.skills=d(T(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await mj(a.nativePluginRoot,i.currentVersion,r.projectRoot):{configuration:`disabled`,startup:`not_checked`}}catch(e){a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}return a}if(!i&&t.action===`remove`)return a;if(!i&&n(r.directory)&&d(r.directory).length>0)throw Error(`Managed plugin directory contains unrecognized content.`);return K_(r.directory),Xv(r.statePath,{projectRoot:r.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{i=ZA(t,r);let e=i?.pending!==void 0;if(i?.pending){if(await $A(i.pending),i.pending.producerDigest!==Ly(w(me(import.meta.url))))throw Error(`Interrupted plugin operation belongs to a different controller; resume with its original version.`);let e=i.pending.staging;if(e&&n(e.path)){let t=w(rj(r,i.pending.targetVersion));if(w(e.path)!==t||!/^\.stage-[a-f0-9-]{36}$/u.test(e.path.slice(t.length+1)))throw Error(`Recorded staging path is outside this version target.`);YA(e.path);let n=o(e.path);if(!n.isDirectory()||(e.device===void 0?d(e.path).length!==0:n.dev!==e.device||n.ino!==e.inode))throw Error(`Interrupted staging directory ownership is unresolved.`);h(e.path,{recursive:!0}),tj(t)}if(i.pending.action!==t.action||i.pending.targetVersion!==a.version)throw Error(`Resume the interrupted original plugin command before selecting a different operation.`)}if((t.action===`update`||t.action===`rollback`)&&(!i||t.action===`update`&&!i.currentVersion))throw Error(`Install a managed plugin before updating or rolling it back.`);let s=t.action===`remove`?null:a.version;if(s===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let c=i?.currentVersion??null;i??={owner:`@aviaratech/ai-delivery.plugin@1`,host:t.host,scope:t.scope,projectRoot:t.scope===`user`?null:r.projectRoot,nativeHome:r.nativeHome,marketplace:r.marketplace,currentVersion:null,previousVersion:null,installedPath:null};let l=QA(process.pid);if(!l)throw Error(`Installer owner identity is unknown.`);i.pending={action:t.action,targetVersion:s,owner:{pid:process.pid,birth:l},producerDigest:Ly(w(me(import.meta.url))),command:{phase:`idle`}},J_(r.statePath,i);let u=new AbortController,f=()=>u.abort();process.once(`SIGINT`,f),process.once(`SIGTERM`,f);let p=e=>{i.pending.command=e,J_(r.statePath,i)},m=e=>ej(r.tool,e,r.projectRoot,u.signal,p),g=`ai-delivery@${r.marketplace}`,_=t.host===`codex`?[`plugin`,`remove`,g,`--json`]:[`plugin`,`uninstall`,g,`--scope`,t.scope,`--keep-data`],v=t.host===`codex`?[`plugin`,`add`,g,`--json`]:[`plugin`,`install`,g,`--scope`,t.scope],y=!1;try{if(i.nativeVersion=(await m([`--version`])).trim(),t.host===`claude-code`&&!(await m([`plugin`,`uninstall`,`--help`])).includes(`--keep-data`))throw Error(`This Claude Code version cannot preserve plugin data; upgrade the native tool first.`);process.stderr.write(`ai-delivery.plugin ${JSON.stringify({action:t.action,host:t.host,scope:t.scope,stage:s?`prepare_version`:`native_remove`,version:s})}\n`);let n=await lj(t,r,u.signal,p),o=uj(t,r,n),l=dj(t,r,n);if(l&&!c&&!(e&&l.version===s))throw Error(`Existing native plugin is not owned by managed state.`);let d=l?.version;if(l&&e&&t.host===`claude-code`&&(d=fj(r).version,d!==c&&d!==s))throw Error(`Interrupted native selection has an incompatible catalog version.`);l&&pj(t,r,l,l.version===c?i.installedPath:T(r.nativeHome,`plugins/cache`,r.marketplace,`ai-delivery`,l.version),d),s&&(await sj(r,s,u.signal,p,e=>{e?i.pending.staging=e:delete i.pending.staging,J_(r.statePath,i)}),y=!0,cj(r,s),o||await m([`plugin`,`marketplace`,`add`,r.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),l&&(l.version!==s||t.action===`remove`)&&(y=!0,await m(_));let f=i.installedPath;if(s){let e=await m(v);t.host===`codex`&&(f=N({installedPath:A()}).parse(JSON.parse(e)).installedPath)}let h=await lj(t,r,u.signal,p);uj(t,r,h);let g=dj(t,r,h);if(s?g?.version!==s:g!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(s&&(pj(t,r,g,g?.installedPath??f),!g.enabled))throw Error(`Native plugin selection is disabled.`);return i.currentVersion=s,c!==s&&(i.previousVersion=c),i.installedPath=s?g?.installedPath??f:null,delete i.pending,J_(r.statePath,i),a.version=s,a.changed=c!==s,a.installed=s!==null,a.restartRequired=!0,s&&(a.nativePluginRoot=t.host===`codex`?i.installedPath??nj(r,s):nj(r,s)),a}catch(t){if(!e&&!u.signal.aborted&&!y&&i.pending?.command.phase===`idle`&&i.pending.staging===void 0){delete i.pending;try{J_(r.statePath,i)}catch(e){throw AggregateError([t,e],`Plugin preparation failed and pending-state cleanup also failed.`)}}if(y&&c)try{cj(r,c)}catch{}throw t}finally{process.removeListener(`SIGINT`,f),process.removeListener(`SIGTERM`,f)}}})}var gj=new Ve;gj.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version($k).option(`--identity <name>`,`Configured author or reviewer identity`).option(`--personal-auth`,`Explicit legacy personal-token author override`).option(`--repo <owner/name>`,`GitHub repository owner/name; works from any directory`).option(`--repo-root <path>`,`Launch directory or explicit clone for local operations`,process.cwd());for(let e=2;e<process.argv.length;e++){let t=process.argv[e],n=gj.options.find(e=>e.long===t.split(`=`)[0]||e.short===t);if(n){n.required&&!t.includes(`=`)&&e++;continue}t===`plugin`&&gj.enablePositionalOptions();break}function _j(){let e=gj.opts(),t=(e.identity??process.env.AI_DELIVERY_IDENTITY)?.trim()||void 0;return{repoRoot:e.repoRoot,...t===void 0?{}:{identity:t},personalAuth:e.personalAuth===!0,...e.repo===void 0?{}:{repo:e.repo}}}function vj(e){return e===void 0?void 0:Number(e)}function yj(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function bj(e){return yj(e)?.map(Number)}function xj(e,t){if(e!==void 0&&t!==void 0)throw Error(`Pass either --body or --body-file.`);return t===void 0?e:l(t,`utf8`)}function Sj(e,t){return oS(e,t,_j()).then(t=>Ge(e,t))}function Cj(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var wj=gj.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`update`,`rollback`,`remove`]){let t=wj.command(e).requiredOption(`--host <host>`,`Native host: codex or claude-code`).option(`--scope <scope>`,`Native scope: user, project, or local; Codex supports user`,`user`).option(`--dry-run`,`Describe the selected target without changing files or contacting native tools`).option(`--json`,`Print the result as JSON`);(e===`install`||e===`update`)&&t.requiredOption(`--version <version>`,`Explicit published package version`),t.action(async t=>{let n=await hj({action:e,host:t.host,scope:t.scope,...t.version===void 0?{}:{version:t.version},dryRun:t.dryRun===!0,repoRoot:_j().repoRoot});if(t.json){Cj(n);return}process.stdout.write(`${n.dryRun?`Dry run: `:``}${n.host} ${n.scope}: ${e}; version ${n.version??`none`}; installed ${n.installed}; changed ${n.changed}\n`),n.mcp&&process.stdout.write(`Bundled MCP startup: ${n.mcp.startup}${n.mcp.error?` (${n.mcp.error})`:``}\n`),n.recoveryRequired&&process.stdout.write(`Resume the interrupted original plugin command to recover this target.
|
|
276
|
-
`)})}gj.command(`runtime:stage`).description(`Stage a reviewed archive in a private directory; does not activate or admit it`).requiredOption(`--archive <path>`).requiredOption(`--archive-sha256 <digest>`).requiredOption(`--package-version <version>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--native-plugin-root <path>`,`Bind the exact reviewed native plugin root`).option(`--max-aggregate-rss-bytes <bytes>`,`Sampled controller plus children RSS limit`).option(`--max-new-output-bytes <bytes>`,`Owned stage and metadata output limit`).option(`--min-free-disk-bytes <bytes>`,`Required free disk headroom`).option(`--max-captured-output-bytes <bytes>`,`Retained command log cap; defaults to 1 MiB`).option(`--authorize-stage`,`Explicit authority to stage this reviewed archive`).action(async e=>Sj(`runtime_stage`,{authority:e.authorizeStage===!0?`runtime:stage`:``,archivePath:e.archive,expectedArchiveSha256:e.archiveSha256,packageVersion:e.packageVersion,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot},...[`maxAggregateRssBytes`,`maxNewOutputBytes`,`minFreeDiskBytes`,`maxCapturedOutputBytes`].some(t=>e[t]!==void 0)?{resourceBounds:{maxAggregateRssBytes:Number(e.maxAggregateRssBytes??1024**3),minFreeDiskBytes:Number(e.minFreeDiskBytes??256*1024**2),maxNewOutputBytes:Number(e.maxNewOutputBytes??512*1024**2),maxCapturedOutputBytes:Number(e.maxCapturedOutputBytes??1024**2)}}:{}})),gj.command(`runtime:admit`).description(`Explicitly publish the existing admission for an exact completed stage`).requiredOption(`--stage-id <digest>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--expected-prior <digest>`,`SHA-256 of the exact current private admission bytes`).option(`--expected-absent`,`Explicitly require no current admission`).option(`--authorize-admit`,`Explicit authority for the final admission write`).action(async e=>{if(e.expectedPrior===void 0==(e.expectedAbsent!==!0))throw Error(`Choose exactly one of --expected-prior or --expected-absent.`);return Sj(`runtime_admit`,{authority:e.authorizeAdmit===!0?`runtime:admit`:``,stageId:e.stageId,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,expectedPriorAdmissionSha256:e.expectedAbsent===!0?null:e.expectedPrior})}),gj.command(`create`).requiredOption(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--milestone <number>`).option(`--parent <number>`).action(async e=>Sj(`issue_create`,{title:e.title,body:xj(e.body,e.bodyFile),issueType:e.type,points:vj(e.points),priority:e.priority,labels:yj(e.labels),blockedBy:bj(e.blockedBy),milestone:vj(e.milestone),parentIssueNumber:vj(e.parent)})),gj.command(`start`).option(`--issue <number>`).option(`--request <text>`).option(`--request-id <id>`,`Stable retry identity for a new issue start`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--milestone <number>`).option(`--parent <number>`).option(`--branch <branch>`).option(`--resume-created`).action(async e=>Sj(`issue_start`,{issueNumber:vj(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:xj(e.body,e.bodyFile),issueType:e.type,points:vj(e.points),priority:e.priority,labels:yj(e.labels),blockedBy:bj(e.blockedBy),milestone:vj(e.milestone),parentIssueNumber:vj(e.parent),branch:e.branch,resumeCreated:e.resumeCreated===!0}));for(let e of[`list`,`search`])gj.command(e).option(`--query <text>`,`Literal text to search in the selected repository`).option(`--state <state>`).option(`--labels <labels>`).option(`--parent <number>`).option(`--type <type>`).option(`--project-status <status>`).option(`--updated-since <timestamp>`).option(`--page <number>`).option(`--per-page <number>`).action(async t=>Sj(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:yj(t.labels),parentIssueNumber:vj(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:vj(t.page),perPage:vj(t.perPage)}));gj.command(`update`).requiredOption(`--issue <number>`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--milestone <number>`).option(`--parent <number>`).option(`--state <state>`).option(`--preserve-history`,`Preserve the previous title and body before a rewrite`).option(`--close-reason <reason>`).option(`--superseded-by <number>`).option(`--park`,`Park execution while retaining the issue worktree`).action(async e=>Sj(`issue_update`,{issueNumber:vj(e.issue),title:e.title,body:xj(e.body,e.bodyFile),issueType:e.type,points:vj(e.points),priority:e.priority,labels:yj(e.labels),blockedBy:bj(e.blockedBy),milestone:vj(e.milestone),parentIssueNumber:vj(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:vj(e.supersededBy),park:e.park===!0||void 0})),gj.command(`info`).requiredOption(`--issue <number>`).action(async e=>Sj(`issue_info`,{issueNumber:vj(e.issue)})),gj.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>Sj(`issue_ready_check`,{issueNumber:vj(e.issue)}));for(let e of[`parent`,`blockers`])gj.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await oS(`issue_info`,{issueNumber:vj(t.issue)},_j());Cj(e===`parent`?{issueNumber:vj(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:vj(t.issue),blockedBy:n.blockedBy})});gj.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await iS(_j(),`subissues`);Cj({issueNumber:vj(e.issue),subissues:await V_(t,Number(e.issue))})}),gj.command(`pr:create`).requiredOption(`--issue <number>`).option(`--title <title>`).option(`--body-file <path>`).option(`--head <branch>`,`Select one GitHub-linked issue branch`).option(`--ready`).option(`--dry-run`).action(async e=>Sj(`issue_pr_create`,{issueNumber:vj(e.issue),title:e.title,body:xj(void 0,e.bodyFile),headBranch:e.head,draft:e.ready!==!0,dryRun:e.dryRun===!0})),gj.command(`pr:info`).option(`--issue <number>`).option(`--pr <number>`).action(async e=>Sj(`issue_pr_info`,{issueNumber:vj(e.issue),prNumber:vj(e.pr)})),gj.command(`pr:list`).option(`--state <state>`,`open, closed or all`,`open`).action(async e=>{if(![`open`,`closed`,`all`].includes(e.state))throw Error(`Invalid PR state.`);Cj(await _v(await iS(_j(),`pr:list`),e.state))}),gj.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{Cj(await vv(await iS(_j(),`pr:checks`),Number(e.pr)))}),gj.command(`pr:review`).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).requiredOption(`--artifact <path>`,`Path to a UTF-8 JSON review artifact file (not inline JSON)`).option(`--dry-run`).action(async e=>Sj(`issue_pr_review`,{issueNumber:vj(e.issue),prNumber:vj(e.pr),artifact:l(e.artifact,`utf8`),dryRun:e.dryRun===!0}));for(let[e,t]of[[`pr:merge`,`issue_pr_merge`],[`finish`,`issue_finish`]])gj.command(e).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).option(`--strategy <method>`).option(`--reviewed-head <sha>`).option(`--dry-run`).action(async e=>Sj(t,{issueNumber:vj(e.issue),prNumber:vj(e.pr),strategy:e.strategy,reviewedHeadSha:e.reviewedHead,dryRun:e.dryRun===!0}));gj.command(`worktree:transition:inspect`).requiredOption(`--issue <number>`).requiredOption(`--purpose <purpose>`,`active-resume or merged-cleanup`).option(`--disposition <disposition>`,`retain (default) or explicitly unheld remove`).option(`--terminal-pr <number>`).option(`--retained-holds <comment-ids>`,`Comma-separated native retained-hold comment IDs`).option(`--retained-admission <path>`).option(`--retained-archive <path>`).action(async e=>Sj(`issue_worktree_transition_inspect`,{issueNumber:vj(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:vj(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:bj(e.retainedHolds)},...e.retainedAdmission===void 0?{}:{retainedAdmissionPath:e.retainedAdmission},...e.retainedArchive===void 0?{}:{retainedArchivePath:e.retainedArchive}})),gj.command(`worktree:transition:apply`).requiredOption(`--plan <path>`).requiredOption(`--plan-id <digest>`).requiredOption(`--relinquishment-comment <id>`).requiredOption(`--acceptance-comment <id>`).option(`--authorize-transition`,`Explicit authority for this exact independently accepted plan`).action(async e=>Sj(`issue_worktree_transition_apply`,{authority:e.authorizeTransition===!0?`worktree:transition`:``,planPath:e.plan,expectedPlanId:e.planId,relinquishmentCommentId:Number(e.relinquishmentComment),acceptanceCommentId:Number(e.acceptanceComment)})),gj.command(`migrate:legacy-issues`).requiredOption(`--input-file <path>`,`Offline legacy issue inventory JSON`).action(e=>{let t=aA(JSON.parse(l(e.inputFile,`utf8`)));process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}),gj.command(`config:resolve`).description(`Read the effective GitHub destination and admission digest`).action(async()=>{let e=await iS(_j(),`config:resolve`);Cj({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await bv(e,void 0,void 0,`development`)})}),gj.command(`mcp:serve`).action(async()=>tA(_j())),gj.parseAsync(process.argv).catch(e=>{process.stderr.write(`ai-delivery: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1});export{};
|
|
271
|
+
deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),ak=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),ok=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mO(),n=$(),r=sO(),i=oO();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),sk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=bO(),n=mO(),r=oO(),i=ok();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),ck=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mO(),n=$(),r=oO(),i=oO();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),lk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=oO();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),uk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:mO().validateUnion,error:{message:`must match a schema in anyOf`}}})),dk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),fk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=oO();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),pk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=oO(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),mk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=oO();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),hk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$O(),n=tk(),r=ek(),i=nk(),a=rk(),o=ik(),s=ak(),c=ok(),l=sk(),u=ck(),d=lk(),f=uk(),p=dk(),m=fk(),h=pk(),g=mk();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),gk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),_k=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[gk().default]})),vk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),yk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=zO(),n=QO(),r=hk(),i=_k(),a=vk();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),bk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),xk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$(),n=bk(),r=CO(),i=SO(),a=oO();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Sk=Ce({$id:()=>wk,$schema:()=>Ck,default:()=>kk,definitions:()=>Ek,properties:()=>Ok,title:()=>Tk,type:()=>Dk}),Ck,wk,Tk,Ek,Dk,Ok,kk,Ak=Se((()=>{Ck=`http://json-schema.org/draft-07/schema#`,wk=`http://json-schema.org/draft-07/schema#`,Tk=`Core schema meta-schema`,Ek={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:[]}},Dk=[`object`,`boolean`],Ok={$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:`#`}},kk={$schema:Ck,$id:wk,title:Tk,definitions:Ek,type:Dk,properties:Ok,default:!0}})),jk=D(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var n=IO(),r=yk(),i=xk(),a=(Ak(),Ee(Sk).default),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`,c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=bO();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=$();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=xO();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=SO();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Mk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:T,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}var ee=/[^\\]\\Z/;function T(e){if(ee.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Nk=D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=jk(),n=$(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Pk=D(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=Mk(),r=Nk(),i=$(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),Fk=Te(jk(),1),Ik=Te(Pk(),1);function Lk(){let e=new Fk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ik.default)(e),e}var Rk=class{constructor(e){this._ajv=e??Lk()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},zk=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CE,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},FE,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function Bk(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function Vk(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var Hk=class extends tO{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(uE.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Rk,this.setRequestHandler(qw,e=>this._oninitialize(e)),this.setNotificationHandler(Xw,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(fE,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=uE.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new zk(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=rO(this._capabilities,e)}setRequestHandler(e,t){let n=rw(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=lw(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=tw(sE,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=tw(oT,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=tw(aE,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Vk(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Bk(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:dw.includes(t)?t:uw,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},Iw)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},wE,t):this.request({method:`sampling/createMessage`,params:e},CE,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},FE,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},FE,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},GE,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},Uk=Symbol.for(`mcp.completable`);function Wk(e){return!!e&&typeof e==`object`&&Uk in e}function Gk(e){return e[Uk]?.complete}var Kk;(function(e){e.Completable=`McpCompletable`})(Kk||={});var qk=/^[A-Za-z0-9._-]{1,128}$/;function Jk(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!qk.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Yk(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Xk(e){let t=Jk(e);return Yk(e,t.warnings),t.isValid}var Zk=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Qk=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Hk(e,t)}get experimental(){return this._experimental||={tasks:new Zk(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(aA(rE)),this.server.assertCanSetRequestHandler(aA(sE)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(rE,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=iw(t.inputSchema);return e?QD(e,{strictUnions:!0,pipeStrategy:`input`}):$k})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=iw(t.outputSchema);e&&(n.outputSchema=QD(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(sE,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Q(Z.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Q(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await nw(iw(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=ow(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await nw(iw(e.outputSchema),t.structuredContent);if(!r.success){let e=ow(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Q(Z.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(aA(zE)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(zE,async e=>{switch(e.params.ref.type){case`ref/prompt`:return BE(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return VE(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return sA;let r=rw(n.argsSchema)?.[e.params.argument.name];if(!Wk(r))return sA;let i=Gk(r);return i?oA(await i(e.params.argument.value,e.params.context)):sA}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return sA;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?oA(await r(e.params.argument.value,e.params.context)):sA}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(aA(wT)),this.server.assertCanSetRequestHandler(aA(ET)),this.server.assertCanSetRequestHandler(aA(AT)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(wT,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(ET,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(AT,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Q(Z.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(aA(VT)),this.server.assertCanSetRequestHandler(aA(WT)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(VT,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?iA(t.argsSchema):void 0}))})),this.server.setRequestHandler(WT,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await nw(iw(n.argsSchema),e.params.arguments);if(!r.success){let t=ow(`error`in r?r.error:`Unknown error`);throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:ew(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=ew(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Wk(e instanceof Wl?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Xk(e);let l={title:t,description:n,inputSchema:rA(r),outputSchema:rA(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Xk(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=ew(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=ew(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(nA(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!nA(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},$k={type:`object`,properties:{}};function eA(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function tA(e){return`_def`in e||`_zod`in e||eA(e)}function nA(e){return typeof e!=`object`||!e||tA(e)?!1:Object.keys(e).length===0||Object.values(e).some(eA)}function rA(e){if(e){if(nA(e))return ew(e);if(!tA(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function iA(e){let t=rw(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:sw(t),required:!cw(t)})):[]}function aA(e){let t=rw(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=lw(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function oA(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var sA={completion:{values:[],hasMore:!1}},cA=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
272
|
+
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),lA(t)}clear(){this._buffer=void 0}};function lA(e){return Fw.parse(JSON.parse(e))}function uA(e){return JSON.stringify(e)+`
|
|
273
|
+
`}var dA=class{constructor(e=ie.stdin,t=ie.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new cA({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=uA(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}},fA=JSON.parse(l(new URL(`../package.json`,import.meta.url),`utf8`));if(typeof fA!=`object`||!fA||!(`version`in fA)||typeof fA.version!=`string`||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(fA.version))throw Error(`The adjacent ai-delivery package identity must contain a stable version.`);var pA=fA.version;function mA(e,t){let n=new Qk({name:`ai-delivery`,version:pA}),r=dS;for(let i of r)n.registerTool(i.name,{description:i.description,inputSchema:i.inputSchema},async(n,r)=>{let a=i.inputSchema.safeParse(n);if(!a.success)return{content:[{type:`text`,text:`Invalid arguments for ${i.name}.`}],isError:!0};try{let n=e.signal===void 0?r.signal:AbortSignal.any([e.signal,r.signal]),o=yS(i.name,a.data,{...e,signal:n});t?.add(o);let s;try{s=await o}finally{t?.delete(o)}return{content:[{type:`text`,text:JSON.stringify(s)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}});return n}async function hA(e){Ng(!0);let t=new AbortController,n=new Set,r=mA({...e,signal:t.signal},n),i,a=()=>(i??=(async()=>{t.abort(),await Promise.allSettled(n),await r.close(),process.exit(0)})(),i);process.once(`SIGINT`,()=>{a()}),process.once(`SIGTERM`,()=>{a()}),await r.connect(new dA),process.stderr.write(`ai-delivery MCP server started
|
|
274
|
+
`),await new Promise(()=>{})}var gA=e=>/^(?:area|risk):[^\s:]+$/u.test(e),_A=gA,vA=P({number:j().int().positive(),body:A(),labels:N(A()),trackingParent:M().optional(),resolvedLegacyBlockers:N(P({number:j().int().positive(),state:I([`OPEN`,`CLOSED`])}).strict()).optional(),existingNative:P({blockedBy:N(P({number:j().int().positive(),state:I([`OPEN`,`CLOSED`])}).strict()),issueType:A().optional(),points:j().int().positive().optional(),priority:A().optional(),projectStatus:I([`Todo`,`In Progress`,`Blocked`,`Done`]).optional()}).strict().optional()}).strict();function yA(e){let t=P({issues:N(vA),repositoryLabels:N(A()).optional()}).strict().parse(e),n=t.issues.map(e=>e.number);if(new Set(n).size!==n.length)throw new R(`Legacy issue input repeats an issue number.`);return{mode:`dry-run`,plans:t.issues.map(e=>{let t=e.existingNative,n=t===void 0?void 0:{blockedBy:t.blockedBy,...t.issueType===void 0?{}:{issueType:t.issueType},...t.points===void 0?{}:{points:t.points},...t.priority===void 0?{}:{priority:t.priority},...t.projectStatus===void 0?{}:{projectStatus:t.projectStatus}};return{number:e.number,...CA({body:e.body,labels:e.labels,...n===void 0?{}:{existingNative:n},...e.resolvedLegacyBlockers===void 0?{}:{resolvedLegacyBlockers:e.resolvedLegacyBlockers},...e.trackingParent===void 0?{}:{trackingParent:e.trackingParent}})}}),retiredRepositoryLabels:wA(t.repositoryLabels??[]),schemaVersion:`ai-delivery.legacy-issue-migration@1`,validated:0}}var bA=new Map([[`effort:l`,5],[`effort:m`,3],[`effort:medium`,3],[`effort:s`,2],[`effort:xl`,8],[`effort:xs`,1]]),xA=new Map([[`priority:high`,`P1`],[`priority:p0`,`P0`],[`priority:p1`,`P1`],[`priority:p2`,`P2`],[`priority:p3`,`P3`],[`priority:p4`,`P4`]]),SA=new Map([[`type:bug`,`Bug`],[`type:design`,`Task`],[`type:epic`,`Task`],[`type:feature`,`Feature`],[`type:spike`,`Task`],[`type:task`,`Task`],[`type:tracking`,`Task`]]);function CA(e){let t=[...new Set(e.labels.map(e=>e.trim()).filter(Boolean))],n=TA(e.body),r=kA(e.body,`executionContract`),i=kA(e.body,`dependencyDeclaration`),a=kA(e.body,`related`),o=DA([...e.existingNative?.blockedBy??[],...e.resolvedLegacyBlockers??[]]),s=jA({dependencyDeclaration:i,executionContract:r,related:a}),c=[...new Set([...o.keys(),...s])].sort((e,t)=>e-t),l=new Set(c.filter(e=>o.get(e)!==`CLOSED`));if(t.some(e=>e.toLowerCase()===`type:tracking`)&&e.trackingParent!==!0)throw new R(`Legacy type:tracking requires a native sub-issue relationship before its label can be retired.`);let u=e.trackingParent===!0,d=u?void 0:e.existingNative?.points??PA({...n.points===void 0?{}:{bodyPoint:n.points},executionContract:r,labels:t}),f=e.existingNative?.priority??FA({label:`priority`,labels:t,mapping:xA}),p=e.existingNative?.issueType??FA({label:`issue type`,labels:t,mapping:SA});if(e.existingNative?.projectStatus===`Done`)throw new R(`An open issue cannot retain Project Done during legacy migration.`);let m=NA({existing:e.existingNative?.projectStatus,labels:t,unresolvedBlockers:l}),h=t.filter(gA);h.sort();let g=t.filter(e=>!h.includes(e)).sort();return{body:AA(n.body),clearPoints:u&&e.existingNative?.points!==void 0,native:{blockedBy:c,...p===void 0?{}:{issueType:p},...d===void 0?{}:{points:d},...f===void 0?{}:{priority:f},projectStatus:m},retainedLabels:h,retiredLabels:g}}function wA(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))].filter(e=>!_A(e)).sort((e,t)=>e.localeCompare(t))}function TA(e){let t=e.split(/\r?\n/u),n=t.flatMap((e,t)=>e.trim().toLowerCase()===`## fibonacci points`?[t]:[]);if(n.length===0)return{body:e};if(n.length>1)throw new R(`Found duplicate legacy Fibonacci points sections.`);let r=n[0];if(r===void 0)return{body:e};let i=t.length;for(let e=r+1;e<t.length;e+=1)if(t[e]?.trimStart().startsWith(`## `)===!0){i=e;break}let a=t.slice(r+1,i).map(e=>e.trim()).filter(Boolean);if(a.length!==1||!/^(?:1|2|3|5|8|13)$/u.test(a[0]??``))throw new R(`Legacy Fibonacci points section must contain exactly one supported numeric value.`);return{body:[...t.slice(0,r),...t.slice(i)].join(`
|
|
275
|
+
`),points:Number(a[0])}}function EA(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function DA(e){let t=new Map;for(let n of e){if(!EA(n.number))throw new R(`Native blocked-by relationship evidence is malformed.`);let e=t.get(n.number);if(e!==void 0&&e!==n.state)throw new R(`Native blocker #${String(n.number)} has conflicting relationship states.`);t.set(n.number,n.state)}return t}function OA(e){if(EA(e))return e;if(typeof e!=`string`)return;let t=/^#?([1-9]\d*)$/u.exec(e.trim()),n=t?.[1]===void 0?NaN:Number(t[1]);return EA(n)?n:void 0}function kA(e,t){let n=RegExp(`<!--\\s*${t}:\\s*([\\s\\S]*?)\\s*-->`,`u`).exec(e)?.[1];if(n!==void 0)try{let e=JSON.parse(n);if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`not an object`);return e}catch{throw new R(`Invalid legacy ${t} payload.`)}}function AA(e){return e.replace(/<!--\s*(?:executionContract|dependencyDeclaration|related):[\s\S]*?-->\s*/gu,``).trim()}function jA({dependencyDeclaration:e,executionContract:t,related:n}){let r=[],i=t?.dependencies;if(Array.isArray(i))for(let e of i){if(typeof e!=`object`||!e)continue;let t=e,n=OA(t.issue);t.type===`blockedBy`&&n!==void 0&&r.push(n)}return r.push(...MA(e?.blockedBy)),r.push(...MA(n?.blockedBy)),[...new Set(r)].sort((e,t)=>e-t)}function MA(e){return Array.isArray(e)?e.map(OA).filter(e=>e!==void 0):[]}function NA(e){if(e.unresolvedBlockers.size>0)return`Blocked`;let t=e.labels.some(e=>[`status:in-progress`,`status:review`].includes(e.toLowerCase()));return e.existing===`In Progress`||t?`In Progress`:`Todo`}function PA(e){let t=[];for(let n of e.labels){let e=bA.get(n.toLowerCase());e!==void 0&&t.push(e);let r=/^points:(1|2|3|5|8|13)$/u.exec(n.toLowerCase());r?.[1]!==void 0&&t.push(Number(r[1]))}let n=e.executionContract?.effort;if(typeof n==`string`){let e=n.startsWith(`effort:`)?n:`effort:${n}`,r=bA.get(e.toLowerCase());r!==void 0&&t.push(r)}e.bodyPoint!==void 0&&t.push(e.bodyPoint);let r=[...new Set(t)];if(r.length>1)throw new R(`Found conflicting legacy sizing values: ${r.join(`, `)}.`);let[i]=r;if(i===void 0)throw new R(`Issue has no canonical Fibonacci sizing value; assign native Points before migration.`);return i}function FA({label:e,labels:t,mapping:n}){let r=t.flatMap(e=>{let t=n.get(e.toLowerCase());return t===void 0?[]:[t]}),i=[...new Set(r)];if(i.length>1)throw new R(`Found conflicting legacy ${e} values.`);return i[0]}var IA=class{constructor(e){this._client=e}async*callToolStream(e,t=aE,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof Q){yield{type:`error`,error:e};return}yield{type:`error`,error:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function LA(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&LA(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&LA(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&LA(n,t)}}function RA(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var zA=class extends tO{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Rk,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,cE,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,$T,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,MT,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new IA(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=rO(this._capabilities,e)}setRequestHandler(e,t){let n=rw(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=lw(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=tw(ME,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=RA(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new Q(Z.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new Q(Z.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=tw(oT,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=tw(FE,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new Q(Z.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{LA(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=tw(SE,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Q(Z.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=tw(oT,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Q(Z.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=tw(i.tools||i.toolChoice?wE:CE,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Q(Z.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:uw,capabilities:this._capabilities,clientInfo:this._clientInfo}},Yw,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!dw.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Bk(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&Vk(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},Iw,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},HE,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},Iw,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},QT,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},HT,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},TT,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},DT,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},jT,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},Iw,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},Iw,t)}async callTool(e,t=aE,n){if(this.isToolTaskRequired(e.name))throw new Q(Z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new Q(Z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new Q(Z.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},iE,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=lE.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},BA=D(((e,t)=>{t.exports=a,a.sync=o;var n=De(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function i(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:r(t,n)}function a(e,t,r){n.stat(e,function(n,a){r(n,!n&&i(a,e,t))})}function o(e,t){return i(n.statSync(e),e,t)}})),VA=D(((e,t)=>{t.exports=r,r.sync=i;var n=De(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),HA=D(((e,t)=>{De(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?BA():VA();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),UA=D(((e,t)=>{var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=De(`path`),i=n?`;`:`:`,a=HA(),o=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),s=(e,t)=>{let r=t.colon||i,a=e.match(/\//)||n&&e.match(/\\/)?[``]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(r)],o=n?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=n?o.split(r):[``];return n&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:a,pathExt:s,pathExtExe:o}},c=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:i,pathExt:c,pathExtExe:l}=s(e,t),u=[],d=n=>new Promise((a,s)=>{if(n===i.length)return t.all&&u.length?a(u):s(o(e));let c=i[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=r.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(f(p,n,0))}),f=(e,n,r)=>new Promise((i,o)=>{if(r===c.length)return i(d(n+1));let s=c[r];a(e+s,{pathExt:l},(a,o)=>{if(!a&&o){if(t.all)u.push(e+s);else return i(e+s)}return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};t.exports=c,c.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:i,pathExtExe:c}=s(e,t),l=[];for(let o=0;o<n.length;o++){let s=n[o],u=/^".*"$/.test(s)?s.slice(1,-1):s,d=r.join(u,e),f=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<i.length;e++){let n=f+i[e];try{if(a.sync(n,{pathExt:c})){if(t.all)l.push(n);else return n}}catch{}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw o(e)}})),WA=D(((e,t)=>{var n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),GA=D(((e,t)=>{var n=De(`path`),r=UA(),i=WA();function a(e,t){let a=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=r.sync(e.command,{path:a[i({env:a})],pathExt:t?n.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=n.resolve(s?e.options.cwd:``,l),l}function o(e){return a(e)||a(e,!0)}t.exports=o})),KA=D(((e,t)=>{var n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),qA=D(((e,t)=>{t.exports=/^#!(.*)/})),JA=D(((e,t)=>{var n=qA();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),YA=D(((e,t)=>{var n=De(`fs`),r=JA();function i(e){let t=Buffer.alloc(150),i;try{i=n.openSync(e,`r`),n.readSync(i,t,0,150,0),n.closeSync(i)}catch{}return r(t.toString())}t.exports=i})),XA=D(((e,t)=>{var n=De(`path`),r=GA(),i=KA(),a=YA(),o=process.platform===`win32`,s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){e.file=r(e);let t=e.file&&a(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}function u(e){if(!o)return e;let t=l(e),r=!s.test(t);if(e.options.forceShell||r){let r=c.test(t);e.command=n.normalize(e.command),e.command=i.command(e.command),e.args=e.args.map(e=>i.argument(e,r)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function d(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:u(r)}t.exports=d})),ZA=D(((e,t)=>{var n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),QA=Te(D(((e,t)=>{var n=De(`child_process`),r=XA(),i=ZA();function a(e,t,a){let o=r(e,t,a),s=n.spawn(o.command,o.args,o.options);return i.hookChildProcess(s,o),s}function o(e,t,a){let o=r(e,t,a),s=n.spawnSync(o.command,o.args,o.options);return s.error=s.error||i.verifyENOENTSync(s.status,o),s}t.exports=a,t.exports.spawn=a,t.exports.sync=o,t.exports._parse=r,t.exports._enoent=i}))(),1),$A=ie.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function ej(){let e={};for(let t of $A){let n=ie.env[t];n!==void 0&&(n.startsWith(`()`)||(e[t]=n))}return e}var tj=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new cA({maxBufferSize:e.maxBufferSize}),(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new he)}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,t)=>{this._process=(0,QA.default)(this._serverParams.command,this._serverParams.args??[],{env:{...ej(),...this._serverParams.env},stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`],shell:!1,windowsHide:ie.platform===`win32`,cwd:this._serverParams.cwd}),this._process.on(`error`,e=>{t(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{e()}),this._process.on(`close`,e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{this.onerror?.(e)}),this._process.stdout?.on(`data`,e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on(`error`,e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once(`close`,()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),e.exitCode===null){try{e.kill(`SIGTERM`)}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(e.exitCode===null)try{e.kill(`SIGKILL`)}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw Error(`Not connected`);let n=uA(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}},nj=A().max(128).regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u),rj=F({action:I([`install`,`doctor`,`update`,`rollback`,`remove`]),host:I([`codex`,`claude-code`]),scope:I([`user`,`project`,`local`]),version:nj.optional(),dryRun:M().default(!1),repoRoot:A().min(1)}),ij=F({pid:j().int().positive(),birth:A().min(1)}),aj=F({action:rj.shape.action,targetVersion:nj.nullable(),owner:ij,producerDigest:A().regex(/^sha256:[a-f0-9]{64}$/u),staging:F({path:A(),device:j().int().nonnegative().optional(),inode:j().int().nonnegative().optional()}).optional(),command:Nl(`phase`,[F({phase:L(`idle`)}),F({phase:L(`starting`)}),F({phase:L(`running`),process:ij,tracked:N(ij.extend({pgid:j().int().positive()})).max(256)})])}),oj=F({owner:L(`@aviaratech/ai-delivery.plugin@1`),host:rj.shape.host,scope:rj.shape.scope,projectRoot:A().nullable(),nativeHome:A().min(1),marketplace:A(),currentVersion:nj.nullable(),previousVersion:nj.nullable(),installedPath:A().nullable(),nativeVersion:A().optional(),pending:aj.optional()}),sj=F({owner:L(`@aviaratech/ai-delivery.plugin-version@1`),version:nj,archiveSha256:A().regex(/^[a-f0-9]{64}$/u),files:zl(A(),A().regex(/^[a-f0-9]{64}$/u))}),cj=e=>se(`sha256`).update(e).digest(`hex`);function lj(e){let t=E(e);for(;;){if(n(t)&&o(t).isSymbolicLink())throw Error(`Managed plugin paths must not use symlinks.`);let e=w(t);if(e===t)break;t=e}}function uj(e){let t=p(E(e.repoRoot)),r=E(t,(e.host===`codex`?process.env.CODEX_HOME:process.env.CLAUDE_CONFIG_DIR)??T(oe(),e.host===`codex`?`.codex`:`.claude`)),i=[];for(;!n(r);)i.unshift(C(r)),r=w(r);let a=T(p(r),...i),s=e.scope===`user`?`user`:`${e.scope}-${se(`sha256`).update(t).digest(`hex`).slice(0,16)}`,c=T(oe(),`.cache`,`ai-delivery`,`plugins`,e.host,s);if(lj(c),n(c)&&(!o(c).isDirectory()||o(c).mode&63))throw Error(`Managed plugin directory is not private.`);return{directory:c,projectRoot:t,nativeHome:a,marketplace:`ai-delivery-${s}`,catalog:T(c,`marketplace`),statePath:T(c,`state.json`),tool:e.host===`codex`?`codex`:`claude`}}function dj(e,t){if(!n(t.statePath))return;let r=o(t.statePath);if(!r.isFile()||r.nlink!==1||r.mode&63||r.size>65536)throw Error(`Managed plugin state is unsafe.`);let i=oj.parse(JSON.parse(l(t.statePath,`utf8`)));if(i.nativeHome!==t.nativeHome)throw Error(`Managed plugin state belongs to a different native profile.`);if(i.host!==e.host||i.scope!==e.scope||i.marketplace!==t.marketplace||i.projectRoot!==(e.scope===`user`?null:t.projectRoot))throw Error(`Managed plugin state belongs to a different target.`);return i}function fj(e){let t=Fy().get(e);return t&&!t.status.startsWith(`Z`)?t.identity:void 0}async function pj(e){if(fj(e.owner.pid)===e.owner.birth)throw Error(`A live plugin installer still owns this target.`);if(e.command.phase===`starting`)throw Error(`Interrupted installer command ownership is unknown; preserve its state before recovery.`);if(e.command.phase!==`running`)return;let t={rootPid:e.command.process.pid,rootIdentity:e.command.process.birth,sampled:!0,tracked:new Map(e.command.tracked.map(({pid:e,birth:t,pgid:n})=>[e,{pid:e,identity:t,pgid:n,ppid:0,rssBytes:0,status:``}]))};By(t),await zy(t)}async function mj(e,t,n,r,i){return(await tb(n,[e,...t],r,void 0,{maxAggregateRssBytes:1024**3,minFreeDiskBytes:256*1024**2,maxNewOutputBytes:512*1024**2},void 0,void 0,{starting:()=>i?.({phase:`starting`}),observed:e=>i?.({phase:`running`,process:{pid:e.rootPid,birth:e.rootIdentity},tracked:[...e.tracked.values()].map(({pid:e,identity:t,pgid:n})=>({pid:e,birth:t,pgid:n}))}),idle:()=>i?.({phase:`idle`}),assertQuiescent:()=>{}},{environment:{...process.env,DISABLE_AUTOUPDATER:`1`},cwd:n,maxCapturedOutputBytes:1048576,stdoutOnly:!0,failedOutput:e=>` Native command output: ${e.toString(`utf8`).slice(-2e3)}`})).toString(`utf8`)}function hj(e){let n=c(e,`r`);try{i(n)}finally{t(n)}}function gj(e,t){return T(e.catalog,`versions`,t,`plugins`,`ai-delivery`)}function _j(e,t){return T(e.catalog,`versions`,t)}function vj(e){let t={},n=0,r=(e,i,a)=>{if(a>16)throw Error(`Plugin tree exceeds the depth bound.`);for(let s of d(e).sort()){if(++n>4096)throw Error(`Plugin tree exceeds the entry bound.`);let c=T(e,s),u=`${i}${s}`,d=o(c);if(d.isSymbolicLink()||!d.isDirectory()&&(!d.isFile()||d.nlink!==1))throw Error(`Plugin tree contains links or special files.`);if(d.isDirectory())r(c,`${u}/`,a+1);else{if(d.size>32*1024**2)throw Error(`Plugin file exceeds the size bound.`);t[u]=cj(l(c))}}};return r(e,``,0),t}function yj(e,t){let r=_j(e,t);lj(r);let i=T(r,`version.json`);if(!n(i))throw Error(`No completed immutable plugin unit for ${t}.`);let a=o(i),s=T(r,`archive.tgz`),c=o(s);if(!a.isFile()||a.nlink!==1||a.size>1048576||!c.isFile()||c.nlink!==1||c.size>32*1024**2)throw Error(`Immutable plugin unit metadata is unsafe.`);let u=sj.parse(JSON.parse(l(i,`utf8`)));if(u.version!==t||JSON.stringify(vj(gj(e,t)))!==JSON.stringify(u.files)||cj(l(s))!==u.archiveSha256)throw Error(`Immutable plugin unit integrity changed.`);return u}function bj(e){if(e.length>32*1024**2)throw Error(`Plugin archive exceeds 32 MiB.`);let t=pe(e,{maxOutputLength:128*1024**2}),n=new Map;for(let e=0;e+512<=t.length;){let r=t.subarray(e,e+512);if(r.every(e=>e===0))break;let i=(e,t)=>r.subarray(e,e+t).toString().replace(/\0.*$/su,``).trim(),a=(e,t)=>{let n=i(e,t);if(!/^[0-7]+$/u.test(n))throw Error(`Unsupported tar numeric header.`);return Number.parseInt(n,8)};if([...r].reduce((e,t,n)=>e+(n>=148&&n<156?32:t),0)!==a(148,8))throw Error(`Plugin archive header checksum mismatch.`);let o=`${i(345,155)?`${i(345,155)}/`:``}${i(0,100)}`,s=a(124,12),c=i(156,1);if(!/^package\/[A-Za-z0-9_./-]+$/u.test(o)||o.split(`/`).some(e=>e===`..`||e===`.`)||o.split(`/`).length>16||![``,`0`,`5`].includes(c)||e+512+s>t.length||n.has(o)||n.size>=4096)throw Error(`Unsafe or unsupported plugin archive member.`);c!==`5`&&n.set(o,t.subarray(e+512,e+512+s)),e+=512+Math.ceil(s/512)*512}return n}async function xj(e,t,r,i,a){let c=_j(e,t);if(n(c)){yj(e,t);return}let u=w(c);G_(u);let d=T(u,`.stage-${le()}`);a({path:d}),s(d,{mode:448});let f=o(d);hj(u),a({path:d,device:f.dev,inode:f.ino});let p=!0,g=!1,_,v=e=>{p=e.phase===`idle`,i(e)};try{let n=JSON.parse(await mj(`npm`,[`pack`,`@aviaratech/ai-delivery@${t}`,`--ignore-scripts`,`--json`,`--logs-max`,`0`,`--cache`,T(e.directory,`npm-cache`),`--pack-destination`,d],d,r,v))[0]?.filename;if(typeof n!=`string`||!/^aviaratech-ai-delivery-[A-Za-z0-9.+_-]+\.tgz$/u.test(n))throw Error(`npm returned an unsafe archive path.`);let i=l(T(d,n)),o=bj(i),s=JSON.parse(o.get(`package/package.json`)?.toString()??`null`);if(s?.name!==`@aviaratech/ai-delivery`||s.version!==t)throw Error(`Archive package identity does not match the explicit version.`);let f=T(d,`plugins`,`ai-delivery`);for(let[e,t]of o)if(e.startsWith(`package/plugins/ai-delivery/`)){let n=T(f,e.slice(28));G_(w(n)),y(n,t,{mode:384,flag:`wx`}),hj(n)}let p=JSON.parse(l(T(f,`plugin.json`),`utf8`)),h=JSON.parse(l(T(f,`.claude-plugin/plugin.json`),`utf8`)),g=JSON.parse(l(T(f,`runtime/package.json`),`utf8`));if(p.name!==`ai-delivery`||p.version!==t||h.name!==p.name||h.version!==t||h.packageVersion!==t||h.deliveryCapabilityVersion!==2||g.name!==s.name||g.version!==t)throw Error(`Archive does not contain a coherent self-contained native plugin.`);if((await mj(process.execPath,[T(f,`runtime/dist/cli.js`),`--version`],d,r,v)).trim()!==t)throw Error(`Built native CLI version does not match its archive.`);m(T(d,n),T(d,`archive.tgz`)),hj(T(d,`archive.tgz`)),q_(T(d,`version.json`),{owner:`@aviaratech/ai-delivery.plugin-version@1`,version:t,archiveSha256:cj(i),files:vj(f)}),m(d,c),hj(u),a(void 0),yj(e,t)}catch(e){g=!0,_=e}try{if(p&&n(d)){let e=o(d);if(e.dev!==f.dev||e.ino!==f.ino||!e.isDirectory()||e.isSymbolicLink())throw Error(`Owned staging directory identity changed.`);h(d,{recursive:!0}),hj(u)}p&&a(void 0)}catch(e){_=g?AggregateError([_,e],`Plugin preparation failed and staging cleanup also failed.`):e,g=!0}if(g)throw _}function Sj(e,t){yj(e,t);let n=`./versions/${t}/plugins/ai-delivery`;q_(T(e.catalog,`.agents/plugins/marketplace.json`),{name:e.marketplace,interface:{displayName:`ai-delivery`},plugins:[{name:`ai-delivery`,source:{source:`local`,path:n},policy:{installation:`AVAILABLE`,authentication:`ON_INSTALL`},category:`Productivity`}]}),q_(T(e.catalog,`.claude-plugin/marketplace.json`),{name:e.marketplace,owner:{name:`AviaraTech`},plugins:[{name:`ai-delivery`,source:n,version:t}]})}async function Cj(e,t,n,r){let i=JSON.parse(await mj(t.tool,[`plugin`,`list`,...e.host===`codex`?[`--marketplace`,t.marketplace,`--available`]:[],`--json`],t.projectRoot,n,r));if(e.host===`claude-code`)return N(zl(A(),wl())).parse(i);let a=P({installed:N(zl(A(),wl())),available:N(zl(A(),wl()))}).parse(i);return[...a.installed.map(e=>({...e,installed:!0})),...a.available.map(e=>({...e,installed:!1}))]}function wj(e,t,r){if(e.host===`claude-code`){let e=T(t.nativeHome,`plugins/known_marketplaces.json`);if(!n(e))return!1;if(!o(e).isFile()||o(e).size>1048576)throw Error(`Native marketplace registry is unsafe.`);let r=zl(A(),wl()).parse(JSON.parse(l(e,`utf8`)));if(r[t.marketplace]===void 0)return!1;let i=P({source:P({source:L(`directory`),path:A()}),installLocation:A()}).parse(r[t.marketplace]);if(E(i.source.path)!==t.catalog||E(i.installLocation)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`);return!0}let i=r.filter(e=>e.marketplaceName===t.marketplace);for(let e of i){let n=P({sourceType:L(`local`),source:A()}).parse(e.marketplaceSource);if(E(n.source)!==t.catalog)throw Error(`Native marketplace name belongs to an unmanaged source.`)}return i.length>0}function Tj(e,t,n){let r=n.filter(n=>(n.pluginId??n.id)===`ai-delivery@${t.marketplace}`&&(e.host===`codex`?n.installed===!0:n.scope===e.scope)&&(e.scope===`user`||n.projectPath===t.projectRoot));if(r.length>1)throw Error(`Native plugin readback is ambiguous.`);let i=r[0];if(!i)return;let a=e.host===`codex`?P({source:L(`local`),path:A()}).parse(i.source).path:void 0;return{version:nj.parse(i.version),enabled:M().parse(i.enabled),...typeof i.installPath==`string`?{installedPath:i.installPath}:{},...a?{sourceRoot:a}:{},...i.mcpServers?{mcpServers:zl(A(),wl()).parse(i.mcpServers)}:{}}}function Ej(e){let t=T(e.catalog,`.claude-plugin/marketplace.json`);if(lj(t),!o(t).isFile()||o(t).size>1048576)throw Error(`Managed Claude catalog is unsafe.`);let n=P({name:L(e.marketplace),plugins:N(P({name:A(),version:nj,source:A()}))}).parse(JSON.parse(l(t,`utf8`))).plugins.filter(e=>e.name===`ai-delivery`);if(n.length!==1)throw Error(`Managed Claude catalog selection is ambiguous.`);let r=n[0];if(!r.source.startsWith(`./`)||E(e.catalog,r.source)!==gj(e,r.version))throw Error(`Claude catalog source differs from the immutable managed unit.`);return r}function Dj(e,t,n,r,i=n.version){let a=yj(t,e.host===`claude-code`?i:n.version),o=gj(t,e.host===`claude-code`?i:n.version);if(e.host===`claude-code`&&Ej(t).version!==i)throw Error(`Claude catalog version differs from its native selection.`);if(e.host===`codex`&&E(n.sourceRoot)!==o)throw Error(`Native plugin source differs from the managed version.`);let s=e.host===`codex`?r:o;if(!s)throw Error(`Native cache path is missing.`);if(e.host===`codex`&&E(s)!==T(t.nativeHome,`plugins/cache`,t.marketplace,`ai-delivery`,n.version))throw Error(`Native cache path is outside the managed native selection.`);if(lj(s),JSON.stringify(vj(s))!==JSON.stringify(a.files))throw Error(`Selected native plugin bytes differ from the verified archive.`);if(e.host===`claude-code`&&!P({command:L(`node`),args:Ll([L("${CLAUDE_PLUGIN_ROOT}/dist/mcp-launcher.js")])}).parse(n.mcpServers?.[`ai-delivery`]))throw Error(`Native MCP binding is missing.`);return s}async function Oj(e,t,n){let r=new tj({command:process.execPath,args:[T(e,`dist/mcp-launcher.js`)],cwd:n,env:{PATH:process.env.PATH??``,NODE_OPTIONS:`--max-old-space-size=1024`},stderr:`pipe`,maxBufferSize:1048576}),i=new zA({name:`ai-delivery-plugin-doctor`,version:`1.0.0`});try{if(await i.connect(r,{timeout:3e4}),i.getServerVersion()?.version!==t)throw Error(`MCP server version differs from the selected archive.`);return await i.listTools({},{timeout:3e4}),{configuration:`native_manifest_present`,startup:`ready`,version:t}}catch(e){return{configuration:`native_manifest_present`,startup:`failed`,error:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}finally{await i.close(),await r.close()}}async function kj(e){let t=rj.parse(e);if(t.host===`codex`&&t.scope!==`user`)throw Error(`Codex currently supports user plugin installation; select --scope user.`);if((t.action===`install`||t.action===`update`)&&t.version===void 0)throw Error(`An explicit --version is required for install and update.`);if(t.version!==void 0&&t.action!==`install`&&t.action!==`update`)throw Error(`--version is supported only for install and update; rollback selects the recorded previous version.`);if(![`darwin`,`linux`].includes(process.platform))throw Error(`Plugin management requires the supported POSIX runtime environment.`);let r=uj(t),i=dj(t,r),a={action:t.action,host:t.host,scope:t.scope,version:t.action===`remove`?null:t.version??(t.action===`rollback`?i?.previousVersion:i?.currentVersion)??null,changed:!1,dryRun:t.dryRun,installed:!1,marketplace:r.marketplace,managedDirectory:r.directory,repositoryAdmission:`explicit_stage_and_admit_required`};if(t.dryRun)return a;if(t.action===`doctor`){if(!i||(a.recoveryRequired=i.pending!==void 0,i.pending||!i.currentVersion))return a;yj(r,i.currentVersion);let e=await Cj(t,r,new AbortController().signal),n=wj(t,r,e),o=Tj(t,r,e);if(a.installed=o?.version===i.currentVersion,a.enabled=o?.enabled??!1,i.installedPath&&(a.nativeCachePath=i.installedPath),i.nativeVersion&&(a.nativeVersion=i.nativeVersion),!n||!a.installed)return a.mcp={configuration:`missing`,startup:`not_checked`},a;try{a.nativePluginRoot=Dj(t,r,o,i.installedPath),a.sourceIntegrity=!0,a.skills=d(T(a.nativePluginRoot,`skills`)).sort(),a.mcp=o.enabled?await Oj(a.nativePluginRoot,i.currentVersion,r.projectRoot):{configuration:`disabled`,startup:`not_checked`}}catch(e){a.sourceIntegrity=!1,a.mcp={configuration:`unverified`,startup:`not_checked`,error:(e instanceof Error?e.message:String(e)).slice(0,2e3)}}return a}if(!i&&t.action===`remove`)return a;if(!i&&n(r.directory)&&d(r.directory).length>0)throw Error(`Managed plugin directory contains unrecognized content.`);return G_(r.directory),ly(r.statePath,{projectRoot:r.directory,timeout:200,onReleaseError:e=>{throw e},operation:async()=>{i=dj(t,r);let e=i?.pending!==void 0;if(i?.pending){if(await pj(i.pending),i.pending.producerDigest!==Xy(w(me(import.meta.url))))throw Error(`Interrupted plugin operation belongs to a different controller; resume with its original version.`);let e=i.pending.staging;if(e&&n(e.path)){let t=w(_j(r,i.pending.targetVersion));if(w(e.path)!==t||!/^\.stage-[a-f0-9-]{36}$/u.test(e.path.slice(t.length+1)))throw Error(`Recorded staging path is outside this version target.`);lj(e.path);let n=o(e.path);if(!n.isDirectory()||(e.device===void 0?d(e.path).length!==0:n.dev!==e.device||n.ino!==e.inode))throw Error(`Interrupted staging directory ownership is unresolved.`);h(e.path,{recursive:!0}),hj(t)}if(i.pending.action!==t.action||i.pending.targetVersion!==a.version)throw Error(`Resume the interrupted original plugin command before selecting a different operation.`)}if((t.action===`update`||t.action===`rollback`)&&(!i||t.action===`update`&&!i.currentVersion))throw Error(`Install a managed plugin before updating or rolling it back.`);let s=t.action===`remove`?null:a.version;if(s===null&&t.action!==`remove`)throw Error(`No previous managed plugin version is available.`);let c=i?.currentVersion??null;i??={owner:`@aviaratech/ai-delivery.plugin@1`,host:t.host,scope:t.scope,projectRoot:t.scope===`user`?null:r.projectRoot,nativeHome:r.nativeHome,marketplace:r.marketplace,currentVersion:null,previousVersion:null,installedPath:null};let l=fj(process.pid);if(!l)throw Error(`Installer owner identity is unknown.`);i.pending={action:t.action,targetVersion:s,owner:{pid:process.pid,birth:l},producerDigest:Xy(w(me(import.meta.url))),command:{phase:`idle`}},q_(r.statePath,i);let u=new AbortController,f=()=>u.abort();process.once(`SIGINT`,f),process.once(`SIGTERM`,f);let p=e=>{i.pending.command=e,q_(r.statePath,i)},m=e=>mj(r.tool,e,r.projectRoot,u.signal,p),g=`ai-delivery@${r.marketplace}`,_=t.host===`codex`?[`plugin`,`remove`,g,`--json`]:[`plugin`,`uninstall`,g,`--scope`,t.scope,`--keep-data`],v=t.host===`codex`?[`plugin`,`add`,g,`--json`]:[`plugin`,`install`,g,`--scope`,t.scope],y=!1;try{if(i.nativeVersion=(await m([`--version`])).trim(),t.host===`claude-code`&&!(await m([`plugin`,`uninstall`,`--help`])).includes(`--keep-data`))throw Error(`This Claude Code version cannot preserve plugin data; upgrade the native tool first.`);process.stderr.write(`ai-delivery.plugin ${JSON.stringify({action:t.action,host:t.host,scope:t.scope,stage:s?`prepare_version`:`native_remove`,version:s})}\n`);let n=await Cj(t,r,u.signal,p),o=wj(t,r,n),l=Tj(t,r,n);if(l&&!c&&!(e&&l.version===s))throw Error(`Existing native plugin is not owned by managed state.`);let d=l?.version;if(l&&e&&t.host===`claude-code`&&(d=Ej(r).version,d!==c&&d!==s))throw Error(`Interrupted native selection has an incompatible catalog version.`);l&&Dj(t,r,l,l.version===c?i.installedPath:T(r.nativeHome,`plugins/cache`,r.marketplace,`ai-delivery`,l.version),d),s&&(await xj(r,s,u.signal,p,e=>{e?i.pending.staging=e:delete i.pending.staging,q_(r.statePath,i)}),y=!0,Sj(r,s),o||await m([`plugin`,`marketplace`,`add`,r.catalog,...t.host===`codex`?[`--json`]:[`--scope`,t.scope]])),l&&(l.version!==s||t.action===`remove`)&&(y=!0,await m(_));let f=i.installedPath;if(s){let e=await m(v);t.host===`codex`&&(f=P({installedPath:A()}).parse(JSON.parse(e)).installedPath)}let h=await Cj(t,r,u.signal,p);if(!wj(t,r,h)&&s)throw Error(`Native marketplace registration is missing.`);let g=Tj(t,r,h);if(s?g?.version!==s:g!==void 0)throw Error(`Native installation readback does not match the selected version.`);if(s&&(Dj(t,r,g,g?.installedPath??f),!g.enabled))throw Error(`Native plugin selection is disabled.`);return i.currentVersion=s,c!==s&&(i.previousVersion=c),i.installedPath=s?g?.installedPath??f:null,delete i.pending,q_(r.statePath,i),a.version=s,a.changed=c!==s,a.installed=s!==null,a.restartRequired=!0,s&&(a.nativePluginRoot=t.host===`codex`?i.installedPath??gj(r,s):gj(r,s)),a}catch(t){if(!e&&!u.signal.aborted&&!y&&i.pending?.command.phase===`idle`&&i.pending.staging===void 0){delete i.pending;try{q_(r.statePath,i)}catch(e){throw AggregateError([t,e],`Plugin preparation failed and pending-state cleanup also failed.`)}}if(y&&c)try{Sj(r,c)}catch{}throw t}finally{process.removeListener(`SIGINT`,f),process.removeListener(`SIGTERM`,f)}}})}var Aj=new Ve;Aj.name(`ai-delivery`).description(`Generic GitHub issue and pull request delivery`).version(pA).option(`--identity <name>`,`Configured author or reviewer identity`).option(`--personal-auth`,`Explicit legacy personal-token author override`).option(`--repo <owner/name>`,`GitHub repository owner/name; works from any directory`).option(`--repo-root <path>`,`Launch directory or explicit clone for local operations`,process.cwd());for(let e=2;e<process.argv.length;e++){let t=process.argv[e],n=Aj.options.find(e=>e.long===t.split(`=`)[0]||e.short===t);if(n){n.required&&!t.includes(`=`)&&e++;continue}t===`plugin`&&Aj.enablePositionalOptions();break}function jj(){let e=Aj.opts(),t=(e.identity??process.env.AI_DELIVERY_IDENTITY)?.trim()||void 0;return{repoRoot:e.repoRoot,...t===void 0?{}:{identity:t},personalAuth:e.personalAuth===!0,...e.repo===void 0?{}:{repo:e.repo}}}function Mj(e){return e===void 0?void 0:Number(e)}function Nj(e){return e===void 0?void 0:e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Pj(e){return Nj(e)?.map(Number)}function Fj(e,t){if(e!==void 0&&t!==void 0)throw Error(`Pass either --body or --body-file.`);return t===void 0?e:l(t,`utf8`)}function Ij(e,t){return yS(e,t,jj()).then(t=>Ge(e,t))}function Lj(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}var Rj=Aj.command(`plugin`).description(`Manage the ai-delivery native plugin`);for(let e of[`install`,`doctor`,`update`,`rollback`,`remove`]){let t=Rj.command(e).requiredOption(`--host <host>`,`Native host: codex or claude-code`).option(`--scope <scope>`,`Native scope: user, project, or local; Codex supports user`,`user`).option(`--dry-run`,`Describe the selected target without changing files or contacting native tools`).option(`--json`,`Print the result as JSON`);(e===`install`||e===`update`)&&t.requiredOption(`--version <version>`,`Explicit published package version`),t.action(async t=>{let n=await kj({action:e,host:t.host,scope:t.scope,...t.version===void 0?{}:{version:t.version},dryRun:t.dryRun===!0,repoRoot:jj().repoRoot});if(t.json){Lj(n);return}process.stdout.write(`${n.dryRun?`Dry run: `:``}${n.host} ${n.scope}: ${e}; version ${n.version??`none`}; installed ${n.installed}; changed ${n.changed}\n`),n.mcp&&process.stdout.write(`Bundled MCP startup: ${n.mcp.startup}${n.mcp.error?` (${n.mcp.error})`:``}\n`),n.recoveryRequired&&process.stdout.write(`Resume the interrupted original plugin command to recover this target.
|
|
276
|
+
`)})}Aj.command(`runtime:stage`).description(`Stage a reviewed archive in a private directory; does not activate or admit it`).requiredOption(`--archive <path>`).requiredOption(`--archive-sha256 <digest>`).requiredOption(`--package-version <version>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--native-plugin-root <path>`,`Bind the exact reviewed native plugin root`).option(`--max-aggregate-rss-bytes <bytes>`,`Sampled controller plus children RSS limit`).option(`--max-new-output-bytes <bytes>`,`Owned stage and metadata output limit`).option(`--min-free-disk-bytes <bytes>`,`Required free disk headroom`).option(`--max-captured-output-bytes <bytes>`,`Retained command log cap; defaults to 1 MiB`).option(`--authorize-stage`,`Explicit authority to stage this reviewed archive`).action(async e=>Ij(`runtime_stage`,{authority:e.authorizeStage===!0?`runtime:stage`:``,archivePath:e.archive,expectedArchiveSha256:e.archiveSha256,packageVersion:e.packageVersion,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,...e.nativePluginRoot===void 0?{}:{nativePluginRoot:e.nativePluginRoot},...[`maxAggregateRssBytes`,`maxNewOutputBytes`,`minFreeDiskBytes`,`maxCapturedOutputBytes`].some(t=>e[t]!==void 0)?{resourceBounds:{maxAggregateRssBytes:Number(e.maxAggregateRssBytes??1024**3),minFreeDiskBytes:Number(e.minFreeDiskBytes??256*1024**2),maxNewOutputBytes:Number(e.maxNewOutputBytes??512*1024**2),maxCapturedOutputBytes:Number(e.maxCapturedOutputBytes??1024**2)}}:{}})),Aj.command(`runtime:admit`).description(`Explicitly publish the existing admission for an exact completed stage`).requiredOption(`--stage-id <digest>`).requiredOption(`--source-commit <sha>`).requiredOption(`--config-digest <digest>`).requiredOption(`--runtime-directory <path>`).option(`--expected-prior <digest>`,`SHA-256 of the exact current private admission bytes`).option(`--expected-absent`,`Explicitly require no current admission`).option(`--authorize-admit`,`Explicit authority for the final admission write`).action(async e=>{if(e.expectedPrior===void 0==(e.expectedAbsent!==!0))throw Error(`Choose exactly one of --expected-prior or --expected-absent.`);return Ij(`runtime_admit`,{authority:e.authorizeAdmit===!0?`runtime:admit`:``,stageId:e.stageId,expectedSourceCommit:e.sourceCommit,expectedConfigDigest:e.configDigest,runtimeDirectory:e.runtimeDirectory,expectedPriorAdmissionSha256:e.expectedAbsent===!0?null:e.expectedPrior})}),Aj.command(`create`).requiredOption(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--milestone <number>`).option(`--parent <number>`).action(async e=>Ij(`issue_create`,{title:e.title,body:Fj(e.body,e.bodyFile),issueType:e.type,points:Mj(e.points),priority:e.priority,labels:Nj(e.labels),blockedBy:Pj(e.blockedBy),milestone:Mj(e.milestone),parentIssueNumber:Mj(e.parent)})),Aj.command(`start`).option(`--issue <number>`).option(`--request <text>`).option(`--request-id <id>`,`Stable retry identity for a new issue start`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--milestone <number>`).option(`--parent <number>`).option(`--branch <branch>`).option(`--resume-created`).action(async e=>Ij(`issue_start`,{issueNumber:Mj(e.issue),request:e.request,requestId:e.requestId,title:e.title,body:Fj(e.body,e.bodyFile),issueType:e.type,points:Mj(e.points),priority:e.priority,labels:Nj(e.labels),blockedBy:Pj(e.blockedBy),milestone:Mj(e.milestone),parentIssueNumber:Mj(e.parent),branch:e.branch,resumeCreated:e.resumeCreated===!0}));for(let e of[`list`,`search`])Aj.command(e).option(`--query <text>`,`Literal text to search in the selected repository`).option(`--state <state>`).option(`--labels <labels>`).option(`--parent <number>`).option(`--type <type>`).option(`--project-status <status>`).option(`--updated-since <timestamp>`).option(`--page <number>`).option(`--per-page <number>`).action(async t=>Ij(e===`list`?`issue_list`:`issue_search`,{query:t.query,state:t.state,labels:Nj(t.labels),parentIssueNumber:Mj(t.parent),issueType:t.type,projectStatus:t.projectStatus,updatedSince:t.updatedSince,page:Mj(t.page),perPage:Mj(t.perPage)}));Aj.command(`update`).requiredOption(`--issue <number>`).option(`--title <title>`).option(`--body <markdown>`).option(`--body-file <path>`).option(`--type <type>`).option(`--points <number>`).option(`--priority <priority>`).option(`--labels <labels>`).option(`--blocked-by <numbers>`).option(`--milestone <number>`).option(`--parent <number>`).option(`--state <state>`).option(`--preserve-history`,`Preserve the previous title and body before a rewrite`).option(`--close-reason <reason>`).option(`--superseded-by <number>`).option(`--park`,`Park execution while retaining the issue worktree`).action(async e=>Ij(`issue_update`,{issueNumber:Mj(e.issue),title:e.title,body:Fj(e.body,e.bodyFile),issueType:e.type,points:Mj(e.points),priority:e.priority,labels:Nj(e.labels),blockedBy:Pj(e.blockedBy),milestone:Mj(e.milestone),parentIssueNumber:Mj(e.parent),state:e.state,preserveHistory:e.preserveHistory===!0||void 0,closeReason:e.closeReason,supersededBy:Mj(e.supersededBy),park:e.park===!0||void 0})),Aj.command(`info`).requiredOption(`--issue <number>`).action(async e=>Ij(`issue_info`,{issueNumber:Mj(e.issue)})),Aj.command(`ready:check`).requiredOption(`--issue <number>`).action(async e=>Ij(`issue_ready_check`,{issueNumber:Mj(e.issue)}));for(let e of[`parent`,`blockers`])Aj.command(e).requiredOption(`--issue <number>`).action(async t=>{let n=await yS(`issue_info`,{issueNumber:Mj(t.issue)},jj());Lj(e===`parent`?{issueNumber:Mj(t.issue),parentIssueNumber:n.parentIssueNumber}:{issueNumber:Mj(t.issue),blockedBy:n.blockedBy})});Aj.command(`subissues`).requiredOption(`--issue <number>`).action(async e=>{let t=await _S(jj(),`subissues`);Lj({issueNumber:Mj(e.issue),subissues:await B_(t,Number(e.issue))})}),Aj.command(`pr:create`).description(`Create a PR from a linked issue branch, or promote an existing associated PR with --head and --ready.`).requiredOption(`--issue <number>`).option(`--pr <number>`,`Exact existing PR selector; never creates a replacement`).option(`--non-closing`,`Retain the issue OPEN using native non-closing reference proof`).option(`--title <title>`).option(`--body-file <path>`).option(`--head <branch>`,`Explicit remote head; existing PR promotion verifies its native issue association`).option(`--ready`,`Publish ready, or promote the author-owned PR selected by --head`).option(`--dry-run`).action(async e=>Ij(`issue_pr_create`,{issueNumber:Mj(e.issue),prNumber:Mj(e.pr),nonClosing:e.nonClosing,title:e.title,body:Fj(void 0,e.bodyFile),headBranch:e.head,draft:e.ready!==!0,dryRun:e.dryRun===!0})),Aj.command(`pr:info`).description(`Inspect an exact PR; combine --issue and --pr to verify its native closing-issue association.`).option(`--non-closing`,`Verify an exact native non-closing PR-to-issue reference`).option(`--issue <number>`,`Issue to verify; issue-only lookup requires a GitHub-linked branch`).option(`--pr <number>`,`Exact PR number; include --issue after issue branch links are replaced on publication`).action(async e=>Ij(`issue_pr_info`,{issueNumber:Mj(e.issue),prNumber:Mj(e.pr),nonClosing:e.nonClosing})),Aj.command(`pr:list`).option(`--state <state>`,`open, closed or all`,`open`).action(async e=>{if(![`open`,`closed`,`all`].includes(e.state))throw Error(`Invalid PR state.`);Lj(await Av(await _S(jj(),`pr:list`),e.state))}),Aj.command(`pr:checks`).requiredOption(`--pr <number>`).action(async e=>{Lj(await jv(await _S(jj(),`pr:checks`),Number(e.pr)))}),Aj.command(`pr:review`).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).requiredOption(`--artifact <path>`,`Path to a UTF-8 JSON review artifact file (not inline JSON)`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`).action(async e=>Ij(`issue_pr_review`,{issueNumber:Mj(e.issue),prNumber:Mj(e.pr),artifact:l(e.artifact,`utf8`),dryRun:e.dryRun===!0,nonClosing:e.nonClosing}));for(let[e,t]of[[`pr:merge`,`issue_pr_merge`],[`finish`,`issue_finish`]])Aj.command(e).requiredOption(`--issue <number>`).requiredOption(`--pr <number>`).option(`--strategy <method>`).option(`--reviewed-head <sha>`).option(`--non-closing`,`Retain the referenced issue OPEN; finish refuses this mode`).option(`--dry-run`).action(async e=>Ij(t,{issueNumber:Mj(e.issue),prNumber:Mj(e.pr),strategy:e.strategy,reviewedHeadSha:e.reviewedHead,dryRun:e.dryRun===!0,nonClosing:e.nonClosing}));Aj.command(`worktree:transition:inspect`).requiredOption(`--issue <number>`).requiredOption(`--purpose <purpose>`,`active-resume or merged-cleanup`).option(`--disposition <disposition>`,`retain (default) or explicitly unheld remove`).option(`--terminal-pr <number>`).option(`--retained-holds <comment-ids>`,`Comma-separated native retained-hold comment IDs`).option(`--retained-admission <path>`).option(`--retained-archive <path>`).action(async e=>Ij(`issue_worktree_transition_inspect`,{issueNumber:Mj(e.issue),purpose:e.purpose,...e.disposition===void 0?{}:{disposition:e.disposition},...e.terminalPr===void 0?{}:{terminalPrNumber:Mj(e.terminalPr)},...e.retainedHolds===void 0?{}:{retainedHoldCommentIds:Pj(e.retainedHolds)},...e.retainedAdmission===void 0?{}:{retainedAdmissionPath:e.retainedAdmission},...e.retainedArchive===void 0?{}:{retainedArchivePath:e.retainedArchive}})),Aj.command(`worktree:transition:apply`).requiredOption(`--plan <path>`).requiredOption(`--plan-id <digest>`).requiredOption(`--relinquishment-comment <id>`).requiredOption(`--acceptance-comment <id>`).option(`--authorize-transition`,`Explicit authority for this exact independently accepted plan`).action(async e=>Ij(`issue_worktree_transition_apply`,{authority:e.authorizeTransition===!0?`worktree:transition`:``,planPath:e.plan,expectedPlanId:e.planId,relinquishmentCommentId:Number(e.relinquishmentComment),acceptanceCommentId:Number(e.acceptanceComment)})),Aj.command(`migrate:legacy-issues`).requiredOption(`--input-file <path>`,`Offline legacy issue inventory JSON`).action(e=>{let t=yA(JSON.parse(l(e.inputFile,`utf8`)));process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}),Aj.command(`config:resolve`).description(`Read the effective GitHub destination and admission digest`).action(async()=>{let e=await _S(jj(),`config:resolve`);Lj({configDigest:e.configuration?.configDigest,routing:e.configuration?.routing,reviewRoute:await Nv(e,void 0,void 0,`development`)})}),Aj.command(`mcp:serve`).action(async()=>hA(jj())),Aj.parseAsync(process.argv).catch(e=>{process.stderr.write(`ai-delivery: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1});export{};
|