@aipt/cli 0.1.18 → 0.1.23

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.
@@ -1,47 +1,48 @@
1
- var Ym=Object.create;var ll=Object.defineProperty;var Hm=Object.getOwnPropertyDescriptor;var Xm=Object.getOwnPropertyNames;var Zm=Object.getPrototypeOf,Qm=Object.prototype.hasOwnProperty;var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var eg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Xm(t))!Qm.call(e,a)&&a!==r&&ll(e,a,{get:()=>t[a],enumerable:!(n=Hm(t,a))||n.enumerable});return e};var Ir=(e,t,r)=>(r=e!=null?Ym(Zm(e)):{},eg(t||!e||!e.__esModule?ll(r,"default",{value:e,enumerable:!0}):r,e));var tn=R(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.regexpCode=G.getEsmExportName=G.getProperty=G.safeStringify=G.stringify=G.strConcat=G.addCodeArg=G.str=G._=G.nil=G._Code=G.Name=G.IDENTIFIER=G._CodeOrName=void 0;var Qr=class{};G._CodeOrName=Qr;G.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var zt=class extends Qr{constructor(t){if(super(),!G.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};G.Name=zt;var Je=class extends Qr{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof zt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};G._Code=Je;G.nil=new Je("");function dl(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Zi(r,t[n]),r.push(e[++n]);return new Je(r)}G._=dl;var Xi=new Je("+");function pl(e,...t){let r=[en(e[0])],n=0;for(;n<t.length;)r.push(Xi),Zi(r,t[n]),r.push(Xi,en(e[++n]));return tg(r),new Je(r)}G.str=pl;function Zi(e,t){t instanceof Je?e.push(...t._items):t instanceof zt?e.push(t):e.push(ag(t))}G.addCodeArg=Zi;function tg(e){let t=1;for(;t<e.length-1;){if(e[t]===Xi){let r=rg(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function rg(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof zt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof zt))return`"${e}${t.slice(1)}`}function ng(e,t){return t.emptyStr()?e:e.emptyStr()?t:pl`${e}${t}`}G.strConcat=ng;function ag(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:en(Array.isArray(e)?e.join(","):e)}function ig(e){return new Je(en(e))}G.stringify=ig;function en(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}G.safeStringify=en;function og(e){return typeof e=="string"&&G.IDENTIFIER.test(e)?new Je(`.${e}`):dl`[${e}]`}G.getProperty=og;function sg(e){if(typeof e=="string"&&G.IDENTIFIER.test(e))return new Je(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}G.getEsmExportName=sg;function cg(e){return new Je(e.toString())}G.regexpCode=cg});var to=R(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.ValueScope=xe.ValueScopeName=xe.Scope=xe.varKinds=xe.UsedValueState=void 0;var Te=tn(),Qi=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},ua;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(ua||(xe.UsedValueState=ua={}));xe.varKinds={const:new Te.Name("const"),let:new Te.Name("let"),var:new Te.Name("var")};var fa=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Te.Name?t:this.name(t)}name(t){return new Te.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};xe.Scope=fa;var ma=class extends Te.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Te._)`.${new Te.Name(r)}[${n}]`}};xe.ValueScopeName=ma;var lg=(0,Te._)`\n`,eo=class extends fa{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?lg:Te.nil}}get(){return this._scope}name(t){return new ma(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:i}=a,o=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[i];if(s){let l=s.get(o);if(l)return l}else s=this._values[i]=new Map;s.set(o,a);let c=this._scope[i]||(this._scope[i]=[]),d=c.length;return c[d]=r.ref,a.setValue(r,{property:i,itemIndex:d}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Te._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let i=Te.nil;for(let o in t){let s=t[o];if(!s)continue;let c=n[o]=n[o]||new Map;s.forEach(d=>{if(c.has(d))return;c.set(d,ua.Started);let l=r(d);if(l){let p=this.opts.es5?xe.varKinds.var:xe.varKinds.const;i=(0,Te._)`${i}${p} ${d} = ${l};${this.opts._n}`}else if(l=a?.(d))i=(0,Te._)`${i}${l}${this.opts._n}`;else throw new Qi(d);c.set(d,ua.Completed)})}return i}};xe.ValueScope=eo});var x=R(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var F=tn(),et=to(),Rt=tn();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Rt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Rt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Rt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Rt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Rt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Rt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Rt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Rt.Name}});var wa=to();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return wa.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return wa.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return wa.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return wa.varKinds}});V.operators={GT:new F._Code(">"),GTE:new F._Code(">="),LT:new F._Code("<"),LTE:new F._Code("<="),EQ:new F._Code("==="),NEQ:new F._Code("!=="),NOT:new F._Code("!"),OR:new F._Code("||"),AND:new F._Code("&&"),ADD:new F._Code("+")};var ht=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ro=class extends ht{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?et.varKinds.var:this.varKind,a=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${a};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=kr(this.rhs,t,r)),this}get names(){return this.rhs instanceof F._CodeOrName?this.rhs.names:{}}},ga=class extends ht{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof F.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=kr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof F.Name?{}:{...this.lhs.names};return ya(t,this.rhs)}},no=class extends ga{constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},ao=class extends ht{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},io=class extends ht{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},oo=class extends ht{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},so=class extends ht{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=kr(this.code,t,r),this}get names(){return this.code instanceof F._CodeOrName?this.code.names:{}}},rn=class extends ht{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let i=n[a];i.optimizeNames(t,r)||(dg(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Gt(t,r.names),{})}},yt=class extends rn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},co=class extends rn{},br=class extends yt{};br.kind="else";var Bt=class e extends yt{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new br(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(ul(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=kr(this.condition,t,r),this}get names(){let t=super.names;return ya(t,this.condition),this.else&&Gt(t,this.else.names),t}};Bt.kind="if";var Jt=class extends yt{};Jt.kind="for";var lo=class extends Jt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=kr(this.iteration,t,r),this}get names(){return Gt(super.names,this.iteration.names)}},po=class extends Jt{constructor(t,r,n,a){super(),this.varKind=t,this.name=r,this.from=n,this.to=a}render(t){let r=t.es5?et.varKinds.var:this.varKind,{name:n,from:a,to:i}=this;return`for(${r} ${n}=${a}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=ya(super.names,this.from);return ya(t,this.to)}},ha=class extends Jt{constructor(t,r,n,a){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=a}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=kr(this.iterable,t,r),this}get names(){return Gt(super.names,this.iterable.names)}},nn=class extends yt{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};nn.kind="func";var an=class extends rn{render(t){return"return "+super.render(t)}};an.kind="return";var uo=class extends yt{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Gt(t,this.catch.names),this.finally&&Gt(t,this.finally.names),t}},on=class extends yt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};on.kind="catch";var sn=class extends yt{render(t){return"finally"+super.render(t)}};sn.kind="finally";var fo=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
- `:""},this._extScope=t,this._scope=new et.Scope({parent:t}),this._nodes=[new co]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new ro(t,i,n)),i}const(t,r,n){return this._def(et.varKinds.const,t,r,n)}let(t,r,n){return this._def(et.varKinds.let,t,r,n)}var(t,r,n){return this._def(et.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new ga(t,r,n))}add(t,r){return this._leafNode(new no(t,V.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==F.nil&&this._leafNode(new so(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,F.addCodeArg)(r,a));return r.push("}"),new F._Code(r)}if(t,r,n){if(this._blockNode(new Bt(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Bt(t))}else(){return this._elseNode(new br)}endIf(){return this._endBlockNode(Bt,br)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new lo(t),r)}forRange(t,r,n,a,i=this.opts.es5?et.varKinds.var:et.varKinds.let){let o=this._scope.toName(t);return this._for(new po(i,o,r,n),()=>a(o))}forOf(t,r,n,a=et.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let o=r instanceof F.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,F._)`${o}.length`,s=>{this.var(i,(0,F._)`${o}[${s}]`),n(i)})}return this._for(new ha("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?et.varKinds.var:et.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,F._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new ha("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Jt)}label(t){return this._leafNode(new ao(t))}break(t){return this._leafNode(new io(t))}return(t){let r=new an;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(an)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new uo;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new on(i),r(i)}return n&&(this._currNode=a.finally=new sn,this.code(n)),this._endBlockNode(on,sn)}throw(t){return this._leafNode(new oo(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=F.nil,n,a){return this._blockNode(new nn(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(nn)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Bt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};V.CodeGen=fo;function Gt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function ya(e,t){return t instanceof F._CodeOrName?Gt(e,t.names):e}function kr(e,t,r){if(e instanceof F.Name)return n(e);if(!a(e))return e;return new F._Code(e._items.reduce((i,o)=>(o instanceof F.Name&&(o=n(o)),o instanceof F._Code?i.push(...o._items):i.push(o),i),[]));function n(i){let o=r[i.str];return o===void 0||t[i.str]!==1?i:(delete t[i.str],o)}function a(i){return i instanceof F._Code&&i._items.some(o=>o instanceof F.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function dg(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function ul(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,F._)`!${mo(e)}`}V.not=ul;var pg=fl(V.operators.AND);function ug(...e){return e.reduce(pg)}V.and=ug;var fg=fl(V.operators.OR);function mg(...e){return e.reduce(fg)}V.or=mg;function fl(e){return(t,r)=>t===F.nil?r:r===F.nil?t:(0,F._)`${mo(t)} ${e} ${mo(r)}`}function mo(e){return e instanceof F.Name?e:(0,F._)`(${e})`}});var U=R(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var te=x(),gg=tn();function hg(e){let t={};for(let r of e)t[r]=!0;return t}q.toHash=hg;function yg(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(hl(e,t),!yl(t,e.self.RULES.all))}q.alwaysValidSchema=yg;function hl(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let i in t)a[i]||Il(e,`unknown keyword: "${i}"`)}q.checkUnknownRules=hl;function yl(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}q.schemaHasRules=yl;function wg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}q.schemaHasRulesButRef=wg;function vg({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,te._)`${r}`}return(0,te._)`${e}${t}${(0,te.getProperty)(n)}`}q.schemaRefOrVal=vg;function Ig(e){return wl(decodeURIComponent(e))}q.unescapeFragment=Ig;function bg(e){return encodeURIComponent(ho(e))}q.escapeFragment=bg;function ho(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=ho;function wl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=wl;function kg(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}q.eachItem=kg;function ml({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,o,s)=>{let c=o===void 0?i:o instanceof te.Name?(i instanceof te.Name?e(a,i,o):t(a,i,o),o):i instanceof te.Name?(t(a,o,i),i):r(i,o);return s===te.Name&&!(c instanceof te.Name)?n(a,c):c}}q.mergeEvaluated={props:ml({mergeNames:(e,t,r)=>e.if((0,te._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,te._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,te._)`${r} || {}`).code((0,te._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,te._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,te._)`${r} || {}`),yo(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:vl}),items:ml({mergeNames:(e,t,r)=>e.if((0,te._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,te._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,te._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,te._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function vl(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,te._)`{}`);return t!==void 0&&yo(e,r,t),r}q.evaluatedPropsToName=vl;function yo(e,t,r){Object.keys(r).forEach(n=>e.assign((0,te._)`${t}${(0,te.getProperty)(n)}`,!0))}q.setEvaluated=yo;var gl={};function _g(e,t){return e.scopeValue("func",{ref:t,code:gl[t.code]||(gl[t.code]=new gg._Code(t.code))})}q.useFunc=_g;var go;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(go||(q.Type=go={}));function Eg(e,t,r){if(e instanceof te.Name){let n=t===go.Num;return r?n?(0,te._)`"[" + ${e} + "]"`:(0,te._)`"['" + ${e} + "']"`:n?(0,te._)`"/" + ${e}`:(0,te._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,te.getProperty)(e).toString():"/"+ho(e)}q.getErrorPath=Eg;function Il(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}q.checkStrictMode=Il});var Ge=R(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});var Ae=x(),Ag={data:new Ae.Name("data"),valCxt:new Ae.Name("valCxt"),instancePath:new Ae.Name("instancePath"),parentData:new Ae.Name("parentData"),parentDataProperty:new Ae.Name("parentDataProperty"),rootData:new Ae.Name("rootData"),dynamicAnchors:new Ae.Name("dynamicAnchors"),vErrors:new Ae.Name("vErrors"),errors:new Ae.Name("errors"),this:new Ae.Name("this"),self:new Ae.Name("self"),scope:new Ae.Name("scope"),json:new Ae.Name("json"),jsonPos:new Ae.Name("jsonPos"),jsonLen:new Ae.Name("jsonLen"),jsonPart:new Ae.Name("jsonPart")};wo.default=Ag});var cn=R(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.extendErrors=Re.resetErrorsCount=Re.reportExtraError=Re.reportError=Re.keyword$DataError=Re.keywordError=void 0;var B=x(),va=U(),Se=Ge();Re.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};Re.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function Rg(e,t=Re.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:o,allErrors:s}=a,c=_l(e,t,r);n??(o||s)?bl(i,c):kl(a,(0,B._)`[${c}]`)}Re.reportError=Rg;function Pg(e,t=Re.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:o}=n,s=_l(e,t,r);bl(a,s),i||o||kl(n,Se.default.vErrors)}Re.reportExtraError=Pg;function Ng(e,t){e.assign(Se.default.errors,t),e.if((0,B._)`${Se.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${Se.default.vErrors}.length`,t),()=>e.assign(Se.default.vErrors,null)))}Re.resetErrorsCount=Ng;function Dg({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let o=e.name("err");e.forRange("i",a,Se.default.errors,s=>{e.const(o,(0,B._)`${Se.default.vErrors}[${s}]`),e.if((0,B._)`${o}.instancePath === undefined`,()=>e.assign((0,B._)`${o}.instancePath`,(0,B.strConcat)(Se.default.instancePath,i.errorPath))),e.assign((0,B._)`${o}.schemaPath`,(0,B.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,B._)`${o}.schema`,r),e.assign((0,B._)`${o}.data`,n))})}Re.extendErrors=Dg;function bl(e,t){let r=e.const("err",t);e.if((0,B._)`${Se.default.vErrors} === null`,()=>e.assign(Se.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${Se.default.vErrors}.push(${r})`),e.code((0,B._)`${Se.default.errors}++`)}function kl(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var Wt={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function _l(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:Sg(e,t,r)}function Sg(e,t,r={}){let{gen:n,it:a}=e,i=[jg(a,r),$g(e,r)];return Og(e,t,i),n.object(...i)}function jg({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,va.getErrorPath)(t,va.Type.Str)}`:e;return[Se.default.instancePath,(0,B.strConcat)(Se.default.instancePath,r)]}function $g({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,B.str)`${t}/${e}`;return r&&(a=(0,B.str)`${a}${(0,va.getErrorPath)(r,va.Type.Str)}`),[Wt.schemaPath,a]}function Og(e,{params:t,message:r},n){let{keyword:a,data:i,schemaValue:o,it:s}=e,{opts:c,propertyName:d,topSchemaRef:l,schemaPath:p}=s;n.push([Wt.keyword,a],[Wt.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Wt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Wt.schema,o],[Wt.parentSchema,(0,B._)`${l}${p}`],[Se.default.data,i]),d&&n.push([Wt.propertyName,d])}});var Al=R(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.boolOrEmptySchema=_r.topBoolOrEmptySchema=void 0;var Cg=cn(),Tg=x(),xg=Ge(),Lg={message:"boolean schema is false"};function Vg(e){let{gen:t,schema:r,validateName:n}=e;r===!1?El(e,!1):typeof r=="object"&&r.$async===!0?t.return(xg.default.data):(t.assign((0,Tg._)`${n}.errors`,null),t.return(!0))}_r.topBoolOrEmptySchema=Vg;function Mg(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),El(e)):r.var(t,!0)}_r.boolOrEmptySchema=Mg;function El(e,t){let{gen:r,data:n}=e,a={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Cg.reportError)(a,Lg,void 0,t)}});var vo=R(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.getRules=Er.isJSONType=void 0;var qg=["string","number","integer","boolean","null","object","array"],Ug=new Set(qg);function Fg(e){return typeof e=="string"&&Ug.has(e)}Er.isJSONType=Fg;function zg(){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:{}}}Er.getRules=zg});var Io=R(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.shouldUseRule=Pt.shouldUseGroup=Pt.schemaHasRulesForType=void 0;function Bg({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Rl(e,n)}Pt.schemaHasRulesForType=Bg;function Rl(e,t){return t.rules.some(r=>Pl(e,r))}Pt.shouldUseGroup=Rl;function Pl(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Pt.shouldUseRule=Pl});var ln=R(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.reportTypeError=Pe.checkDataTypes=Pe.checkDataType=Pe.coerceAndCheckDataType=Pe.getJSONTypes=Pe.getSchemaTypes=Pe.DataType=void 0;var Jg=vo(),Gg=Io(),Wg=cn(),L=x(),Nl=U(),Ar;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Ar||(Pe.DataType=Ar={}));function Kg(e){let t=Dl(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Pe.getSchemaTypes=Kg;function Dl(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Jg.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Pe.getJSONTypes=Dl;function Yg(e,t){let{gen:r,data:n,opts:a}=e,i=Hg(t,a.coerceTypes),o=t.length>0&&!(i.length===0&&t.length===1&&(0,Gg.schemaHasRulesForType)(e,t[0]));if(o){let s=ko(t,n,a.strictNumbers,Ar.Wrong);r.if(s,()=>{i.length?Xg(e,t,i):_o(e)})}return o}Pe.coerceAndCheckDataType=Yg;var Sl=new Set(["string","number","integer","boolean","null"]);function Hg(e,t){return t?e.filter(r=>Sl.has(r)||t==="array"&&r==="array"):[]}function Xg(e,t,r){let{gen:n,data:a,opts:i}=e,o=n.let("dataType",(0,L._)`typeof ${a}`),s=n.let("coerced",(0,L._)`undefined`);i.coerceTypes==="array"&&n.if((0,L._)`${o} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,L._)`${a}[0]`).assign(o,(0,L._)`typeof ${a}`).if(ko(t,a,i.strictNumbers),()=>n.assign(s,a))),n.if((0,L._)`${s} !== undefined`);for(let d of r)(Sl.has(d)||d==="array"&&i.coerceTypes==="array")&&c(d);n.else(),_o(e),n.endIf(),n.if((0,L._)`${s} !== undefined`,()=>{n.assign(a,s),Zg(e,s)});function c(d){switch(d){case"string":n.elseIf((0,L._)`${o} == "number" || ${o} == "boolean"`).assign(s,(0,L._)`"" + ${a}`).elseIf((0,L._)`${a} === null`).assign(s,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${o} == "boolean" || ${a} === null
1
+ var Hm=Object.create;var ll=Object.defineProperty;var Xm=Object.getOwnPropertyDescriptor;var Zm=Object.getOwnPropertyNames;var Qm=Object.getPrototypeOf,eg=Object.prototype.hasOwnProperty;var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var tg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Zm(t))!eg.call(e,a)&&a!==r&&ll(e,a,{get:()=>t[a],enumerable:!(n=Xm(t,a))||n.enumerable});return e};var Ir=(e,t,r)=>(r=e!=null?Hm(Qm(e)):{},tg(t||!e||!e.__esModule?ll(r,"default",{value:e,enumerable:!0}):r,e));var tn=R(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.regexpCode=G.getEsmExportName=G.getProperty=G.safeStringify=G.stringify=G.strConcat=G.addCodeArg=G.str=G._=G.nil=G._Code=G.Name=G.IDENTIFIER=G._CodeOrName=void 0;var Qr=class{};G._CodeOrName=Qr;G.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Bt=class extends Qr{constructor(t){if(super(),!G.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};G.Name=Bt;var Je=class extends Qr{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Bt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};G._Code=Je;G.nil=new Je("");function dl(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Zi(r,t[n]),r.push(e[++n]);return new Je(r)}G._=dl;var Xi=new Je("+");function pl(e,...t){let r=[en(e[0])],n=0;for(;n<t.length;)r.push(Xi),Zi(r,t[n]),r.push(Xi,en(e[++n]));return rg(r),new Je(r)}G.str=pl;function Zi(e,t){t instanceof Je?e.push(...t._items):t instanceof Bt?e.push(t):e.push(ig(t))}G.addCodeArg=Zi;function rg(e){let t=1;for(;t<e.length-1;){if(e[t]===Xi){let r=ng(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function ng(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Bt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Bt))return`"${e}${t.slice(1)}`}function ag(e,t){return t.emptyStr()?e:e.emptyStr()?t:pl`${e}${t}`}G.strConcat=ag;function ig(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:en(Array.isArray(e)?e.join(","):e)}function og(e){return new Je(en(e))}G.stringify=og;function en(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}G.safeStringify=en;function sg(e){return typeof e=="string"&&G.IDENTIFIER.test(e)?new Je(`.${e}`):dl`[${e}]`}G.getProperty=sg;function cg(e){if(typeof e=="string"&&G.IDENTIFIER.test(e))return new Je(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}G.getEsmExportName=cg;function lg(e){return new Je(e.toString())}G.regexpCode=lg});var to=R(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.ValueScope=xe.ValueScopeName=xe.Scope=xe.varKinds=xe.UsedValueState=void 0;var Te=tn(),Qi=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},ua;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(ua||(xe.UsedValueState=ua={}));xe.varKinds={const:new Te.Name("const"),let:new Te.Name("let"),var:new Te.Name("var")};var fa=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Te.Name?t:this.name(t)}name(t){return new Te.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};xe.Scope=fa;var ma=class extends Te.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Te._)`.${new Te.Name(r)}[${n}]`}};xe.ValueScopeName=ma;var dg=(0,Te._)`\n`,eo=class extends fa{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?dg:Te.nil}}get(){return this._scope}name(t){return new ma(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:i}=a,o=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[i];if(s){let l=s.get(o);if(l)return l}else s=this._values[i]=new Map;s.set(o,a);let c=this._scope[i]||(this._scope[i]=[]),d=c.length;return c[d]=r.ref,a.setValue(r,{property:i,itemIndex:d}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Te._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let i=Te.nil;for(let o in t){let s=t[o];if(!s)continue;let c=n[o]=n[o]||new Map;s.forEach(d=>{if(c.has(d))return;c.set(d,ua.Started);let l=r(d);if(l){let p=this.opts.es5?xe.varKinds.var:xe.varKinds.const;i=(0,Te._)`${i}${p} ${d} = ${l};${this.opts._n}`}else if(l=a?.(d))i=(0,Te._)`${i}${l}${this.opts._n}`;else throw new Qi(d);c.set(d,ua.Completed)})}return i}};xe.ValueScope=eo});var x=R(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var F=tn(),et=to(),Pt=tn();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Pt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Pt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Pt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Pt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Pt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Pt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Pt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Pt.Name}});var wa=to();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return wa.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return wa.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return wa.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return wa.varKinds}});V.operators={GT:new F._Code(">"),GTE:new F._Code(">="),LT:new F._Code("<"),LTE:new F._Code("<="),EQ:new F._Code("==="),NEQ:new F._Code("!=="),NOT:new F._Code("!"),OR:new F._Code("||"),AND:new F._Code("&&"),ADD:new F._Code("+")};var wt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},ro=class extends wt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?et.varKinds.var:this.varKind,a=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${a};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=kr(this.rhs,t,r)),this}get names(){return this.rhs instanceof F._CodeOrName?this.rhs.names:{}}},ga=class extends wt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof F.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=kr(this.rhs,t,r),this}get names(){let t=this.lhs instanceof F.Name?{}:{...this.lhs.names};return ya(t,this.rhs)}},no=class extends ga{constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},ao=class extends wt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},io=class extends wt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},oo=class extends wt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},so=class extends wt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=kr(this.code,t,r),this}get names(){return this.code instanceof F._CodeOrName?this.code.names:{}}},rn=class extends wt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let i=n[a];i.optimizeNames(t,r)||(pg(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Wt(t,r.names),{})}},vt=class extends rn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},co=class extends rn{},br=class extends vt{};br.kind="else";var Jt=class e extends vt{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new br(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(ul(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=kr(this.condition,t,r),this}get names(){let t=super.names;return ya(t,this.condition),this.else&&Wt(t,this.else.names),t}};Jt.kind="if";var Gt=class extends vt{};Gt.kind="for";var lo=class extends Gt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=kr(this.iteration,t,r),this}get names(){return Wt(super.names,this.iteration.names)}},po=class extends Gt{constructor(t,r,n,a){super(),this.varKind=t,this.name=r,this.from=n,this.to=a}render(t){let r=t.es5?et.varKinds.var:this.varKind,{name:n,from:a,to:i}=this;return`for(${r} ${n}=${a}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=ya(super.names,this.from);return ya(t,this.to)}},ha=class extends Gt{constructor(t,r,n,a){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=a}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=kr(this.iterable,t,r),this}get names(){return Wt(super.names,this.iterable.names)}},nn=class extends vt{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};nn.kind="func";var an=class extends rn{render(t){return"return "+super.render(t)}};an.kind="return";var uo=class extends vt{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Wt(t,this.catch.names),this.finally&&Wt(t,this.finally.names),t}},on=class extends vt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};on.kind="catch";var sn=class extends vt{render(t){return"finally"+super.render(t)}};sn.kind="finally";var fo=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=t,this._scope=new et.Scope({parent:t}),this._nodes=[new co]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new ro(t,i,n)),i}const(t,r,n){return this._def(et.varKinds.const,t,r,n)}let(t,r,n){return this._def(et.varKinds.let,t,r,n)}var(t,r,n){return this._def(et.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new ga(t,r,n))}add(t,r){return this._leafNode(new no(t,V.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==F.nil&&this._leafNode(new so(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,F.addCodeArg)(r,a));return r.push("}"),new F._Code(r)}if(t,r,n){if(this._blockNode(new Jt(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Jt(t))}else(){return this._elseNode(new br)}endIf(){return this._endBlockNode(Jt,br)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new lo(t),r)}forRange(t,r,n,a,i=this.opts.es5?et.varKinds.var:et.varKinds.let){let o=this._scope.toName(t);return this._for(new po(i,o,r,n),()=>a(o))}forOf(t,r,n,a=et.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let o=r instanceof F.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,F._)`${o}.length`,s=>{this.var(i,(0,F._)`${o}[${s}]`),n(i)})}return this._for(new ha("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?et.varKinds.var:et.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,F._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new ha("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Gt)}label(t){return this._leafNode(new ao(t))}break(t){return this._leafNode(new io(t))}return(t){let r=new an;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(an)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new uo;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new on(i),r(i)}return n&&(this._currNode=a.finally=new sn,this.code(n)),this._endBlockNode(on,sn)}throw(t){return this._leafNode(new oo(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=F.nil,n,a){return this._blockNode(new nn(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(nn)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Jt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};V.CodeGen=fo;function Wt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function ya(e,t){return t instanceof F._CodeOrName?Wt(e,t.names):e}function kr(e,t,r){if(e instanceof F.Name)return n(e);if(!a(e))return e;return new F._Code(e._items.reduce((i,o)=>(o instanceof F.Name&&(o=n(o)),o instanceof F._Code?i.push(...o._items):i.push(o),i),[]));function n(i){let o=r[i.str];return o===void 0||t[i.str]!==1?i:(delete t[i.str],o)}function a(i){return i instanceof F._Code&&i._items.some(o=>o instanceof F.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function pg(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function ul(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,F._)`!${mo(e)}`}V.not=ul;var ug=fl(V.operators.AND);function fg(...e){return e.reduce(ug)}V.and=fg;var mg=fl(V.operators.OR);function gg(...e){return e.reduce(mg)}V.or=gg;function fl(e){return(t,r)=>t===F.nil?r:r===F.nil?t:(0,F._)`${mo(t)} ${e} ${mo(r)}`}function mo(e){return e instanceof F.Name?e:(0,F._)`(${e})`}});var U=R(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var te=x(),hg=tn();function yg(e){let t={};for(let r of e)t[r]=!0;return t}q.toHash=yg;function wg(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(hl(e,t),!yl(t,e.self.RULES.all))}q.alwaysValidSchema=wg;function hl(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let i in t)a[i]||Il(e,`unknown keyword: "${i}"`)}q.checkUnknownRules=hl;function yl(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}q.schemaHasRules=yl;function vg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}q.schemaHasRulesButRef=vg;function Ig({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,te._)`${r}`}return(0,te._)`${e}${t}${(0,te.getProperty)(n)}`}q.schemaRefOrVal=Ig;function bg(e){return wl(decodeURIComponent(e))}q.unescapeFragment=bg;function kg(e){return encodeURIComponent(ho(e))}q.escapeFragment=kg;function ho(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=ho;function wl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=wl;function _g(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}q.eachItem=_g;function ml({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,o,s)=>{let c=o===void 0?i:o instanceof te.Name?(i instanceof te.Name?e(a,i,o):t(a,i,o),o):i instanceof te.Name?(t(a,o,i),i):r(i,o);return s===te.Name&&!(c instanceof te.Name)?n(a,c):c}}q.mergeEvaluated={props:ml({mergeNames:(e,t,r)=>e.if((0,te._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,te._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,te._)`${r} || {}`).code((0,te._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,te._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,te._)`${r} || {}`),yo(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:vl}),items:ml({mergeNames:(e,t,r)=>e.if((0,te._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,te._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,te._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,te._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function vl(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,te._)`{}`);return t!==void 0&&yo(e,r,t),r}q.evaluatedPropsToName=vl;function yo(e,t,r){Object.keys(r).forEach(n=>e.assign((0,te._)`${t}${(0,te.getProperty)(n)}`,!0))}q.setEvaluated=yo;var gl={};function Eg(e,t){return e.scopeValue("func",{ref:t,code:gl[t.code]||(gl[t.code]=new hg._Code(t.code))})}q.useFunc=Eg;var go;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(go||(q.Type=go={}));function Ag(e,t,r){if(e instanceof te.Name){let n=t===go.Num;return r?n?(0,te._)`"[" + ${e} + "]"`:(0,te._)`"['" + ${e} + "']"`:n?(0,te._)`"/" + ${e}`:(0,te._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,te.getProperty)(e).toString():"/"+ho(e)}q.getErrorPath=Ag;function Il(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}q.checkStrictMode=Il});var Ge=R(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});var Ae=x(),Rg={data:new Ae.Name("data"),valCxt:new Ae.Name("valCxt"),instancePath:new Ae.Name("instancePath"),parentData:new Ae.Name("parentData"),parentDataProperty:new Ae.Name("parentDataProperty"),rootData:new Ae.Name("rootData"),dynamicAnchors:new Ae.Name("dynamicAnchors"),vErrors:new Ae.Name("vErrors"),errors:new Ae.Name("errors"),this:new Ae.Name("this"),self:new Ae.Name("self"),scope:new Ae.Name("scope"),json:new Ae.Name("json"),jsonPos:new Ae.Name("jsonPos"),jsonLen:new Ae.Name("jsonLen"),jsonPart:new Ae.Name("jsonPart")};wo.default=Rg});var cn=R(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.extendErrors=Re.resetErrorsCount=Re.reportExtraError=Re.reportError=Re.keyword$DataError=Re.keywordError=void 0;var B=x(),va=U(),je=Ge();Re.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};Re.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function Pg(e,t=Re.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:o,allErrors:s}=a,c=_l(e,t,r);n??(o||s)?bl(i,c):kl(a,(0,B._)`[${c}]`)}Re.reportError=Pg;function Ng(e,t=Re.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:o}=n,s=_l(e,t,r);bl(a,s),i||o||kl(n,je.default.vErrors)}Re.reportExtraError=Ng;function Dg(e,t){e.assign(je.default.errors,t),e.if((0,B._)`${je.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${je.default.vErrors}.length`,t),()=>e.assign(je.default.vErrors,null)))}Re.resetErrorsCount=Dg;function Sg({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let o=e.name("err");e.forRange("i",a,je.default.errors,s=>{e.const(o,(0,B._)`${je.default.vErrors}[${s}]`),e.if((0,B._)`${o}.instancePath === undefined`,()=>e.assign((0,B._)`${o}.instancePath`,(0,B.strConcat)(je.default.instancePath,i.errorPath))),e.assign((0,B._)`${o}.schemaPath`,(0,B.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,B._)`${o}.schema`,r),e.assign((0,B._)`${o}.data`,n))})}Re.extendErrors=Sg;function bl(e,t){let r=e.const("err",t);e.if((0,B._)`${je.default.vErrors} === null`,()=>e.assign(je.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${je.default.vErrors}.push(${r})`),e.code((0,B._)`${je.default.errors}++`)}function kl(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var Kt={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function _l(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:jg(e,t,r)}function jg(e,t,r={}){let{gen:n,it:a}=e,i=[$g(a,r),Og(e,r)];return Cg(e,t,i),n.object(...i)}function $g({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,va.getErrorPath)(t,va.Type.Str)}`:e;return[je.default.instancePath,(0,B.strConcat)(je.default.instancePath,r)]}function Og({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,B.str)`${t}/${e}`;return r&&(a=(0,B.str)`${a}${(0,va.getErrorPath)(r,va.Type.Str)}`),[Kt.schemaPath,a]}function Cg(e,{params:t,message:r},n){let{keyword:a,data:i,schemaValue:o,it:s}=e,{opts:c,propertyName:d,topSchemaRef:l,schemaPath:p}=s;n.push([Kt.keyword,a],[Kt.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Kt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Kt.schema,o],[Kt.parentSchema,(0,B._)`${l}${p}`],[je.default.data,i]),d&&n.push([Kt.propertyName,d])}});var Al=R(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.boolOrEmptySchema=_r.topBoolOrEmptySchema=void 0;var Tg=cn(),xg=x(),Lg=Ge(),Vg={message:"boolean schema is false"};function Mg(e){let{gen:t,schema:r,validateName:n}=e;r===!1?El(e,!1):typeof r=="object"&&r.$async===!0?t.return(Lg.default.data):(t.assign((0,xg._)`${n}.errors`,null),t.return(!0))}_r.topBoolOrEmptySchema=Mg;function qg(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),El(e)):r.var(t,!0)}_r.boolOrEmptySchema=qg;function El(e,t){let{gen:r,data:n}=e,a={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Tg.reportError)(a,Vg,void 0,t)}});var vo=R(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.getRules=Er.isJSONType=void 0;var Ug=["string","number","integer","boolean","null","object","array"],Fg=new Set(Ug);function zg(e){return typeof e=="string"&&Fg.has(e)}Er.isJSONType=zg;function Bg(){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:{}}}Er.getRules=Bg});var Io=R(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.shouldUseRule=Nt.shouldUseGroup=Nt.schemaHasRulesForType=void 0;function Jg({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Rl(e,n)}Nt.schemaHasRulesForType=Jg;function Rl(e,t){return t.rules.some(r=>Pl(e,r))}Nt.shouldUseGroup=Rl;function Pl(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Nt.shouldUseRule=Pl});var ln=R(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.reportTypeError=Pe.checkDataTypes=Pe.checkDataType=Pe.coerceAndCheckDataType=Pe.getJSONTypes=Pe.getSchemaTypes=Pe.DataType=void 0;var Gg=vo(),Wg=Io(),Kg=cn(),L=x(),Nl=U(),Ar;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Ar||(Pe.DataType=Ar={}));function Yg(e){let t=Dl(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Pe.getSchemaTypes=Yg;function Dl(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Gg.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Pe.getJSONTypes=Dl;function Hg(e,t){let{gen:r,data:n,opts:a}=e,i=Xg(t,a.coerceTypes),o=t.length>0&&!(i.length===0&&t.length===1&&(0,Wg.schemaHasRulesForType)(e,t[0]));if(o){let s=ko(t,n,a.strictNumbers,Ar.Wrong);r.if(s,()=>{i.length?Zg(e,t,i):_o(e)})}return o}Pe.coerceAndCheckDataType=Hg;var Sl=new Set(["string","number","integer","boolean","null"]);function Xg(e,t){return t?e.filter(r=>Sl.has(r)||t==="array"&&r==="array"):[]}function Zg(e,t,r){let{gen:n,data:a,opts:i}=e,o=n.let("dataType",(0,L._)`typeof ${a}`),s=n.let("coerced",(0,L._)`undefined`);i.coerceTypes==="array"&&n.if((0,L._)`${o} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,L._)`${a}[0]`).assign(o,(0,L._)`typeof ${a}`).if(ko(t,a,i.strictNumbers),()=>n.assign(s,a))),n.if((0,L._)`${s} !== undefined`);for(let d of r)(Sl.has(d)||d==="array"&&i.coerceTypes==="array")&&c(d);n.else(),_o(e),n.endIf(),n.if((0,L._)`${s} !== undefined`,()=>{n.assign(a,s),Qg(e,s)});function c(d){switch(d){case"string":n.elseIf((0,L._)`${o} == "number" || ${o} == "boolean"`).assign(s,(0,L._)`"" + ${a}`).elseIf((0,L._)`${a} === null`).assign(s,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${o} == "boolean" || ${a} === null
3
3
  || (${o} == "string" && ${a} && ${a} == +${a})`).assign(s,(0,L._)`+${a}`);return;case"integer":n.elseIf((0,L._)`${o} === "boolean" || ${a} === null
4
4
  || (${o} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(s,(0,L._)`+${a}`);return;case"boolean":n.elseIf((0,L._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(s,!1).elseIf((0,L._)`${a} === "true" || ${a} === 1`).assign(s,!0);return;case"null":n.elseIf((0,L._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(s,null);return;case"array":n.elseIf((0,L._)`${o} === "string" || ${o} === "number"
5
- || ${o} === "boolean" || ${a} === null`).assign(s,(0,L._)`[${a}]`)}}}function Zg({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${r}]`,n))}function bo(e,t,r,n=Ar.Correct){let a=n===Ar.Correct?L.operators.EQ:L.operators.NEQ,i;switch(e){case"null":return(0,L._)`${t} ${a} null`;case"array":i=(0,L._)`Array.isArray(${t})`;break;case"object":i=(0,L._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=o((0,L._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=o();break;default:return(0,L._)`typeof ${t} ${a} ${e}`}return n===Ar.Correct?i:(0,L.not)(i);function o(s=L.nil){return(0,L.and)((0,L._)`typeof ${t} == "number"`,s,r?(0,L._)`isFinite(${t})`:L.nil)}}Pe.checkDataType=bo;function ko(e,t,r,n){if(e.length===1)return bo(e[0],t,r,n);let a,i=(0,Nl.toHash)(e);if(i.array&&i.object){let o=(0,L._)`typeof ${t} != "object"`;a=i.null?o:(0,L._)`!${t} || ${o}`,delete i.null,delete i.array,delete i.object}else a=L.nil;i.number&&delete i.integer;for(let o in i)a=(0,L.and)(a,bo(o,t,r,n));return a}Pe.checkDataTypes=ko;var Qg={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function _o(e){let t=eh(e);(0,Wg.reportError)(t,Qg)}Pe.reportTypeError=_o;function eh(e){let{gen:t,data:r,schema:n}=e,a=(0,Nl.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}});var $l=R(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.assignDefaults=void 0;var Rr=x(),th=U();function rh(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)jl(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>jl(e,i,a.default))}Ia.assignDefaults=rh;function jl(e,t,r){let{gen:n,compositeRule:a,data:i,opts:o}=e;if(r===void 0)return;let s=(0,Rr._)`${i}${(0,Rr.getProperty)(t)}`;if(a){(0,th.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,Rr._)`${s} === undefined`;o.useDefaults==="empty"&&(c=(0,Rr._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,Rr._)`${s} = ${(0,Rr.stringify)(r)}`)}});var We=R(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.validateUnion=Q.validateArray=Q.usePattern=Q.callValidateCode=Q.schemaProperties=Q.allSchemaProperties=Q.noPropertyInData=Q.propertyInData=Q.isOwnProperty=Q.hasPropFunc=Q.reportMissingProp=Q.checkMissingProp=Q.checkReportMissingProp=void 0;var ie=x(),Eo=U(),Nt=Ge(),nh=U();function ah(e,t){let{gen:r,data:n,it:a}=e;r.if(Ro(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ie._)`${t}`},!0),e.error()})}Q.checkReportMissingProp=ah;function ih({gen:e,data:t,it:{opts:r}},n,a){return(0,ie.or)(...n.map(i=>(0,ie.and)(Ro(e,t,i,r.ownProperties),(0,ie._)`${a} = ${i}`)))}Q.checkMissingProp=ih;function oh(e,t){e.setParams({missingProperty:t},!0),e.error()}Q.reportMissingProp=oh;function Ol(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ie._)`Object.prototype.hasOwnProperty`})}Q.hasPropFunc=Ol;function Ao(e,t,r){return(0,ie._)`${Ol(e)}.call(${t}, ${r})`}Q.isOwnProperty=Ao;function sh(e,t,r,n){let a=(0,ie._)`${t}${(0,ie.getProperty)(r)} !== undefined`;return n?(0,ie._)`${a} && ${Ao(e,t,r)}`:a}Q.propertyInData=sh;function Ro(e,t,r,n){let a=(0,ie._)`${t}${(0,ie.getProperty)(r)} === undefined`;return n?(0,ie.or)(a,(0,ie.not)(Ao(e,t,r))):a}Q.noPropertyInData=Ro;function Cl(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Q.allSchemaProperties=Cl;function ch(e,t){return Cl(t).filter(r=>!(0,Eo.alwaysValidSchema)(e,t[r]))}Q.schemaProperties=ch;function lh({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:o},s,c,d){let l=d?(0,ie._)`${e}, ${t}, ${n}${a}`:t,p=[[Nt.default.instancePath,(0,ie.strConcat)(Nt.default.instancePath,i)],[Nt.default.parentData,o.parentData],[Nt.default.parentDataProperty,o.parentDataProperty],[Nt.default.rootData,Nt.default.rootData]];o.opts.dynamicRef&&p.push([Nt.default.dynamicAnchors,Nt.default.dynamicAnchors]);let f=(0,ie._)`${l}, ${r.object(...p)}`;return c!==ie.nil?(0,ie._)`${s}.call(${c}, ${f})`:(0,ie._)`${s}(${f})`}Q.callValidateCode=lh;var dh=(0,ie._)`new RegExp`;function ph({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,ie._)`${a.code==="new RegExp"?dh:(0,nh.useFunc)(e,a)}(${r}, ${n})`})}Q.usePattern=ph;function uh(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let s=t.let("valid",!0);return o(()=>t.assign(s,!1)),s}return t.var(i,!0),o(()=>t.break()),i;function o(s){let c=t.const("len",(0,ie._)`${r}.length`);t.forRange("i",0,c,d=>{e.subschema({keyword:n,dataProp:d,dataPropType:Eo.Type.Num},i),t.if((0,ie.not)(i),s)})}}Q.validateArray=uh;function fh(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Eo.alwaysValidSchema)(a,c))&&!a.opts.unevaluated)return;let o=t.let("valid",!1),s=t.name("_valid");t.block(()=>r.forEach((c,d)=>{let l=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},s);t.assign(o,(0,ie._)`${o} || ${s}`),e.mergeValidEvaluated(l,s)||t.if((0,ie.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}Q.validateUnion=fh});var Ll=R(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.validateKeywordUsage=pt.validSchemaType=pt.funcKeywordCode=pt.macroKeywordCode=void 0;var je=x(),Kt=Ge(),mh=We(),gh=cn();function hh(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:o}=e,s=t.macro.call(o.self,a,i,o),c=xl(r,n,s);o.opts.validateSchema!==!1&&o.self.validateSchema(s,!0);let d=r.name("valid");e.subschema({schema:s,schemaPath:je.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}pt.macroKeywordCode=hh;function yh(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:o,$data:s,it:c}=e;vh(c,t);let d=!s&&t.compile?t.compile.call(c.self,i,o,c):t.validate,l=xl(n,a,d),p=n.let("valid");e.block$data(p,f),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function f(){if(t.errors===!1)g(),t.modifying&&Tl(e),h(()=>e.error());else{let w=t.async?u():m();t.modifying&&Tl(e),h(()=>wh(e,w))}}function u(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,je._)`await `),_=>n.assign(p,!1).if((0,je._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,je._)`${_}.errors`),()=>n.throw(_))),w}function m(){let w=(0,je._)`${l}.errors`;return n.assign(w,null),g(je.nil),w}function g(w=t.async?(0,je._)`await `:je.nil){let _=c.opts.passContext?Kt.default.this:Kt.default.self,I=!("compile"in t&&!s||t.schema===!1);n.assign(p,(0,je._)`${w}${(0,mh.callValidateCode)(e,l,_,I)}`,t.modifying)}function h(w){var _;n.if((0,je.not)((_=t.valid)!==null&&_!==void 0?_:p),w)}}pt.funcKeywordCode=yh;function Tl(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,je._)`${n.parentData}[${n.parentDataProperty}]`))}function wh(e,t){let{gen:r}=e;r.if((0,je._)`Array.isArray(${t})`,()=>{r.assign(Kt.default.vErrors,(0,je._)`${Kt.default.vErrors} === null ? ${t} : ${Kt.default.vErrors}.concat(${t})`).assign(Kt.default.errors,(0,je._)`${Kt.default.vErrors}.length`),(0,gh.extendErrors)(e)},()=>e.error())}function vh({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function xl(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,je.stringify)(r)})}function Ih(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}pt.validSchemaType=Ih;function bh({schema:e,opts:t,self:r,errSchemaPath:n},a,i){if(Array.isArray(a.keyword)?!a.keyword.includes(i):a.keyword!==i)throw new Error("ajv implementation error");let o=a.dependencies;if(o?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}pt.validateKeywordUsage=bh});var Ml=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.extendSubschemaMode=Dt.extendSubschemaData=Dt.getSubschema=void 0;var ut=x(),Vl=U();function kh(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:i,topSchemaRef:o}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0,ut._)`${e.schemaPath}${(0,ut.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,ut._)`${e.schemaPath}${(0,ut.getProperty)(t)}${(0,ut.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Vl.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||i===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:a,topSchemaRef:o,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Dt.getSubschema=kh;function _h(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:i,propertyName:o}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:d,dataPathArr:l,opts:p}=t,f=s.let("data",(0,ut._)`${t.data}${(0,ut.getProperty)(r)}`,!0);c(f),e.errorPath=(0,ut.str)`${d}${(0,Vl.getErrorPath)(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=(0,ut._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let d=a instanceof ut.Name?a:s.let("data",a,!0);c(d),o!==void 0&&(e.propertyName=o)}i&&(e.dataTypes=i);function c(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}Dt.extendSubschemaData=_h;function Eh(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:i}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}Dt.extendSubschemaMode=Eh});var Po=R((KA,ql)=>{"use strict";ql.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var o=i[a];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var Fl=R((YA,Ul)=>{"use strict";var St=Ul.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},a=r.post||function(){};ba(t,n,a,e,"",e)};St.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};St.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};St.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};St.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 ba(e,t,r,n,a,i,o,s,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,i,o,s,c,d);for(var l in n){var p=n[l];if(Array.isArray(p)){if(l in St.arrayKeywords)for(var f=0;f<p.length;f++)ba(e,t,r,p[f],a+"/"+l+"/"+f,i,a,l,n,f)}else if(l in St.propsKeywords){if(p&&typeof p=="object")for(var u in p)ba(e,t,r,p[u],a+"/"+l+"/"+Ah(u),i,a,l,n,u)}else(l in St.keywords||e.allKeys&&!(l in St.skipKeywords))&&ba(e,t,r,p,a+"/"+l,i,a,l,n)}r(n,a,i,o,s,c,d)}}function Ah(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var dn=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.getSchemaRefs=Le.resolveUrl=Le.normalizeId=Le._getFullPath=Le.getFullPath=Le.inlineRef=void 0;var Rh=U(),Ph=Po(),Nh=Fl(),Dh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Sh(e,t=!0){return typeof e=="boolean"?!0:t===!0?!No(e):t?zl(e)<=t:!1}Le.inlineRef=Sh;var jh=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function No(e){for(let t in e){if(jh.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(No)||typeof r=="object"&&No(r))return!0}return!1}function zl(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Dh.has(r)&&(typeof e[r]=="object"&&(0,Rh.eachItem)(e[r],n=>t+=zl(n)),t===1/0))return 1/0}return t}function Bl(e,t="",r){r!==!1&&(t=Pr(t));let n=e.parse(t);return Jl(e,n)}Le.getFullPath=Bl;function Jl(e,t){return e.serialize(t).split("#")[0]+"#"}Le._getFullPath=Jl;var $h=/#\/?$/;function Pr(e){return e?e.replace($h,""):""}Le.normalizeId=Pr;function Oh(e,t,r){return r=Pr(r),e.resolve(t,r)}Le.resolveUrl=Oh;var Ch=/^[a-z_][-a-z0-9._]*$/i;function Th(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Pr(e[r]||t),i={"":a},o=Bl(n,a,!1),s={},c=new Set;return Nh(e,{allKeys:!0},(p,f,u,m)=>{if(m===void 0)return;let g=o+f,h=i[m];typeof p[r]=="string"&&(h=w.call(this,p[r])),_.call(this,p.$anchor),_.call(this,p.$dynamicAnchor),i[f]=h;function w(I){let A=this.opts.uriResolver.resolve;if(I=Pr(h?A(h,I):I),c.has(I))throw l(I);c.add(I);let y=this.refs[I];return typeof y=="string"&&(y=this.refs[y]),typeof y=="object"?d(p,y.schema,I):I!==Pr(g)&&(I[0]==="#"?(d(p,s[I],I),s[I]=p):this.refs[I]=g),I}function _(I){if(typeof I=="string"){if(!Ch.test(I))throw new Error(`invalid anchor "${I}"`);w.call(this,`#${I}`)}}}),s;function d(p,f,u){if(f!==void 0&&!Ph(p,f))throw l(u)}function l(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Le.getSchemaRefs=Th});var fn=R(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.getData=jt.KeywordCxt=jt.validateFunctionCode=void 0;var Hl=Al(),Gl=ln(),So=Io(),ka=ln(),xh=$l(),un=Ll(),Do=Ml(),D=x(),T=Ge(),Lh=dn(),wt=U(),pn=cn();function Vh(e){if(Ql(e)&&(ed(e),Zl(e))){Uh(e);return}Xl(e,()=>(0,Hl.topBoolOrEmptySchema)(e))}jt.validateFunctionCode=Vh;function Xl({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,D._)`${T.default.data}, ${T.default.valCxt}`,n.$async,()=>{e.code((0,D._)`"use strict"; ${Wl(r,a)}`),qh(e,a),e.code(i)}):e.func(t,(0,D._)`${T.default.data}, ${Mh(a)}`,n.$async,()=>e.code(Wl(r,a)).code(i))}function Mh(e){return(0,D._)`{${T.default.instancePath}="", ${T.default.parentData}, ${T.default.parentDataProperty}, ${T.default.rootData}=${T.default.data}${e.dynamicRef?(0,D._)`, ${T.default.dynamicAnchors}={}`:D.nil}}={}`}function qh(e,t){e.if(T.default.valCxt,()=>{e.var(T.default.instancePath,(0,D._)`${T.default.valCxt}.${T.default.instancePath}`),e.var(T.default.parentData,(0,D._)`${T.default.valCxt}.${T.default.parentData}`),e.var(T.default.parentDataProperty,(0,D._)`${T.default.valCxt}.${T.default.parentDataProperty}`),e.var(T.default.rootData,(0,D._)`${T.default.valCxt}.${T.default.rootData}`),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`${T.default.valCxt}.${T.default.dynamicAnchors}`)},()=>{e.var(T.default.instancePath,(0,D._)`""`),e.var(T.default.parentData,(0,D._)`undefined`),e.var(T.default.parentDataProperty,(0,D._)`undefined`),e.var(T.default.rootData,T.default.data),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`{}`)})}function Uh(e){let{schema:t,opts:r,gen:n}=e;Xl(e,()=>{r.$comment&&t.$comment&&rd(e),Gh(e),n.let(T.default.vErrors,null),n.let(T.default.errors,0),r.unevaluated&&Fh(e),td(e),Yh(e)})}function Fh(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,D._)`${r}.evaluated`),t.if((0,D._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,D._)`${e.evaluated}.props`,(0,D._)`undefined`)),t.if((0,D._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,D._)`${e.evaluated}.items`,(0,D._)`undefined`))}function Wl(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function zh(e,t){if(Ql(e)&&(ed(e),Zl(e))){Bh(e,t);return}(0,Hl.boolOrEmptySchema)(e,t)}function Zl({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Ql(e){return typeof e.schema!="boolean"}function Bh(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&rd(e),Wh(e),Kh(e);let i=n.const("_errs",T.default.errors);td(e,i),n.var(t,(0,D._)`${i} === ${T.default.errors}`)}function ed(e){(0,wt.checkUnknownRules)(e),Jh(e)}function td(e,t){if(e.opts.jtd)return Kl(e,[],!1,t);let r=(0,Gl.getSchemaTypes)(e.schema),n=(0,Gl.coerceAndCheckDataType)(e,r);Kl(e,r,!n,t)}function Jh(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,wt.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Gh(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,wt.checkStrictMode)(e,"default is ignored in the schema root")}function Wh(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Lh.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Kh(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function rd({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,D._)`${T.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let o=(0,D.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,D._)`${T.default.self}.opts.$comment(${i}, ${o}, ${s}.schema)`)}}function Yh(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,D._)`${T.default.errors} === 0`,()=>t.return(T.default.data),()=>t.throw((0,D._)`new ${a}(${T.default.vErrors})`)):(t.assign((0,D._)`${n}.errors`,T.default.vErrors),i.unevaluated&&Hh(e),t.return((0,D._)`${T.default.errors} === 0`))}function Hh({gen:e,evaluated:t,props:r,items:n}){r instanceof D.Name&&e.assign((0,D._)`${t}.props`,r),n instanceof D.Name&&e.assign((0,D._)`${t}.items`,n)}function Kl(e,t,r,n){let{gen:a,schema:i,data:o,allErrors:s,opts:c,self:d}=e,{RULES:l}=d;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,wt.schemaHasRulesButRef)(i,l))){a.block(()=>ad(e,"$ref",l.all.$ref.definition));return}c.jtd||Xh(e,t),a.block(()=>{for(let f of l.rules)p(f);p(l.post)});function p(f){(0,So.shouldUseGroup)(i,f)&&(f.type?(a.if((0,ka.checkDataType)(f.type,o,c.strictNumbers)),Yl(e,f),t.length===1&&t[0]===f.type&&r&&(a.else(),(0,ka.reportTypeError)(e)),a.endIf()):Yl(e,f),s||a.if((0,D._)`${T.default.errors} === ${n||0}`))}}function Yl(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,xh.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,So.shouldUseRule)(n,i)&&ad(e,i.keyword,i.definition,t.type)})}function Xh(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Zh(e,t),e.opts.allowUnionTypes||Qh(e,t),ey(e,e.dataTypes))}function Zh(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{nd(e.dataTypes,r)||jo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),ry(e,t)}}function Qh(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&jo(e,"use allowUnionTypes to allow union type keyword")}function ey(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,So.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(o=>ty(t,o))&&jo(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function ty(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function nd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function ry(e,t){let r=[];for(let n of e.dataTypes)nd(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function jo(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,wt.checkStrictMode)(e,t,e.opts.strictTypes)}var _a=class{constructor(t,r,n){if((0,un.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,wt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",id(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,un.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",T.default.errors))}result(t,r,n){this.failResult((0,D.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,D.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?pn.reportExtraError:pn.reportError)(this,this.def.error,r)}$dataError(){(0,pn.reportError)(this,this.def.$dataError||pn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,pn.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=D.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:o}=this;n.if((0,D.or)((0,D._)`${a} === undefined`,r)),t!==D.nil&&n.assign(t,!0),(i.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==D.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,D.or)(o(),s());function o(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,ka.checkDataTypes)(c,r,i.opts.strictNumbers,ka.DataType.Wrong)}`}return D.nil}function s(){if(a.validateSchema){let c=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(t,r){let n=(0,Do.getSubschema)(this.it,t);(0,Do.extendSubschemaData)(n,this.it,t),(0,Do.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return zh(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=wt.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=wt.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,D.Name)),!0}};jt.KeywordCxt=_a;function ad(e,t,r,n){let a=new _a(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,un.funcKeywordCode)(a,r):"macro"in r?(0,un.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,un.funcKeywordCode)(a,r)}var ny=/^\/(?:[^~]|~0|~1)*$/,ay=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function id(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return T.default.rootData;if(e[0]==="/"){if(!ny.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=T.default.rootData}else{let d=ay.exec(e);if(!d)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+d[1];if(a=d[2],a==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(i=r[t-l],!a)return i}let o=i,s=a.split("/");for(let d of s)d&&(i=(0,D._)`${i}${(0,D.getProperty)((0,wt.unescapeJsonPointer)(d))}`,o=(0,D._)`${o} && ${i}`);return o;function c(d,l){return`Cannot access ${d} ${l} levels up, current level is ${t}`}}jt.getData=id});var Ea=R(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var $o=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Oo.default=$o});var mn=R(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var Co=dn(),To=class extends Error{constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Co.resolveUrl)(t,r,n),this.missingSchema=(0,Co.normalizeId)((0,Co.getFullPath)(t,this.missingRef))}};xo.default=To});var gn=R(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.resolveSchema=Ke.getCompilingSchema=Ke.resolveRef=Ke.compileSchema=Ke.SchemaEnv=void 0;var tt=x(),iy=Ea(),Yt=Ge(),rt=dn(),od=U(),oy=fn(),Nr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,rt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Ke.SchemaEnv=Nr;function Vo(e){let t=sd.call(this,e);if(t)return t;let r=(0,rt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,o=new tt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),s;e.$async&&(s=o.scopeValue("Error",{ref:iy.default,code:(0,tt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");e.validateName=c;let d={gen:o,allErrors:this.opts.allErrors,data:Yt.default.data,parentData:Yt.default.parentData,parentDataProperty:Yt.default.parentDataProperty,dataNames:[Yt.default.data],dataPathArr:[tt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,tt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:tt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,tt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,oy.validateFunctionCode)(d),o.optimize(this.opts.code.optimize);let p=o.toString();l=`${o.scopeRefs(Yt.default.scope)}return ${p}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let u=new Function(`${Yt.default.self}`,`${Yt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:u}),u.errors=null,u.schema=e.schema,u.schemaEnv=e,e.$async&&(u.$async=!0),this.opts.code.source===!0&&(u.source={validateName:c,validateCode:p,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:g}=d;u.evaluated={props:m instanceof tt.Name?void 0:m,items:g instanceof tt.Name?void 0:g,dynamicProps:m instanceof tt.Name,dynamicItems:g instanceof tt.Name},u.source&&(u.source.evaluated=(0,tt.stringify)(u.evaluated))}return e.validate=u,e}catch(p){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),p}finally{this._compilations.delete(e)}}Ke.compileSchema=Vo;function sy(e,t,r){var n;r=(0,rt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=dy.call(this,e,r);if(i===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;o&&(i=new Nr({schema:o,schemaId:s,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=cy.call(this,i)}Ke.resolveRef=sy;function cy(e){return(0,rt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Vo.call(this,e)}function sd(e){for(let t of this._compilations)if(ly(t,e))return t}Ke.getCompilingSchema=sd;function ly(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function dy(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Aa.call(this,e,t)}function Aa(e,t){let r=this.opts.uriResolver.parse(t),n=(0,rt._getFullPath)(this.opts.uriResolver,r),a=(0,rt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Lo.call(this,r,e);let i=(0,rt.normalizeId)(n),o=this.refs[i]||this.schemas[i];if(typeof o=="string"){let s=Aa.call(this,e,o);return typeof s?.schema!="object"?void 0:Lo.call(this,r,s)}if(typeof o?.schema=="object"){if(o.validate||Vo.call(this,o),i===(0,rt.normalizeId)(t)){let{schema:s}=o,{schemaId:c}=this.opts,d=s[c];return d&&(a=(0,rt.resolveUrl)(this.opts.uriResolver,a,d)),new Nr({schema:s,schemaId:c,root:e,baseId:a})}return Lo.call(this,r,o)}}Ke.resolveSchema=Aa;var py=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Lo(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,od.unescapeFragment)(s)];if(c===void 0)return;r=c;let d=typeof r=="object"&&r[this.opts.schemaId];!py.has(s)&&d&&(t=(0,rt.resolveUrl)(this.opts.uriResolver,t,d))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,od.schemaHasRulesButRef)(r,this.RULES)){let s=(0,rt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Aa.call(this,n,s)}let{schemaId:o}=this.opts;if(i=i||new Nr({schema:r,schemaId:o,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var cd=R((tR,uy)=>{uy.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Uo=R((rR,md)=>{"use strict";var fy=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),dd=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),Mo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),pd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),my=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function qo(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var gy=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ld(e){return e.length=0,!0}function hy(e,t,r){if(e.length){let n=qo(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function yy(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,o=!1,s=hy;for(let c=0;c<e.length;c++){let d=e[c];if(!(d==="["||d==="]"))if(d===":"){if(i===!0&&(o=!0),!s(a,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(d==="%"){if(!s(a,n,r))break;s=ld}else{a.push(d);continue}}return a.length&&(s===ld?r.zone=a.join(""):o?n.push(a.join("")):n.push(qo(a))),r.address=n.join(""),r}function ud(e){if(wy(e,":")<2)return{host:e,isIPV6:!1};let t=yy(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function wy(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function vy(e){let t=e,r=[],n=-1,a=0;for(;a=t.length;){if(a===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(a===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(a===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var Iy={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},by=/[@/?#:]/g,ky=/[@/?#]/g;function fd(e,t){let r=t?ky:by;return r.lastIndex=0,e.replace(r,n=>Iy[n])}function _y(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let a=e.slice(n+1,n+3);if(Mo(a)){let i=a.toUpperCase(),o=String.fromCharCode(parseInt(i,16));t&&pd(o)?r+=o:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function Ey(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Mo(n)){let a=n.toUpperCase(),i=String.fromCharCode(parseInt(a,16));i!=="."&&pd(i)?t+=i:t+="%"+a,r+=2;continue}}my(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Ay(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Mo(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Ry(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!dd(r)){let n=ud(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=fd(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}md.exports={nonSimpleDomain:gy,recomposeAuthority:Ry,reescapeHostDelimiters:fd,normalizePercentEncoding:_y,normalizePathEncoding:Ey,escapePreservingEscapes:Ay,removeDotSegments:vy,isIPv4:dd,isUUID:fy,normalizeIPv6:ud,stringArrayToHexStripped:qo}});var vd=R((nR,wd)=>{"use strict";var{isUUID:Py}=Uo(),Ny=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Dy=["http","https","ws","wss","urn","urn:uuid"];function Sy(e){return Dy.indexOf(e)!==-1}function Fo(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 gd(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function hd(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function jy(e){return e.secure=Fo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function $y(e){if((e.port===(Fo(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,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Oy(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Ny);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=zo(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Cy(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=zo(a);i&&(e=i.serialize(e,t));let o=e,s=e.nss;return o.path=`${n||t.nid}:${s}`,t.skipEscape=!0,o}function Ty(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Py(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function xy(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var yd={scheme:"http",domainHost:!0,parse:gd,serialize:hd},Ly={scheme:"https",domainHost:yd.domainHost,parse:gd,serialize:hd},Ra={scheme:"ws",domainHost:!0,parse:jy,serialize:$y},Vy={scheme:"wss",domainHost:Ra.domainHost,parse:Ra.parse,serialize:Ra.serialize},My={scheme:"urn",parse:Oy,serialize:Cy,skipNormalize:!0},qy={scheme:"urn:uuid",parse:Ty,serialize:xy,skipNormalize:!0},Pa={http:yd,https:Ly,ws:Ra,wss:Vy,urn:My,"urn:uuid":qy};Object.setPrototypeOf(Pa,null);function zo(e){return e&&(Pa[e]||Pa[e.toLowerCase()])||void 0}wd.exports={wsIsSecure:Fo,SCHEMES:Pa,isValidSchemeName:Sy,getSchemeHandler:zo}});var Ed=R((aR,Sa)=>{"use strict";var{normalizeIPv6:Uy,removeDotSegments:hn,recomposeAuthority:Fy,normalizePercentEncoding:zy,normalizePathEncoding:By,escapePreservingEscapes:Jy,reescapeHostDelimiters:Gy,isIPv4:Wy,nonSimpleDomain:Ky}=Uo(),{SCHEMES:Yy,getSchemeHandler:bd}=vd();function Hy(e,t){return typeof e=="string"?e=nw(e,t):typeof e=="object"&&(e=Da(Ht(e,t),t)),e}function Xy(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:a,malformedAuthorityOrPort:i}=Na(e,n),{parsed:o,malformedAuthorityOrPort:s}=Na(t,n);if(i||s)throw new Error(a.error||o.error||"URI is malformed.");let c=kd(a,o,n,!0);return n.skipEscape=!0,Ht(c,n)}function kd(e,t,r,n){let a={};return n||(e=Da(Ht(e,r),r),t=Da(Ht(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=hn(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=hn(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=hn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=hn(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function Zy(e,t,r){let n=Id(e,r),a=Id(t,r);return n!==void 0&&a!==void 0&&n.toLowerCase()===a.toLowerCase()}function Ht(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),a=[],i=bd(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=zy(r.path):(r.path=Jy(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&a.push(r.scheme,":");let o=Fy(r);if(o!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(o),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let s=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(s=hn(s)),o===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),a.push(s)}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}var Qy=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ew=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,tw=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function rw(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 Na(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=!1,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let o=e.match(ew);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",a=!0);let s=e.match(tw);if(s!==null){let d=s[1],l=d.replace(/[\t\n\r]/g,"");l.length>=2&&(l.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",a=!0):d.length!==l.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",a=!0))}let c=e.match(Qy);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let d=rw(n,c);if(d!==void 0&&(n.error=n.error||d,a=!0),n.host)if(Wy(n.host)===!1){let f=Uy(n.host);n.host=f.host.toLowerCase(),i=f.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let l=bd(r.scheme||n.scheme);if(!r.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(r.domainHost||l&&l.domainHost)&&i===!1&&Ky(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!l||l&&!l.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Gy(unescape(n.host),i))),n.path&&(n.path=By(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:a}}function Da(e,t){return Na(e,t).parsed}function nw(e,t){return _d(e,t).normalized}function _d(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Na(e,t);return{normalized:n?e:Ht(r,t),malformedAuthorityOrPort:n}}function Id(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=_d(e,t);return n?void 0:r}if(typeof e=="object")return Ht(e,t)}var Bo={SCHEMES:Yy,normalize:Hy,resolve:Xy,resolveComponent:kd,equal:Zy,serialize:Ht,parse:Da};Sa.exports=Bo;Sa.exports.default=Bo;Sa.exports.fastUri=Bo});var Rd=R(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});var Ad=Ed();Ad.code='require("ajv/dist/runtime/uri").default';Jo.default=Ad});var Cd=R(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=void 0;var aw=fn();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return aw.KeywordCxt}});var Dr=x();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return Dr._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return Dr.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return Dr.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return Dr.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return Dr.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return Dr.CodeGen}});var iw=Ea(),jd=mn(),ow=vo(),yn=gn(),sw=x(),wn=dn(),ja=ln(),Wo=U(),Pd=cd(),cw=Rd(),$d=(e,t)=>new RegExp(e,t);$d.code="new RegExp";var lw=["removeAdditional","useDefaults","coerceTypes"],dw=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),pw={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."},uw={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Nd=200;function fw(e){var t,r,n,a,i,o,s,c,d,l,p,f,u,m,g,h,w,_,I,A,y,k,S,O,ae;let $=e.strict,P=(t=e.code)===null||t===void 0?void 0:t.optimize,W=P===!0||P===void 0?1:P||0,re=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:$d,Be=(a=e.uriResolver)!==null&&a!==void 0?a:cw.default;return{strictSchema:(o=(i=e.strictSchema)!==null&&i!==void 0?i:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:$)!==null&&c!==void 0?c:!0,strictTypes:(l=(d=e.strictTypes)!==null&&d!==void 0?d:$)!==null&&l!==void 0?l:"log",strictTuples:(f=(p=e.strictTuples)!==null&&p!==void 0?p:$)!==null&&f!==void 0?f:"log",strictRequired:(m=(u=e.strictRequired)!==null&&u!==void 0?u:$)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:W,regExp:re}:{optimize:W,regExp:re},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:Nd,loopEnum:(h=e.loopEnum)!==null&&h!==void 0?h:Nd,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(_=e.messages)!==null&&_!==void 0?_:!0,inlineRefs:(I=e.inlineRefs)!==null&&I!==void 0?I:!0,schemaId:(A=e.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(y=e.addUsedSchema)!==null&&y!==void 0?y:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(S=e.validateFormats)!==null&&S!==void 0?S:!0,unicodeRegExp:(O=e.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(ae=e.int32range)!==null&&ae!==void 0?ae:!0,uriResolver:Be}}var vn=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...fw(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new sw.ValueScope({scope:{},prefixes:dw,es5:r,lines:n}),this.logger=vw(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,ow.getRules)(),Dd.call(this,pw,t,"NOT SUPPORTED"),Dd.call(this,uw,t,"DEPRECATED","warn"),this._metaOpts=yw.call(this),t.formats&&gw.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&hw.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),mw.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Pd;n==="id"&&(a={...Pd},a.id=a.$id,delete a.$id),r&&t&&this.addMetaSchema(a,a[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let a=n(r);return"$async"in n||(this.errors=n.errors),a}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return a.call(this,t,r);async function a(l,p){await i.call(this,l.$schema);let f=this._addSchema(l,p);return f.validate||o.call(this,f)}async function i(l){l&&!this.getSchema(l)&&await a.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(p){if(!(p instanceof jd.default))throw p;return s.call(this,p),await c.call(this,p.missingSchema),o.call(this,l)}}function s({missingSchema:l,missingRef:p}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${p} cannot be resolved`)}async function c(l){let p=await d.call(this,l);this.refs[l]||await i.call(this,p.$schema),this.refs[l]||this.addSchema(p,l,r)}async function d(l){let p=this._loading[l];if(p)return p;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,a=this.opts.validateSchema){if(Array.isArray(t)){for(let o of t)this.addSchema(o,void 0,n,a);return this}let i;if(typeof t=="object"){let{schemaId:o}=this.opts;if(i=t[o],i!==void 0&&typeof i!="string")throw new Error(`schema ${o} must be string`)}return r=(0,wn.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,a,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let a=this.validate(n,t);if(!a&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return a}getSchema(t){let r;for(;typeof(r=Sd.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new yn.SchemaEnv({schema:{},schemaId:n});if(r=yn.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Sd.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,wn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(bw.call(this,n,r),!r)return(0,Wo.eachItem)(n,i=>Go.call(this,i)),this;_w.call(this,r);let a={...r,type:(0,ja.getJSONTypes)(r.type),schemaType:(0,ja.getJSONTypes)(r.schemaType)};return(0,Wo.eachItem)(n,a.type.length===0?i=>Go.call(this,i,a):i=>a.type.forEach(o=>Go.call(this,i,a,o))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),o=t;for(let s of i)o=o[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:d}=c.definition,l=o[s];d&&l&&(o[s]=Od(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let a=t[n];(!r||r.test(n))&&(typeof a=="string"?delete t[n]:a&&!a.meta&&(this._cache.delete(a.schema),delete t[n]))}}_addSchema(t,r,n,a=this.opts.validateSchema,i=this.opts.addUsedSchema){let o,{schemaId:s}=this.opts;if(typeof t=="object")o=t[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,wn.normalizeId)(o||n);let d=wn.getSchemaRefs.call(this,t,n);return c=new yn.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:d}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),a&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):yn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{yn.compileSchema.call(this,t)}finally{this.opts=r}}};vn.ValidationError=iw.default;vn.MissingRefError=jd.default;ve.default=vn;function Dd(e,t,r,n="error"){for(let a in e){let i=a;i in t&&this.logger[n](`${r}: option ${a}. ${e[i]}`)}}function Sd(e){return e=(0,wn.normalizeId)(e),this.schemas[e]||this.refs[e]}function mw(){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 gw(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function hw(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 r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function yw(){let e={...this.opts};for(let t of lw)delete e[t];return e}var ww={log(){},warn(){},error(){}};function vw(e){if(e===!1)return ww;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var Iw=/^[a-z_$][a-z0-9_$:-]*$/i;function bw(e,t){let{RULES:r}=this;if((0,Wo.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Iw.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Go(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,o=a?i.post:i.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},i.rules.push(o)),i.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,ja.getJSONTypes)(t.type),schemaType:(0,ja.getJSONTypes)(t.schemaType)}};t.before?kw.call(this,o,s,t.before):o.rules.push(s),i.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function kw(e,t,r){let n=e.rules.findIndex(a=>a.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function _w(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Od(t)),e.validateSchema=this.compile(t,!0))}var Ew={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Od(e){return{anyOf:[e,Ew]}}});var Td=R(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});var Aw={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ko.default=Aw});var Ca=R(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.callRef=Xt.getValidate=void 0;var Rw=mn(),xd=We(),Ve=x(),Sr=Ge(),Ld=gn(),$a=U(),Pw={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:i,validateName:o,opts:s,self:c}=n,{root:d}=i;if((r==="#"||r==="#/")&&a===d.baseId)return p();let l=Ld.resolveRef.call(c,d,a,r);if(l===void 0)throw new Rw.default(n.opts.uriResolver,a,r);if(l instanceof Ld.SchemaEnv)return f(l);return u(l);function p(){if(i===d)return Oa(e,o,i,i.$async);let m=t.scopeValue("root",{ref:d});return Oa(e,(0,Ve._)`${m}.validate`,d,d.$async)}function f(m){let g=Vd(e,m);Oa(e,g,m,m.$async)}function u(m){let g=t.scopeValue("schema",s.code.source===!0?{ref:m,code:(0,Ve.stringify)(m)}:{ref:m}),h=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Ve.nil,topSchemaRef:g,errSchemaPath:r},h);e.mergeEvaluated(w),e.ok(h)}}};function Vd(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ve._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Xt.getValidate=Vd;function Oa(e,t,r,n){let{gen:a,it:i}=e,{allErrors:o,schemaEnv:s,opts:c}=i,d=c.passContext?Sr.default.this:Ve.nil;n?l():p();function l(){if(!s.$async)throw new Error("async schema referenced by sync schema");let m=a.let("valid");a.try(()=>{a.code((0,Ve._)`await ${(0,xd.callValidateCode)(e,t,d)}`),u(t),o||a.assign(m,!0)},g=>{a.if((0,Ve._)`!(${g} instanceof ${i.ValidationError})`,()=>a.throw(g)),f(g),o||a.assign(m,!1)}),e.ok(m)}function p(){e.result((0,xd.callValidateCode)(e,t,d),()=>u(t),()=>f(t))}function f(m){let g=(0,Ve._)`${m}.errors`;a.assign(Sr.default.vErrors,(0,Ve._)`${Sr.default.vErrors} === null ? ${g} : ${Sr.default.vErrors}.concat(${g})`),a.assign(Sr.default.errors,(0,Ve._)`${Sr.default.vErrors}.length`)}function u(m){var g;if(!i.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(i.props=$a.mergeEvaluated.props(a,h.props,i.props));else{let w=a.var("props",(0,Ve._)`${m}.evaluated.props`);i.props=$a.mergeEvaluated.props(a,w,i.props,Ve.Name)}if(i.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(i.items=$a.mergeEvaluated.items(a,h.items,i.items));else{let w=a.var("items",(0,Ve._)`${m}.evaluated.items`);i.items=$a.mergeEvaluated.items(a,w,i.items,Ve.Name)}}}Xt.callRef=Oa;Xt.default=Pw});var Md=R(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var Nw=Td(),Dw=Ca(),Sw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Nw.default,Dw.default];Yo.default=Sw});var qd=R(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});var Ta=x(),$t=Ta.operators,xa={maximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},minimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},exclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},exclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},jw={message:({keyword:e,schemaCode:t})=>(0,Ta.str)`must be ${xa[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ta._)`{comparison: ${xa[e].okStr}, limit: ${t}}`},$w={keyword:Object.keys(xa),type:"number",schemaType:"number",$data:!0,error:jw,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Ta._)`${r} ${xa[t].fail} ${n} || isNaN(${r})`)}};Ho.default=$w});var Ud=R(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});var In=x(),Ow={message:({schemaCode:e})=>(0,In.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,In._)`{multipleOf: ${e}}`},Cw={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Ow,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,o=t.let("res"),s=i?(0,In._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:(0,In._)`${o} !== parseInt(${o})`;e.fail$data((0,In._)`(${n} === 0 || (${o} = ${r}/${n}, ${s}))`)}};Xo.default=Cw});var zd=R(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});function Fd(e){let t=e.length,r=0,n=0,a;for(;n<t;)r++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<t&&(a=e.charCodeAt(n),(a&64512)===56320&&n++);return r}Zo.default=Fd;Fd.code='require("ajv/dist/runtime/ucs2length").default'});var Bd=R(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var Zt=x(),Tw=U(),xw=zd(),Lw={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Zt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Zt._)`{limit: ${e}}`},Vw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Lw,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?Zt.operators.GT:Zt.operators.LT,o=a.opts.unicode===!1?(0,Zt._)`${r}.length`:(0,Zt._)`${(0,Tw.useFunc)(e.gen,xw.default)}(${r})`;e.fail$data((0,Zt._)`${o} ${i} ${n}`)}};Qo.default=Vw});var Jd=R(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var Mw=We(),qw=U(),jr=x(),Uw={message:({schemaCode:e})=>(0,jr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,jr._)`{pattern: ${e}}`},Fw={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Uw,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:o}=e,s=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,d=c.code==="new RegExp"?(0,jr._)`new RegExp`:(0,qw.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,jr._)`${d}(${i}, ${s}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,jr._)`!${l}`)}else{let c=(0,Mw.usePattern)(e,a);e.fail$data((0,jr._)`!${c}.test(${r})`)}}};es.default=Fw});var Gd=R(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});var bn=x(),zw={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,bn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,bn._)`{limit: ${e}}`},Bw={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:zw,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?bn.operators.GT:bn.operators.LT;e.fail$data((0,bn._)`Object.keys(${r}).length ${a} ${n}`)}};ts.default=Bw});var Wd=R(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var kn=We(),_n=x(),Jw=U(),Gw={message:({params:{missingProperty:e}})=>(0,_n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,_n._)`{missingProperty: ${e}}`},Ww={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Gw,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:o}=e,{opts:s}=o;if(!i&&r.length===0)return;let c=r.length>=s.loopRequired;if(o.allErrors?d():l(),s.strictRequired){let u=e.parentSchema.properties,{definedProperties:m}=e.it;for(let g of r)if(u?.[g]===void 0&&!m.has(g)){let h=o.schemaEnv.baseId+o.errSchemaPath,w=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,Jw.checkStrictMode)(o,w,o.opts.strictRequired)}}function d(){if(c||i)e.block$data(_n.nil,p);else for(let u of r)(0,kn.checkReportMissingProp)(e,u)}function l(){let u=t.let("missing");if(c||i){let m=t.let("valid",!0);e.block$data(m,()=>f(u,m)),e.ok(m)}else t.if((0,kn.checkMissingProp)(e,r,u)),(0,kn.reportMissingProp)(e,u),t.else()}function p(){t.forOf("prop",n,u=>{e.setParams({missingProperty:u}),t.if((0,kn.noPropertyInData)(t,a,u,s.ownProperties),()=>e.error())})}function f(u,m){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(m,(0,kn.propertyInData)(t,a,u,s.ownProperties)),t.if((0,_n.not)(m),()=>{e.error(),t.break()})},_n.nil)}}};rs.default=Ww});var Kd=R(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});var En=x(),Kw={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,En.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,En._)`{limit: ${e}}`},Yw={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Kw,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?En.operators.GT:En.operators.LT;e.fail$data((0,En._)`${r}.length ${a} ${n}`)}};ns.default=Yw});var La=R(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});var Yd=Po();Yd.code='require("ajv/dist/runtime/equal").default';as.default=Yd});var Hd=R(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});var is=ln(),Ie=x(),Hw=U(),Xw=La(),Zw={message:({params:{i:e,j:t}})=>(0,Ie.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Ie._)`{i: ${e}, j: ${t}}`},Qw={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Zw,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:o,it:s}=e;if(!n&&!a)return;let c=t.let("valid"),d=i.items?(0,is.getSchemaTypes)(i.items):[];e.block$data(c,l,(0,Ie._)`${o} === false`),e.ok(c);function l(){let m=t.let("i",(0,Ie._)`${r}.length`),g=t.let("j");e.setParams({i:m,j:g}),t.assign(c,!0),t.if((0,Ie._)`${m} > 1`,()=>(p()?f:u)(m,g))}function p(){return d.length>0&&!d.some(m=>m==="object"||m==="array")}function f(m,g){let h=t.name("item"),w=(0,is.checkDataTypes)(d,h,s.opts.strictNumbers,is.DataType.Wrong),_=t.const("indices",(0,Ie._)`{}`);t.for((0,Ie._)`;${m}--;`,()=>{t.let(h,(0,Ie._)`${r}[${m}]`),t.if(w,(0,Ie._)`continue`),d.length>1&&t.if((0,Ie._)`typeof ${h} == "string"`,(0,Ie._)`${h} += "_"`),t.if((0,Ie._)`typeof ${_}[${h}] == "number"`,()=>{t.assign(g,(0,Ie._)`${_}[${h}]`),e.error(),t.assign(c,!1).break()}).code((0,Ie._)`${_}[${h}] = ${m}`)})}function u(m,g){let h=(0,Hw.useFunc)(t,Xw.default),w=t.name("outer");t.label(w).for((0,Ie._)`;${m}--;`,()=>t.for((0,Ie._)`${g} = ${m}; ${g}--;`,()=>t.if((0,Ie._)`${h}(${r}[${m}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};os.default=Qw});var Xd=R(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var ss=x(),ev=U(),tv=La(),rv={message:"must be equal to constant",params:({schemaCode:e})=>(0,ss._)`{allowedValue: ${e}}`},nv={keyword:"const",$data:!0,error:rv,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,ss._)`!${(0,ev.useFunc)(t,tv.default)}(${r}, ${a})`):e.fail((0,ss._)`${i} !== ${r}`)}};cs.default=nv});var Zd=R(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var An=x(),av=U(),iv=La(),ov={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,An._)`{allowedValues: ${e}}`},sv={keyword:"enum",schemaType:"array",$data:!0,error:ov,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:o}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let s=a.length>=o.opts.loopEnum,c,d=()=>c??(c=(0,av.useFunc)(t,iv.default)),l;if(s||n)l=t.let("valid"),e.block$data(l,p);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let u=t.const("vSchema",i);l=(0,An.or)(...a.map((m,g)=>f(u,g)))}e.pass(l);function p(){t.assign(l,!1),t.forOf("v",i,u=>t.if((0,An._)`${d()}(${r}, ${u})`,()=>t.assign(l,!0).break()))}function f(u,m){let g=a[m];return typeof g=="object"&&g!==null?(0,An._)`${d()}(${r}, ${u}[${m}])`:(0,An._)`${r} === ${g}`}}};ls.default=sv});var Qd=R(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var cv=qd(),lv=Ud(),dv=Bd(),pv=Jd(),uv=Gd(),fv=Wd(),mv=Kd(),gv=Hd(),hv=Xd(),yv=Zd(),wv=[cv.default,lv.default,dv.default,pv.default,uv.default,fv.default,mv.default,gv.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},hv.default,yv.default];ds.default=wv});var us=R(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.validateAdditionalItems=void 0;var Qt=x(),ps=U(),vv={message:({params:{len:e}})=>(0,Qt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Qt._)`{limit: ${e}}`},Iv={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:vv,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ps.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ep(e,n)}};function ep(e,t){let{gen:r,schema:n,data:a,keyword:i,it:o}=e;o.items=!0;let s=r.const("len",(0,Qt._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Qt._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,ps.alwaysValidSchema)(o,n)){let d=r.var("valid",(0,Qt._)`${s} <= ${t.length}`);r.if((0,Qt.not)(d),()=>c(d)),e.ok(d)}function c(d){r.forRange("i",t.length,s,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:ps.Type.Num},d),o.allErrors||r.if((0,Qt.not)(d),()=>r.break())})}}Rn.validateAdditionalItems=ep;Rn.default=Iv});var fs=R(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.validateTuple=void 0;var tp=x(),Va=U(),bv=We(),kv={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return rp(e,"additionalItems",t);r.items=!0,!(0,Va.alwaysValidSchema)(r,t)&&e.ok((0,bv.validateArray)(e))}};function rp(e,t,r=e.schema){let{gen:n,parentSchema:a,data:i,keyword:o,it:s}=e;l(a),s.opts.unevaluated&&r.length&&s.items!==!0&&(s.items=Va.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),d=n.const("len",(0,tp._)`${i}.length`);r.forEach((p,f)=>{(0,Va.alwaysValidSchema)(s,p)||(n.if((0,tp._)`${d} > ${f}`,()=>e.subschema({keyword:o,schemaProp:f,dataProp:f},c)),e.ok(c))});function l(p){let{opts:f,errSchemaPath:u}=s,m=r.length,g=m===p.minItems&&(m===p.maxItems||p[t]===!1);if(f.strictTuples&&!g){let h=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Va.checkStrictMode)(s,h,f.strictTuples)}}}Pn.validateTuple=rp;Pn.default=kv});var np=R(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var _v=fs(),Ev={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,_v.validateTuple)(e,"items")};ms.default=Ev});var ip=R(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var ap=x(),Av=U(),Rv=We(),Pv=us(),Nv={message:({params:{len:e}})=>(0,ap.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ap._)`{limit: ${e}}`},Dv={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Nv,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,Av.alwaysValidSchema)(n,t)&&(a?(0,Pv.validateAdditionalItems)(e,a):e.ok((0,Rv.validateArray)(e)))}};gs.default=Dv});var op=R(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var Ye=x(),Ma=U(),Sv={message:({params:{min:e,max:t}})=>t===void 0?(0,Ye.str)`must contain at least ${e} valid item(s)`:(0,Ye.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ye._)`{minContains: ${e}}`:(0,Ye._)`{minContains: ${e}, maxContains: ${t}}`},jv={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Sv,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e,o,s,{minContains:c,maxContains:d}=n;i.opts.next?(o=c===void 0?1:c,s=d):o=1;let l=t.const("len",(0,Ye._)`${a}.length`);if(e.setParams({min:o,max:s}),s===void 0&&o===0){(0,Ma.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&o>s){(0,Ma.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ma.alwaysValidSchema)(i,r)){let g=(0,Ye._)`${l} >= ${o}`;s!==void 0&&(g=(0,Ye._)`${g} && ${l} <= ${s}`),e.pass(g);return}i.items=!0;let p=t.name("valid");s===void 0&&o===1?u(p,()=>t.if(p,()=>t.break())):o===0?(t.let(p,!0),s!==void 0&&t.if((0,Ye._)`${a}.length > 0`,f)):(t.let(p,!1),f()),e.result(p,()=>e.reset());function f(){let g=t.name("_valid"),h=t.let("count",0);u(g,()=>t.if(g,()=>m(h)))}function u(g,h){t.forRange("i",0,l,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Ma.Type.Num,compositeRule:!0},g),h()})}function m(g){t.code((0,Ye._)`${g}++`),s===void 0?t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0).break()):(t.if((0,Ye._)`${g} > ${s}`,()=>t.assign(p,!1).break()),o===1?t.assign(p,!0):t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0)))}}};hs.default=jv});var qa=R(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateSchemaDeps=ft.validatePropertyDeps=ft.error=void 0;var ys=x(),$v=U(),Nn=We();ft.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,ys.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,ys._)`{property: ${e},
5
+ || ${o} === "boolean" || ${a} === null`).assign(s,(0,L._)`[${a}]`)}}}function Qg({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${r}]`,n))}function bo(e,t,r,n=Ar.Correct){let a=n===Ar.Correct?L.operators.EQ:L.operators.NEQ,i;switch(e){case"null":return(0,L._)`${t} ${a} null`;case"array":i=(0,L._)`Array.isArray(${t})`;break;case"object":i=(0,L._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=o((0,L._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=o();break;default:return(0,L._)`typeof ${t} ${a} ${e}`}return n===Ar.Correct?i:(0,L.not)(i);function o(s=L.nil){return(0,L.and)((0,L._)`typeof ${t} == "number"`,s,r?(0,L._)`isFinite(${t})`:L.nil)}}Pe.checkDataType=bo;function ko(e,t,r,n){if(e.length===1)return bo(e[0],t,r,n);let a,i=(0,Nl.toHash)(e);if(i.array&&i.object){let o=(0,L._)`typeof ${t} != "object"`;a=i.null?o:(0,L._)`!${t} || ${o}`,delete i.null,delete i.array,delete i.object}else a=L.nil;i.number&&delete i.integer;for(let o in i)a=(0,L.and)(a,bo(o,t,r,n));return a}Pe.checkDataTypes=ko;var eh={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function _o(e){let t=th(e);(0,Kg.reportError)(t,eh)}Pe.reportTypeError=_o;function th(e){let{gen:t,data:r,schema:n}=e,a=(0,Nl.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}});var $l=R(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.assignDefaults=void 0;var Rr=x(),rh=U();function nh(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)jl(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>jl(e,i,a.default))}Ia.assignDefaults=nh;function jl(e,t,r){let{gen:n,compositeRule:a,data:i,opts:o}=e;if(r===void 0)return;let s=(0,Rr._)`${i}${(0,Rr.getProperty)(t)}`;if(a){(0,rh.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,Rr._)`${s} === undefined`;o.useDefaults==="empty"&&(c=(0,Rr._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,Rr._)`${s} = ${(0,Rr.stringify)(r)}`)}});var We=R(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.validateUnion=Q.validateArray=Q.usePattern=Q.callValidateCode=Q.schemaProperties=Q.allSchemaProperties=Q.noPropertyInData=Q.propertyInData=Q.isOwnProperty=Q.hasPropFunc=Q.reportMissingProp=Q.checkMissingProp=Q.checkReportMissingProp=void 0;var oe=x(),Eo=U(),Dt=Ge(),ah=U();function ih(e,t){let{gen:r,data:n,it:a}=e;r.if(Ro(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,oe._)`${t}`},!0),e.error()})}Q.checkReportMissingProp=ih;function oh({gen:e,data:t,it:{opts:r}},n,a){return(0,oe.or)(...n.map(i=>(0,oe.and)(Ro(e,t,i,r.ownProperties),(0,oe._)`${a} = ${i}`)))}Q.checkMissingProp=oh;function sh(e,t){e.setParams({missingProperty:t},!0),e.error()}Q.reportMissingProp=sh;function Ol(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,oe._)`Object.prototype.hasOwnProperty`})}Q.hasPropFunc=Ol;function Ao(e,t,r){return(0,oe._)`${Ol(e)}.call(${t}, ${r})`}Q.isOwnProperty=Ao;function ch(e,t,r,n){let a=(0,oe._)`${t}${(0,oe.getProperty)(r)} !== undefined`;return n?(0,oe._)`${a} && ${Ao(e,t,r)}`:a}Q.propertyInData=ch;function Ro(e,t,r,n){let a=(0,oe._)`${t}${(0,oe.getProperty)(r)} === undefined`;return n?(0,oe.or)(a,(0,oe.not)(Ao(e,t,r))):a}Q.noPropertyInData=Ro;function Cl(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Q.allSchemaProperties=Cl;function lh(e,t){return Cl(t).filter(r=>!(0,Eo.alwaysValidSchema)(e,t[r]))}Q.schemaProperties=lh;function dh({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:o},s,c,d){let l=d?(0,oe._)`${e}, ${t}, ${n}${a}`:t,p=[[Dt.default.instancePath,(0,oe.strConcat)(Dt.default.instancePath,i)],[Dt.default.parentData,o.parentData],[Dt.default.parentDataProperty,o.parentDataProperty],[Dt.default.rootData,Dt.default.rootData]];o.opts.dynamicRef&&p.push([Dt.default.dynamicAnchors,Dt.default.dynamicAnchors]);let m=(0,oe._)`${l}, ${r.object(...p)}`;return c!==oe.nil?(0,oe._)`${s}.call(${c}, ${m})`:(0,oe._)`${s}(${m})`}Q.callValidateCode=dh;var ph=(0,oe._)`new RegExp`;function uh({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,oe._)`${a.code==="new RegExp"?ph:(0,ah.useFunc)(e,a)}(${r}, ${n})`})}Q.usePattern=uh;function fh(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let s=t.let("valid",!0);return o(()=>t.assign(s,!1)),s}return t.var(i,!0),o(()=>t.break()),i;function o(s){let c=t.const("len",(0,oe._)`${r}.length`);t.forRange("i",0,c,d=>{e.subschema({keyword:n,dataProp:d,dataPropType:Eo.Type.Num},i),t.if((0,oe.not)(i),s)})}}Q.validateArray=fh;function mh(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Eo.alwaysValidSchema)(a,c))&&!a.opts.unevaluated)return;let o=t.let("valid",!1),s=t.name("_valid");t.block(()=>r.forEach((c,d)=>{let l=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},s);t.assign(o,(0,oe._)`${o} || ${s}`),e.mergeValidEvaluated(l,s)||t.if((0,oe.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}Q.validateUnion=mh});var Ll=R(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.validateKeywordUsage=pt.validSchemaType=pt.funcKeywordCode=pt.macroKeywordCode=void 0;var $e=x(),Yt=Ge(),gh=We(),hh=cn();function yh(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:o}=e,s=t.macro.call(o.self,a,i,o),c=xl(r,n,s);o.opts.validateSchema!==!1&&o.self.validateSchema(s,!0);let d=r.name("valid");e.subschema({schema:s,schemaPath:$e.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}pt.macroKeywordCode=yh;function wh(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:o,$data:s,it:c}=e;Ih(c,t);let d=!s&&t.compile?t.compile.call(c.self,i,o,c):t.validate,l=xl(n,a,d),p=n.let("valid");e.block$data(p,m),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function m(){if(t.errors===!1)g(),t.modifying&&Tl(e),h(()=>e.error());else{let w=t.async?u():f();t.modifying&&Tl(e),h(()=>vh(e,w))}}function u(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,$e._)`await `),_=>n.assign(p,!1).if((0,$e._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,$e._)`${_}.errors`),()=>n.throw(_))),w}function f(){let w=(0,$e._)`${l}.errors`;return n.assign(w,null),g($e.nil),w}function g(w=t.async?(0,$e._)`await `:$e.nil){let _=c.opts.passContext?Yt.default.this:Yt.default.self,b=!("compile"in t&&!s||t.schema===!1);n.assign(p,(0,$e._)`${w}${(0,gh.callValidateCode)(e,l,_,b)}`,t.modifying)}function h(w){var _;n.if((0,$e.not)((_=t.valid)!==null&&_!==void 0?_:p),w)}}pt.funcKeywordCode=wh;function Tl(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,$e._)`${n.parentData}[${n.parentDataProperty}]`))}function vh(e,t){let{gen:r}=e;r.if((0,$e._)`Array.isArray(${t})`,()=>{r.assign(Yt.default.vErrors,(0,$e._)`${Yt.default.vErrors} === null ? ${t} : ${Yt.default.vErrors}.concat(${t})`).assign(Yt.default.errors,(0,$e._)`${Yt.default.vErrors}.length`),(0,hh.extendErrors)(e)},()=>e.error())}function Ih({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function xl(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,$e.stringify)(r)})}function bh(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}pt.validSchemaType=bh;function kh({schema:e,opts:t,self:r,errSchemaPath:n},a,i){if(Array.isArray(a.keyword)?!a.keyword.includes(i):a.keyword!==i)throw new Error("ajv implementation error");let o=a.dependencies;if(o?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}pt.validateKeywordUsage=kh});var Ml=R(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.extendSubschemaMode=St.extendSubschemaData=St.getSubschema=void 0;var ut=x(),Vl=U();function _h(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:i,topSchemaRef:o}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0,ut._)`${e.schemaPath}${(0,ut.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,ut._)`${e.schemaPath}${(0,ut.getProperty)(t)}${(0,ut.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Vl.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||i===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:a,topSchemaRef:o,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}St.getSubschema=_h;function Eh(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:i,propertyName:o}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:d,dataPathArr:l,opts:p}=t,m=s.let("data",(0,ut._)`${t.data}${(0,ut.getProperty)(r)}`,!0);c(m),e.errorPath=(0,ut.str)`${d}${(0,Vl.getErrorPath)(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=(0,ut._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let d=a instanceof ut.Name?a:s.let("data",a,!0);c(d),o!==void 0&&(e.propertyName=o)}i&&(e.dataTypes=i);function c(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}St.extendSubschemaData=Eh;function Ah(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:i}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}St.extendSubschemaMode=Ah});var Po=R((HA,ql)=>{"use strict";ql.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var o=i[a];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var Fl=R((XA,Ul)=>{"use strict";var jt=Ul.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},a=r.post||function(){};ba(t,n,a,e,"",e)};jt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};jt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};jt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};jt.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 ba(e,t,r,n,a,i,o,s,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,i,o,s,c,d);for(var l in n){var p=n[l];if(Array.isArray(p)){if(l in jt.arrayKeywords)for(var m=0;m<p.length;m++)ba(e,t,r,p[m],a+"/"+l+"/"+m,i,a,l,n,m)}else if(l in jt.propsKeywords){if(p&&typeof p=="object")for(var u in p)ba(e,t,r,p[u],a+"/"+l+"/"+Rh(u),i,a,l,n,u)}else(l in jt.keywords||e.allKeys&&!(l in jt.skipKeywords))&&ba(e,t,r,p,a+"/"+l,i,a,l,n)}r(n,a,i,o,s,c,d)}}function Rh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var dn=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.getSchemaRefs=Le.resolveUrl=Le.normalizeId=Le._getFullPath=Le.getFullPath=Le.inlineRef=void 0;var Ph=U(),Nh=Po(),Dh=Fl(),Sh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function jh(e,t=!0){return typeof e=="boolean"?!0:t===!0?!No(e):t?zl(e)<=t:!1}Le.inlineRef=jh;var $h=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function No(e){for(let t in e){if($h.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(No)||typeof r=="object"&&No(r))return!0}return!1}function zl(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Sh.has(r)&&(typeof e[r]=="object"&&(0,Ph.eachItem)(e[r],n=>t+=zl(n)),t===1/0))return 1/0}return t}function Bl(e,t="",r){r!==!1&&(t=Pr(t));let n=e.parse(t);return Jl(e,n)}Le.getFullPath=Bl;function Jl(e,t){return e.serialize(t).split("#")[0]+"#"}Le._getFullPath=Jl;var Oh=/#\/?$/;function Pr(e){return e?e.replace(Oh,""):""}Le.normalizeId=Pr;function Ch(e,t,r){return r=Pr(r),e.resolve(t,r)}Le.resolveUrl=Ch;var Th=/^[a-z_][-a-z0-9._]*$/i;function xh(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Pr(e[r]||t),i={"":a},o=Bl(n,a,!1),s={},c=new Set;return Dh(e,{allKeys:!0},(p,m,u,f)=>{if(f===void 0)return;let g=o+m,h=i[f];typeof p[r]=="string"&&(h=w.call(this,p[r])),_.call(this,p.$anchor),_.call(this,p.$dynamicAnchor),i[m]=h;function w(b){let A=this.opts.uriResolver.resolve;if(b=Pr(h?A(h,b):b),c.has(b))throw l(b);c.add(b);let y=this.refs[b];return typeof y=="string"&&(y=this.refs[y]),typeof y=="object"?d(p,y.schema,b):b!==Pr(g)&&(b[0]==="#"?(d(p,s[b],b),s[b]=p):this.refs[b]=g),b}function _(b){if(typeof b=="string"){if(!Th.test(b))throw new Error(`invalid anchor "${b}"`);w.call(this,`#${b}`)}}}),s;function d(p,m,u){if(m!==void 0&&!Nh(p,m))throw l(u)}function l(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Le.getSchemaRefs=xh});var fn=R($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getData=$t.KeywordCxt=$t.validateFunctionCode=void 0;var Hl=Al(),Gl=ln(),So=Io(),ka=ln(),Lh=$l(),un=Ll(),Do=Ml(),D=x(),T=Ge(),Vh=dn(),It=U(),pn=cn();function Mh(e){if(Ql(e)&&(ed(e),Zl(e))){Fh(e);return}Xl(e,()=>(0,Hl.topBoolOrEmptySchema)(e))}$t.validateFunctionCode=Mh;function Xl({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,D._)`${T.default.data}, ${T.default.valCxt}`,n.$async,()=>{e.code((0,D._)`"use strict"; ${Wl(r,a)}`),Uh(e,a),e.code(i)}):e.func(t,(0,D._)`${T.default.data}, ${qh(a)}`,n.$async,()=>e.code(Wl(r,a)).code(i))}function qh(e){return(0,D._)`{${T.default.instancePath}="", ${T.default.parentData}, ${T.default.parentDataProperty}, ${T.default.rootData}=${T.default.data}${e.dynamicRef?(0,D._)`, ${T.default.dynamicAnchors}={}`:D.nil}}={}`}function Uh(e,t){e.if(T.default.valCxt,()=>{e.var(T.default.instancePath,(0,D._)`${T.default.valCxt}.${T.default.instancePath}`),e.var(T.default.parentData,(0,D._)`${T.default.valCxt}.${T.default.parentData}`),e.var(T.default.parentDataProperty,(0,D._)`${T.default.valCxt}.${T.default.parentDataProperty}`),e.var(T.default.rootData,(0,D._)`${T.default.valCxt}.${T.default.rootData}`),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`${T.default.valCxt}.${T.default.dynamicAnchors}`)},()=>{e.var(T.default.instancePath,(0,D._)`""`),e.var(T.default.parentData,(0,D._)`undefined`),e.var(T.default.parentDataProperty,(0,D._)`undefined`),e.var(T.default.rootData,T.default.data),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`{}`)})}function Fh(e){let{schema:t,opts:r,gen:n}=e;Xl(e,()=>{r.$comment&&t.$comment&&rd(e),Wh(e),n.let(T.default.vErrors,null),n.let(T.default.errors,0),r.unevaluated&&zh(e),td(e),Hh(e)})}function zh(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,D._)`${r}.evaluated`),t.if((0,D._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,D._)`${e.evaluated}.props`,(0,D._)`undefined`)),t.if((0,D._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,D._)`${e.evaluated}.items`,(0,D._)`undefined`))}function Wl(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function Bh(e,t){if(Ql(e)&&(ed(e),Zl(e))){Jh(e,t);return}(0,Hl.boolOrEmptySchema)(e,t)}function Zl({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Ql(e){return typeof e.schema!="boolean"}function Jh(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&rd(e),Kh(e),Yh(e);let i=n.const("_errs",T.default.errors);td(e,i),n.var(t,(0,D._)`${i} === ${T.default.errors}`)}function ed(e){(0,It.checkUnknownRules)(e),Gh(e)}function td(e,t){if(e.opts.jtd)return Kl(e,[],!1,t);let r=(0,Gl.getSchemaTypes)(e.schema),n=(0,Gl.coerceAndCheckDataType)(e,r);Kl(e,r,!n,t)}function Gh(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,It.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Wh(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,It.checkStrictMode)(e,"default is ignored in the schema root")}function Kh(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Vh.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Yh(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function rd({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,D._)`${T.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let o=(0,D.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,D._)`${T.default.self}.opts.$comment(${i}, ${o}, ${s}.schema)`)}}function Hh(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,D._)`${T.default.errors} === 0`,()=>t.return(T.default.data),()=>t.throw((0,D._)`new ${a}(${T.default.vErrors})`)):(t.assign((0,D._)`${n}.errors`,T.default.vErrors),i.unevaluated&&Xh(e),t.return((0,D._)`${T.default.errors} === 0`))}function Xh({gen:e,evaluated:t,props:r,items:n}){r instanceof D.Name&&e.assign((0,D._)`${t}.props`,r),n instanceof D.Name&&e.assign((0,D._)`${t}.items`,n)}function Kl(e,t,r,n){let{gen:a,schema:i,data:o,allErrors:s,opts:c,self:d}=e,{RULES:l}=d;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,It.schemaHasRulesButRef)(i,l))){a.block(()=>ad(e,"$ref",l.all.$ref.definition));return}c.jtd||Zh(e,t),a.block(()=>{for(let m of l.rules)p(m);p(l.post)});function p(m){(0,So.shouldUseGroup)(i,m)&&(m.type?(a.if((0,ka.checkDataType)(m.type,o,c.strictNumbers)),Yl(e,m),t.length===1&&t[0]===m.type&&r&&(a.else(),(0,ka.reportTypeError)(e)),a.endIf()):Yl(e,m),s||a.if((0,D._)`${T.default.errors} === ${n||0}`))}}function Yl(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,Lh.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,So.shouldUseRule)(n,i)&&ad(e,i.keyword,i.definition,t.type)})}function Zh(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Qh(e,t),e.opts.allowUnionTypes||ey(e,t),ty(e,e.dataTypes))}function Qh(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{nd(e.dataTypes,r)||jo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),ny(e,t)}}function ey(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&jo(e,"use allowUnionTypes to allow union type keyword")}function ty(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,So.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(o=>ry(t,o))&&jo(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function ry(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function nd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function ny(e,t){let r=[];for(let n of e.dataTypes)nd(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function jo(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,It.checkStrictMode)(e,t,e.opts.strictTypes)}var _a=class{constructor(t,r,n){if((0,un.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,It.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",id(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,un.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",T.default.errors))}result(t,r,n){this.failResult((0,D.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,D.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?pn.reportExtraError:pn.reportError)(this,this.def.error,r)}$dataError(){(0,pn.reportError)(this,this.def.$dataError||pn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,pn.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=D.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:o}=this;n.if((0,D.or)((0,D._)`${a} === undefined`,r)),t!==D.nil&&n.assign(t,!0),(i.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==D.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,D.or)(o(),s());function o(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,ka.checkDataTypes)(c,r,i.opts.strictNumbers,ka.DataType.Wrong)}`}return D.nil}function s(){if(a.validateSchema){let c=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(t,r){let n=(0,Do.getSubschema)(this.it,t);(0,Do.extendSubschemaData)(n,this.it,t),(0,Do.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return Bh(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=It.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=It.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,D.Name)),!0}};$t.KeywordCxt=_a;function ad(e,t,r,n){let a=new _a(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,un.funcKeywordCode)(a,r):"macro"in r?(0,un.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,un.funcKeywordCode)(a,r)}var ay=/^\/(?:[^~]|~0|~1)*$/,iy=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function id(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return T.default.rootData;if(e[0]==="/"){if(!ay.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=T.default.rootData}else{let d=iy.exec(e);if(!d)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+d[1];if(a=d[2],a==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(i=r[t-l],!a)return i}let o=i,s=a.split("/");for(let d of s)d&&(i=(0,D._)`${i}${(0,D.getProperty)((0,It.unescapeJsonPointer)(d))}`,o=(0,D._)`${o} && ${i}`);return o;function c(d,l){return`Cannot access ${d} ${l} levels up, current level is ${t}`}}$t.getData=id});var Ea=R(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var $o=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Oo.default=$o});var mn=R(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var Co=dn(),To=class extends Error{constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Co.resolveUrl)(t,r,n),this.missingSchema=(0,Co.normalizeId)((0,Co.getFullPath)(t,this.missingRef))}};xo.default=To});var gn=R(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.resolveSchema=Ke.getCompilingSchema=Ke.resolveRef=Ke.compileSchema=Ke.SchemaEnv=void 0;var tt=x(),oy=Ea(),Ht=Ge(),rt=dn(),od=U(),sy=fn(),Nr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,rt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Ke.SchemaEnv=Nr;function Vo(e){let t=sd.call(this,e);if(t)return t;let r=(0,rt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,o=new tt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),s;e.$async&&(s=o.scopeValue("Error",{ref:oy.default,code:(0,tt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");e.validateName=c;let d={gen:o,allErrors:this.opts.allErrors,data:Ht.default.data,parentData:Ht.default.parentData,parentDataProperty:Ht.default.parentDataProperty,dataNames:[Ht.default.data],dataPathArr:[tt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,tt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:tt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,tt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,sy.validateFunctionCode)(d),o.optimize(this.opts.code.optimize);let p=o.toString();l=`${o.scopeRefs(Ht.default.scope)}return ${p}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let u=new Function(`${Ht.default.self}`,`${Ht.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:u}),u.errors=null,u.schema=e.schema,u.schemaEnv=e,e.$async&&(u.$async=!0),this.opts.code.source===!0&&(u.source={validateName:c,validateCode:p,scopeValues:o._values}),this.opts.unevaluated){let{props:f,items:g}=d;u.evaluated={props:f instanceof tt.Name?void 0:f,items:g instanceof tt.Name?void 0:g,dynamicProps:f instanceof tt.Name,dynamicItems:g instanceof tt.Name},u.source&&(u.source.evaluated=(0,tt.stringify)(u.evaluated))}return e.validate=u,e}catch(p){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),p}finally{this._compilations.delete(e)}}Ke.compileSchema=Vo;function cy(e,t,r){var n;r=(0,rt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=py.call(this,e,r);if(i===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;o&&(i=new Nr({schema:o,schemaId:s,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=ly.call(this,i)}Ke.resolveRef=cy;function ly(e){return(0,rt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Vo.call(this,e)}function sd(e){for(let t of this._compilations)if(dy(t,e))return t}Ke.getCompilingSchema=sd;function dy(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function py(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Aa.call(this,e,t)}function Aa(e,t){let r=this.opts.uriResolver.parse(t),n=(0,rt._getFullPath)(this.opts.uriResolver,r),a=(0,rt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Lo.call(this,r,e);let i=(0,rt.normalizeId)(n),o=this.refs[i]||this.schemas[i];if(typeof o=="string"){let s=Aa.call(this,e,o);return typeof s?.schema!="object"?void 0:Lo.call(this,r,s)}if(typeof o?.schema=="object"){if(o.validate||Vo.call(this,o),i===(0,rt.normalizeId)(t)){let{schema:s}=o,{schemaId:c}=this.opts,d=s[c];return d&&(a=(0,rt.resolveUrl)(this.opts.uriResolver,a,d)),new Nr({schema:s,schemaId:c,root:e,baseId:a})}return Lo.call(this,r,o)}}Ke.resolveSchema=Aa;var uy=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Lo(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,od.unescapeFragment)(s)];if(c===void 0)return;r=c;let d=typeof r=="object"&&r[this.opts.schemaId];!uy.has(s)&&d&&(t=(0,rt.resolveUrl)(this.opts.uriResolver,t,d))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,od.schemaHasRulesButRef)(r,this.RULES)){let s=(0,rt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Aa.call(this,n,s)}let{schemaId:o}=this.opts;if(i=i||new Nr({schema:r,schemaId:o,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var cd=R((nR,fy)=>{fy.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Uo=R((aR,md)=>{"use strict";var my=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),dd=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),Mo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),pd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),gy=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function qo(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var hy=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ld(e){return e.length=0,!0}function yy(e,t,r){if(e.length){let n=qo(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function wy(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,o=!1,s=yy;for(let c=0;c<e.length;c++){let d=e[c];if(!(d==="["||d==="]"))if(d===":"){if(i===!0&&(o=!0),!s(a,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(d==="%"){if(!s(a,n,r))break;s=ld}else{a.push(d);continue}}return a.length&&(s===ld?r.zone=a.join(""):o?n.push(a.join("")):n.push(qo(a))),r.address=n.join(""),r}function ud(e){if(vy(e,":")<2)return{host:e,isIPV6:!1};let t=wy(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function vy(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Iy(e){let t=e,r=[],n=-1,a=0;for(;a=t.length;){if(a===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(a===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(a===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var by={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ky=/[@/?#:]/g,_y=/[@/?#]/g;function fd(e,t){let r=t?_y:ky;return r.lastIndex=0,e.replace(r,n=>by[n])}function Ey(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let a=e.slice(n+1,n+3);if(Mo(a)){let i=a.toUpperCase(),o=String.fromCharCode(parseInt(i,16));t&&pd(o)?r+=o:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function Ay(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Mo(n)){let a=n.toUpperCase(),i=String.fromCharCode(parseInt(a,16));i!=="."&&pd(i)?t+=i:t+="%"+a,r+=2;continue}}gy(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Ry(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Mo(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Py(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!dd(r)){let n=ud(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=fd(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}md.exports={nonSimpleDomain:hy,recomposeAuthority:Py,reescapeHostDelimiters:fd,normalizePercentEncoding:Ey,normalizePathEncoding:Ay,escapePreservingEscapes:Ry,removeDotSegments:Iy,isIPv4:dd,isUUID:my,normalizeIPv6:ud,stringArrayToHexStripped:qo}});var vd=R((iR,wd)=>{"use strict";var{isUUID:Ny}=Uo(),Dy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Sy=["http","https","ws","wss","urn","urn:uuid"];function jy(e){return Sy.indexOf(e)!==-1}function Fo(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 gd(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function hd(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function $y(e){return e.secure=Fo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Oy(e){if((e.port===(Fo(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,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Cy(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Dy);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=zo(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Ty(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=zo(a);i&&(e=i.serialize(e,t));let o=e,s=e.nss;return o.path=`${n||t.nid}:${s}`,t.skipEscape=!0,o}function xy(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Ny(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Ly(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var yd={scheme:"http",domainHost:!0,parse:gd,serialize:hd},Vy={scheme:"https",domainHost:yd.domainHost,parse:gd,serialize:hd},Ra={scheme:"ws",domainHost:!0,parse:$y,serialize:Oy},My={scheme:"wss",domainHost:Ra.domainHost,parse:Ra.parse,serialize:Ra.serialize},qy={scheme:"urn",parse:Cy,serialize:Ty,skipNormalize:!0},Uy={scheme:"urn:uuid",parse:xy,serialize:Ly,skipNormalize:!0},Pa={http:yd,https:Vy,ws:Ra,wss:My,urn:qy,"urn:uuid":Uy};Object.setPrototypeOf(Pa,null);function zo(e){return e&&(Pa[e]||Pa[e.toLowerCase()])||void 0}wd.exports={wsIsSecure:Fo,SCHEMES:Pa,isValidSchemeName:jy,getSchemeHandler:zo}});var Ed=R((oR,Sa)=>{"use strict";var{normalizeIPv6:Fy,removeDotSegments:hn,recomposeAuthority:zy,normalizePercentEncoding:By,normalizePathEncoding:Jy,escapePreservingEscapes:Gy,reescapeHostDelimiters:Wy,isIPv4:Ky,nonSimpleDomain:Yy}=Uo(),{SCHEMES:Hy,getSchemeHandler:bd}=vd();function Xy(e,t){return typeof e=="string"?e=aw(e,t):typeof e=="object"&&(e=Da(Xt(e,t),t)),e}function Zy(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:a,malformedAuthorityOrPort:i}=Na(e,n),{parsed:o,malformedAuthorityOrPort:s}=Na(t,n);if(i||s)throw new Error(a.error||o.error||"URI is malformed.");let c=kd(a,o,n,!0);return n.skipEscape=!0,Xt(c,n)}function kd(e,t,r,n){let a={};return n||(e=Da(Xt(e,r),r),t=Da(Xt(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=hn(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=hn(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=hn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=hn(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function Qy(e,t,r){let n=Id(e,r),a=Id(t,r);return n!==void 0&&a!==void 0&&n.toLowerCase()===a.toLowerCase()}function Xt(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),a=[],i=bd(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=By(r.path):(r.path=Gy(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&a.push(r.scheme,":");let o=zy(r);if(o!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(o),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let s=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(s=hn(s)),o===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),a.push(s)}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}var ew=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,tw=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,rw=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function nw(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 Na(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=!1,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let o=e.match(tw);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",a=!0);let s=e.match(rw);if(s!==null){let d=s[1],l=d.replace(/[\t\n\r]/g,"");l.length>=2&&(l.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",a=!0):d.length!==l.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",a=!0))}let c=e.match(ew);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let d=nw(n,c);if(d!==void 0&&(n.error=n.error||d,a=!0),n.host)if(Ky(n.host)===!1){let m=Fy(n.host);n.host=m.host.toLowerCase(),i=m.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let l=bd(r.scheme||n.scheme);if(!r.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(r.domainHost||l&&l.domainHost)&&i===!1&&Yy(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!l||l&&!l.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Wy(unescape(n.host),i))),n.path&&(n.path=Jy(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:a}}function Da(e,t){return Na(e,t).parsed}function aw(e,t){return _d(e,t).normalized}function _d(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Na(e,t);return{normalized:n?e:Xt(r,t),malformedAuthorityOrPort:n}}function Id(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=_d(e,t);return n?void 0:r}if(typeof e=="object")return Xt(e,t)}var Bo={SCHEMES:Hy,normalize:Xy,resolve:Zy,resolveComponent:kd,equal:Qy,serialize:Xt,parse:Da};Sa.exports=Bo;Sa.exports.default=Bo;Sa.exports.fastUri=Bo});var Rd=R(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});var Ad=Ed();Ad.code='require("ajv/dist/runtime/uri").default';Jo.default=Ad});var Cd=R(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var iw=fn();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return iw.KeywordCxt}});var Dr=x();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return Dr._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return Dr.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return Dr.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return Dr.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return Dr.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return Dr.CodeGen}});var ow=Ea(),jd=mn(),sw=vo(),yn=gn(),cw=x(),wn=dn(),ja=ln(),Wo=U(),Pd=cd(),lw=Rd(),$d=(e,t)=>new RegExp(e,t);$d.code="new RegExp";var dw=["removeAdditional","useDefaults","coerceTypes"],pw=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),uw={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."},fw={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Nd=200;function mw(e){var t,r,n,a,i,o,s,c,d,l,p,m,u,f,g,h,w,_,b,A,y,k,S,O,ie;let $=e.strict,P=(t=e.code)===null||t===void 0?void 0:t.optimize,K=P===!0||P===void 0?1:P||0,re=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:$d,Be=(a=e.uriResolver)!==null&&a!==void 0?a:lw.default;return{strictSchema:(o=(i=e.strictSchema)!==null&&i!==void 0?i:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:$)!==null&&c!==void 0?c:!0,strictTypes:(l=(d=e.strictTypes)!==null&&d!==void 0?d:$)!==null&&l!==void 0?l:"log",strictTuples:(m=(p=e.strictTuples)!==null&&p!==void 0?p:$)!==null&&m!==void 0?m:"log",strictRequired:(f=(u=e.strictRequired)!==null&&u!==void 0?u:$)!==null&&f!==void 0?f:!1,code:e.code?{...e.code,optimize:K,regExp:re}:{optimize:K,regExp:re},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:Nd,loopEnum:(h=e.loopEnum)!==null&&h!==void 0?h:Nd,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(_=e.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(A=e.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(y=e.addUsedSchema)!==null&&y!==void 0?y:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(S=e.validateFormats)!==null&&S!==void 0?S:!0,unicodeRegExp:(O=e.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(ie=e.int32range)!==null&&ie!==void 0?ie:!0,uriResolver:Be}}var vn=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...mw(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new cw.ValueScope({scope:{},prefixes:pw,es5:r,lines:n}),this.logger=Iw(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,sw.getRules)(),Dd.call(this,uw,t,"NOT SUPPORTED"),Dd.call(this,fw,t,"DEPRECATED","warn"),this._metaOpts=ww.call(this),t.formats&&hw.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&yw.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),gw.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Pd;n==="id"&&(a={...Pd},a.id=a.$id,delete a.$id),r&&t&&this.addMetaSchema(a,a[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let a=n(r);return"$async"in n||(this.errors=n.errors),a}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return a.call(this,t,r);async function a(l,p){await i.call(this,l.$schema);let m=this._addSchema(l,p);return m.validate||o.call(this,m)}async function i(l){l&&!this.getSchema(l)&&await a.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(p){if(!(p instanceof jd.default))throw p;return s.call(this,p),await c.call(this,p.missingSchema),o.call(this,l)}}function s({missingSchema:l,missingRef:p}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${p} cannot be resolved`)}async function c(l){let p=await d.call(this,l);this.refs[l]||await i.call(this,p.$schema),this.refs[l]||this.addSchema(p,l,r)}async function d(l){let p=this._loading[l];if(p)return p;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,a=this.opts.validateSchema){if(Array.isArray(t)){for(let o of t)this.addSchema(o,void 0,n,a);return this}let i;if(typeof t=="object"){let{schemaId:o}=this.opts;if(i=t[o],i!==void 0&&typeof i!="string")throw new Error(`schema ${o} must be string`)}return r=(0,wn.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,a,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let a=this.validate(n,t);if(!a&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return a}getSchema(t){let r;for(;typeof(r=Sd.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new yn.SchemaEnv({schema:{},schemaId:n});if(r=yn.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Sd.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,wn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(kw.call(this,n,r),!r)return(0,Wo.eachItem)(n,i=>Go.call(this,i)),this;Ew.call(this,r);let a={...r,type:(0,ja.getJSONTypes)(r.type),schemaType:(0,ja.getJSONTypes)(r.schemaType)};return(0,Wo.eachItem)(n,a.type.length===0?i=>Go.call(this,i,a):i=>a.type.forEach(o=>Go.call(this,i,a,o))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),o=t;for(let s of i)o=o[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:d}=c.definition,l=o[s];d&&l&&(o[s]=Od(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let a=t[n];(!r||r.test(n))&&(typeof a=="string"?delete t[n]:a&&!a.meta&&(this._cache.delete(a.schema),delete t[n]))}}_addSchema(t,r,n,a=this.opts.validateSchema,i=this.opts.addUsedSchema){let o,{schemaId:s}=this.opts;if(typeof t=="object")o=t[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,wn.normalizeId)(o||n);let d=wn.getSchemaRefs.call(this,t,n);return c=new yn.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:d}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),a&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):yn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{yn.compileSchema.call(this,t)}finally{this.opts=r}}};vn.ValidationError=ow.default;vn.MissingRefError=jd.default;Ie.default=vn;function Dd(e,t,r,n="error"){for(let a in e){let i=a;i in t&&this.logger[n](`${r}: option ${a}. ${e[i]}`)}}function Sd(e){return e=(0,wn.normalizeId)(e),this.schemas[e]||this.refs[e]}function gw(){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 hw(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function yw(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 r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function ww(){let e={...this.opts};for(let t of dw)delete e[t];return e}var vw={log(){},warn(){},error(){}};function Iw(e){if(e===!1)return vw;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var bw=/^[a-z_$][a-z0-9_$:-]*$/i;function kw(e,t){let{RULES:r}=this;if((0,Wo.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!bw.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Go(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,o=a?i.post:i.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},i.rules.push(o)),i.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,ja.getJSONTypes)(t.type),schemaType:(0,ja.getJSONTypes)(t.schemaType)}};t.before?_w.call(this,o,s,t.before):o.rules.push(s),i.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function _w(e,t,r){let n=e.rules.findIndex(a=>a.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function Ew(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Od(t)),e.validateSchema=this.compile(t,!0))}var Aw={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Od(e){return{anyOf:[e,Aw]}}});var Td=R(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});var Rw={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ko.default=Rw});var Ca=R(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.callRef=Zt.getValidate=void 0;var Pw=mn(),xd=We(),Ve=x(),Sr=Ge(),Ld=gn(),$a=U(),Nw={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:i,validateName:o,opts:s,self:c}=n,{root:d}=i;if((r==="#"||r==="#/")&&a===d.baseId)return p();let l=Ld.resolveRef.call(c,d,a,r);if(l===void 0)throw new Pw.default(n.opts.uriResolver,a,r);if(l instanceof Ld.SchemaEnv)return m(l);return u(l);function p(){if(i===d)return Oa(e,o,i,i.$async);let f=t.scopeValue("root",{ref:d});return Oa(e,(0,Ve._)`${f}.validate`,d,d.$async)}function m(f){let g=Vd(e,f);Oa(e,g,f,f.$async)}function u(f){let g=t.scopeValue("schema",s.code.source===!0?{ref:f,code:(0,Ve.stringify)(f)}:{ref:f}),h=t.name("valid"),w=e.subschema({schema:f,dataTypes:[],schemaPath:Ve.nil,topSchemaRef:g,errSchemaPath:r},h);e.mergeEvaluated(w),e.ok(h)}}};function Vd(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ve._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Zt.getValidate=Vd;function Oa(e,t,r,n){let{gen:a,it:i}=e,{allErrors:o,schemaEnv:s,opts:c}=i,d=c.passContext?Sr.default.this:Ve.nil;n?l():p();function l(){if(!s.$async)throw new Error("async schema referenced by sync schema");let f=a.let("valid");a.try(()=>{a.code((0,Ve._)`await ${(0,xd.callValidateCode)(e,t,d)}`),u(t),o||a.assign(f,!0)},g=>{a.if((0,Ve._)`!(${g} instanceof ${i.ValidationError})`,()=>a.throw(g)),m(g),o||a.assign(f,!1)}),e.ok(f)}function p(){e.result((0,xd.callValidateCode)(e,t,d),()=>u(t),()=>m(t))}function m(f){let g=(0,Ve._)`${f}.errors`;a.assign(Sr.default.vErrors,(0,Ve._)`${Sr.default.vErrors} === null ? ${g} : ${Sr.default.vErrors}.concat(${g})`),a.assign(Sr.default.errors,(0,Ve._)`${Sr.default.vErrors}.length`)}function u(f){var g;if(!i.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(i.props=$a.mergeEvaluated.props(a,h.props,i.props));else{let w=a.var("props",(0,Ve._)`${f}.evaluated.props`);i.props=$a.mergeEvaluated.props(a,w,i.props,Ve.Name)}if(i.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(i.items=$a.mergeEvaluated.items(a,h.items,i.items));else{let w=a.var("items",(0,Ve._)`${f}.evaluated.items`);i.items=$a.mergeEvaluated.items(a,w,i.items,Ve.Name)}}}Zt.callRef=Oa;Zt.default=Nw});var Md=R(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var Dw=Td(),Sw=Ca(),jw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Dw.default,Sw.default];Yo.default=jw});var qd=R(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});var Ta=x(),Ot=Ta.operators,xa={maximum:{okStr:"<=",ok:Ot.LTE,fail:Ot.GT},minimum:{okStr:">=",ok:Ot.GTE,fail:Ot.LT},exclusiveMaximum:{okStr:"<",ok:Ot.LT,fail:Ot.GTE},exclusiveMinimum:{okStr:">",ok:Ot.GT,fail:Ot.LTE}},$w={message:({keyword:e,schemaCode:t})=>(0,Ta.str)`must be ${xa[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ta._)`{comparison: ${xa[e].okStr}, limit: ${t}}`},Ow={keyword:Object.keys(xa),type:"number",schemaType:"number",$data:!0,error:$w,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Ta._)`${r} ${xa[t].fail} ${n} || isNaN(${r})`)}};Ho.default=Ow});var Ud=R(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});var In=x(),Cw={message:({schemaCode:e})=>(0,In.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,In._)`{multipleOf: ${e}}`},Tw={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Cw,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,o=t.let("res"),s=i?(0,In._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:(0,In._)`${o} !== parseInt(${o})`;e.fail$data((0,In._)`(${n} === 0 || (${o} = ${r}/${n}, ${s}))`)}};Xo.default=Tw});var zd=R(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});function Fd(e){let t=e.length,r=0,n=0,a;for(;n<t;)r++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<t&&(a=e.charCodeAt(n),(a&64512)===56320&&n++);return r}Zo.default=Fd;Fd.code='require("ajv/dist/runtime/ucs2length").default'});var Bd=R(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var Qt=x(),xw=U(),Lw=zd(),Vw={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Qt._)`{limit: ${e}}`},Mw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Vw,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?Qt.operators.GT:Qt.operators.LT,o=a.opts.unicode===!1?(0,Qt._)`${r}.length`:(0,Qt._)`${(0,xw.useFunc)(e.gen,Lw.default)}(${r})`;e.fail$data((0,Qt._)`${o} ${i} ${n}`)}};Qo.default=Mw});var Jd=R(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var qw=We(),Uw=U(),jr=x(),Fw={message:({schemaCode:e})=>(0,jr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,jr._)`{pattern: ${e}}`},zw={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Fw,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:o}=e,s=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,d=c.code==="new RegExp"?(0,jr._)`new RegExp`:(0,Uw.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,jr._)`${d}(${i}, ${s}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,jr._)`!${l}`)}else{let c=(0,qw.usePattern)(e,a);e.fail$data((0,jr._)`!${c}.test(${r})`)}}};es.default=zw});var Gd=R(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});var bn=x(),Bw={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,bn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,bn._)`{limit: ${e}}`},Jw={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Bw,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?bn.operators.GT:bn.operators.LT;e.fail$data((0,bn._)`Object.keys(${r}).length ${a} ${n}`)}};ts.default=Jw});var Wd=R(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var kn=We(),_n=x(),Gw=U(),Ww={message:({params:{missingProperty:e}})=>(0,_n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,_n._)`{missingProperty: ${e}}`},Kw={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Ww,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:o}=e,{opts:s}=o;if(!i&&r.length===0)return;let c=r.length>=s.loopRequired;if(o.allErrors?d():l(),s.strictRequired){let u=e.parentSchema.properties,{definedProperties:f}=e.it;for(let g of r)if(u?.[g]===void 0&&!f.has(g)){let h=o.schemaEnv.baseId+o.errSchemaPath,w=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,Gw.checkStrictMode)(o,w,o.opts.strictRequired)}}function d(){if(c||i)e.block$data(_n.nil,p);else for(let u of r)(0,kn.checkReportMissingProp)(e,u)}function l(){let u=t.let("missing");if(c||i){let f=t.let("valid",!0);e.block$data(f,()=>m(u,f)),e.ok(f)}else t.if((0,kn.checkMissingProp)(e,r,u)),(0,kn.reportMissingProp)(e,u),t.else()}function p(){t.forOf("prop",n,u=>{e.setParams({missingProperty:u}),t.if((0,kn.noPropertyInData)(t,a,u,s.ownProperties),()=>e.error())})}function m(u,f){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(f,(0,kn.propertyInData)(t,a,u,s.ownProperties)),t.if((0,_n.not)(f),()=>{e.error(),t.break()})},_n.nil)}}};rs.default=Kw});var Kd=R(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});var En=x(),Yw={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,En.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,En._)`{limit: ${e}}`},Hw={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Yw,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?En.operators.GT:En.operators.LT;e.fail$data((0,En._)`${r}.length ${a} ${n}`)}};ns.default=Hw});var La=R(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});var Yd=Po();Yd.code='require("ajv/dist/runtime/equal").default';as.default=Yd});var Hd=R(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});var is=ln(),be=x(),Xw=U(),Zw=La(),Qw={message:({params:{i:e,j:t}})=>(0,be.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,be._)`{i: ${e}, j: ${t}}`},ev={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Qw,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:o,it:s}=e;if(!n&&!a)return;let c=t.let("valid"),d=i.items?(0,is.getSchemaTypes)(i.items):[];e.block$data(c,l,(0,be._)`${o} === false`),e.ok(c);function l(){let f=t.let("i",(0,be._)`${r}.length`),g=t.let("j");e.setParams({i:f,j:g}),t.assign(c,!0),t.if((0,be._)`${f} > 1`,()=>(p()?m:u)(f,g))}function p(){return d.length>0&&!d.some(f=>f==="object"||f==="array")}function m(f,g){let h=t.name("item"),w=(0,is.checkDataTypes)(d,h,s.opts.strictNumbers,is.DataType.Wrong),_=t.const("indices",(0,be._)`{}`);t.for((0,be._)`;${f}--;`,()=>{t.let(h,(0,be._)`${r}[${f}]`),t.if(w,(0,be._)`continue`),d.length>1&&t.if((0,be._)`typeof ${h} == "string"`,(0,be._)`${h} += "_"`),t.if((0,be._)`typeof ${_}[${h}] == "number"`,()=>{t.assign(g,(0,be._)`${_}[${h}]`),e.error(),t.assign(c,!1).break()}).code((0,be._)`${_}[${h}] = ${f}`)})}function u(f,g){let h=(0,Xw.useFunc)(t,Zw.default),w=t.name("outer");t.label(w).for((0,be._)`;${f}--;`,()=>t.for((0,be._)`${g} = ${f}; ${g}--;`,()=>t.if((0,be._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};os.default=ev});var Xd=R(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var ss=x(),tv=U(),rv=La(),nv={message:"must be equal to constant",params:({schemaCode:e})=>(0,ss._)`{allowedValue: ${e}}`},av={keyword:"const",$data:!0,error:nv,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,ss._)`!${(0,tv.useFunc)(t,rv.default)}(${r}, ${a})`):e.fail((0,ss._)`${i} !== ${r}`)}};cs.default=av});var Zd=R(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var An=x(),iv=U(),ov=La(),sv={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,An._)`{allowedValues: ${e}}`},cv={keyword:"enum",schemaType:"array",$data:!0,error:sv,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:o}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let s=a.length>=o.opts.loopEnum,c,d=()=>c??(c=(0,iv.useFunc)(t,ov.default)),l;if(s||n)l=t.let("valid"),e.block$data(l,p);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let u=t.const("vSchema",i);l=(0,An.or)(...a.map((f,g)=>m(u,g)))}e.pass(l);function p(){t.assign(l,!1),t.forOf("v",i,u=>t.if((0,An._)`${d()}(${r}, ${u})`,()=>t.assign(l,!0).break()))}function m(u,f){let g=a[f];return typeof g=="object"&&g!==null?(0,An._)`${d()}(${r}, ${u}[${f}])`:(0,An._)`${r} === ${g}`}}};ls.default=cv});var Qd=R(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var lv=qd(),dv=Ud(),pv=Bd(),uv=Jd(),fv=Gd(),mv=Wd(),gv=Kd(),hv=Hd(),yv=Xd(),wv=Zd(),vv=[lv.default,dv.default,pv.default,uv.default,fv.default,mv.default,gv.default,hv.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yv.default,wv.default];ds.default=vv});var us=R(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.validateAdditionalItems=void 0;var er=x(),ps=U(),Iv={message:({params:{len:e}})=>(0,er.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,er._)`{limit: ${e}}`},bv={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Iv,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ps.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ep(e,n)}};function ep(e,t){let{gen:r,schema:n,data:a,keyword:i,it:o}=e;o.items=!0;let s=r.const("len",(0,er._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,er._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,ps.alwaysValidSchema)(o,n)){let d=r.var("valid",(0,er._)`${s} <= ${t.length}`);r.if((0,er.not)(d),()=>c(d)),e.ok(d)}function c(d){r.forRange("i",t.length,s,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:ps.Type.Num},d),o.allErrors||r.if((0,er.not)(d),()=>r.break())})}}Rn.validateAdditionalItems=ep;Rn.default=bv});var fs=R(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.validateTuple=void 0;var tp=x(),Va=U(),kv=We(),_v={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return rp(e,"additionalItems",t);r.items=!0,!(0,Va.alwaysValidSchema)(r,t)&&e.ok((0,kv.validateArray)(e))}};function rp(e,t,r=e.schema){let{gen:n,parentSchema:a,data:i,keyword:o,it:s}=e;l(a),s.opts.unevaluated&&r.length&&s.items!==!0&&(s.items=Va.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),d=n.const("len",(0,tp._)`${i}.length`);r.forEach((p,m)=>{(0,Va.alwaysValidSchema)(s,p)||(n.if((0,tp._)`${d} > ${m}`,()=>e.subschema({keyword:o,schemaProp:m,dataProp:m},c)),e.ok(c))});function l(p){let{opts:m,errSchemaPath:u}=s,f=r.length,g=f===p.minItems&&(f===p.maxItems||p[t]===!1);if(m.strictTuples&&!g){let h=`"${o}" is ${f}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Va.checkStrictMode)(s,h,m.strictTuples)}}}Pn.validateTuple=rp;Pn.default=_v});var np=R(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var Ev=fs(),Av={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ev.validateTuple)(e,"items")};ms.default=Av});var ip=R(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var ap=x(),Rv=U(),Pv=We(),Nv=us(),Dv={message:({params:{len:e}})=>(0,ap.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ap._)`{limit: ${e}}`},Sv={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Dv,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,Rv.alwaysValidSchema)(n,t)&&(a?(0,Nv.validateAdditionalItems)(e,a):e.ok((0,Pv.validateArray)(e)))}};gs.default=Sv});var op=R(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var Ye=x(),Ma=U(),jv={message:({params:{min:e,max:t}})=>t===void 0?(0,Ye.str)`must contain at least ${e} valid item(s)`:(0,Ye.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ye._)`{minContains: ${e}}`:(0,Ye._)`{minContains: ${e}, maxContains: ${t}}`},$v={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:jv,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e,o,s,{minContains:c,maxContains:d}=n;i.opts.next?(o=c===void 0?1:c,s=d):o=1;let l=t.const("len",(0,Ye._)`${a}.length`);if(e.setParams({min:o,max:s}),s===void 0&&o===0){(0,Ma.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&o>s){(0,Ma.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ma.alwaysValidSchema)(i,r)){let g=(0,Ye._)`${l} >= ${o}`;s!==void 0&&(g=(0,Ye._)`${g} && ${l} <= ${s}`),e.pass(g);return}i.items=!0;let p=t.name("valid");s===void 0&&o===1?u(p,()=>t.if(p,()=>t.break())):o===0?(t.let(p,!0),s!==void 0&&t.if((0,Ye._)`${a}.length > 0`,m)):(t.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let g=t.name("_valid"),h=t.let("count",0);u(g,()=>t.if(g,()=>f(h)))}function u(g,h){t.forRange("i",0,l,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Ma.Type.Num,compositeRule:!0},g),h()})}function f(g){t.code((0,Ye._)`${g}++`),s===void 0?t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0).break()):(t.if((0,Ye._)`${g} > ${s}`,()=>t.assign(p,!1).break()),o===1?t.assign(p,!0):t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0)))}}};hs.default=$v});var qa=R(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateSchemaDeps=ft.validatePropertyDeps=ft.error=void 0;var ys=x(),Ov=U(),Nn=We();ft.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,ys.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,ys._)`{property: ${e},
6
6
  missingProperty: ${n},
7
7
  depsCount: ${t},
8
- deps: ${r}}`};var Ov={keyword:"dependencies",type:"object",schemaType:"object",error:ft.error,code(e){let[t,r]=Cv(e);sp(e,t),cp(e,r)}};function Cv({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let a=Array.isArray(e[n])?t:r;a[n]=e[n]}return[t,r]}function sp(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let o in t){let s=t[o];if(s.length===0)continue;let c=(0,Nn.propertyInData)(r,n,o,a.opts.ownProperties);e.setParams({property:o,depsCount:s.length,deps:s.join(", ")}),a.allErrors?r.if(c,()=>{for(let d of s)(0,Nn.checkReportMissingProp)(e,d)}):(r.if((0,ys._)`${c} && (${(0,Nn.checkMissingProp)(e,s,i)})`),(0,Nn.reportMissingProp)(e,i),r.else())}}ft.validatePropertyDeps=sp;function cp(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,o=r.name("valid");for(let s in t)(0,$v.alwaysValidSchema)(i,t[s])||(r.if((0,Nn.propertyInData)(r,n,s,i.opts.ownProperties),()=>{let c=e.subschema({keyword:a,schemaProp:s},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o))}ft.validateSchemaDeps=cp;ft.default=Ov});var dp=R(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var lp=x(),Tv=U(),xv={message:"property name must be valid",params:({params:e})=>(0,lp._)`{propertyName: ${e.propertyName}}`},Lv={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xv,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,Tv.alwaysValidSchema)(a,r))return;let i=t.name("valid");t.forIn("key",n,o=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},i),t.if((0,lp.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};ws.default=Lv});var Is=R(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var Ua=We(),nt=x(),Vv=Ge(),Fa=U(),Mv={message:"must NOT have additional properties",params:({params:e})=>(0,nt._)`{additionalProperty: ${e.additionalProperty}}`},qv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Mv,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:i,it:o}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Fa.alwaysValidSchema)(o,r))return;let d=(0,Ua.allSchemaProperties)(n.properties),l=(0,Ua.allSchemaProperties)(n.patternProperties);p(),e.ok((0,nt._)`${i} === ${Vv.default.errors}`);function p(){t.forIn("key",a,h=>{!d.length&&!l.length?m(h):t.if(f(h),()=>m(h))})}function f(h){let w;if(d.length>8){let _=(0,Fa.schemaRefOrVal)(o,n.properties,"properties");w=(0,Ua.isOwnProperty)(t,_,h)}else d.length?w=(0,nt.or)(...d.map(_=>(0,nt._)`${h} === ${_}`)):w=nt.nil;return l.length&&(w=(0,nt.or)(w,...l.map(_=>(0,nt._)`${(0,Ua.usePattern)(e,_)}.test(${h})`))),(0,nt.not)(w)}function u(h){t.code((0,nt._)`delete ${a}[${h}]`)}function m(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){u(h);return}if(r===!1){e.setParams({additionalProperty:h}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,Fa.alwaysValidSchema)(o,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(h,w,!1),t.if((0,nt.not)(w),()=>{e.reset(),u(h)})):(g(h,w),s||t.if((0,nt.not)(w),()=>t.break()))}}function g(h,w,_){let I={keyword:"additionalProperties",dataProp:h,dataPropType:Fa.Type.Str};_===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(I,w)}}};vs.default=qv});var fp=R(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Uv=fn(),pp=We(),bs=U(),up=Is(),Fv={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&up.default.code(new Uv.KeywordCxt(i,up.default,"additionalProperties"));let o=(0,pp.allSchemaProperties)(r);for(let p of o)i.definedProperties.add(p);i.opts.unevaluated&&o.length&&i.props!==!0&&(i.props=bs.mergeEvaluated.props(t,(0,bs.toHash)(o),i.props));let s=o.filter(p=>!(0,bs.alwaysValidSchema)(i,r[p]));if(s.length===0)return;let c=t.name("valid");for(let p of s)d(p)?l(p):(t.if((0,pp.propertyInData)(t,a,p,i.opts.ownProperties)),l(p),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(p),e.ok(c);function d(p){return i.opts.useDefaults&&!i.compositeRule&&r[p].default!==void 0}function l(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};ks.default=Fv});var yp=R(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var mp=We(),za=x(),gp=U(),hp=U(),zv={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:i}=e,{opts:o}=i,s=(0,mp.allSchemaProperties)(r),c=s.filter(g=>(0,gp.alwaysValidSchema)(i,r[g]));if(s.length===0||c.length===s.length&&(!i.opts.unevaluated||i.props===!0))return;let d=o.strictSchema&&!o.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof za.Name)&&(i.props=(0,hp.evaluatedPropsToName)(t,i.props));let{props:p}=i;f();function f(){for(let g of s)d&&u(g),i.allErrors?m(g):(t.var(l,!0),m(g),t.if(l))}function u(g){for(let h in d)new RegExp(g).test(h)&&(0,gp.checkStrictMode)(i,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){t.forIn("key",n,h=>{t.if((0,za._)`${(0,mp.usePattern)(e,g)}.test(${h})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:hp.Type.Str},l),i.opts.unevaluated&&p!==!0?t.assign((0,za._)`${p}[${h}]`,!0):!w&&!i.allErrors&&t.if((0,za.not)(l),()=>t.break())})})}}};_s.default=zv});var wp=R(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Bv=U(),Jv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Bv.alwaysValidSchema)(n,r)){e.fail();return}let a=t.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"}};Es.default=Jv});var vp=R(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Gv=We(),Wv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Gv.validateUnion,error:{message:"must match a schema in anyOf"}};As.default=Wv});var Ip=R(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var Ba=x(),Kv=U(),Yv={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Ba._)`{passingSchemas: ${e.passing}}`},Hv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Yv,code(e){let{gen:t,schema:r,parentSchema:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&n.discriminator)return;let i=r,o=t.let("valid",!1),s=t.let("passing",null),c=t.name("_valid");e.setParams({passing:s}),t.block(d),e.result(o,()=>e.reset(),()=>e.error(!0));function d(){i.forEach((l,p)=>{let f;(0,Kv.alwaysValidSchema)(a,l)?t.var(c,!0):f=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&t.if((0,Ba._)`${c} && ${o}`).assign(o,!1).assign(s,(0,Ba._)`[${s}, ${p}]`).else(),t.if(c,()=>{t.assign(o,!0),t.assign(s,p),f&&e.mergeEvaluated(f,Ba.Name)})})}}};Rs.default=Hv});var bp=R(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var Xv=U(),Zv={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let a=t.name("valid");r.forEach((i,o)=>{if((0,Xv.alwaysValidSchema)(n,i))return;let s=e.subschema({keyword:"allOf",schemaProp:o},a);e.ok(a),e.mergeEvaluated(s)})}};Ps.default=Zv});var Ep=R(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var Ja=x(),_p=U(),Qv={message:({params:e})=>(0,Ja.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ja._)`{failingKeyword: ${e.ifClause}}`},eI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Qv,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,_p.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=kp(n,"then"),i=kp(n,"else");if(!a&&!i)return;let o=t.let("valid",!0),s=t.name("_valid");if(c(),e.reset(),a&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(s,d("then",l),d("else",l))}else a?t.if(s,d("then")):t.if((0,Ja.not)(s),d("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);e.mergeEvaluated(l)}function d(l,p){return()=>{let f=e.subschema({keyword:l},s);t.assign(o,s),e.mergeValidEvaluated(f,o),p?t.assign(p,(0,Ja._)`${l}`):e.setParams({ifClause:l})}}}};function kp(e,t){let r=e.schema[t];return r!==void 0&&!(0,_p.alwaysValidSchema)(e,r)}Ns.default=eI});var Ap=R(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var tI=U(),rI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,tI.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Ds.default=rI});var Rp=R(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var nI=us(),aI=np(),iI=fs(),oI=ip(),sI=op(),cI=qa(),lI=dp(),dI=Is(),pI=fp(),uI=yp(),fI=wp(),mI=vp(),gI=Ip(),hI=bp(),yI=Ep(),wI=Ap();function vI(e=!1){let t=[fI.default,mI.default,gI.default,hI.default,yI.default,wI.default,lI.default,dI.default,cI.default,pI.default,uI.default];return e?t.push(aI.default,oI.default):t.push(nI.default,iI.default),t.push(sI.default),t}Ss.default=vI});var $s=R(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.dynamicAnchor=void 0;var js=x(),II=Ge(),Pp=gn(),bI=Ca(),kI={keyword:"$dynamicAnchor",schemaType:"string",code:e=>Np(e,e.schema)};function Np(e,t){let{gen:r,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let a=(0,js._)`${II.default.dynamicAnchors}${(0,js.getProperty)(t)}`,i=n.errSchemaPath==="#"?n.validateName:_I(e);r.if((0,js._)`!${a}`,()=>r.assign(a,i))}Dn.dynamicAnchor=Np;function _I(e){let{schemaEnv:t,schema:r,self:n}=e.it,{root:a,baseId:i,localRefs:o,meta:s}=t.root,{schemaId:c}=n.opts,d=new Pp.SchemaEnv({schema:r,schemaId:c,root:a,baseId:i,localRefs:o,meta:s});return Pp.compileSchema.call(n,d),(0,bI.getValidate)(e,d)}Dn.default=kI});var Os=R(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.dynamicRef=void 0;var Dp=x(),EI=Ge(),Sp=Ca(),AI={keyword:"$dynamicRef",schemaType:"string",code:e=>jp(e,e.schema)};function jp(e,t){let{gen:r,keyword:n,it:a}=e;if(t[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let i=t.slice(1);if(a.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(a.schemaEnv.root.dynamicAnchors[i]){let d=r.let("_v",(0,Dp._)`${EI.default.dynamicAnchors}${(0,Dp.getProperty)(i)}`);r.if(d,s(d,c),s(a.validateName,c))}else s(a.validateName,c)()}function s(c,d){return d?()=>r.block(()=>{(0,Sp.callRef)(e,c),r.let(d,!0)}):()=>(0,Sp.callRef)(e,c)}}Sn.dynamicRef=jp;Sn.default=AI});var $p=R(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var RI=$s(),PI=U(),NI={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,RI.dynamicAnchor)(e,""):(0,PI.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Cs.default=NI});var Op=R(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var DI=Os(),SI={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,DI.dynamicRef)(e,e.schema)};Ts.default=SI});var Cp=R(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});var jI=$s(),$I=Os(),OI=$p(),CI=Op(),TI=[jI.default,$I.default,OI.default,CI.default];xs.default=TI});var xp=R(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Tp=qa(),xI={keyword:"dependentRequired",type:"object",schemaType:"object",error:Tp.error,code:e=>(0,Tp.validatePropertyDeps)(e)};Ls.default=xI});var Lp=R(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var LI=qa(),VI={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,LI.validateSchemaDeps)(e)};Vs.default=VI});var Vp=R(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var MI=U(),qI={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){t.contains===void 0&&(0,MI.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ms.default=qI});var Mp=R(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var UI=xp(),FI=Lp(),zI=Vp(),BI=[UI.default,FI.default,zI.default];qs.default=BI});var Up=R(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var Ot=x(),qp=U(),JI=Ge(),GI={message:"must NOT have unevaluated properties",params:({params:e})=>(0,Ot._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},WI={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:GI,code(e){let{gen:t,schema:r,data:n,errsCount:a,it:i}=e;if(!a)throw new Error("ajv implementation error");let{allErrors:o,props:s}=i;s instanceof Ot.Name?t.if((0,Ot._)`${s} !== true`,()=>t.forIn("key",n,p=>t.if(d(s,p),()=>c(p)))):s!==!0&&t.forIn("key",n,p=>s===void 0?c(p):t.if(l(s,p),()=>c(p))),i.props=!0,e.ok((0,Ot._)`${a} === ${JI.default.errors}`);function c(p){if(r===!1){e.setParams({unevaluatedProperty:p}),e.error(),o||t.break();return}if(!(0,qp.alwaysValidSchema)(i,r)){let f=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:qp.Type.Str},f),o||t.if((0,Ot.not)(f),()=>t.break())}}function d(p,f){return(0,Ot._)`!${p} || !${p}[${f}]`}function l(p,f){let u=[];for(let m in p)p[m]===!0&&u.push((0,Ot._)`${f} !== ${m}`);return(0,Ot.and)(...u)}}};Us.default=WI});var zp=R(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var er=x(),Fp=U(),KI={message:({params:{len:e}})=>(0,er.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,er._)`{limit: ${e}}`},YI={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:KI,code(e){let{gen:t,schema:r,data:n,it:a}=e,i=a.items||0;if(i===!0)return;let o=t.const("len",(0,er._)`${n}.length`);if(r===!1)e.setParams({len:i}),e.fail((0,er._)`${o} > ${i}`);else if(typeof r=="object"&&!(0,Fp.alwaysValidSchema)(a,r)){let c=t.var("valid",(0,er._)`${o} <= ${i}`);t.if((0,er.not)(c),()=>s(c,i)),e.ok(c)}a.items=!0;function s(c,d){t.forRange("i",d,o,l=>{e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:Fp.Type.Num},c),a.allErrors||t.if((0,er.not)(c),()=>t.break())})}}};Fs.default=YI});var Bp=R(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var HI=Up(),XI=zp(),ZI=[HI.default,XI.default];zs.default=ZI});var Jp=R(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var ue=x(),QI={message:({schemaCode:e})=>(0,ue.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ue._)`{format: ${e}}`},eb={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:QI,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:o,it:s}=e,{opts:c,errSchemaPath:d,schemaEnv:l,self:p}=s;if(!c.validateFormats)return;a?f():u();function f(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,ue._)`${m}[${o}]`),h=r.let("fType"),w=r.let("format");r.if((0,ue._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,ue._)`${g}.type || "string"`).assign(w,(0,ue._)`${g}.validate`),()=>r.assign(h,(0,ue._)`"string"`).assign(w,g)),e.fail$data((0,ue.or)(_(),I()));function _(){return c.strictSchema===!1?ue.nil:(0,ue._)`${o} && !${w}`}function I(){let A=l.$async?(0,ue._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ue._)`${w}(${n})`,y=(0,ue._)`(typeof ${w} == "function" ? ${A} : ${w}.test(${n}))`;return(0,ue._)`${w} && ${w} !== true && ${h} === ${t} && !${y}`}}function u(){let m=p.formats[i];if(!m){_();return}if(m===!0)return;let[g,h,w]=I(m);g===t&&e.pass(A());function _(){if(c.strictSchema===!1){p.logger.warn(y());return}throw new Error(y());function y(){return`unknown format "${i}" ignored in schema at path "${d}"`}}function I(y){let k=y instanceof RegExp?(0,ue.regexpCode)(y):c.code.formats?(0,ue._)`${c.code.formats}${(0,ue.getProperty)(i)}`:void 0,S=r.scopeValue("formats",{key:i,ref:y,code:k});return typeof y=="object"&&!(y instanceof RegExp)?[y.type||"string",y.validate,(0,ue._)`${S}.validate`]:["string",y,S]}function A(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ue._)`await ${w}(${n})`}return typeof h=="function"?(0,ue._)`${w}(${n})`:(0,ue._)`${w}.test(${n})`}}}};Bs.default=eb});var Gp=R(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var tb=Jp(),rb=[tb.default];Js.default=rb});var Wp=R($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.contentVocabulary=$r.metadataVocabulary=void 0;$r.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];$r.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Yp=R(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var nb=Md(),ab=Qd(),ib=Rp(),ob=Cp(),sb=Mp(),cb=Bp(),lb=Gp(),Kp=Wp(),db=[ob.default,nb.default,ab.default,(0,ib.default)(!0),lb.default,Kp.metadataVocabulary,Kp.contentVocabulary,sb.default,cb.default];Gs.default=db});var Xp=R(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.DiscrError=void 0;var Hp;(function(e){e.Tag="tag",e.Mapping="mapping"})(Hp||(Ga.DiscrError=Hp={}))});var Qp=R(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Or=x(),Ws=Xp(),Zp=gn(),pb=mn(),ub=U(),fb={message:({params:{discrError:e,tagName:t}})=>e===Ws.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Or._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},mb={keyword:"discriminator",type:"object",schemaType:"object",error:fb,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:i}=e,{oneOf:o}=a;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),d=t.const("tag",(0,Or._)`${r}${(0,Or.getProperty)(s)}`);t.if((0,Or._)`typeof ${d} == "string"`,()=>l(),()=>e.error(!1,{discrError:Ws.DiscrError.Tag,tag:d,tagName:s})),e.ok(c);function l(){let u=f();t.if(!1);for(let m in u)t.elseIf((0,Or._)`${d} === ${m}`),t.assign(c,p(u[m]));t.else(),e.error(!1,{discrError:Ws.DiscrError.Mapping,tag:d,tagName:s}),t.endIf()}function p(u){let m=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:u},m);return e.mergeEvaluated(g,Or.Name),m}function f(){var u;let m={},g=w(a),h=!0;for(let A=0;A<o.length;A++){let y=o[A];if(y?.$ref&&!(0,ub.schemaHasRulesButRef)(y,i.self.RULES)){let S=y.$ref;if(y=Zp.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,S),y instanceof Zp.SchemaEnv&&(y=y.schema),y===void 0)throw new pb.default(i.opts.uriResolver,i.baseId,S)}let k=(u=y?.properties)===null||u===void 0?void 0:u[s];if(typeof k!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);h=h&&(g||w(y)),_(k,A)}if(!h)throw new Error(`discriminator: "${s}" must be required`);return m;function w({required:A}){return Array.isArray(A)&&A.includes(s)}function _(A,y){if(A.const)I(A.const,y);else if(A.enum)for(let k of A.enum)I(k,y);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function I(A,y){if(typeof A!="string"||A in m)throw new Error(`discriminator: "${s}" values must be unique strings`);m[A]=y}}}};Ks.default=mb});var eu=R((a0,gb)=>{gb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var tu=R((i0,hb)=>{hb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var ru=R((o0,yb)=>{yb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var nu=R((s0,wb)=>{wb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var au=R((c0,vb)=>{vb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var iu=R((l0,Ib)=>{Ib.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var ou=R((d0,bb)=>{bb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var su=R((p0,kb)=>{kb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var cu=R(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var _b=eu(),Eb=tu(),Ab=ru(),Rb=nu(),Pb=au(),Nb=iu(),Db=ou(),Sb=su(),jb=["/properties"];function $b(e){return[_b,Eb,Ab,Rb,Pb,t(this,Nb),Db,t(this,Sb)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function t(r,n){return e?r.$dataMetaSchema(n,jb):n}}Ys.default=$b});var tr=R((oe,Xs)=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.MissingRefError=oe.ValidationError=oe.CodeGen=oe.Name=oe.nil=oe.stringify=oe.str=oe._=oe.KeywordCxt=oe.Ajv2020=void 0;var Ob=Cd(),Cb=Yp(),Tb=Qp(),xb=cu(),Hs="https://json-schema.org/draft/2020-12/schema",Cr=class extends Ob.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Cb.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(Tb.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:r}=this.opts;r&&(xb.default.call(this,t),this.refs["http://json-schema.org/schema"]=Hs)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Hs)?Hs:void 0)}};oe.Ajv2020=Cr;Xs.exports=oe=Cr;Xs.exports.Ajv2020=Cr;Object.defineProperty(oe,"__esModule",{value:!0});oe.default=Cr;var Lb=fn();Object.defineProperty(oe,"KeywordCxt",{enumerable:!0,get:function(){return Lb.KeywordCxt}});var Tr=x();Object.defineProperty(oe,"_",{enumerable:!0,get:function(){return Tr._}});Object.defineProperty(oe,"str",{enumerable:!0,get:function(){return Tr.str}});Object.defineProperty(oe,"stringify",{enumerable:!0,get:function(){return Tr.stringify}});Object.defineProperty(oe,"nil",{enumerable:!0,get:function(){return Tr.nil}});Object.defineProperty(oe,"Name",{enumerable:!0,get:function(){return Tr.Name}});Object.defineProperty(oe,"CodeGen",{enumerable:!0,get:function(){return Tr.CodeGen}});var Vb=Ea();Object.defineProperty(oe,"ValidationError",{enumerable:!0,get:function(){return Vb.default}});var Mb=mn();Object.defineProperty(oe,"MissingRefError",{enumerable:!0,get:function(){return Mb.default}})});import{readFile as ee,readdir as Mm,realpath as lt}from"node:fs/promises";import{execFile as rA,spawn as nA}from"node:child_process";import N from"node:path";import{parseArgs as se,promisify as aA}from"node:util";var H="^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$",dt="^sha256:[a-f0-9]{64}$";import{constants as pi}from"node:fs";import{lstat as hk,mkdir as Gr,open as Eu,readFile as Vn,realpath as cr,rename as yk,unlink as fc}from"node:fs/promises";import{randomUUID as mc}from"node:crypto";import he from"node:path";var lu=Ir(tr(),1);var be={type:"string",pattern:dt},qb={type:"string",pattern:"^[a-z][a-z0-9.-]{2,127}$"},Zs={type:"string",format:"date-time"},Qs={enum:["typescript.typecheck","vitest.run","typescript.build","npm.pack-dry-run","workspace.structure","capability.assets","node.application-smoke","web.application-build","web.application-smoke","expo.application-config","expo.application-export","react.library-build","next.application-test","next.application-build","next.application-package","next.application-smoke","application.config-contract"]},du={type:"object",additionalProperties:!1,required:["node","pnpm","typescript"],properties:{node:{type:"string",minLength:1,maxLength:64},pnpm:{type:"string",minLength:1,maxLength:64},typescript:{type:"string",minLength:1,maxLength:64}}},ec={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","consumerProfile","compatibility","assets","verifiers","exit"],properties:{schemaVersion:{const:1},capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:be,consumerProfile:{enum:["blank-typescript-library","standalone-npm-package","react-component-library","nextjs-full-stack-application","workspace-root","workspace-npm-package","workspace-node-application","workspace-web-application","workspace-expo-application","any-project"]},kind:{enum:["profile","engineering-feature","integration-feature","domain-extension"]},dependencies:{type:"object",additionalProperties:!1,required:["profiles"],properties:{profiles:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}},capabilities:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:H}}}},compatibility:du,integration:{type:"object",additionalProperties:!1,required:["title","purpose","packages","codeAssets"],properties:{title:{type:"string",minLength:1,maxLength:128},purpose:{type:"string",minLength:1,maxLength:512},packages:{type:"array",items:{type:"object",additionalProperties:!1,required:["packageName","version","usage","imports"],properties:{packageName:{type:"string",minLength:1,maxLength:214},version:{type:"string",minLength:1,maxLength:128},usage:{enum:["runtime","development","build","test"]},imports:{type:"array",items:{type:"object",additionalProperties:!1,required:["importFrom","symbol"],properties:{importFrom:{type:"string",minLength:1,maxLength:214},symbol:{type:"string",minLength:1,maxLength:128},referencePath:{type:"string",minLength:1,maxLength:512}}}}}}},codeAssets:{type:"array",items:{type:"object",additionalProperties:!1,required:["sourcePath","targetPath","ownership"],properties:{sourcePath:{type:"string",minLength:1,maxLength:512},targetPath:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]}}}}}},assets:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["path","ownership","digest","mode"],properties:{path:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]},digest:be,mode:{type:"integer",minimum:0,maximum:511},regionId:{type:"string",pattern:H},renderer:{enum:["npm-package-json-v1","npm-package-json-v2","react-component-package-json-v1","nextjs-application-package-json-v1","workspace-root-package-json-v1","node-application-package-json-v1","web-application-package-json-v1","expo-application-package-json-v1","application-config-contract-v1","application-config-binding-v1"]}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:H}},required:["regionId"]},else:{not:{required:["regionId"]}}}]}},verifiers:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["id"],properties:{id:Qs}}},exit:{type:"object",additionalProperties:!1,required:["ownedAssets"],properties:{ownedAssets:{type:"array",items:{type:"string",minLength:1,maxLength:512}}}}}},pu={type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",pattern:"^registry\\.[a-z0-9][a-z0-9.-]{1,126}$"},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$",maxLength:214},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$",maxLength:64},integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]{86}==$"},tarballDigest:be,deliveryReceiptId:be,usage:{enum:["runtime","development"]}}},{$id:m0,...uu}=ec,Ub={...uu,$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v2.json",required:[...ec.required,"availability","packageSources"],properties:{...ec.properties,schemaVersion:{const:2},availability:{oneOf:[{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"local-artifact"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"development-registry"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"available"},visibility:{const:"catalog-consumers"},sourceState:{const:"registry-verified"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","reasonCode"],properties:{maturity:{const:"withdrawn"},visibility:{const:"existing-locks-only"},reasonCode:{type:"string",pattern:"^[A-Z][A-Z0-9_]{2,63}$"}}}]},packageSources:{type:"array",maxItems:128,items:pu}}},Fb={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release.json",oneOf:[uu,(()=>{let{$id:e,...t}=Ub;return t})()]},Wa={$id:"https://schemas.dyyto.dev/platform/verification-result-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","verifierId","result","issuer","commandId","exitCode","stdoutDigest","stderrDigest","startedAt","completedAt","projectStateDigest","runtime"],properties:{schemaVersion:{const:1},verifierId:Qs,result:{enum:["passed","failed"]},issuer:{enum:["dyyto-cli","test-harness","external-ci"]},commandId:Qs,exitCode:{type:"integer",minimum:0,maximum:255},stdoutDigest:be,stderrDigest:be,startedAt:Zs,completedAt:Zs,projectStateDigest:be,runtime:du}},zb={...Wa,$id:"https://schemas.dyyto.dev/platform/adoption-evidence-v1.json",required:[...Wa.required,"evidenceId","capabilityId","capabilityVersion","capabilityIntegrity"],properties:{...Wa.properties,evidenceId:be,capabilityId:{type:"string",pattern:H},capabilityVersion:{type:"string",minLength:1,maxLength:128},capabilityIntegrity:be}},Bb={$id:"https://schemas.dyyto.dev/platform/project-adoption-lock.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{enum:[1,2]},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","consumerProfile","appliedPlanId","projectStateDigest","assets","evidenceIds","committedAt"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:be,consumerProfile:{type:"string",minLength:1,maxLength:128},appliedPlanId:be,projectStateDigest:be,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:{type:"string",minLength:1,maxLength:512},digest:be,ownership:{enum:["owned-file","managed-region","seed-file"]},regionId:{type:"string",pattern:H}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:H}},required:["regionId"]}}]}},evidenceIds:{type:"array",items:be},committedAt:Zs,packageAdoption:{type:"object",additionalProperties:!1,required:["registryRevisions","sources","packageJsonDigest","lockfileDigest"],properties:{sourceChannel:{enum:["production","development"]},registryRevisions:{type:"array",items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:qb,revision:be}}},sources:{type:"array",minItems:1,maxItems:128,items:pu},packageJsonDigest:be,lockfileDigest:be}}}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{capabilities:{type:"array",items:{type:"object",not:{type:"object",properties:{packageAdoption:{}},required:["packageAdoption"]}}}}}}]},jn=new lu.Ajv2020({allErrors:!0,strict:!0});jn.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var Ya={capabilityBundleRelease:jn.compile(Fb),verificationResult:jn.compile(Wa),adoptionEvidence:jn.compile(zb),projectAdoptionLock:jn.compile(Bb)},Ka=class extends Error{contract;issues;code="ADOPTION_CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function Ha(e,t,r){if(!t(r))throw new Ka(e,t.errors??[]);return r}var fu=e=>{let t=Ha("capabilityBundleRelease",Ya.capabilityBundleRelease,e);if(t.schemaVersion===2){let r=()=>{throw new Ka("capabilityBundleRelease",[])},n=t.packageSources;(t.availability.maturity==="candidate"&&t.availability.sourceState==="local-artifact"&&n.length!==0||t.availability.maturity==="candidate"&&t.availability.sourceState==="development-registry"&&n.length===0||t.availability.maturity!=="candidate"&&n.length===0)&&r();let a="",i=new Set;for(let s of n){let c=`${s.packageName}@${s.version}`;(c.localeCompare(a)<=0||i.has(c))&&r(),a=c,i.add(c)}let o=t.integration?.packages??[];(t.availability.maturity!=="candidate"||t.availability.sourceState==="development-registry")&&(o.length!==n.length||o.some(s=>!n.some(c=>c.packageName===s.packageName&&c.version===s.version&&c.usage===s.usage)))&&r()}return t},mu=e=>Ha("verificationResult",Ya.verificationResult,e),$n=e=>Ha("adoptionEvidence",Ya.adoptionEvidence,e),$e=e=>Ha("projectAdoptionLock",Ya.projectAdoptionLock,e);import{lstat as Qb,readFile as ac,realpath as ic}from"node:fs/promises";import Lr from"node:path";import{createHash as Jb}from"node:crypto";function v(e){return`sha256:${Jb("sha256").update(e).digest("hex")}`}function E(e){return Array.isArray(e)?`[${e.map(E).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${E(n)}`).join(",")}}`:JSON.stringify(e)}var mt=class extends Error{code="MANAGED_REGION_INVALID";constructor(t){super(t)}};function gu(e){if(!new RegExp(H).test(e))throw new mt("Region identity is invalid");return{begin:`<!-- dyyto:begin ${e} -->`,end:`<!-- dyyto:end ${e} -->`}}function Xa(e,t){if(e.includes("\r"))throw new mt("Managed regions require LF newlines");let{begin:r,end:n}=gu(t),a=e.split(r).length-1,i=e.split(n).length-1;if(a!==1||i!==1)throw new mt("Managed region markers are unavailable or ambiguous");let o=e.indexOf(r)+r.length,s=e.indexOf(n,o),c=e.slice(o,s);if(/<!-- dyyto:(?:begin|end) /.test(c))throw new mt("Managed regions cannot overlap");return`${c.replace(/^\n+|\n+$/g,"")}
8
+ deps: ${r}}`};var Cv={keyword:"dependencies",type:"object",schemaType:"object",error:ft.error,code(e){let[t,r]=Tv(e);sp(e,t),cp(e,r)}};function Tv({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let a=Array.isArray(e[n])?t:r;a[n]=e[n]}return[t,r]}function sp(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let o in t){let s=t[o];if(s.length===0)continue;let c=(0,Nn.propertyInData)(r,n,o,a.opts.ownProperties);e.setParams({property:o,depsCount:s.length,deps:s.join(", ")}),a.allErrors?r.if(c,()=>{for(let d of s)(0,Nn.checkReportMissingProp)(e,d)}):(r.if((0,ys._)`${c} && (${(0,Nn.checkMissingProp)(e,s,i)})`),(0,Nn.reportMissingProp)(e,i),r.else())}}ft.validatePropertyDeps=sp;function cp(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,o=r.name("valid");for(let s in t)(0,Ov.alwaysValidSchema)(i,t[s])||(r.if((0,Nn.propertyInData)(r,n,s,i.opts.ownProperties),()=>{let c=e.subschema({keyword:a,schemaProp:s},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o))}ft.validateSchemaDeps=cp;ft.default=Cv});var dp=R(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var lp=x(),xv=U(),Lv={message:"property name must be valid",params:({params:e})=>(0,lp._)`{propertyName: ${e.propertyName}}`},Vv={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Lv,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,xv.alwaysValidSchema)(a,r))return;let i=t.name("valid");t.forIn("key",n,o=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},i),t.if((0,lp.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};ws.default=Vv});var Is=R(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var Ua=We(),nt=x(),Mv=Ge(),Fa=U(),qv={message:"must NOT have additional properties",params:({params:e})=>(0,nt._)`{additionalProperty: ${e.additionalProperty}}`},Uv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:qv,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:i,it:o}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Fa.alwaysValidSchema)(o,r))return;let d=(0,Ua.allSchemaProperties)(n.properties),l=(0,Ua.allSchemaProperties)(n.patternProperties);p(),e.ok((0,nt._)`${i} === ${Mv.default.errors}`);function p(){t.forIn("key",a,h=>{!d.length&&!l.length?f(h):t.if(m(h),()=>f(h))})}function m(h){let w;if(d.length>8){let _=(0,Fa.schemaRefOrVal)(o,n.properties,"properties");w=(0,Ua.isOwnProperty)(t,_,h)}else d.length?w=(0,nt.or)(...d.map(_=>(0,nt._)`${h} === ${_}`)):w=nt.nil;return l.length&&(w=(0,nt.or)(w,...l.map(_=>(0,nt._)`${(0,Ua.usePattern)(e,_)}.test(${h})`))),(0,nt.not)(w)}function u(h){t.code((0,nt._)`delete ${a}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){u(h);return}if(r===!1){e.setParams({additionalProperty:h}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,Fa.alwaysValidSchema)(o,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(h,w,!1),t.if((0,nt.not)(w),()=>{e.reset(),u(h)})):(g(h,w),s||t.if((0,nt.not)(w),()=>t.break()))}}function g(h,w,_){let b={keyword:"additionalProperties",dataProp:h,dataPropType:Fa.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,w)}}};vs.default=Uv});var fp=R(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Fv=fn(),pp=We(),bs=U(),up=Is(),zv={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&up.default.code(new Fv.KeywordCxt(i,up.default,"additionalProperties"));let o=(0,pp.allSchemaProperties)(r);for(let p of o)i.definedProperties.add(p);i.opts.unevaluated&&o.length&&i.props!==!0&&(i.props=bs.mergeEvaluated.props(t,(0,bs.toHash)(o),i.props));let s=o.filter(p=>!(0,bs.alwaysValidSchema)(i,r[p]));if(s.length===0)return;let c=t.name("valid");for(let p of s)d(p)?l(p):(t.if((0,pp.propertyInData)(t,a,p,i.opts.ownProperties)),l(p),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(p),e.ok(c);function d(p){return i.opts.useDefaults&&!i.compositeRule&&r[p].default!==void 0}function l(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};ks.default=zv});var yp=R(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var mp=We(),za=x(),gp=U(),hp=U(),Bv={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:i}=e,{opts:o}=i,s=(0,mp.allSchemaProperties)(r),c=s.filter(g=>(0,gp.alwaysValidSchema)(i,r[g]));if(s.length===0||c.length===s.length&&(!i.opts.unevaluated||i.props===!0))return;let d=o.strictSchema&&!o.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof za.Name)&&(i.props=(0,hp.evaluatedPropsToName)(t,i.props));let{props:p}=i;m();function m(){for(let g of s)d&&u(g),i.allErrors?f(g):(t.var(l,!0),f(g),t.if(l))}function u(g){for(let h in d)new RegExp(g).test(h)&&(0,gp.checkStrictMode)(i,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){t.forIn("key",n,h=>{t.if((0,za._)`${(0,mp.usePattern)(e,g)}.test(${h})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:hp.Type.Str},l),i.opts.unevaluated&&p!==!0?t.assign((0,za._)`${p}[${h}]`,!0):!w&&!i.allErrors&&t.if((0,za.not)(l),()=>t.break())})})}}};_s.default=Bv});var wp=R(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Jv=U(),Gv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Jv.alwaysValidSchema)(n,r)){e.fail();return}let a=t.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"}};Es.default=Gv});var vp=R(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Wv=We(),Kv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Wv.validateUnion,error:{message:"must match a schema in anyOf"}};As.default=Kv});var Ip=R(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var Ba=x(),Yv=U(),Hv={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Ba._)`{passingSchemas: ${e.passing}}`},Xv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Hv,code(e){let{gen:t,schema:r,parentSchema:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&n.discriminator)return;let i=r,o=t.let("valid",!1),s=t.let("passing",null),c=t.name("_valid");e.setParams({passing:s}),t.block(d),e.result(o,()=>e.reset(),()=>e.error(!0));function d(){i.forEach((l,p)=>{let m;(0,Yv.alwaysValidSchema)(a,l)?t.var(c,!0):m=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&t.if((0,Ba._)`${c} && ${o}`).assign(o,!1).assign(s,(0,Ba._)`[${s}, ${p}]`).else(),t.if(c,()=>{t.assign(o,!0),t.assign(s,p),m&&e.mergeEvaluated(m,Ba.Name)})})}}};Rs.default=Xv});var bp=R(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var Zv=U(),Qv={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let a=t.name("valid");r.forEach((i,o)=>{if((0,Zv.alwaysValidSchema)(n,i))return;let s=e.subschema({keyword:"allOf",schemaProp:o},a);e.ok(a),e.mergeEvaluated(s)})}};Ps.default=Qv});var Ep=R(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var Ja=x(),_p=U(),eI={message:({params:e})=>(0,Ja.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ja._)`{failingKeyword: ${e.ifClause}}`},tI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:eI,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,_p.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=kp(n,"then"),i=kp(n,"else");if(!a&&!i)return;let o=t.let("valid",!0),s=t.name("_valid");if(c(),e.reset(),a&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(s,d("then",l),d("else",l))}else a?t.if(s,d("then")):t.if((0,Ja.not)(s),d("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);e.mergeEvaluated(l)}function d(l,p){return()=>{let m=e.subschema({keyword:l},s);t.assign(o,s),e.mergeValidEvaluated(m,o),p?t.assign(p,(0,Ja._)`${l}`):e.setParams({ifClause:l})}}}};function kp(e,t){let r=e.schema[t];return r!==void 0&&!(0,_p.alwaysValidSchema)(e,r)}Ns.default=tI});var Ap=R(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var rI=U(),nI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,rI.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Ds.default=nI});var Rp=R(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var aI=us(),iI=np(),oI=fs(),sI=ip(),cI=op(),lI=qa(),dI=dp(),pI=Is(),uI=fp(),fI=yp(),mI=wp(),gI=vp(),hI=Ip(),yI=bp(),wI=Ep(),vI=Ap();function II(e=!1){let t=[mI.default,gI.default,hI.default,yI.default,wI.default,vI.default,dI.default,pI.default,lI.default,uI.default,fI.default];return e?t.push(iI.default,sI.default):t.push(aI.default,oI.default),t.push(cI.default),t}Ss.default=II});var $s=R(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.dynamicAnchor=void 0;var js=x(),bI=Ge(),Pp=gn(),kI=Ca(),_I={keyword:"$dynamicAnchor",schemaType:"string",code:e=>Np(e,e.schema)};function Np(e,t){let{gen:r,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let a=(0,js._)`${bI.default.dynamicAnchors}${(0,js.getProperty)(t)}`,i=n.errSchemaPath==="#"?n.validateName:EI(e);r.if((0,js._)`!${a}`,()=>r.assign(a,i))}Dn.dynamicAnchor=Np;function EI(e){let{schemaEnv:t,schema:r,self:n}=e.it,{root:a,baseId:i,localRefs:o,meta:s}=t.root,{schemaId:c}=n.opts,d=new Pp.SchemaEnv({schema:r,schemaId:c,root:a,baseId:i,localRefs:o,meta:s});return Pp.compileSchema.call(n,d),(0,kI.getValidate)(e,d)}Dn.default=_I});var Os=R(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.dynamicRef=void 0;var Dp=x(),AI=Ge(),Sp=Ca(),RI={keyword:"$dynamicRef",schemaType:"string",code:e=>jp(e,e.schema)};function jp(e,t){let{gen:r,keyword:n,it:a}=e;if(t[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let i=t.slice(1);if(a.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(a.schemaEnv.root.dynamicAnchors[i]){let d=r.let("_v",(0,Dp._)`${AI.default.dynamicAnchors}${(0,Dp.getProperty)(i)}`);r.if(d,s(d,c),s(a.validateName,c))}else s(a.validateName,c)()}function s(c,d){return d?()=>r.block(()=>{(0,Sp.callRef)(e,c),r.let(d,!0)}):()=>(0,Sp.callRef)(e,c)}}Sn.dynamicRef=jp;Sn.default=RI});var $p=R(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var PI=$s(),NI=U(),DI={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,PI.dynamicAnchor)(e,""):(0,NI.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Cs.default=DI});var Op=R(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var SI=Os(),jI={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,SI.dynamicRef)(e,e.schema)};Ts.default=jI});var Cp=R(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});var $I=$s(),OI=Os(),CI=$p(),TI=Op(),xI=[$I.default,OI.default,CI.default,TI.default];xs.default=xI});var xp=R(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Tp=qa(),LI={keyword:"dependentRequired",type:"object",schemaType:"object",error:Tp.error,code:e=>(0,Tp.validatePropertyDeps)(e)};Ls.default=LI});var Lp=R(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var VI=qa(),MI={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,VI.validateSchemaDeps)(e)};Vs.default=MI});var Vp=R(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var qI=U(),UI={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){t.contains===void 0&&(0,qI.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ms.default=UI});var Mp=R(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var FI=xp(),zI=Lp(),BI=Vp(),JI=[FI.default,zI.default,BI.default];qs.default=JI});var Up=R(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var Ct=x(),qp=U(),GI=Ge(),WI={message:"must NOT have unevaluated properties",params:({params:e})=>(0,Ct._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},KI={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:WI,code(e){let{gen:t,schema:r,data:n,errsCount:a,it:i}=e;if(!a)throw new Error("ajv implementation error");let{allErrors:o,props:s}=i;s instanceof Ct.Name?t.if((0,Ct._)`${s} !== true`,()=>t.forIn("key",n,p=>t.if(d(s,p),()=>c(p)))):s!==!0&&t.forIn("key",n,p=>s===void 0?c(p):t.if(l(s,p),()=>c(p))),i.props=!0,e.ok((0,Ct._)`${a} === ${GI.default.errors}`);function c(p){if(r===!1){e.setParams({unevaluatedProperty:p}),e.error(),o||t.break();return}if(!(0,qp.alwaysValidSchema)(i,r)){let m=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:qp.Type.Str},m),o||t.if((0,Ct.not)(m),()=>t.break())}}function d(p,m){return(0,Ct._)`!${p} || !${p}[${m}]`}function l(p,m){let u=[];for(let f in p)p[f]===!0&&u.push((0,Ct._)`${m} !== ${f}`);return(0,Ct.and)(...u)}}};Us.default=KI});var zp=R(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var tr=x(),Fp=U(),YI={message:({params:{len:e}})=>(0,tr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,tr._)`{limit: ${e}}`},HI={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:YI,code(e){let{gen:t,schema:r,data:n,it:a}=e,i=a.items||0;if(i===!0)return;let o=t.const("len",(0,tr._)`${n}.length`);if(r===!1)e.setParams({len:i}),e.fail((0,tr._)`${o} > ${i}`);else if(typeof r=="object"&&!(0,Fp.alwaysValidSchema)(a,r)){let c=t.var("valid",(0,tr._)`${o} <= ${i}`);t.if((0,tr.not)(c),()=>s(c,i)),e.ok(c)}a.items=!0;function s(c,d){t.forRange("i",d,o,l=>{e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:Fp.Type.Num},c),a.allErrors||t.if((0,tr.not)(c),()=>t.break())})}}};Fs.default=HI});var Bp=R(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var XI=Up(),ZI=zp(),QI=[XI.default,ZI.default];zs.default=QI});var Jp=R(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var ue=x(),eb={message:({schemaCode:e})=>(0,ue.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ue._)`{format: ${e}}`},tb={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:eb,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:o,it:s}=e,{opts:c,errSchemaPath:d,schemaEnv:l,self:p}=s;if(!c.validateFormats)return;a?m():u();function m(){let f=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,ue._)`${f}[${o}]`),h=r.let("fType"),w=r.let("format");r.if((0,ue._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,ue._)`${g}.type || "string"`).assign(w,(0,ue._)`${g}.validate`),()=>r.assign(h,(0,ue._)`"string"`).assign(w,g)),e.fail$data((0,ue.or)(_(),b()));function _(){return c.strictSchema===!1?ue.nil:(0,ue._)`${o} && !${w}`}function b(){let A=l.$async?(0,ue._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ue._)`${w}(${n})`,y=(0,ue._)`(typeof ${w} == "function" ? ${A} : ${w}.test(${n}))`;return(0,ue._)`${w} && ${w} !== true && ${h} === ${t} && !${y}`}}function u(){let f=p.formats[i];if(!f){_();return}if(f===!0)return;let[g,h,w]=b(f);g===t&&e.pass(A());function _(){if(c.strictSchema===!1){p.logger.warn(y());return}throw new Error(y());function y(){return`unknown format "${i}" ignored in schema at path "${d}"`}}function b(y){let k=y instanceof RegExp?(0,ue.regexpCode)(y):c.code.formats?(0,ue._)`${c.code.formats}${(0,ue.getProperty)(i)}`:void 0,S=r.scopeValue("formats",{key:i,ref:y,code:k});return typeof y=="object"&&!(y instanceof RegExp)?[y.type||"string",y.validate,(0,ue._)`${S}.validate`]:["string",y,S]}function A(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ue._)`await ${w}(${n})`}return typeof h=="function"?(0,ue._)`${w}(${n})`:(0,ue._)`${w}.test(${n})`}}}};Bs.default=tb});var Gp=R(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var rb=Jp(),nb=[rb.default];Js.default=nb});var Wp=R($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.contentVocabulary=$r.metadataVocabulary=void 0;$r.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];$r.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Yp=R(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var ab=Md(),ib=Qd(),ob=Rp(),sb=Cp(),cb=Mp(),lb=Bp(),db=Gp(),Kp=Wp(),pb=[sb.default,ab.default,ib.default,(0,ob.default)(!0),db.default,Kp.metadataVocabulary,Kp.contentVocabulary,cb.default,lb.default];Gs.default=pb});var Xp=R(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.DiscrError=void 0;var Hp;(function(e){e.Tag="tag",e.Mapping="mapping"})(Hp||(Ga.DiscrError=Hp={}))});var Qp=R(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Or=x(),Ws=Xp(),Zp=gn(),ub=mn(),fb=U(),mb={message:({params:{discrError:e,tagName:t}})=>e===Ws.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Or._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},gb={keyword:"discriminator",type:"object",schemaType:"object",error:mb,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:i}=e,{oneOf:o}=a;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),d=t.const("tag",(0,Or._)`${r}${(0,Or.getProperty)(s)}`);t.if((0,Or._)`typeof ${d} == "string"`,()=>l(),()=>e.error(!1,{discrError:Ws.DiscrError.Tag,tag:d,tagName:s})),e.ok(c);function l(){let u=m();t.if(!1);for(let f in u)t.elseIf((0,Or._)`${d} === ${f}`),t.assign(c,p(u[f]));t.else(),e.error(!1,{discrError:Ws.DiscrError.Mapping,tag:d,tagName:s}),t.endIf()}function p(u){let f=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:u},f);return e.mergeEvaluated(g,Or.Name),f}function m(){var u;let f={},g=w(a),h=!0;for(let A=0;A<o.length;A++){let y=o[A];if(y?.$ref&&!(0,fb.schemaHasRulesButRef)(y,i.self.RULES)){let S=y.$ref;if(y=Zp.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,S),y instanceof Zp.SchemaEnv&&(y=y.schema),y===void 0)throw new ub.default(i.opts.uriResolver,i.baseId,S)}let k=(u=y?.properties)===null||u===void 0?void 0:u[s];if(typeof k!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);h=h&&(g||w(y)),_(k,A)}if(!h)throw new Error(`discriminator: "${s}" must be required`);return f;function w({required:A}){return Array.isArray(A)&&A.includes(s)}function _(A,y){if(A.const)b(A.const,y);else if(A.enum)for(let k of A.enum)b(k,y);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function b(A,y){if(typeof A!="string"||A in f)throw new Error(`discriminator: "${s}" values must be unique strings`);f[A]=y}}}};Ks.default=gb});var eu=R((o0,hb)=>{hb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var tu=R((s0,yb)=>{yb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var ru=R((c0,wb)=>{wb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var nu=R((l0,vb)=>{vb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var au=R((d0,Ib)=>{Ib.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var iu=R((p0,bb)=>{bb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var ou=R((u0,kb)=>{kb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var su=R((f0,_b)=>{_b.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var cu=R(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var Eb=eu(),Ab=tu(),Rb=ru(),Pb=nu(),Nb=au(),Db=iu(),Sb=ou(),jb=su(),$b=["/properties"];function Ob(e){return[Eb,Ab,Rb,Pb,Nb,t(this,Db),Sb,t(this,jb)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function t(r,n){return e?r.$dataMetaSchema(n,$b):n}}Ys.default=Ob});var rr=R((se,Xs)=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.MissingRefError=se.ValidationError=se.CodeGen=se.Name=se.nil=se.stringify=se.str=se._=se.KeywordCxt=se.Ajv2020=void 0;var Cb=Cd(),Tb=Yp(),xb=Qp(),Lb=cu(),Hs="https://json-schema.org/draft/2020-12/schema",Cr=class extends Cb.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Tb.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(xb.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:r}=this.opts;r&&(Lb.default.call(this,t),this.refs["http://json-schema.org/schema"]=Hs)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Hs)?Hs:void 0)}};se.Ajv2020=Cr;Xs.exports=se=Cr;Xs.exports.Ajv2020=Cr;Object.defineProperty(se,"__esModule",{value:!0});se.default=Cr;var Vb=fn();Object.defineProperty(se,"KeywordCxt",{enumerable:!0,get:function(){return Vb.KeywordCxt}});var Tr=x();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Tr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Tr.str}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Tr.stringify}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Tr.nil}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Tr.Name}});Object.defineProperty(se,"CodeGen",{enumerable:!0,get:function(){return Tr.CodeGen}});var Mb=Ea();Object.defineProperty(se,"ValidationError",{enumerable:!0,get:function(){return Mb.default}});var qb=mn();Object.defineProperty(se,"MissingRefError",{enumerable:!0,get:function(){return qb.default}})});import{readFile as ee,readdir as qm,realpath as lt}from"node:fs/promises";import{execFile as aA,spawn as iA}from"node:child_process";import N from"node:path";import{parseArgs as ce,promisify as oA}from"node:util";var H="^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$",dt="^sha256:[a-f0-9]{64}$";import{constants as pi}from"node:fs";import{lstat as yk,mkdir as Gr,open as Eu,readFile as Vn,realpath as lr,rename as wk,unlink as fc}from"node:fs/promises";import{randomUUID as mc}from"node:crypto";import ye from"node:path";var lu=Ir(rr(),1);var ke={type:"string",pattern:dt},Ub={type:"string",pattern:"^[a-z][a-z0-9.-]{2,127}$"},Zs={type:"string",format:"date-time"},Qs={enum:["typescript.typecheck","vitest.run","typescript.build","npm.pack-dry-run","workspace.structure","capability.assets","node.application-smoke","web.application-build","web.application-smoke","expo.application-config","expo.application-export","react.library-build","next.application-test","next.application-build","next.application-package","next.application-smoke","application.config-contract"]},du={type:"object",additionalProperties:!1,required:["node","pnpm","typescript"],properties:{node:{type:"string",minLength:1,maxLength:64},pnpm:{type:"string",minLength:1,maxLength:64},typescript:{type:"string",minLength:1,maxLength:64}}},ec={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","consumerProfile","compatibility","assets","verifiers","exit"],properties:{schemaVersion:{const:1},capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:ke,consumerProfile:{enum:["blank-typescript-library","standalone-npm-package","react-component-library","nextjs-full-stack-application","workspace-root","workspace-npm-package","workspace-node-application","workspace-web-application","workspace-expo-application","any-project"]},kind:{enum:["profile","engineering-feature","integration-feature","domain-extension"]},dependencies:{type:"object",additionalProperties:!1,required:["profiles"],properties:{profiles:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}},capabilities:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:H}}}},compatibility:du,integration:{type:"object",additionalProperties:!1,required:["title","purpose","packages","codeAssets"],properties:{title:{type:"string",minLength:1,maxLength:128},purpose:{type:"string",minLength:1,maxLength:512},packages:{type:"array",items:{type:"object",additionalProperties:!1,required:["packageName","version","usage","imports"],properties:{packageName:{type:"string",minLength:1,maxLength:214},version:{type:"string",minLength:1,maxLength:128},usage:{enum:["runtime","development","build","test"]},imports:{type:"array",items:{type:"object",additionalProperties:!1,required:["importFrom","symbol"],properties:{importFrom:{type:"string",minLength:1,maxLength:214},symbol:{type:"string",minLength:1,maxLength:128},referencePath:{type:"string",minLength:1,maxLength:512}}}}}}},codeAssets:{type:"array",items:{type:"object",additionalProperties:!1,required:["sourcePath","targetPath","ownership"],properties:{sourcePath:{type:"string",minLength:1,maxLength:512},targetPath:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]}}}}}},assets:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["path","ownership","digest","mode"],properties:{path:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]},digest:ke,mode:{type:"integer",minimum:0,maximum:511},regionId:{type:"string",pattern:H},renderer:{enum:["npm-package-json-v1","npm-package-json-v2","react-component-package-json-v1","nextjs-application-package-json-v1","workspace-root-package-json-v1","node-application-package-json-v1","web-application-package-json-v1","expo-application-package-json-v1","application-config-contract-v1","application-config-binding-v1"]}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:H}},required:["regionId"]},else:{not:{required:["regionId"]}}}]}},verifiers:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["id"],properties:{id:Qs}}},exit:{type:"object",additionalProperties:!1,required:["ownedAssets"],properties:{ownedAssets:{type:"array",items:{type:"string",minLength:1,maxLength:512}}}}}},pu={type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",pattern:"^registry\\.[a-z0-9][a-z0-9.-]{1,126}$"},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$",maxLength:214},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$",maxLength:64},integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]{86}==$"},tarballDigest:ke,deliveryReceiptId:ke,usage:{enum:["runtime","development"]}}},{$id:h0,...uu}=ec,Fb={...uu,$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v2.json",required:[...ec.required,"availability","packageSources"],properties:{...ec.properties,schemaVersion:{const:2},availability:{oneOf:[{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"local-artifact"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"development-registry"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"available"},visibility:{const:"catalog-consumers"},sourceState:{const:"registry-verified"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","reasonCode"],properties:{maturity:{const:"withdrawn"},visibility:{const:"existing-locks-only"},reasonCode:{type:"string",pattern:"^[A-Z][A-Z0-9_]{2,63}$"}}}]},packageSources:{type:"array",maxItems:128,items:pu}}},zb={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release.json",oneOf:[uu,(()=>{let{$id:e,...t}=Fb;return t})()]},Wa={$id:"https://schemas.dyyto.dev/platform/verification-result-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","verifierId","result","issuer","commandId","exitCode","stdoutDigest","stderrDigest","startedAt","completedAt","projectStateDigest","runtime"],properties:{schemaVersion:{const:1},verifierId:Qs,result:{enum:["passed","failed"]},issuer:{enum:["dyyto-cli","test-harness","external-ci"]},commandId:Qs,exitCode:{type:"integer",minimum:0,maximum:255},stdoutDigest:ke,stderrDigest:ke,startedAt:Zs,completedAt:Zs,projectStateDigest:ke,runtime:du}},Bb={...Wa,$id:"https://schemas.dyyto.dev/platform/adoption-evidence-v1.json",required:[...Wa.required,"evidenceId","capabilityId","capabilityVersion","capabilityIntegrity"],properties:{...Wa.properties,evidenceId:ke,capabilityId:{type:"string",pattern:H},capabilityVersion:{type:"string",minLength:1,maxLength:128},capabilityIntegrity:ke}},Jb={$id:"https://schemas.dyyto.dev/platform/project-adoption-lock.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{enum:[1,2]},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","consumerProfile","appliedPlanId","projectStateDigest","assets","evidenceIds","committedAt"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:ke,consumerProfile:{type:"string",minLength:1,maxLength:128},appliedPlanId:ke,projectStateDigest:ke,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:{type:"string",minLength:1,maxLength:512},digest:ke,ownership:{enum:["owned-file","managed-region","seed-file"]},regionId:{type:"string",pattern:H}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:H}},required:["regionId"]}}]}},evidenceIds:{type:"array",items:ke},committedAt:Zs,packageAdoption:{type:"object",additionalProperties:!1,required:["registryRevisions","sources","packageJsonDigest","lockfileDigest"],properties:{sourceChannel:{enum:["production","development"]},registryRevisions:{type:"array",items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:Ub,revision:ke}}},sources:{type:"array",minItems:1,maxItems:128,items:pu},packageJsonDigest:ke,lockfileDigest:ke}}}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{capabilities:{type:"array",items:{type:"object",not:{type:"object",properties:{packageAdoption:{}},required:["packageAdoption"]}}}}}}]},jn=new lu.Ajv2020({allErrors:!0,strict:!0});jn.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var Ya={capabilityBundleRelease:jn.compile(zb),verificationResult:jn.compile(Wa),adoptionEvidence:jn.compile(Bb),projectAdoptionLock:jn.compile(Jb)},Ka=class extends Error{contract;issues;code="ADOPTION_CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function Ha(e,t,r){if(!t(r))throw new Ka(e,t.errors??[]);return r}var fu=e=>{let t=Ha("capabilityBundleRelease",Ya.capabilityBundleRelease,e);if(t.schemaVersion===2){let r=()=>{throw new Ka("capabilityBundleRelease",[])},n=t.packageSources;(t.availability.maturity==="candidate"&&t.availability.sourceState==="local-artifact"&&n.length!==0||t.availability.maturity==="candidate"&&t.availability.sourceState==="development-registry"&&n.length===0||t.availability.maturity!=="candidate"&&n.length===0)&&r();let a="",i=new Set;for(let s of n){let c=`${s.packageName}@${s.version}`;(c.localeCompare(a)<=0||i.has(c))&&r(),a=c,i.add(c)}let o=t.integration?.packages??[];(t.availability.maturity!=="candidate"||t.availability.sourceState==="development-registry")&&(o.length!==n.length||o.some(s=>!n.some(c=>c.packageName===s.packageName&&c.version===s.version&&c.usage===s.usage)))&&r()}return t},mu=e=>Ha("verificationResult",Ya.verificationResult,e),$n=e=>Ha("adoptionEvidence",Ya.adoptionEvidence,e),Oe=e=>Ha("projectAdoptionLock",Ya.projectAdoptionLock,e);import{lstat as ek,readFile as ac,realpath as ic}from"node:fs/promises";import Lr from"node:path";import{createHash as Gb}from"node:crypto";function v(e){return`sha256:${Gb("sha256").update(e).digest("hex")}`}function E(e){return Array.isArray(e)?`[${e.map(E).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${E(n)}`).join(",")}}`:JSON.stringify(e)}var mt=class extends Error{code="MANAGED_REGION_INVALID";constructor(t){super(t)}};function gu(e){if(!new RegExp(H).test(e))throw new mt("Region identity is invalid");return{begin:`<!-- dyyto:begin ${e} -->`,end:`<!-- dyyto:end ${e} -->`}}function Xa(e,t){if(e.includes("\r"))throw new mt("Managed regions require LF newlines");let{begin:r,end:n}=gu(t),a=e.split(r).length-1,i=e.split(n).length-1;if(a!==1||i!==1)throw new mt("Managed region markers are unavailable or ambiguous");let o=e.indexOf(r)+r.length,s=e.indexOf(n,o),c=e.slice(o,s);if(/<!-- dyyto:(?:begin|end) /.test(c))throw new mt("Managed regions cannot overlap");return`${c.replace(/^\n+|\n+$/g,"")}
9
9
  `}function hu(e){let{begin:t,end:r}=gu(e.regionId);if(e.source.includes("\r")||e.content.includes("\r"))throw new mt("Managed regions require LF newlines");let n=e.source.split(t).length-1,a=e.source.split(r).length-1;if(n>1||a>1||n!==a)throw new mt("Managed region markers are ambiguous");let i=e.content.replace(/^\n+|\n+$/g,"");if(/<!-- dyyto:(?:begin|end) /.test(i))throw new mt("Managed regions cannot contain nested Dyyto markers");let o=`${t}
10
10
  ${i}
11
11
  ${r}`;if(n===0){let l=e.source.replace(/\n*$/g,"");return`${l}${l.length===0?"":`
12
12
 
13
13
  `}${o}
14
- `}let s=e.source.indexOf(t),c=e.source.indexOf(r,s)+r.length,d=e.source.slice(s+t.length,c-r.length);if(/<!-- dyyto:(?:begin|end) /.test(d))throw new mt("Managed regions cannot overlap");return`${e.source.slice(0,s)}${o}${e.source.slice(c)}`}import yu from"node:path";var Ct=class extends Error{assetPath;code="PLAN_PRECONDITION_FAILED";constructor(t,r){super(t),this.assetPath=r}};function Za(e){if(e.length===0||yu.posix.isAbsolute(e)||yu.win32.isAbsolute(e)||e.includes("\\")||e.split("/").some(t=>t===".."||t==="."))throw new Ct("Asset path must be a normalized project-relative POSIX path",e)}function Gb(e,t){Za(e.path);let r=e.kind==="merge"&&e.ownership==="managed-region"&&e.regionId!==void 0&&new RegExp(H).test(e.regionId);if((e.kind==="merge"||e.ownership==="managed-region"||e.regionId!==void 0)&&!r)throw new Ct("Managed regions require merge ownership and a valid region identity",e.path);if(e.ownership==="user-file")return{...e,disposition:"conflict",conflictCode:"USER_OWNED"};let n=t?.exists??!1,a=t?.digest;return e.kind==="create"?n?e.desiredDigest!==void 0&&a===e.desiredDigest?{...e,disposition:"noop"}:{...e,disposition:"conflict",conflictCode:"UNEXPECTED_EXISTING"}:{...e,disposition:"ready"}:e.kind==="remove"&&!n?{...e,disposition:"noop"}:e.kind!=="remove"&&n&&e.desiredDigest===a?{...e,disposition:"noop"}:!n||e.baseDigest===void 0||a!==e.baseDigest?{...e,disposition:"conflict",conflictCode:"BASE_DIGEST_MISMATCH"}:{...e,disposition:"ready"}}function Oe(e){if(Number.isNaN(Date.parse(e.generatedAt))||Number.isNaN(Date.parse(e.expiresAt)))throw new Ct("Plan timestamps must be valid ISO date-time values");if(Date.parse(e.expiresAt)<=Date.parse(e.generatedAt))throw new Ct("Plan expiry must be later than generation time");let t=new Map;for(let s of e.observedAssets){if(Za(s.path),t.has(s.path))throw new Ct("Observed asset paths must be unique",s.path);t.set(s.path,s)}let r=new Set,n=e.changes.map(s=>{if(r.has(s.path))throw new Ct("Proposed change paths must be unique",s.path);return r.add(s.path),Gb(s,t.get(s.path))}).sort((s,c)=>s.path.localeCompare(c.path)),a={action:e.action,capability:{capabilityId:e.capability.capabilityId,version:e.capability.version,integrity:e.capability.integrity},changes:e.changes,observedAssets:e.observedAssets,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}},i=v(E(a)),o={schemaVersion:1,action:e.action,state:n.some(s=>s.disposition==="conflict")?"conflicted":"reviewable",capability:a.capability,generatedAt:e.generatedAt,expiresAt:e.expiresAt,inputDigest:i,operations:n,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}};return{...o,planId:v(E(o))}}function Qa(e){return v(E(e))}var wu=Ir(tr(),1);var X={type:"string",pattern:dt},xr={type:"string",pattern:H},ar={type:"string",minLength:1,maxLength:128},nr={type:"string",minLength:1,maxLength:512,pattern:"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\).+$"},Wb={$id:"https://schemas.dyyto.dev/platform/capability-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","assets","verifiers"],properties:{schemaVersion:{const:1},capabilityId:xr,version:ar,integrity:X,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","ownership"],properties:{path:nr,ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:X}}},verifiers:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1,maxLength:128},kind:{enum:["command","file-digest"]}}}}}},Kb={$id:"https://schemas.dyyto.dev/platform/project-manifest-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},template:{type:"object",additionalProperties:!1,required:["id","version"],properties:{id:xr,version:ar}},profile:{type:"object",additionalProperties:!1,required:["id","parameters"],properties:{id:{type:"string",pattern:H},parameters:{type:"object",minProperties:0,maxProperties:32,propertyNames:{pattern:"^[a-z][A-Za-z0-9]*$"},additionalProperties:{type:"string",maxLength:256}}}},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:xr,version:ar}}}}},Yb={$id:"https://schemas.dyyto.dev/platform/project-lock-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","appliedPlanId","assets","evidenceIds"],properties:{capabilityId:xr,version:ar,integrity:X,appliedPlanId:X,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:nr,digest:X}}},evidenceIds:{type:"array",items:{type:"string",minLength:1,maxLength:256}}}}}}},Hb={$id:"https://schemas.dyyto.dev/platform/evidence-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","evidenceId","capabilityId","capabilityVersion","verifierId","result","observedAt"],properties:{schemaVersion:{const:1},evidenceId:{type:"string",minLength:1,maxLength:256},capabilityId:xr,capabilityVersion:ar,verifierId:{type:"string",minLength:1,maxLength:128},result:{enum:["passed","failed"]},observedAt:{type:"string",format:"date-time"}}},Xb={$id:"https://schemas.dyyto.dev/platform/change-plan-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","planId","action","state","capability","generatedAt","expiresAt","inputDigest","operations"],properties:{schemaVersion:{const:1},planId:X,action:{enum:["adopt","upgrade","remove"]},state:{enum:["reviewable","conflicted"]},capability:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity"],properties:{capabilityId:xr,version:ar,integrity:X}},generatedAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"},inputDigest:X,packageAdoption:{type:"object",additionalProperties:!1,required:["schemaVersion","packageJsonPreimageDigest","desiredPackageJsonDigest","lockfilePreimage","desiredLockfileDigest","registryRevisions","endpointBindings","sources","installPolicy"],properties:{schemaVersion:{enum:[1,2]},sourceChannel:{enum:["production","development"]},packageJsonPreimageDigest:X,desiredPackageJsonDigest:X,lockfilePreimage:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest"],properties:{kind:{const:"present"},digest:X}}]},desiredLockfileDigest:X,registryRevisions:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:{type:"string",minLength:1,maxLength:128},revision:X}}},endpointBindings:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","registryConfigRevision","bindingDigest","expiresAt"],properties:{registryId:{type:"string",minLength:1,maxLength:128},registryConfigRevision:X,bindingDigest:X,expiresAt:{type:"string",format:"date-time"}}}},sources:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",minLength:1,maxLength:128},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$"},version:ar,integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]+={0,2}$"},tarballDigest:X,deliveryReceiptId:X,usage:{enum:["runtime","development"]}}}},installPolicy:{type:"object",additionalProperties:!1,required:["ignoreScripts","allowWorkspaceProtocol","allowPublicRegistryFallback"],properties:{ignoreScripts:{const:!0},allowWorkspaceProtocol:{const:!1},allowPublicRegistryFallback:{const:!1}}},topology:{type:"object",additionalProperties:!1,required:["mode","unitRelativeRoot","unitImporterId","lockfilePath"],properties:{mode:{enum:["standalone","pnpm-shared-lockfile"]},unitRelativeRoot:nr,unitImporterId:nr,lockfilePath:{const:"pnpm-lock.yaml"},workspaceManifestPath:{const:"pnpm-workspace.yaml"},workspaceManifestDigest:X}},preservedDependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["section","packageName","specifier"],properties:{section:{enum:["dependencies","devDependencies","optionalDependencies"]},packageName:{type:"string",minLength:1,maxLength:214},specifier:{type:"string",minLength:1,maxLength:512}}}},preservedImporterDigests:{type:"array",items:{type:"object",additionalProperties:!1,required:["importerId","preimageDigest","desiredDigest"],properties:{importerId:nr,preimageDigest:X,desiredDigest:X}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{topology:!1,preservedDependencies:!1,preservedImporterDigests:!1}}},{if:{properties:{schemaVersion:{const:2}},required:["schemaVersion"]},then:{required:["topology","preservedDependencies","preservedImporterDigests"]}}]},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","kind","ownership","disposition"],properties:{path:nr,kind:{enum:["create","replace","merge","remove"]},ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:X,baseDigest:X,regionId:{type:"string",pattern:H},disposition:{enum:["ready","noop","conflict"]},conflictCode:{enum:["USER_OWNED","UNEXPECTED_EXISTING","BASE_DIGEST_MISMATCH"]}}}}}},Zb={$id:"https://schemas.dyyto.dev/platform/transaction-journal-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","transactionId","planId","approvedPlanId","projectRootDigest","state","createdAt","updatedAt","operations","journalDigest"],properties:{schemaVersion:{const:1},transactionId:{type:"string",minLength:1,maxLength:128},planId:X,approvedPlanId:X,projectRootDigest:X,state:{enum:["preparing","prepared","applying","applied","recovery-required","recovering","recovered"]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["index","path","kind","before","status"],properties:{index:{type:"integer",minimum:0},path:nr,kind:{enum:["create","replace","merge","remove"]},before:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest","mode","preimageDigest"],properties:{kind:{const:"present"},digest:X,mode:{type:"integer",minimum:0,maximum:511},preimageDigest:X}}]},desiredDigest:X,status:{enum:["pending","applied","restored"]}}}},failure:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",minLength:1,maxLength:128},operationIndex:{type:"integer",minimum:0}}},journalDigest:X}},rr=new wu.Ajv2020({allErrors:!0,strict:!0});rr.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var rc={capabilityRelease:rr.compile(Wb),projectManifest:rr.compile(Kb),projectLock:rr.compile(Yb),evidence:rr.compile(Hb),changePlan:rr.compile(Xb),transactionJournal:rr.compile(Zb)},tc=class extends Error{contract;issues;code="CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function nc(e,t,r){if(!t(r))throw new tc(e,t.errors??[]);return r}var K=e=>nc("projectManifest",rc.projectManifest,e);var Tt=e=>nc("changePlan",rc.changePlan,e),vu=e=>nc("transactionJournal",rc.transactionJournal,e);var M=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};async function ei(e){if(e.currentLock!==void 0){let i=await ti({...e,manifest:{schemaVersion:1,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}});return{state:i.plan.state==="conflicted"?"drifted":"adopted",operations:i.plan.operations}}let t=await ic(Lr.resolve(e.projectRoot)),r=[],n=0,a=0;for(let i of e.release.release.assets){let o=await oc(t,i.path);o.exists&&(n+=1),o.digest===i.digest&&(a+=1),r.push({path:i.path,kind:"create",ownership:i.ownership,desiredDigest:i.ownership==="seed-file"&&o.digest?o.digest:i.digest,disposition:o.exists?i.ownership==="seed-file"||o.digest===i.digest?"noop":"conflict":"ready",...o.exists&&o.digest!==i.digest?{conflictCode:"UNEXPECTED_EXISTING"}:{}})}return n===0?{state:"planned",operations:r}:a===e.release.release.assets.length?{state:"applied-unverified",operations:r}:{state:"drifted",operations:r}}async function oc(e,t){let r=Lr.join(e,...t.split("/"));try{let n=await Qb(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Blank profile target must be a regular file",t);return{path:t,exists:!0,digest:v(await ac(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function ir(e){let t=await ic(Lr.resolve(e.projectRoot)),r=[];for(let n of e.expectedAssets){let a=await oc(t,n.path),i=a.exists&&a.digest===n.digest;if(n.ownership==="managed-region"&&n.regionId!==void 0&&a.exists)try{i=v(Xa(await ac(Lr.join(t,...n.path.split("/")),"utf8"),n.regionId))===n.digest}catch{i=!1}if(!i)throw new M("PROJECT_STATE_INVALID","A managed project asset does not match the approved plan",n.path);r.push({path:n.path,digest:n.digest,...n.ownership===void 0?{}:{ownership:n.ownership},...n.regionId===void 0?{}:{regionId:n.regionId}})}return{assets:r,projectStateDigest:v(E(r))}}async function ti(e){let t=K(e.manifest);if(t.capabilities.filter(l=>l.capabilityId===e.release.release.capabilityId&&l.version===e.release.release.version).length!==1||t.capabilities.length!==1)throw new M("RELEASE_NOT_FOUND","Manifest must select exactly the loaded M3 capability release");let a=(e.currentLock===void 0?void 0:$e(e.currentLock))?.capabilities.find(l=>l.capabilityId===e.release.release.capabilityId);if(a!==void 0&&(a.version!==e.release.release.version||a.integrity!==e.release.release.integrity))throw new M("CONSUMER_PROFILE_UNSUPPORTED","M3 does not support upgrading a different locked release");let i=await ic(Lr.resolve(e.projectRoot)),o=[],s=[],c=new Map(e.release.contents);for(let l of e.release.release.assets){let p=await oc(i,l.path);if(o.push(p),p.exists&&a===void 0&&l.ownership!=="seed-file")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Blank profile cannot adopt over an existing file without a lock",l.path);let f=l.ownership==="seed-file"&&p.digest?p.digest:l.digest;l.ownership==="seed-file"&&p.exists&&c.set(l.path,await ac(Lr.join(i,...l.path.split("/")))),s.push({path:l.path,kind:"create",ownership:l.ownership,desiredDigest:f})}let d={schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:e.release.release.assets.map(l=>({path:l.path,ownership:l.ownership,desiredDigest:l.digest})),verifiers:e.release.release.verifiers.map(l=>({id:l.id,kind:"command"}))};return{manifest:t,release:e.release,plan:Oe({action:"adopt",capability:d,changes:s,observedAssets:o,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),desiredContents:c}}import{chmod as tk,lstat as si,mkdir as Vr,open as ku,readFile as ci,realpath as rk,rename as ii,rm as sc,unlink as or}from"node:fs/promises";import{constants as ni}from"node:fs";import{homedir as nk}from"node:os";import J from"node:path";import{randomUUID as Ur}from"node:crypto";function ek(e){let t=e?.code;return typeof t=="string"&&/^[A-Z0-9_]+$/.test(t)?t:"UNKNOWN"}async function He(e){let t=process.hrtime.bigint();try{let r=await e.run();return await Iu(e.context,e.operation,e.bytes??0,t,"succeeded"),r}catch(r){throw await Iu(e.context,e.operation,e.bytes??0,t,"failed",ek(r)),r}}async function Iu(e,t,r,n,a,i){if(e?.sink===void 0)return;let o=process.hrtime.bigint(),s={schemaVersion:1,phase:e.phase,operation:t,pathCategory:e.pathCategory,bytes:r,barrierId:e.barrierId,startedMonotonicNs:n.toString(),completedMonotonicNs:o.toString(),result:a,...i===void 0?{}:{errorCategory:i}},c=Object.freeze({...s,eventId:v(E(s))});try{await e.sink(c)}catch{}}var _u=Symbol("prepared-transaction"),xt=new Map,ak=5*1024*1024,ik=25*1024*1024,bu=8,oi=class extends Error{};async function ri(e,t,r){try{await e?.onCheckpoint?.(t,r)}catch(n){throw new oi("Simulated prepare crash",{cause:n})}}var C=class extends Error{code;relativePath;operationIndex;constructor(t,r,n,a){super(r),this.code=t,this.relativePath=n,this.operationIndex=a}};function On(e,t){let r=J.join(e,".dyyto"),n=J.join(r,"transactions",t);return{platformDirectory:r,lock:J.join(r,"transaction-lock.json"),transactionDirectory:n,journal:J.join(n,"journal.json"),preimages:J.join(n,"preimages"),quarantine:J.join(n,"quarantine")}}async function vt(e){try{return await si(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Fr(e,t=!1){if(e?.sink!==void 0)return{sink:e.sink,phase:e.phase,pathCategory:t?"directory":e.category,barrierId:e.barrierId}}function at(e,t,r,n){return e===void 0?void 0:{sink:e,phase:t,category:r,barrierId:n}}async function Xe(e,t){let r=await ku(e,ni.O_RDONLY);try{await He({context:Fr(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function Cn(e,t,r=384,n){let a=await ku(e,ni.O_CREAT|ni.O_EXCL|ni.O_WRONLY,r);try{await He({context:Fr(n),operation:"write",bytes:t.byteLength,run:()=>a.writeFile(t)}),await He({context:Fr(n),operation:"file-sync",bytes:t.byteLength,run:()=>a.sync()})}finally{await a.close()}}async function cc(e,t,r){let n=J.dirname(e),a=J.join(n,`.tmp-${Ur()}`),i=Buffer.from(`${JSON.stringify(t,null,2)}
15
- `);await Cn(a,i,384,r),await He({context:Fr(r),operation:"rename",bytes:i.byteLength,run:()=>ii(a,e)}),await Xe(n,r)}function lc(e){return{...e,journalDigest:v(E(e))}}function ok(e){let t;try{t=vu(e)}catch{throw new C("JOURNAL_CORRUPTED","Transaction journal shape is invalid")}let{journalDigest:r,...n}=t;if(r!==v(E(n)))throw new C("JOURNAL_CORRUPTED","Transaction journal digest or shape is invalid");let a=new Set;for(let[i,o]of t.operations.entries()){if(o.index!==i||a.has(o.path)||o.kind==="create"&&o.before.kind!=="absent"||o.kind!=="create"&&o.before.kind!=="present"||o.kind!=="remove"&&o.desiredDigest===void 0||o.kind==="remove"&&o.desiredDigest!==void 0)throw new C("JOURNAL_CORRUPTED","Transaction journal operation is inconsistent");a.add(o.path)}return t}async function dc(e){try{return ok(JSON.parse(await ci(e,"utf8")))}catch(t){throw t instanceof C?t:new C("JOURNAL_CORRUPTED","Transaction journal cannot be read")}}async function Lt(e,t,r){let{journalDigest:n,...a}=t,i=lc(a);return await cc(e,i,r),i}async function li(e){let t=J.resolve(e),r=J.parse(t);if(t===r.root||t===J.resolve(nk()))throw new C("PROJECT_ROOT_UNSAFE","Project root cannot be the filesystem root or user home");let n=await si(t);if(!n.isDirectory()||n.isSymbolicLink())throw new C("PROJECT_ROOT_UNSAFE","Project root must be a real directory");let a=await rk(t);if(a!==t)throw new C("PROJECT_ROOT_UNSAFE","Project root cannot resolve through a symbolic link");return a}function zr(e,t){if((t===".dyyto"||t.startsWith(".dyyto/"))&&t!==".dyyto/application-config-binding.json"||t.length===0||J.posix.isAbsolute(t)||J.win32.isAbsolute(t)||t.includes("\\")||t.split("/").some(n=>n==="."||n===".."))throw new C("PROJECT_ROOT_UNSAFE","Target path is unsafe",t);let r=J.resolve(e,...t.split("/"));if(!r.startsWith(`${e}${J.sep}`))throw new C("PROJECT_ROOT_UNSAFE","Target escapes project root",t);return r}async function Mr(e,t){let r=t.split("/"),n=e;for(let a of r){n=J.join(n,a);try{if((await si(n)).isSymbolicLink())throw new C("PATH_SYMLINK_UNSAFE","Symbolic links are not valid transaction targets",t)}catch(i){if(i.code==="ENOENT")return;throw i}}}async function qr(e){try{let t=await si(e);if(!t.isFile()||t.isSymbolicLink())throw new C("PATH_SYMLINK_UNSAFE","Transaction target must be a regular file");let r=await ci(e);return{bytes:r,digest:v(r),mode:t.mode&511}}catch(t){if(t.code==="ENOENT")return;throw t}}function sk(e,t,r){Tt(e);let{planId:n,...a}=e;if(Qa(a)!==e.planId)throw new C("PLAN_CONTENT_MISMATCH","Plan content does not match planId");if(e.planId!==t)throw new C("PLAN_APPROVAL_MISMATCH","Approval does not match planId");if(e.state!=="reviewable")throw new C("PLAN_PRECONDITION_FAILED","Only reviewable plans can be applied");if(Date.parse(e.expiresAt)<=Date.parse(r))throw new C("PLAN_EXPIRED","Plan has expired")}function ck(e){let t=e.operations.filter(r=>r.disposition==="ready");for(let r of t)if(!((r.ownership==="owned-file"||r.ownership==="seed-file")&&["create","replace","remove"].includes(r.kind)||r.ownership==="managed-region"&&r.kind==="merge"&&r.regionId!==void 0))throw new C("OPERATION_UNSUPPORTED","Operation ownership is not supported",r.path);return t}async function pc(e,t,r){try{await Cn(e,Buffer.from(`${JSON.stringify(t,null,2)}
16
- `),384,r),await Xe(J.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new C("TRANSACTION_ACTIVE","Another platform transaction is active"):n}}async function ai(e){try{let t=JSON.parse(await ci(e,"utf8"));if(t.schemaVersion!==1||typeof t.transactionId!="string"||typeof t.planId!="string"||typeof t.startedAt!="string"||typeof t.nonce!="string")throw new Error("invalid lock");return t}catch{throw new C("JOURNAL_CORRUPTED","Transaction lock is invalid")}}function lk(e,t,r){return{[_u]:!0,projectRoot:e,plan:t,transactionId:r}}async function dk(e,t){sk(e.plan,e.approvedPlanId,e.now);let r=await li(e.projectRoot),n=ck(e.plan),a=new Set(e.plan.operations.filter(u=>u.kind!=="remove"&&u.disposition!=="conflict").map(u=>u.path));for(let u of e.desiredContents.keys())if(!a.has(u))throw new C("DESIRED_CONTENT_MISMATCH","Desired content is not declared by the plan",u);for(let u of n)if(zr(r,u.path),await Mr(r,u.path),u.kind!=="remove"){let m=e.desiredContents.get(u.path);if(m===void 0||v(m)!==u.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired content digest does not match the plan",u.path)}let i=On(r,e.plan.planId);await Vr(i.platformDirectory,{recursive:!0,mode:448}),await Mr(r,".dyyto");let o=Ur();await pc(i.lock,{schemaVersion:1,transactionId:o,planId:e.plan.planId,startedAt:e.now,nonce:Ur()},at(t?.durabilityTrace,"prepare","lock",`${o}:prepare-lock`));let s=e.limits?.maxFileBytes??ak,c=e.limits?.maxTransactionBytes??ik,d=0,l=[],p=[],f=!1;try{if(await ri(t,"lock-created"),await vt(i.transactionDirectory))throw new C("PLAN_PRECONDITION_FAILED","This plan already has a transaction record");await Vr(i.preimages,{recursive:!0,mode:448}),await Vr(i.quarantine,{recursive:!0,mode:448}),f=!0;for(let[m,g]of n.entries()){let h=zr(r,g.path);await Mr(r,g.path);let w=await qr(h);if(g.kind==="create"){if(w!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target now exists",g.path,m)}else if(w===void 0||w.digest!==g.baseDigest)throw new C("PLAN_PRECONDITION_FAILED","Target no longer matches plan base digest",g.path,m);let _={kind:"absent"};if(w!==void 0){if(d+=w.bytes.byteLength,w.bytes.byteLength>s||d>c)throw new C("PREIMAGE_LIMIT_EXCEEDED","Preimage size limit exceeded",g.path,m);let I=J.join(i.preimages,`${m}.bin`);await Cn(I,w.bytes,384,at(t?.durabilityTrace,"prepare","preimage",`${o}:preimage:${m}`)),p.push(m),await ri(t,"preimage-written-pending-directory-sync",m),_={kind:"present",digest:w.digest,mode:w.mode,preimageDigest:v(w.bytes)}}l.push({index:m,path:g.path,kind:g.kind,before:_,...g.desiredDigest===void 0?{}:{desiredDigest:g.desiredDigest},status:"pending"})}if(p.length>0){await Xe(i.preimages,at(t?.durabilityTrace,"prepare","directory",`${o}:preimages-directory-batch`));for(let m of p)await ri(t,"preimage-persisted",m)}let u=lc({schemaVersion:1,transactionId:o,planId:e.plan.planId,approvedPlanId:e.approvedPlanId,projectRootDigest:v(r),state:"prepared",createdAt:e.now,updatedAt:e.now,operations:l});return await cc(i.journal,u,at(t?.durabilityTrace,"prepare","journal",`${o}:journal-prepared`)),xt.set(o,{desiredContents:e.desiredContents,journal:u}),await ri(t,"journal-prepared"),lk(r,e.plan,o)}catch(u){if(u instanceof oi)throw xt.delete(o),new C("RECOVERY_REQUIRED","Prepare was interrupted; recovery is required");try{f&&await sc(i.transactionDirectory,{recursive:!0,force:!0}),await or(i.lock),await Xe(i.platformDirectory)}catch{throw new C("RECOVERY_REQUIRED","Prepare failed and transaction lock could not be released")}throw u}}async function Br(e){return dk(e)}async function pk(e,t,r,n){return Lt(e.journal,{...t,state:"recovery-required",updatedAt:new Date().toISOString(),failure:{code:"APPLY_INTERRUPTED",...r===void 0?{}:{operationIndex:r}}},at(n,"apply","journal",`${t.transactionId}:recovery-required`))}async function uk(e,t,r,n,a,i){let o=zr(e,n.path);await Mr(e,n.path);let s=await qr(o);if(n.before.kind==="absent"){if(s!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target changed after prepare",n.path,n.index)}else if(s===void 0||s.digest!==n.before.digest)throw new C("PLAN_PRECONDITION_FAILED","Target changed after prepare",n.path,n.index);if(n.kind==="remove"){let p=J.join(t.quarantine,`${n.index}.bin`),f=at(i?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await He({context:Fr(f),operation:"rename",run:()=>ii(o,p)}),await i?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[J.dirname(o),t.quarantine]}let c=a.get(n.path);if(c===void 0||v(c)!==n.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired bytes are missing or changed",n.path,n.index);await Vr(J.dirname(o),{recursive:!0}),await Mr(e,n.path);let d=J.join(J.dirname(o),`.dyyto-${r}-${n.index}.tmp`),l=at(i?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await Cn(d,c,n.before.kind==="present"?n.before.mode&511:420,l),await i?.onCheckpoint?.("temporary-file-synced",n.index),await He({context:Fr(l),operation:"rename",bytes:c.byteLength,run:()=>ii(d,o)}),await i?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[J.dirname(o)]}async function fk(e,t){let r=xt.get(e.transactionId);if(r===void 0||e[_u]!==!0)throw new C("PLAN_PRECONDITION_FAILED","Prepared transaction is not active");let n=On(e.projectRoot,e.plan.planId),a=await Lt(n.journal,{...r.journal,state:"applying",updatedAt:new Date().toISOString()},at(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applying`));try{await t?.onCheckpoint?.("prepared");let i=new Map;for(let o=0;o<a.operations.length;o+=bu){let s=a.operations.slice(o,o+bu),c=await Promise.allSettled(s.map(l=>uk(e.projectRoot,n,e.transactionId,l,r.desiredContents,t))),d=c.find(l=>l.status==="rejected");if(d?.status==="rejected")throw d.reason;for(let l of c)if(l.status==="fulfilled")for(let p of l.value)i.has(p)||i.set(p,at(t?.durabilityTrace,"apply","directory",`${e.transactionId}:target-directory-batch`))}for(let[o,s]of i)await Xe(o,s);for(let o of a.operations)await t?.onCheckpoint?.("target-renamed",o.index),o.status="applied",await t?.onCheckpoint?.("operation-applied",o.index);a=await Lt(n.journal,{...a,operations:a.operations,updatedAt:new Date().toISOString()},at(t?.durabilityTrace,"apply","journal",`${e.transactionId}:operation-batch`));for(let o of a.operations)await t?.onCheckpoint?.("operation-journaled",o.index);return a=await Lt(n.journal,{...a,state:"applied",updatedAt:new Date().toISOString()},at(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applied`)),await t?.onCheckpoint?.("applied"),await or(n.lock),await Xe(n.platformDirectory),xt.delete(e.transactionId),sr(a)}catch(i){throw a=await pk(n,a,i instanceof C?i.operationIndex:void 0,t?.durabilityTrace),xt.set(e.transactionId,{desiredContents:r.desiredContents,journal:a}),new C("RECOVERY_REQUIRED","Apply was interrupted; recovery is required")}}async function Jr(e){return fk(e)}function sr(e){return{transactionId:e.transactionId,planId:e.planId,state:e.state,operations:e.operations}}async function It(e){let t=await li(e.projectRoot),r=On(t,e.planId);if(!await vt(r.journal)){if(!await vt(r.lock))return null;let n=await ai(r.lock);return n.planId!==e.planId?null:{transactionId:n.transactionId,planId:n.planId,state:"preparing",operations:[]}}return sr(await dc(r.journal))}async function mk(e,t,r){await Vr(J.dirname(e),{recursive:!0});let n=J.join(J.dirname(e),`.dyyto-recover-${Ur()}.tmp`);await Cn(n,t,r&511),await ii(n,e),await tk(e,r&511),await Xe(J.dirname(e))}async function gk(e){let t=await li(e.projectRoot),r=On(t,e.planId);if(!await vt(r.journal)){if(!await vt(r.lock))throw new C("JOURNAL_CORRUPTED","No transaction record exists");let a=await ai(r.lock);if(a.planId!==e.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another plan");await sc(r.transactionDirectory,{recursive:!0,force:!0}),await Vr(r.transactionDirectory,{recursive:!0,mode:448});let i=lc({schemaVersion:1,transactionId:a.transactionId,planId:a.planId,approvedPlanId:a.planId,projectRootDigest:v(t),state:"recovered",createdAt:a.startedAt,updatedAt:e.now,operations:[]});return await cc(r.journal,i),await or(r.lock),await Xe(r.platformDirectory),sr(i)}let n=await dc(r.journal);if(n.state==="recovered")return sr(n);if(n.state==="applied"){for(let a of n.operations){let i=await qr(zr(t,a.path));if(!(a.kind==="remove"?i===void 0:i?.digest===a.desiredDigest))throw new C("RECOVERY_CONFLICT","Completed transaction target changed before lock cleanup",a.path,a.index)}if(await vt(r.lock)){let a=await ai(r.lock);if(a.transactionId!==n.transactionId||a.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction");await or(r.lock),await Xe(r.platformDirectory)}return xt.delete(n.transactionId),sr(n)}if(n.projectRootDigest!==v(t))throw new C("JOURNAL_CORRUPTED","Journal belongs to a different project root");if(await vt(r.lock)){let a=await ai(r.lock);if(a.transactionId!==n.transactionId||a.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction")}else await pc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Ur()});n=await Lt(r.journal,{...n,state:"recovering",updatedAt:e.now});for(let a of[...n.operations].reverse()){if(a.status==="restored")continue;let i=zr(t,a.path);if(await Mr(t,a.path),a.kind!=="remove"){let s=J.join(J.dirname(i),`.dyyto-${n.transactionId}-${a.index}.tmp`);if(await vt(s)){if((await qr(s))?.digest!==a.desiredDigest)throw new C("RECOVERY_CONFLICT","Transaction temporary file was modified externally",a.path,a.index);await or(s),await Xe(J.dirname(s))}}let o=await qr(i);if(a.before.kind==="absent"){if(o!==void 0){if(o.digest!==a.desiredDigest)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",a.path,a.index);await or(i),await Xe(J.dirname(i))}}else if(o?.digest!==a.before.digest){let s=J.join(r.quarantine,`${a.index}.bin`),c=o?.digest===a.desiredDigest,d=a.kind==="remove"&&o===void 0&&await vt(s),l=e.approvedConflicts?.find(f=>f.path===a.path&&f.currentDigest===o?.digest);if(!c&&!d&&!l)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",a.path,a.index);let p=await ci(J.join(r.preimages,`${a.index}.bin`));if(v(p)!==a.before.preimageDigest)throw new C("JOURNAL_CORRUPTED","Preimage digest is invalid",a.path,a.index);await mk(i,p,a.before.mode),d&&await sc(s,{force:!0})}a.status="restored",n=await Lt(r.journal,{...n,operations:n.operations,updatedAt:e.now}),await e.hooks?.onCheckpoint?.("operation-journaled",a.index)}return n=await Lt(r.journal,{...n,state:"recovered",updatedAt:e.now}),await or(r.lock),await Xe(r.platformDirectory),xt.delete(n.transactionId),sr(n)}async function Tn(e){return gk(e)}async function uc(e){let t=await li(e.projectRoot),r=On(t,e.planId),n=await dc(r.journal);if(n.state==="recovered")return sr(n);if(n.state!=="applied")throw new C("PLAN_PRECONDITION_FAILED","Only an applied transaction can be rolled back");let a;for(let i of n.operations){let o=await qr(zr(t,i.path)),s=i.kind==="remove"?o===void 0:o?.digest===i.desiredDigest,c=i.before.kind==="absent"?o===void 0:o?.digest===i.before.digest;if(!s&&!c){a=i;break}}if(await pc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Ur()}),n=await Lt(r.journal,{...n,state:"recovery-required",updatedAt:e.now,failure:{code:e.failureCode}}),a!==void 0)throw new C("RECOVERY_CONFLICT","Rollback would overwrite external content",a.path,a.index);return xt.set(n.transactionId,{desiredContents:new Map,journal:n}),Tn({projectRoot:t,planId:e.planId,now:e.now})}var ye=class extends Error{code;constructor(t,r){super(r),this.code=t}},xn=class extends Error{};function Mn(e,t){let r=he.join(e,".dyyto"),n=he.join(r,"metadata-transactions",t);return{platformDirectory:r,evidenceDirectory:he.join(r,"evidence"),lockFile:he.join(r,"project-lock.json"),transactionLock:he.join(r,"metadata-lock.json"),transactionDirectory:n,journal:he.join(n,"journal.json")}}async function Vt(e){try{return await hk(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function bt(e,t,r){return e===void 0?void 0:{sink:e,category:t,barrierId:r}}function fi(e,t=!1){if(e!==void 0)return{sink:e.sink,phase:"metadata",pathCategory:t?"directory":e.category,barrierId:e.barrierId}}async function mi(e,t){let r=await Eu(e,pi.O_RDONLY);try{await He({context:fi(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function gc(e,t,r){let n=await Eu(e,pi.O_CREAT|pi.O_EXCL|pi.O_WRONLY,384);try{await He({context:fi(r),operation:"write",bytes:t.byteLength,run:()=>n.writeFile(t)}),await He({context:fi(r),operation:"file-sync",bytes:t.byteLength,run:()=>n.sync()})}finally{await n.close()}}async function Ln(e,t,r){let n=he.dirname(e),a=he.join(n,`.tmp-${mc()}`),i=Buffer.from(`${JSON.stringify(t,null,2)}
17
- `);await gc(a,i,r),await He({context:fi(r),operation:"rename",bytes:i.byteLength,run:()=>yk(a,e)}),await mi(n,r)}function hc(e){return{...e,journalDigest:v(E(e))}}async function di(e,t,r){let{journalDigest:n,...a}=t,i=hc(a);return await Ln(e,i,r),i}async function Au(e){try{let t=JSON.parse(await Vn(e,"utf8")),{journalDigest:r,...n}=t;if(t.schemaVersion!==1||!Array.isArray(t.evidence)||r!==v(E(n)))throw new Error("invalid journal");return t.evidence.forEach($n),$e(t.lock),t}catch{throw new ye("METADATA_JOURNAL_CORRUPTED","Metadata journal cannot be trusted")}}async function yc(e,t,r){try{await gc(e,Buffer.from(`${JSON.stringify(t,null,2)}
18
- `),r),await mi(he.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new ye("METADATA_TRANSACTION_ACTIVE","Another metadata transaction is active"):n}}function Ru(e,t){let r={...t,capabilityId:e.capabilityId,capabilityVersion:e.version,capabilityIntegrity:e.integrity};return{...r,evidenceId:v(E(r))}}function Pu(e,t,r){let n=t.map(mu),a=e.verifiers.map(o=>o.id).sort(),i=n.map(o=>o.verifierId).sort();if(a.length!==i.length||a.some((o,s)=>o!==i[s]))throw new ye("VERIFICATION_INCOMPLETE","Verification results do not cover the release verifier set");for(let o of n){if(o.commandId!==o.verifierId||o.result!=="passed"||o.exitCode!==0)throw new ye("VERIFICATION_FAILED",`Verifier ${o.verifierId} did not pass`);if(o.projectStateDigest!==r)throw new ye("PROJECT_STATE_CHANGED","Verification result belongs to a different project state")}return n}async function wk(e,t,r){let n=he.join(e,`${t.evidenceId}.json`);if(await Vt(n)){let a=$n(JSON.parse(await Vn(n,"utf8")));if(E(a)!==E(t))throw new ye("METADATA_JOURNAL_CORRUPTED","Existing evidence content does not match its identity");return}await gc(n,Buffer.from(`${JSON.stringify(t,null,2)}
19
- `),r),await mi(e,r)}async function vk(e,t,r,n){if(await Vt(e)){let a=$e(JSON.parse(await Vn(e,"utf8")));if(E(a)===E(t))return;if(r===void 0||v(E(a))!==r)throw new ye("PROJECT_STATE_CHANGED","The project lock changed before metadata commit");await Ln(e,t,n);return}await Ln(e,t,n)}async function ui(e,t){try{await e?.onCheckpoint?.(t)}catch(r){throw new xn("Simulated metadata crash",{cause:r})}}async function wc(e,t,r){let n=Mn(e,t.planId),a=t;try{for(let i of a.evidence)await wk(n.evidenceDirectory,i,bt(r?.durabilityTrace,"evidence",`${a.transactionId}:evidence`));return a=await di(n.journal,{...a,state:"evidence-written",updatedAt:new Date().toISOString()},bt(r?.durabilityTrace,"journal",`${a.transactionId}:evidence-written`)),await ui(r,"evidence-written"),await vk(n.lockFile,a.lock,a.previousLockDigest,bt(r?.durabilityTrace,"lock",`${a.transactionId}:project-lock`)),a=await di(n.journal,{...a,state:"lock-written",updatedAt:new Date().toISOString()},bt(r?.durabilityTrace,"journal",`${a.transactionId}:lock-written`)),await ui(r,"lock-written"),a=await di(n.journal,{...a,state:"committed",updatedAt:new Date().toISOString()},bt(r?.durabilityTrace,"journal",`${a.transactionId}:committed`)),await ui(r,"committed"),await fc(n.transactionLock),await mi(n.platformDirectory,bt(r?.durabilityTrace,"directory",`${a.transactionId}:unlock`)),a.lock}catch(i){if(i instanceof xn)throw new ye("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted");try{await di(n.journal,{...a,state:"recovery-required",updatedAt:new Date().toISOString()},bt(r?.durabilityTrace,"journal",`${a.transactionId}:recovery-required`))}catch{}throw i}}async function Ik(e){let t=await cr(he.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await cr(he.resolve(e.transactionRoot));if((await It({projectRoot:r,planId:e.plan.planId}))?.state!=="applied")throw new ye("APPLY_NOT_COMPLETED","The filesystem transaction is not applied");let a;try{a=await ir({projectRoot:t,expectedAssets:e.expectedAssets??e.release.assets.map(m=>({path:m.path,digest:m.digest}))})}catch{throw new ye("PROJECT_STATE_CHANGED","Managed project assets no longer match the approved plan")}let o=Pu(e.release,e.verificationResults,a.projectStateDigest).map(m=>Ru(e.release,m)),s={capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,consumerProfile:e.release.consumerProfile,appliedPlanId:e.plan.planId,projectStateDigest:a.projectStateDigest,assets:a.assets,evidenceIds:o.map(m=>m.evidenceId).sort(),committedAt:e.committedAt,...e.plan.packageAdoption===void 0?{}:{packageAdoption:{...e.plan.packageAdoption.sourceChannel===void 0?{}:{sourceChannel:e.plan.packageAdoption.sourceChannel},registryRevisions:e.plan.packageAdoption.registryRevisions.map(m=>({...m})),sources:e.plan.packageAdoption.sources.map(m=>({...m})),packageJsonDigest:e.plan.packageAdoption.desiredPackageJsonDigest,lockfileDigest:e.plan.packageAdoption.desiredLockfileDigest}}},c=e.previousLock?.capabilities??[],d=e.previousLock!==void 0&&e.plan.action==="adopt"?[...c.filter(m=>m.capabilityId!==e.release.capabilityId),s].sort((m,g)=>m.capabilityId.localeCompare(g.capabilityId)):e.previousLock!==void 0&&e.plan.action==="upgrade"?[...c.filter(m=>m.capabilityId!==e.release.capabilityId),s].sort((m,g)=>m.capabilityId.localeCompare(g.capabilityId)):[s],l={schemaVersion:d.some(m=>m.packageAdoption!==void 0)?2:1,capabilities:d};$e(l);let p=Mn(t,e.plan.planId);if(await Gr(p.platformDirectory,{recursive:!0,mode:448}),await Gr(p.evidenceDirectory,{recursive:!0,mode:448}),await Vt(p.lockFile)&&e.previousLock===void 0){let m=$e(JSON.parse(await Vn(p.lockFile,"utf8")));if(E(m)===E(l))return m;throw new ye("PROJECT_STATE_CHANGED","An incompatible project lock already exists")}let f=mc();if(await yc(p.transactionLock,{planId:e.plan.planId,transactionId:f,createdAt:e.committedAt},bt(e.hooks?.durabilityTrace,"lock",`${f}:metadata-lock`)),await Vt(p.transactionDirectory))throw await fc(p.transactionLock),new ye("METADATA_TRANSACTION_ACTIVE","This plan already has a metadata transaction");await Gr(p.transactionDirectory,{recursive:!0,mode:448});let u=hc({schemaVersion:1,planId:e.plan.planId,transactionId:f,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:o,lock:l,...e.previousLock===void 0?{}:{previousLockDigest:v(E($e(e.previousLock)))}});await Ln(p.journal,u,bt(e.hooks?.durabilityTrace,"journal",`${f}:prepared`));try{await ui(e.hooks,"journal-prepared")}catch(m){throw m instanceof xn?new ye("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted"):m}return wc(t,u,e.hooks)}async function vc(e){return Ik(e)}async function Ic(e){let t=await cr(he.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await cr(he.resolve(e.transactionRoot));if((await It({projectRoot:r,planId:e.plan.planId}))?.state!=="applied")throw new ye("APPLY_NOT_COMPLETED","The filesystem transaction is not applied");let a=e.previousLock.capabilities.find(h=>h.capabilityId===e.release.capabilityId&&h.version===e.release.version);if(a===void 0)throw new ye("PROJECT_STATE_CHANGED","The removed capability is not present in the project lock");let i=e.previousLock.capabilities.filter(h=>h!==a),o=e.plan.packageAdoption?.schemaVersion===2&&e.plan.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${e.plan.packageAdoption.topology.unitRelativeRoot}/`:"",s=new Map(e.plan.operations.flatMap(h=>h.desiredDigest===void 0||!h.path.startsWith(o)?[]:[[h.path.slice(o.length),h.desiredDigest]])),c=e.expectedAssets??i.flatMap(h=>h.assets).map(h=>({...h,digest:s.get(h.path)??h.digest})),d=await ir({projectRoot:t,expectedAssets:c}),p=Pu(e.release,e.verificationResults,d.projectStateDigest).map(h=>Ru(e.release,h)),f={schemaVersion:i.some(h=>h.packageAdoption!==void 0)?2:1,capabilities:i};$e(f);let u=Mn(t,e.plan.planId);await Gr(u.platformDirectory,{recursive:!0,mode:448}),await Gr(u.evidenceDirectory,{recursive:!0,mode:448});let m=mc();await yc(u.transactionLock,{planId:e.plan.planId,transactionId:m,createdAt:e.committedAt}),await Gr(u.transactionDirectory,{recursive:!1,mode:448});let g=hc({schemaVersion:1,planId:e.plan.planId,transactionId:m,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:p,lock:f,previousLockDigest:v(E($e(e.previousLock)))});return await Ln(u.journal,g),wc(t,g)}async function bc(e){let t=await cr(he.resolve(e.projectRoot)),r=Mn(t,e.planId),n=await Au(r.journal);return n.state==="committed"?(await Vt(r.transactionLock)&&await fc(r.transactionLock),n.lock):(await Vt(r.transactionLock)||await yc(r.transactionLock,{planId:n.planId,transactionId:n.transactionId,createdAt:n.createdAt}),wc(t,n))}async function kc(e){let t=await cr(he.resolve(e.projectRoot)),r=Mn(t,e.planId);if(!await Vt(r.journal))return null;let n=await Au(r.journal);return{planId:n.planId,state:n.state}}async function Ne(e){let t=await cr(he.resolve(e)),r=he.join(t,".dyyto","project-lock.json");return await Vt(r)?$e(JSON.parse(await Vn(r,"utf8"))):null}import{lstat as Su,readFile as Nu,realpath as Du}from"node:fs/promises";import Mt from"node:path";var it=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};function ju(e){return v(E(e))}async function bk(e,t){let r=Mt.join(e,"assets",...t.split("/"));try{return await Su(r),r}catch(n){if(n.code!=="ENOENT"||Mt.posix.basename(t)!==".gitignore")throw n}return Mt.join(e,"assets",...Mt.posix.dirname(t).split("/").filter(n=>n!=="."),"__dyyto_dotfiles__","gitignore")}async function me(e){let t=await Du(Mt.resolve(e)),r;try{r=fu(JSON.parse(await Nu(Mt.join(t,"release.json"),"utf8")))}catch(c){throw c instanceof it?c:new it("RELEASE_INVALID","Capability release metadata is invalid")}let{integrity:n,...a}=r;if(ju(a)!==n)throw new it("RELEASE_INTEGRITY_MISMATCH","Capability release integrity does not match metadata");let i=new Map,o=new Set,s="";for(let c of r.assets){try{Za(c.path)}catch{throw new it("RELEASE_ASSET_INVALID","Release asset path is unsafe",c.path)}if((c.path===".dyyto"||c.path.startsWith(".dyyto/"))&&c.path!==".dyyto/application-config-binding.json"||o.has(c.path)||c.path.localeCompare(s)<0)throw new it("RELEASE_ASSET_INVALID","Release assets must be unique, sorted and outside reserved .dyyto paths",c.path);o.add(c.path),s=c.path;let d=await bk(t,c.path),l=await Du(d),p=Mt.join(t,"assets");if(!l.startsWith(`${p}${Mt.sep}`))throw new it("RELEASE_ASSET_INVALID","Release asset escapes its bundle",c.path);let f=await Su(d);if(!f.isFile()||f.isSymbolicLink())throw new it("RELEASE_ASSET_INVALID","Release asset must be a regular file",c.path);let u=await Nu(d);if(v(u)!==c.digest)throw new it("RELEASE_ASSET_INTEGRITY_MISMATCH","Release asset digest does not match metadata",c.path);i.set(c.path,u)}if(r.exit.ownedAssets.length!==r.assets.length||r.exit.ownedAssets.some((c,d)=>c!==r.assets[d]?.path))throw new it("RELEASE_INVALID","Exit owned assets must exactly match release assets");return{release:r,contents:i}}import{link as kk,open as Ou,lstat as lr,mkdir as Cu,readFile as _c,readdir as gi,realpath as kt,rm as _k,unlink as Ek}from"node:fs/promises";import de from"node:path";var ke=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="ProjectBootstrapError"}},Ak={schemaVersion:1,profile:{id:"workspace-root",parameters:{}},capabilities:[{capabilityId:"foundation.workspace-root",version:"1.2.0"}]};function Rk(){return new TextEncoder().encode(`${JSON.stringify(Ak,null,2)}
20
- `)}async function Pk(e,t=!1){let r=de.resolve(e),n=await lr(r).catch(()=>null);if(n===null||!n.isDirectory()||n.isSymbolicLink())throw new ke("TARGET_INVALID","Workspace target must be a real existing directory");let a=await kt(r);for(let i of t?["AGENTS.md","README.md"]:["package.json","pnpm-workspace.yaml"]){let o=await lr(de.join(a,i)).catch(()=>null);if(o===null||!o.isFile()||o.isSymbolicLink())throw new ke("WORKSPACE_MARKER_MISSING",`Existing workspace must contain a real ${i}`)}if(await lr(de.join(a,"project-capabilities.json")).catch(()=>null))throw new ke("MANIFEST_EXISTS","Project manifest already exists");return a}async function Tu(e){let t=await Pk(e.projectRoot,e.documentationOnly===!0),r=Rk(),n=Oe({action:"adopt",capability:{schemaVersion:1,capabilityId:"foundation.workspace-root",version:"1.2.0",integrity:e.capabilityIntegrity,assets:[],verifiers:[]},changes:[{path:"project-capabilities.json",kind:"create",ownership:"owned-file",desiredDigest:v(r)}],observedAssets:[{path:"project-capabilities.json",exists:!1}],generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{projectRoot:t,plan:n,desiredContents:new Map([["project-capabilities.json",r]])}}async function Nk(e){let t=await Ou(e,"r");try{await t.sync()}finally{await t.close()}}async function xu(e,t){let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`,n=await Ou(r,"wx",384);try{await n.writeFile(t,"utf8"),await n.sync()}finally{await n.close()}try{await kk(r,e),await Ek(r),await Nk(de.dirname(e))}catch(a){throw await _k(r,{force:!0}),a}}async function Dk(e){let t=de.resolve(e);try{let r=await lr(t);if(!r.isDirectory()||r.isSymbolicLink())throw new ke("TARGET_INVALID","Project target must be a real directory");if((await gi(t)).length!==0)throw new ke("TARGET_NOT_EMPTY","Project target must be empty")}catch(r){if(r.code!=="ENOENT")throw r;let n=de.dirname(t),a=await lr(n).catch(()=>null);if(a===null||!a.isDirectory()||a.isSymbolicLink())throw new ke("TARGET_INVALID","Project target parent must be a real directory");await Cu(t)}return kt(t)}async function hi(e){let t=K(e.manifest),r=await Dk(e.projectRoot),n=de.join(r,"project-capabilities.json");try{await xu(n,`${JSON.stringify(t,null,2)}
21
- `)}catch(a){throw a.code==="EEXIST"?new ke("MANIFEST_EXISTS","Project manifest already exists"):a}return{projectRoot:r,manifest:t}}function qn(e){let{planId:t,...r}=e;if(Qa(r)!==e.planId)throw new ke("PLAN_INTEGRITY_INVALID","Saved plan integrity is invalid")}async function Sk(e){let t=await kt(de.resolve(e.projectRoot)),r=Tt(e.plan);qn(r);let n=de.join(t,".dyyto","plans");await Cu(n,{recursive:!0,mode:448});let a=de.join(n,`${r.planId}.json`);try{await xu(a,`${E(r)}
22
- `)}catch(i){if(i.code!=="EEXIST")throw i;let o=Tt(JSON.parse(await _c(a,"utf8")));if(qn(o),E(o)!==E(r))throw new ke("PLAN_INTEGRITY_INVALID","Plan ID content mismatch")}return a}function $u(e){return E({action:e.action,state:e.state,capability:e.capability,operations:e.operations,packageAdoption:e.packageAdoption})}async function dr(e){let t=await kt(de.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await kt(de.resolve(e.transactionRoot)),n=Tt(e.plan);qn(n);let a=de.join(t,".dyyto","plans"),i=await gi(a).catch(s=>{if(s.code==="ENOENT")return[];throw s}),o=[];for(let s of i.filter(c=>c.endsWith(".json")).sort()){let c=Tt(JSON.parse(await _c(de.join(a,s),"utf8")));qn(c),!await lr(de.join(r,".dyyto","transactions",c.planId)).then(()=>!0).catch(l=>l.code==="ENOENT"?!1:Promise.reject(l))&&Date.parse(c.expiresAt)>Date.parse(e.now)&&$u(c)===$u(n)&&o.push(c)}return o.sort((s,c)=>s.generatedAt.localeCompare(c.generatedAt)),o[0]!==void 0?o[0]:(await Sk({projectRoot:t,plan:n}),n)}async function Un(e){let t=await kt(de.resolve(e.projectRoot)),r=de.join(t,".dyyto","plans",`${e.planId}.json`);try{let n=Tt(JSON.parse(await _c(r,"utf8")));if(qn(n),n.planId!==e.planId)throw new ke("PLAN_INTEGRITY_INVALID","Saved plan identity mismatch");return n}catch(n){throw n.code==="ENOENT"?new ke("PLAN_NOT_FOUND","Saved plan was not found"):n}}async function yi(e,t=[],r,n=[]){let a=await kt(de.resolve(e)),i=r===void 0?a:await kt(de.resolve(r)),o=de.join(a,".dyyto","plans"),s=await gi(o).catch(l=>{if(l.code==="ENOENT")return[];throw l}),c=[];for(let l of s.filter(p=>p.endsWith(".json")).sort()){let p=l.slice(0,-5),f=await Un({projectRoot:a,planId:p}),u=await It({projectRoot:i,planId:p}),m=await lr(de.join(a,".dyyto","metadata-transactions",p)).then(()=>!0).catch(g=>g.code==="ENOENT"?!1:Promise.reject(g));u?.state==="applied"&&!m&&!t.includes(f.planId)&&(!n.includes(f.capability.capabilityId)||f.action==="upgrade"||f.action==="remove"||f.action==="adopt"&&f.operations.every(g=>g.disposition==="noop"))&&c.push(f)}let d=jk(c);if(d===void 0)throw new ke("PLAN_NOT_FOUND",c.length===0?"No applied plan is available for verification":"More than one applied plan requires inspection before verification");return d}function jk(e){if(e.length===1)return e[0];if(e.length===0)return;let t=e[0]?.capability.capabilityId;if(!(t===void 0||e.some(r=>r.capability.capabilityId!==t)))return[...e].sort((r,n)=>r.generatedAt.localeCompare(n.generatedAt)).at(-1)}async function Ec(e){let t=await kt(de.resolve(e)),r=de.join(t,".dyyto","plans"),n=await gi(r).catch(i=>{if(i.code==="ENOENT")return[];throw i}),a=[];for(let i of n.filter(o=>o.endsWith(".json")).sort())a.push(await Un({projectRoot:t,planId:i.slice(0,-5)}));return a}import{lstat as Lu,readFile as $k,readdir as wP,realpath as Ok}from"node:fs/promises";import Me from"node:path";import{homedir as Vu}from"node:os";var gt=class extends Error{code;constructor(t){super(t),this.code=t,this.name="WorkspaceTopologyError"}};async function Ck(e){let t=Me.resolve(e),r=await Lu(t).catch(()=>null);if(!r?.isDirectory()||r.isSymbolicLink()||t===Me.parse(t).root||t===Me.resolve(Vu()))throw new gt("WORKSPACE_PATH_UNSAFE");let n=await Ok(t);if(n!==t)throw new gt("WORKSPACE_PATH_UNSAFE");return n}async function Fn(e){let t=await Lu(e).catch(()=>null);if(t!==null){if(!t.isFile()||t.isSymbolicLink())throw new gt("WORKSPACE_PATH_UNSAFE");return $k(e)}}function Tk(e){let t=e.split(/\r?\n/u),r=[],n=!1;for(let a of t){if(/^packages:\s*(?:#.*)?$/u.test(a)){n=!0;continue}if(!n)continue;let i=/^\s+-\s+["']?([^"'#]+?)["']?\s*(?:#.*)?$/u.exec(a);if(i){r.push(i[1].trim().replace(/^\.\//u,"").replace(/\/$/u,""));continue}if(a.trim()&&!/^\s/u.test(a))break}if(r.length===0)throw new gt("WORKSPACE_MANIFEST_INVALID");return r}function xk(e,t){if(e.includes("**")){let r=e.split("**",1)[0].replace(/\/$/u,"");return t===r||t.startsWith(`${r}/`)}if(e.endsWith("/*")){let r=e.slice(0,-2);return t.startsWith(`${r}/`)&&!t.slice(r.length+1).includes("/")}return e===t}async function Wr(e){let t=await Ck(e);if(await Fn(Me.join(t,"pnpm-lock.yaml")))return Object.freeze({schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"});if(await Fn(Me.join(t,"pnpm-workspace.yaml")))throw new gt("WORKSPACE_NESTED_UNSUPPORTED");let r=Me.dirname(t),n;for(;r!==Me.parse(r).root&&r!==Me.resolve(Vu());){let i=await Fn(Me.join(r,"pnpm-workspace.yaml"));if(i){if(n)throw new gt("WORKSPACE_NESTED_UNSUPPORTED");n={root:r,manifest:i};break}r=Me.dirname(r)}if(!n||!await Fn(Me.join(n.root,"pnpm-lock.yaml"))||!await Fn(Me.join(n.root,"project-capabilities.json")))throw new gt("WORKSPACE_OWNER_MISSING");let a=Me.relative(n.root,t).split(Me.sep).join("/");if(!a||a.startsWith("../")||Tk(n.manifest.toString("utf8")).filter(i=>xk(i,a)).length!==1)throw new gt("WORKSPACE_UNIT_NOT_DECLARED");return Object.freeze({schemaVersion:1,mode:"pnpm-shared-lockfile",transactionRoot:n.root,unitRoot:t,unitRelativeRoot:a,unitImporterId:a,workspaceManifestPath:"pnpm-workspace.yaml",workspaceManifestDigest:v(n.manifest),lockfilePath:"pnpm-lock.yaml"})}var Mu=new Set(["preparing","prepared","applying","recovery-required","recovering"]);async function Ac(e){let t=await Ec(e);for(let r of t){let n=await It({projectRoot:e,planId:r.planId});if(n!==null&&Mu.has(n.state))return{required:!0,kind:"filesystem",planId:r.planId,state:n.state}}for(let r of t){let n=await kc({projectRoot:e,planId:r.planId});if(n!==null&&n.state!=="committed")return{required:!0,kind:"metadata",planId:r.planId,state:n.state}}return{required:!1}}async function Lk(e){let t=await Ac(e.projectRoot);if(!t.required)return{kind:"none",state:"not-required"};if(t.kind==="filesystem"){let r=await Tn({projectRoot:e.projectRoot,planId:t.planId,now:e.now});return{kind:"filesystem",planId:t.planId,state:r.state}}return await bc({projectRoot:e.projectRoot,planId:t.planId}),{kind:"metadata",planId:t.planId,state:"committed"}}async function qu(e){let t=await Lk(e);if(t.kind!=="none")return t;let r=await Wr(e.projectRoot).catch(()=>{});if(r?.mode!=="pnpm-shared-lockfile")return t;let n=new Set((await Ec(e.projectRoot)).map(c=>c.planId)),a=await import("node:fs/promises").then(({readFile:c})=>c(`${r.transactionRoot}/.dyyto/transaction-lock.json`,"utf8")).catch(c=>c.code==="ENOENT"?void 0:Promise.reject(c));if(!a)return t;let i;try{let c=JSON.parse(a);if(typeof c.planId!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.planId)||!n.has(c.planId))return t;i=c.planId}catch{return t}let o=await It({projectRoot:r.transactionRoot,planId:i});if(!o||!Mu.has(o.state))return t;let s=await Tn({projectRoot:r.transactionRoot,planId:i,now:e.now});return{kind:"filesystem",planId:i,state:s.state}}import{lstat as Vk,readFile as Rc,realpath as Uu}from"node:fs/promises";import zn from"node:path";var Mk=new Set(["MIT","Apache-2.0","UNLICENSED"]),qk=new Set(["public","restricted","private"]),Uk=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Fk=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function zk(e){let t;try{t=new URL(e)}catch{throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL")}if(t.protocol!=="https:"||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname==="/"||t.pathname.includes(".."))throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL");t.pathname=t.pathname.replace(/\/$/,"").replace(/\.git$/,"");let r=t.href.replace(/\/$/,"");if(r!==e)throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository URL must already be canonical");return r}function pr(e){if(e.profile?.id!=="workspace-node-application"&&e.profile?.id!=="workspace-web-application"&&e.profile?.id!=="workspace-expo-application"&&e.profile?.id!=="nextjs-full-stack-application")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Manifest must select a workspace application profile");let t=Object.keys(e.profile.parameters),r=e.profile.parameters.name;if(t.length!==1||t[0]!=="name"||r===void 0||r.length>128||!/^[a-z0-9][a-z0-9._-]*$/.test(r))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Application parameters must contain one valid lowercase name");return{name:r}}function qt(e,t="standalone-npm-package"){if(e.profile?.id!==t)throw new M("CONSUMER_PROFILE_UNSUPPORTED",`Manifest must select ${t} profile`);let r=e.profile.parameters,n=Object.keys(r).sort(),a=e.capabilities.find(f=>f.capabilityId===`foundation.${t}`)?.version,i=a==="1.1.0"||a==="1.2.0"||t==="react-component-library",o=i?["license","name","publishAccess","repository","version"]:["license","name","publishAccess","version"];if(n.length!==o.length||n.some((f,u)=>f!==o[u]))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Standalone npm profile parameters must be exact");let{name:s,version:c,license:d,publishAccess:l,repository:p}=r;if(s===void 0||s.length>214||!Uk.test(s))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package name must be a valid lowercase name");if(c===void 0||!Fk.test(c))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package version must be a stable SemVer");if(d===void 0||!Mk.has(d))throw new M("CONSUMER_PROFILE_UNSUPPORTED","license must be MIT, Apache-2.0, or UNLICENSED");if(l===void 0||!qk.has(l))throw new M("CONSUMER_PROFILE_UNSUPPORTED","publish access must be public, restricted, or private");if(l==="restricted"&&!s.startsWith("@"))throw new M("CONSUMER_PROFILE_UNSUPPORTED","restricted access requires a scoped package name");return{name:s,version:c,license:d,publishAccess:l,...i?{repository:zk(p)}:{}}}function Pc(e){let t={name:e.name,version:e.version,...e.publishAccess==="private"?{private:!0}:{},license:e.license,...e.repository===void 0?{}:{repository:{type:"git",url:e.repository}},type:"module",sideEffects:!1,main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},files:["dist"],engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run",check:"corepack pnpm typecheck && corepack pnpm test",prepack:"corepack pnpm check && corepack pnpm build"},...e.publishAccess==="private"?{}:{publishConfig:{access:e.publishAccess}},devDependencies:{"@types/node":"24.10.13",typescript:"6.0.3",vitest:"4.1.10"}};return Buffer.from(`${JSON.stringify(t,null,2)}
14
+ `}let s=e.source.indexOf(t),c=e.source.indexOf(r,s)+r.length,d=e.source.slice(s+t.length,c-r.length);if(/<!-- dyyto:(?:begin|end) /.test(d))throw new mt("Managed regions cannot overlap");return`${e.source.slice(0,s)}${o}${e.source.slice(c)}`}import yu from"node:path";var Tt=class extends Error{assetPath;code="PLAN_PRECONDITION_FAILED";constructor(t,r){super(t),this.assetPath=r}};function Za(e){if(e.length===0||yu.posix.isAbsolute(e)||yu.win32.isAbsolute(e)||e.includes("\\")||e.split("/").some(t=>t===".."||t==="."))throw new Tt("Asset path must be a normalized project-relative POSIX path",e)}function Wb(e,t){Za(e.path);let r=e.kind==="merge"&&e.ownership==="managed-region"&&e.regionId!==void 0&&new RegExp(H).test(e.regionId);if((e.kind==="merge"||e.ownership==="managed-region"||e.regionId!==void 0)&&!r)throw new Tt("Managed regions require merge ownership and a valid region identity",e.path);if(e.ownership==="user-file")return{...e,disposition:"conflict",conflictCode:"USER_OWNED"};let n=t?.exists??!1,a=t?.digest;return e.kind==="create"?n?e.desiredDigest!==void 0&&a===e.desiredDigest?{...e,disposition:"noop"}:{...e,disposition:"conflict",conflictCode:"UNEXPECTED_EXISTING"}:{...e,disposition:"ready"}:e.kind==="remove"&&!n?{...e,disposition:"noop"}:e.kind!=="remove"&&n&&e.desiredDigest===a?{...e,disposition:"noop"}:!n||e.baseDigest===void 0||a!==e.baseDigest?{...e,disposition:"conflict",conflictCode:"BASE_DIGEST_MISMATCH"}:{...e,disposition:"ready"}}function Ne(e){if(Number.isNaN(Date.parse(e.generatedAt))||Number.isNaN(Date.parse(e.expiresAt)))throw new Tt("Plan timestamps must be valid ISO date-time values");if(Date.parse(e.expiresAt)<=Date.parse(e.generatedAt))throw new Tt("Plan expiry must be later than generation time");let t=new Map;for(let s of e.observedAssets){if(Za(s.path),t.has(s.path))throw new Tt("Observed asset paths must be unique",s.path);t.set(s.path,s)}let r=new Set,n=e.changes.map(s=>{if(r.has(s.path))throw new Tt("Proposed change paths must be unique",s.path);return r.add(s.path),Wb(s,t.get(s.path))}).sort((s,c)=>s.path.localeCompare(c.path)),a={action:e.action,capability:{capabilityId:e.capability.capabilityId,version:e.capability.version,integrity:e.capability.integrity},changes:e.changes,observedAssets:e.observedAssets,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}},i=v(E(a)),o={schemaVersion:1,action:e.action,state:n.some(s=>s.disposition==="conflict")?"conflicted":"reviewable",capability:a.capability,generatedAt:e.generatedAt,expiresAt:e.expiresAt,inputDigest:i,operations:n,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}};return{...o,planId:v(E(o))}}function Qa(e){return v(E(e))}var wu=Ir(rr(),1);var X={type:"string",pattern:dt},xr={type:"string",pattern:H},ir={type:"string",minLength:1,maxLength:128},ar={type:"string",minLength:1,maxLength:512,pattern:"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\).+$"},Kb={$id:"https://schemas.dyyto.dev/platform/capability-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","assets","verifiers"],properties:{schemaVersion:{const:1},capabilityId:xr,version:ir,integrity:X,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","ownership"],properties:{path:ar,ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:X}}},verifiers:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1,maxLength:128},kind:{enum:["command","file-digest"]}}}}}},Yb={$id:"https://schemas.dyyto.dev/platform/project-manifest-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},template:{type:"object",additionalProperties:!1,required:["id","version"],properties:{id:xr,version:ir}},profile:{type:"object",additionalProperties:!1,required:["id","parameters"],properties:{id:{type:"string",pattern:H},parameters:{type:"object",minProperties:0,maxProperties:32,propertyNames:{pattern:"^[a-z][A-Za-z0-9]*$"},additionalProperties:{type:"string",maxLength:256}}}},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:xr,version:ir}}}}},Hb={$id:"https://schemas.dyyto.dev/platform/project-lock-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","appliedPlanId","assets","evidenceIds"],properties:{capabilityId:xr,version:ir,integrity:X,appliedPlanId:X,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:ar,digest:X}}},evidenceIds:{type:"array",items:{type:"string",minLength:1,maxLength:256}}}}}}},Xb={$id:"https://schemas.dyyto.dev/platform/evidence-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","evidenceId","capabilityId","capabilityVersion","verifierId","result","observedAt"],properties:{schemaVersion:{const:1},evidenceId:{type:"string",minLength:1,maxLength:256},capabilityId:xr,capabilityVersion:ir,verifierId:{type:"string",minLength:1,maxLength:128},result:{enum:["passed","failed"]},observedAt:{type:"string",format:"date-time"}}},Zb={$id:"https://schemas.dyyto.dev/platform/change-plan-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","planId","action","state","capability","generatedAt","expiresAt","inputDigest","operations"],properties:{schemaVersion:{const:1},planId:X,action:{enum:["adopt","upgrade","remove"]},state:{enum:["reviewable","conflicted"]},capability:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity"],properties:{capabilityId:xr,version:ir,integrity:X}},generatedAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"},inputDigest:X,packageAdoption:{type:"object",additionalProperties:!1,required:["schemaVersion","packageJsonPreimageDigest","desiredPackageJsonDigest","lockfilePreimage","desiredLockfileDigest","registryRevisions","endpointBindings","sources","installPolicy"],properties:{schemaVersion:{enum:[1,2]},sourceChannel:{enum:["production","development"]},packageJsonPreimageDigest:X,desiredPackageJsonDigest:X,lockfilePreimage:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest"],properties:{kind:{const:"present"},digest:X}}]},desiredLockfileDigest:X,registryRevisions:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:{type:"string",minLength:1,maxLength:128},revision:X}}},endpointBindings:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","registryConfigRevision","bindingDigest","expiresAt"],properties:{registryId:{type:"string",minLength:1,maxLength:128},registryConfigRevision:X,bindingDigest:X,expiresAt:{type:"string",format:"date-time"}}}},sources:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",minLength:1,maxLength:128},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$"},version:ir,integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]+={0,2}$"},tarballDigest:X,deliveryReceiptId:X,usage:{enum:["runtime","development"]}}}},installPolicy:{type:"object",additionalProperties:!1,required:["ignoreScripts","allowWorkspaceProtocol","allowPublicRegistryFallback"],properties:{ignoreScripts:{const:!0},allowWorkspaceProtocol:{const:!1},allowPublicRegistryFallback:{const:!1}}},topology:{type:"object",additionalProperties:!1,required:["mode","unitRelativeRoot","unitImporterId","lockfilePath"],properties:{mode:{enum:["standalone","pnpm-shared-lockfile"]},unitRelativeRoot:ar,unitImporterId:ar,lockfilePath:{const:"pnpm-lock.yaml"},workspaceManifestPath:{const:"pnpm-workspace.yaml"},workspaceManifestDigest:X}},preservedDependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["section","packageName","specifier"],properties:{section:{enum:["dependencies","devDependencies","optionalDependencies"]},packageName:{type:"string",minLength:1,maxLength:214},specifier:{type:"string",minLength:1,maxLength:512}}}},preservedImporterDigests:{type:"array",items:{type:"object",additionalProperties:!1,required:["importerId","preimageDigest","desiredDigest"],properties:{importerId:ar,preimageDigest:X,desiredDigest:X}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{topology:!1,preservedDependencies:!1,preservedImporterDigests:!1}}},{if:{properties:{schemaVersion:{const:2}},required:["schemaVersion"]},then:{required:["topology","preservedDependencies","preservedImporterDigests"]}}]},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","kind","ownership","disposition"],properties:{path:ar,kind:{enum:["create","replace","merge","remove"]},ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:X,baseDigest:X,regionId:{type:"string",pattern:H},disposition:{enum:["ready","noop","conflict"]},conflictCode:{enum:["USER_OWNED","UNEXPECTED_EXISTING","BASE_DIGEST_MISMATCH"]}}}}}},Qb={$id:"https://schemas.dyyto.dev/platform/transaction-journal-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","transactionId","planId","approvedPlanId","projectRootDigest","state","createdAt","updatedAt","operations","journalDigest"],properties:{schemaVersion:{const:1},transactionId:{type:"string",minLength:1,maxLength:128},planId:X,approvedPlanId:X,projectRootDigest:X,state:{enum:["preparing","prepared","applying","applied","recovery-required","recovering","recovered"]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["index","path","kind","before","status"],properties:{index:{type:"integer",minimum:0},path:ar,kind:{enum:["create","replace","merge","remove"]},before:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest","mode","preimageDigest"],properties:{kind:{const:"present"},digest:X,mode:{type:"integer",minimum:0,maximum:511},preimageDigest:X}}]},desiredDigest:X,status:{enum:["pending","applied","restored"]}}}},failure:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",minLength:1,maxLength:128},operationIndex:{type:"integer",minimum:0}}},journalDigest:X}},nr=new wu.Ajv2020({allErrors:!0,strict:!0});nr.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var rc={capabilityRelease:nr.compile(Kb),projectManifest:nr.compile(Yb),projectLock:nr.compile(Hb),evidence:nr.compile(Xb),changePlan:nr.compile(Zb),transactionJournal:nr.compile(Qb)},tc=class extends Error{contract;issues;code="CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function nc(e,t,r){if(!t(r))throw new tc(e,t.errors??[]);return r}var W=e=>nc("projectManifest",rc.projectManifest,e);var xt=e=>nc("changePlan",rc.changePlan,e),vu=e=>nc("transactionJournal",rc.transactionJournal,e);var M=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};async function ei(e){if(e.currentLock!==void 0){let i=await ti({...e,manifest:{schemaVersion:1,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}});return{state:i.plan.state==="conflicted"?"drifted":"adopted",operations:i.plan.operations}}let t=await ic(Lr.resolve(e.projectRoot)),r=[],n=0,a=0;for(let i of e.release.release.assets){let o=await oc(t,i.path);o.exists&&(n+=1),o.digest===i.digest&&(a+=1),r.push({path:i.path,kind:"create",ownership:i.ownership,desiredDigest:i.ownership==="seed-file"&&o.digest?o.digest:i.digest,disposition:o.exists?i.ownership==="seed-file"||o.digest===i.digest?"noop":"conflict":"ready",...o.exists&&o.digest!==i.digest?{conflictCode:"UNEXPECTED_EXISTING"}:{}})}return n===0?{state:"planned",operations:r}:a===e.release.release.assets.length?{state:"applied-unverified",operations:r}:{state:"drifted",operations:r}}async function oc(e,t){let r=Lr.join(e,...t.split("/"));try{let n=await ek(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Blank profile target must be a regular file",t);return{path:t,exists:!0,digest:v(await ac(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function or(e){let t=await ic(Lr.resolve(e.projectRoot)),r=[];for(let n of e.expectedAssets){let a=await oc(t,n.path),i=a.exists&&a.digest===n.digest;if(n.ownership==="managed-region"&&n.regionId!==void 0&&a.exists)try{i=v(Xa(await ac(Lr.join(t,...n.path.split("/")),"utf8"),n.regionId))===n.digest}catch{i=!1}if(!i)throw new M("PROJECT_STATE_INVALID","A managed project asset does not match the approved plan",n.path);r.push({path:n.path,digest:n.digest,...n.ownership===void 0?{}:{ownership:n.ownership},...n.regionId===void 0?{}:{regionId:n.regionId}})}return{assets:r,projectStateDigest:v(E(r))}}async function ti(e){let t=W(e.manifest);if(t.capabilities.filter(l=>l.capabilityId===e.release.release.capabilityId&&l.version===e.release.release.version).length!==1||t.capabilities.length!==1)throw new M("RELEASE_NOT_FOUND","Manifest must select exactly the loaded M3 capability release");let a=(e.currentLock===void 0?void 0:Oe(e.currentLock))?.capabilities.find(l=>l.capabilityId===e.release.release.capabilityId);if(a!==void 0&&(a.version!==e.release.release.version||a.integrity!==e.release.release.integrity))throw new M("CONSUMER_PROFILE_UNSUPPORTED","M3 does not support upgrading a different locked release");let i=await ic(Lr.resolve(e.projectRoot)),o=[],s=[],c=new Map(e.release.contents);for(let l of e.release.release.assets){let p=await oc(i,l.path);if(o.push(p),p.exists&&a===void 0&&l.ownership!=="seed-file")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Blank profile cannot adopt over an existing file without a lock",l.path);let m=l.ownership==="seed-file"&&p.digest?p.digest:l.digest;l.ownership==="seed-file"&&p.exists&&c.set(l.path,await ac(Lr.join(i,...l.path.split("/")))),s.push({path:l.path,kind:"create",ownership:l.ownership,desiredDigest:m})}let d={schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:e.release.release.assets.map(l=>({path:l.path,ownership:l.ownership,desiredDigest:l.digest})),verifiers:e.release.release.verifiers.map(l=>({id:l.id,kind:"command"}))};return{manifest:t,release:e.release,plan:Ne({action:"adopt",capability:d,changes:s,observedAssets:o,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),desiredContents:c}}import{chmod as rk,lstat as si,mkdir as Vr,open as ku,readFile as ci,realpath as nk,rename as ii,rm as sc,unlink as sr}from"node:fs/promises";import{constants as ni}from"node:fs";import{homedir as ak}from"node:os";import J from"node:path";import{randomUUID as Ur}from"node:crypto";function tk(e){let t=e?.code;return typeof t=="string"&&/^[A-Z0-9_]+$/.test(t)?t:"UNKNOWN"}async function He(e){let t=process.hrtime.bigint();try{let r=await e.run();return await Iu(e.context,e.operation,e.bytes??0,t,"succeeded"),r}catch(r){throw await Iu(e.context,e.operation,e.bytes??0,t,"failed",tk(r)),r}}async function Iu(e,t,r,n,a,i){if(e?.sink===void 0)return;let o=process.hrtime.bigint(),s={schemaVersion:1,phase:e.phase,operation:t,pathCategory:e.pathCategory,bytes:r,barrierId:e.barrierId,startedMonotonicNs:n.toString(),completedMonotonicNs:o.toString(),result:a,...i===void 0?{}:{errorCategory:i}},c=Object.freeze({...s,eventId:v(E(s))});try{await e.sink(c)}catch{}}var _u=Symbol("prepared-transaction"),Lt=new Map,ik=5*1024*1024,ok=25*1024*1024,bu=8,oi=class extends Error{};async function ri(e,t,r){try{await e?.onCheckpoint?.(t,r)}catch(n){throw new oi("Simulated prepare crash",{cause:n})}}var C=class extends Error{code;relativePath;operationIndex;constructor(t,r,n,a){super(r),this.code=t,this.relativePath=n,this.operationIndex=a}};function On(e,t){let r=J.join(e,".dyyto"),n=J.join(r,"transactions",t);return{platformDirectory:r,lock:J.join(r,"transaction-lock.json"),transactionDirectory:n,journal:J.join(n,"journal.json"),preimages:J.join(n,"preimages"),quarantine:J.join(n,"quarantine")}}async function bt(e){try{return await si(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Fr(e,t=!1){if(e?.sink!==void 0)return{sink:e.sink,phase:e.phase,pathCategory:t?"directory":e.category,barrierId:e.barrierId}}function at(e,t,r,n){return e===void 0?void 0:{sink:e,phase:t,category:r,barrierId:n}}async function Xe(e,t){let r=await ku(e,ni.O_RDONLY);try{await He({context:Fr(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function Cn(e,t,r=384,n){let a=await ku(e,ni.O_CREAT|ni.O_EXCL|ni.O_WRONLY,r);try{await He({context:Fr(n),operation:"write",bytes:t.byteLength,run:()=>a.writeFile(t)}),await He({context:Fr(n),operation:"file-sync",bytes:t.byteLength,run:()=>a.sync()})}finally{await a.close()}}async function cc(e,t,r){let n=J.dirname(e),a=J.join(n,`.tmp-${Ur()}`),i=Buffer.from(`${JSON.stringify(t,null,2)}
15
+ `);await Cn(a,i,384,r),await He({context:Fr(r),operation:"rename",bytes:i.byteLength,run:()=>ii(a,e)}),await Xe(n,r)}function lc(e){return{...e,journalDigest:v(E(e))}}function sk(e){let t;try{t=vu(e)}catch{throw new C("JOURNAL_CORRUPTED","Transaction journal shape is invalid")}let{journalDigest:r,...n}=t;if(r!==v(E(n)))throw new C("JOURNAL_CORRUPTED","Transaction journal digest or shape is invalid");let a=new Set;for(let[i,o]of t.operations.entries()){if(o.index!==i||a.has(o.path)||o.kind==="create"&&o.before.kind!=="absent"||o.kind!=="create"&&o.before.kind!=="present"||o.kind!=="remove"&&o.desiredDigest===void 0||o.kind==="remove"&&o.desiredDigest!==void 0)throw new C("JOURNAL_CORRUPTED","Transaction journal operation is inconsistent");a.add(o.path)}return t}async function dc(e){try{return sk(JSON.parse(await ci(e,"utf8")))}catch(t){throw t instanceof C?t:new C("JOURNAL_CORRUPTED","Transaction journal cannot be read")}}async function Vt(e,t,r){let{journalDigest:n,...a}=t,i=lc(a);return await cc(e,i,r),i}async function li(e){let t=J.resolve(e),r=J.parse(t);if(t===r.root||t===J.resolve(ak()))throw new C("PROJECT_ROOT_UNSAFE","Project root cannot be the filesystem root or user home");let n=await si(t);if(!n.isDirectory()||n.isSymbolicLink())throw new C("PROJECT_ROOT_UNSAFE","Project root must be a real directory");let a=await nk(t);if(a!==t)throw new C("PROJECT_ROOT_UNSAFE","Project root cannot resolve through a symbolic link");return a}function zr(e,t){if((t===".dyyto"||t.startsWith(".dyyto/"))&&t!==".dyyto/application-config-binding.json"||t.length===0||J.posix.isAbsolute(t)||J.win32.isAbsolute(t)||t.includes("\\")||t.split("/").some(n=>n==="."||n===".."))throw new C("PROJECT_ROOT_UNSAFE","Target path is unsafe",t);let r=J.resolve(e,...t.split("/"));if(!r.startsWith(`${e}${J.sep}`))throw new C("PROJECT_ROOT_UNSAFE","Target escapes project root",t);return r}async function Mr(e,t){let r=t.split("/"),n=e;for(let a of r){n=J.join(n,a);try{if((await si(n)).isSymbolicLink())throw new C("PATH_SYMLINK_UNSAFE","Symbolic links are not valid transaction targets",t)}catch(i){if(i.code==="ENOENT")return;throw i}}}async function qr(e){try{let t=await si(e);if(!t.isFile()||t.isSymbolicLink())throw new C("PATH_SYMLINK_UNSAFE","Transaction target must be a regular file");let r=await ci(e);return{bytes:r,digest:v(r),mode:t.mode&511}}catch(t){if(t.code==="ENOENT")return;throw t}}function ck(e,t,r){xt(e);let{planId:n,...a}=e;if(Qa(a)!==e.planId)throw new C("PLAN_CONTENT_MISMATCH","Plan content does not match planId");if(e.planId!==t)throw new C("PLAN_APPROVAL_MISMATCH","Approval does not match planId");if(e.state!=="reviewable")throw new C("PLAN_PRECONDITION_FAILED","Only reviewable plans can be applied");if(Date.parse(e.expiresAt)<=Date.parse(r))throw new C("PLAN_EXPIRED","Plan has expired")}function lk(e){let t=e.operations.filter(r=>r.disposition==="ready");for(let r of t)if(!((r.ownership==="owned-file"||r.ownership==="seed-file")&&["create","replace","remove"].includes(r.kind)||r.ownership==="managed-region"&&r.kind==="merge"&&r.regionId!==void 0))throw new C("OPERATION_UNSUPPORTED","Operation ownership is not supported",r.path);return t}async function pc(e,t,r){try{await Cn(e,Buffer.from(`${JSON.stringify(t,null,2)}
16
+ `),384,r),await Xe(J.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new C("TRANSACTION_ACTIVE","Another platform transaction is active"):n}}async function ai(e){try{let t=JSON.parse(await ci(e,"utf8"));if(t.schemaVersion!==1||typeof t.transactionId!="string"||typeof t.planId!="string"||typeof t.startedAt!="string"||typeof t.nonce!="string")throw new Error("invalid lock");return t}catch{throw new C("JOURNAL_CORRUPTED","Transaction lock is invalid")}}function dk(e,t,r){return{[_u]:!0,projectRoot:e,plan:t,transactionId:r}}async function pk(e,t){ck(e.plan,e.approvedPlanId,e.now);let r=await li(e.projectRoot),n=lk(e.plan),a=new Set(e.plan.operations.filter(u=>u.kind!=="remove"&&u.disposition!=="conflict").map(u=>u.path));for(let u of e.desiredContents.keys())if(!a.has(u))throw new C("DESIRED_CONTENT_MISMATCH","Desired content is not declared by the plan",u);for(let u of n)if(zr(r,u.path),await Mr(r,u.path),u.kind!=="remove"){let f=e.desiredContents.get(u.path);if(f===void 0||v(f)!==u.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired content digest does not match the plan",u.path)}let i=On(r,e.plan.planId);await Vr(i.platformDirectory,{recursive:!0,mode:448}),await Mr(r,".dyyto");let o=Ur();await pc(i.lock,{schemaVersion:1,transactionId:o,planId:e.plan.planId,startedAt:e.now,nonce:Ur()},at(t?.durabilityTrace,"prepare","lock",`${o}:prepare-lock`));let s=e.limits?.maxFileBytes??ik,c=e.limits?.maxTransactionBytes??ok,d=0,l=[],p=[],m=!1;try{if(await ri(t,"lock-created"),await bt(i.transactionDirectory))throw new C("PLAN_PRECONDITION_FAILED","This plan already has a transaction record");await Vr(i.preimages,{recursive:!0,mode:448}),await Vr(i.quarantine,{recursive:!0,mode:448}),m=!0;for(let[f,g]of n.entries()){let h=zr(r,g.path);await Mr(r,g.path);let w=await qr(h);if(g.kind==="create"){if(w!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target now exists",g.path,f)}else if(w===void 0||w.digest!==g.baseDigest)throw new C("PLAN_PRECONDITION_FAILED","Target no longer matches plan base digest",g.path,f);let _={kind:"absent"};if(w!==void 0){if(d+=w.bytes.byteLength,w.bytes.byteLength>s||d>c)throw new C("PREIMAGE_LIMIT_EXCEEDED","Preimage size limit exceeded",g.path,f);let b=J.join(i.preimages,`${f}.bin`);await Cn(b,w.bytes,384,at(t?.durabilityTrace,"prepare","preimage",`${o}:preimage:${f}`)),p.push(f),await ri(t,"preimage-written-pending-directory-sync",f),_={kind:"present",digest:w.digest,mode:w.mode,preimageDigest:v(w.bytes)}}l.push({index:f,path:g.path,kind:g.kind,before:_,...g.desiredDigest===void 0?{}:{desiredDigest:g.desiredDigest},status:"pending"})}if(p.length>0){await Xe(i.preimages,at(t?.durabilityTrace,"prepare","directory",`${o}:preimages-directory-batch`));for(let f of p)await ri(t,"preimage-persisted",f)}let u=lc({schemaVersion:1,transactionId:o,planId:e.plan.planId,approvedPlanId:e.approvedPlanId,projectRootDigest:v(r),state:"prepared",createdAt:e.now,updatedAt:e.now,operations:l});return await cc(i.journal,u,at(t?.durabilityTrace,"prepare","journal",`${o}:journal-prepared`)),Lt.set(o,{desiredContents:e.desiredContents,journal:u}),await ri(t,"journal-prepared"),dk(r,e.plan,o)}catch(u){if(u instanceof oi)throw Lt.delete(o),new C("RECOVERY_REQUIRED","Prepare was interrupted; recovery is required");try{m&&await sc(i.transactionDirectory,{recursive:!0,force:!0}),await sr(i.lock),await Xe(i.platformDirectory)}catch{throw new C("RECOVERY_REQUIRED","Prepare failed and transaction lock could not be released")}throw u}}async function Br(e){return pk(e)}async function uk(e,t,r,n){return Vt(e.journal,{...t,state:"recovery-required",updatedAt:new Date().toISOString(),failure:{code:"APPLY_INTERRUPTED",...r===void 0?{}:{operationIndex:r}}},at(n,"apply","journal",`${t.transactionId}:recovery-required`))}async function fk(e,t,r,n,a,i){let o=zr(e,n.path);await Mr(e,n.path);let s=await qr(o);if(n.before.kind==="absent"){if(s!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target changed after prepare",n.path,n.index)}else if(s===void 0||s.digest!==n.before.digest)throw new C("PLAN_PRECONDITION_FAILED","Target changed after prepare",n.path,n.index);if(n.kind==="remove"){let p=J.join(t.quarantine,`${n.index}.bin`),m=at(i?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await He({context:Fr(m),operation:"rename",run:()=>ii(o,p)}),await i?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[J.dirname(o),t.quarantine]}let c=a.get(n.path);if(c===void 0||v(c)!==n.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired bytes are missing or changed",n.path,n.index);await Vr(J.dirname(o),{recursive:!0}),await Mr(e,n.path);let d=J.join(J.dirname(o),`.dyyto-${r}-${n.index}.tmp`),l=at(i?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await Cn(d,c,n.before.kind==="present"?n.before.mode&511:420,l),await i?.onCheckpoint?.("temporary-file-synced",n.index),await He({context:Fr(l),operation:"rename",bytes:c.byteLength,run:()=>ii(d,o)}),await i?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[J.dirname(o)]}async function mk(e,t){let r=Lt.get(e.transactionId);if(r===void 0||e[_u]!==!0)throw new C("PLAN_PRECONDITION_FAILED","Prepared transaction is not active");let n=On(e.projectRoot,e.plan.planId),a=await Vt(n.journal,{...r.journal,state:"applying",updatedAt:new Date().toISOString()},at(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applying`));try{await t?.onCheckpoint?.("prepared");let i=new Map;for(let o=0;o<a.operations.length;o+=bu){let s=a.operations.slice(o,o+bu),c=await Promise.allSettled(s.map(l=>fk(e.projectRoot,n,e.transactionId,l,r.desiredContents,t))),d=c.find(l=>l.status==="rejected");if(d?.status==="rejected")throw d.reason;for(let l of c)if(l.status==="fulfilled")for(let p of l.value)i.has(p)||i.set(p,at(t?.durabilityTrace,"apply","directory",`${e.transactionId}:target-directory-batch`))}for(let[o,s]of i)await Xe(o,s);for(let o of a.operations)await t?.onCheckpoint?.("target-renamed",o.index),o.status="applied",await t?.onCheckpoint?.("operation-applied",o.index);a=await Vt(n.journal,{...a,operations:a.operations,updatedAt:new Date().toISOString()},at(t?.durabilityTrace,"apply","journal",`${e.transactionId}:operation-batch`));for(let o of a.operations)await t?.onCheckpoint?.("operation-journaled",o.index);return a=await Vt(n.journal,{...a,state:"applied",updatedAt:new Date().toISOString()},at(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applied`)),await t?.onCheckpoint?.("applied"),await sr(n.lock),await Xe(n.platformDirectory),Lt.delete(e.transactionId),cr(a)}catch(i){throw a=await uk(n,a,i instanceof C?i.operationIndex:void 0,t?.durabilityTrace),Lt.set(e.transactionId,{desiredContents:r.desiredContents,journal:a}),new C("RECOVERY_REQUIRED","Apply was interrupted; recovery is required")}}async function Jr(e){return mk(e)}function cr(e){return{transactionId:e.transactionId,planId:e.planId,state:e.state,operations:e.operations}}async function kt(e){let t=await li(e.projectRoot),r=On(t,e.planId);if(!await bt(r.journal)){if(!await bt(r.lock))return null;let n=await ai(r.lock);return n.planId!==e.planId?null:{transactionId:n.transactionId,planId:n.planId,state:"preparing",operations:[]}}return cr(await dc(r.journal))}async function gk(e,t,r){await Vr(J.dirname(e),{recursive:!0});let n=J.join(J.dirname(e),`.dyyto-recover-${Ur()}.tmp`);await Cn(n,t,r&511),await ii(n,e),await rk(e,r&511),await Xe(J.dirname(e))}async function hk(e){let t=await li(e.projectRoot),r=On(t,e.planId);if(!await bt(r.journal)){if(!await bt(r.lock))throw new C("JOURNAL_CORRUPTED","No transaction record exists");let a=await ai(r.lock);if(a.planId!==e.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another plan");await sc(r.transactionDirectory,{recursive:!0,force:!0}),await Vr(r.transactionDirectory,{recursive:!0,mode:448});let i=lc({schemaVersion:1,transactionId:a.transactionId,planId:a.planId,approvedPlanId:a.planId,projectRootDigest:v(t),state:"recovered",createdAt:a.startedAt,updatedAt:e.now,operations:[]});return await cc(r.journal,i),await sr(r.lock),await Xe(r.platformDirectory),cr(i)}let n=await dc(r.journal);if(n.state==="recovered")return cr(n);if(n.state==="applied"){for(let a of n.operations){let i=await qr(zr(t,a.path));if(!(a.kind==="remove"?i===void 0:i?.digest===a.desiredDigest))throw new C("RECOVERY_CONFLICT","Completed transaction target changed before lock cleanup",a.path,a.index)}if(await bt(r.lock)){let a=await ai(r.lock);if(a.transactionId!==n.transactionId||a.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction");await sr(r.lock),await Xe(r.platformDirectory)}return Lt.delete(n.transactionId),cr(n)}if(n.projectRootDigest!==v(t))throw new C("JOURNAL_CORRUPTED","Journal belongs to a different project root");if(await bt(r.lock)){let a=await ai(r.lock);if(a.transactionId!==n.transactionId||a.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction")}else await pc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Ur()});n=await Vt(r.journal,{...n,state:"recovering",updatedAt:e.now});for(let a of[...n.operations].reverse()){if(a.status==="restored")continue;let i=zr(t,a.path);if(await Mr(t,a.path),a.kind!=="remove"){let s=J.join(J.dirname(i),`.dyyto-${n.transactionId}-${a.index}.tmp`);if(await bt(s)){if((await qr(s))?.digest!==a.desiredDigest)throw new C("RECOVERY_CONFLICT","Transaction temporary file was modified externally",a.path,a.index);await sr(s),await Xe(J.dirname(s))}}let o=await qr(i);if(a.before.kind==="absent"){if(o!==void 0){if(o.digest!==a.desiredDigest)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",a.path,a.index);await sr(i),await Xe(J.dirname(i))}}else if(o?.digest!==a.before.digest){let s=J.join(r.quarantine,`${a.index}.bin`),c=o?.digest===a.desiredDigest,d=a.kind==="remove"&&o===void 0&&await bt(s),l=e.approvedConflicts?.find(m=>m.path===a.path&&m.currentDigest===o?.digest);if(!c&&!d&&!l)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",a.path,a.index);let p=await ci(J.join(r.preimages,`${a.index}.bin`));if(v(p)!==a.before.preimageDigest)throw new C("JOURNAL_CORRUPTED","Preimage digest is invalid",a.path,a.index);await gk(i,p,a.before.mode),d&&await sc(s,{force:!0})}a.status="restored",n=await Vt(r.journal,{...n,operations:n.operations,updatedAt:e.now}),await e.hooks?.onCheckpoint?.("operation-journaled",a.index)}return n=await Vt(r.journal,{...n,state:"recovered",updatedAt:e.now}),await sr(r.lock),await Xe(r.platformDirectory),Lt.delete(n.transactionId),cr(n)}async function Tn(e){return hk(e)}async function uc(e){let t=await li(e.projectRoot),r=On(t,e.planId),n=await dc(r.journal);if(n.state==="recovered")return cr(n);if(n.state!=="applied")throw new C("PLAN_PRECONDITION_FAILED","Only an applied transaction can be rolled back");let a;for(let i of n.operations){let o=await qr(zr(t,i.path)),s=i.kind==="remove"?o===void 0:o?.digest===i.desiredDigest,c=i.before.kind==="absent"?o===void 0:o?.digest===i.before.digest;if(!s&&!c){a=i;break}}if(await pc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Ur()}),n=await Vt(r.journal,{...n,state:"recovery-required",updatedAt:e.now,failure:{code:e.failureCode}}),a!==void 0)throw new C("RECOVERY_CONFLICT","Rollback would overwrite external content",a.path,a.index);return Lt.set(n.transactionId,{desiredContents:new Map,journal:n}),Tn({projectRoot:t,planId:e.planId,now:e.now})}var we=class extends Error{code;constructor(t,r){super(r),this.code=t}},xn=class extends Error{};function Mn(e,t){let r=ye.join(e,".dyyto"),n=ye.join(r,"metadata-transactions",t);return{platformDirectory:r,evidenceDirectory:ye.join(r,"evidence"),lockFile:ye.join(r,"project-lock.json"),transactionLock:ye.join(r,"metadata-lock.json"),transactionDirectory:n,journal:ye.join(n,"journal.json")}}async function Mt(e){try{return await yk(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function _t(e,t,r){return e===void 0?void 0:{sink:e,category:t,barrierId:r}}function fi(e,t=!1){if(e!==void 0)return{sink:e.sink,phase:"metadata",pathCategory:t?"directory":e.category,barrierId:e.barrierId}}async function mi(e,t){let r=await Eu(e,pi.O_RDONLY);try{await He({context:fi(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function gc(e,t,r){let n=await Eu(e,pi.O_CREAT|pi.O_EXCL|pi.O_WRONLY,384);try{await He({context:fi(r),operation:"write",bytes:t.byteLength,run:()=>n.writeFile(t)}),await He({context:fi(r),operation:"file-sync",bytes:t.byteLength,run:()=>n.sync()})}finally{await n.close()}}async function Ln(e,t,r){let n=ye.dirname(e),a=ye.join(n,`.tmp-${mc()}`),i=Buffer.from(`${JSON.stringify(t,null,2)}
17
+ `);await gc(a,i,r),await He({context:fi(r),operation:"rename",bytes:i.byteLength,run:()=>wk(a,e)}),await mi(n,r)}function hc(e){return{...e,journalDigest:v(E(e))}}async function di(e,t,r){let{journalDigest:n,...a}=t,i=hc(a);return await Ln(e,i,r),i}async function Au(e){try{let t=JSON.parse(await Vn(e,"utf8")),{journalDigest:r,...n}=t;if(t.schemaVersion!==1||!Array.isArray(t.evidence)||r!==v(E(n)))throw new Error("invalid journal");return t.evidence.forEach($n),Oe(t.lock),t}catch{throw new we("METADATA_JOURNAL_CORRUPTED","Metadata journal cannot be trusted")}}async function yc(e,t,r){try{await gc(e,Buffer.from(`${JSON.stringify(t,null,2)}
18
+ `),r),await mi(ye.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new we("METADATA_TRANSACTION_ACTIVE","Another metadata transaction is active"):n}}function Ru(e,t){let r={...t,capabilityId:e.capabilityId,capabilityVersion:e.version,capabilityIntegrity:e.integrity};return{...r,evidenceId:v(E(r))}}function Pu(e,t,r){let n=t.map(mu),a=e.verifiers.map(o=>o.id).sort(),i=n.map(o=>o.verifierId).sort();if(a.length!==i.length||a.some((o,s)=>o!==i[s]))throw new we("VERIFICATION_INCOMPLETE","Verification results do not cover the release verifier set");for(let o of n){if(o.commandId!==o.verifierId||o.result!=="passed"||o.exitCode!==0)throw new we("VERIFICATION_FAILED",`Verifier ${o.verifierId} did not pass`);if(o.projectStateDigest!==r)throw new we("PROJECT_STATE_CHANGED","Verification result belongs to a different project state")}return n}async function vk(e,t,r){let n=ye.join(e,`${t.evidenceId}.json`);if(await Mt(n)){let a=$n(JSON.parse(await Vn(n,"utf8")));if(E(a)!==E(t))throw new we("METADATA_JOURNAL_CORRUPTED","Existing evidence content does not match its identity");return}await gc(n,Buffer.from(`${JSON.stringify(t,null,2)}
19
+ `),r),await mi(e,r)}async function Ik(e,t,r,n){if(await Mt(e)){let a=Oe(JSON.parse(await Vn(e,"utf8")));if(E(a)===E(t))return;if(r===void 0||v(E(a))!==r)throw new we("PROJECT_STATE_CHANGED","The project lock changed before metadata commit");await Ln(e,t,n);return}await Ln(e,t,n)}async function ui(e,t){try{await e?.onCheckpoint?.(t)}catch(r){throw new xn("Simulated metadata crash",{cause:r})}}async function wc(e,t,r){let n=Mn(e,t.planId),a=t;try{for(let i of a.evidence)await vk(n.evidenceDirectory,i,_t(r?.durabilityTrace,"evidence",`${a.transactionId}:evidence`));return a=await di(n.journal,{...a,state:"evidence-written",updatedAt:new Date().toISOString()},_t(r?.durabilityTrace,"journal",`${a.transactionId}:evidence-written`)),await ui(r,"evidence-written"),await Ik(n.lockFile,a.lock,a.previousLockDigest,_t(r?.durabilityTrace,"lock",`${a.transactionId}:project-lock`)),a=await di(n.journal,{...a,state:"lock-written",updatedAt:new Date().toISOString()},_t(r?.durabilityTrace,"journal",`${a.transactionId}:lock-written`)),await ui(r,"lock-written"),a=await di(n.journal,{...a,state:"committed",updatedAt:new Date().toISOString()},_t(r?.durabilityTrace,"journal",`${a.transactionId}:committed`)),await ui(r,"committed"),await fc(n.transactionLock),await mi(n.platformDirectory,_t(r?.durabilityTrace,"directory",`${a.transactionId}:unlock`)),a.lock}catch(i){if(i instanceof xn)throw new we("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted");try{await di(n.journal,{...a,state:"recovery-required",updatedAt:new Date().toISOString()},_t(r?.durabilityTrace,"journal",`${a.transactionId}:recovery-required`))}catch{}throw i}}async function bk(e){let t=await lr(ye.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await lr(ye.resolve(e.transactionRoot));if((await kt({projectRoot:r,planId:e.plan.planId}))?.state!=="applied")throw new we("APPLY_NOT_COMPLETED","The filesystem transaction is not applied");let a;try{a=await or({projectRoot:t,expectedAssets:e.expectedAssets??e.release.assets.map(f=>({path:f.path,digest:f.digest}))})}catch{throw new we("PROJECT_STATE_CHANGED","Managed project assets no longer match the approved plan")}let o=Pu(e.release,e.verificationResults,a.projectStateDigest).map(f=>Ru(e.release,f)),s={capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,consumerProfile:e.release.consumerProfile,appliedPlanId:e.plan.planId,projectStateDigest:a.projectStateDigest,assets:a.assets,evidenceIds:o.map(f=>f.evidenceId).sort(),committedAt:e.committedAt,...e.plan.packageAdoption===void 0?{}:{packageAdoption:{...e.plan.packageAdoption.sourceChannel===void 0?{}:{sourceChannel:e.plan.packageAdoption.sourceChannel},registryRevisions:e.plan.packageAdoption.registryRevisions.map(f=>({...f})),sources:e.plan.packageAdoption.sources.map(f=>({...f})),packageJsonDigest:e.plan.packageAdoption.desiredPackageJsonDigest,lockfileDigest:e.plan.packageAdoption.desiredLockfileDigest}}},c=e.previousLock?.capabilities??[],d=e.previousLock!==void 0&&e.plan.action==="adopt"?[...c.filter(f=>f.capabilityId!==e.release.capabilityId),s].sort((f,g)=>f.capabilityId.localeCompare(g.capabilityId)):e.previousLock!==void 0&&e.plan.action==="upgrade"?[...c.filter(f=>f.capabilityId!==e.release.capabilityId),s].sort((f,g)=>f.capabilityId.localeCompare(g.capabilityId)):[s],l={schemaVersion:d.some(f=>f.packageAdoption!==void 0)?2:1,capabilities:d};Oe(l);let p=Mn(t,e.plan.planId);if(await Gr(p.platformDirectory,{recursive:!0,mode:448}),await Gr(p.evidenceDirectory,{recursive:!0,mode:448}),await Mt(p.lockFile)&&e.previousLock===void 0){let f=Oe(JSON.parse(await Vn(p.lockFile,"utf8")));if(E(f)===E(l))return f;throw new we("PROJECT_STATE_CHANGED","An incompatible project lock already exists")}let m=mc();if(await yc(p.transactionLock,{planId:e.plan.planId,transactionId:m,createdAt:e.committedAt},_t(e.hooks?.durabilityTrace,"lock",`${m}:metadata-lock`)),await Mt(p.transactionDirectory))throw await fc(p.transactionLock),new we("METADATA_TRANSACTION_ACTIVE","This plan already has a metadata transaction");await Gr(p.transactionDirectory,{recursive:!0,mode:448});let u=hc({schemaVersion:1,planId:e.plan.planId,transactionId:m,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:o,lock:l,...e.previousLock===void 0?{}:{previousLockDigest:v(E(Oe(e.previousLock)))}});await Ln(p.journal,u,_t(e.hooks?.durabilityTrace,"journal",`${m}:prepared`));try{await ui(e.hooks,"journal-prepared")}catch(f){throw f instanceof xn?new we("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted"):f}return wc(t,u,e.hooks)}async function vc(e){return bk(e)}async function Ic(e){let t=await lr(ye.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await lr(ye.resolve(e.transactionRoot));if((await kt({projectRoot:r,planId:e.plan.planId}))?.state!=="applied")throw new we("APPLY_NOT_COMPLETED","The filesystem transaction is not applied");let a=e.previousLock.capabilities.find(h=>h.capabilityId===e.release.capabilityId&&h.version===e.release.version);if(a===void 0)throw new we("PROJECT_STATE_CHANGED","The removed capability is not present in the project lock");let i=e.previousLock.capabilities.filter(h=>h!==a),o=e.plan.packageAdoption?.schemaVersion===2&&e.plan.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${e.plan.packageAdoption.topology.unitRelativeRoot}/`:"",s=new Map(e.plan.operations.flatMap(h=>h.desiredDigest===void 0||!h.path.startsWith(o)?[]:[[h.path.slice(o.length),h.desiredDigest]])),c=e.expectedAssets??i.flatMap(h=>h.assets).map(h=>({...h,digest:s.get(h.path)??h.digest})),d=await or({projectRoot:t,expectedAssets:c}),p=Pu(e.release,e.verificationResults,d.projectStateDigest).map(h=>Ru(e.release,h)),m={schemaVersion:i.some(h=>h.packageAdoption!==void 0)?2:1,capabilities:i};Oe(m);let u=Mn(t,e.plan.planId);await Gr(u.platformDirectory,{recursive:!0,mode:448}),await Gr(u.evidenceDirectory,{recursive:!0,mode:448});let f=mc();await yc(u.transactionLock,{planId:e.plan.planId,transactionId:f,createdAt:e.committedAt}),await Gr(u.transactionDirectory,{recursive:!1,mode:448});let g=hc({schemaVersion:1,planId:e.plan.planId,transactionId:f,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:p,lock:m,previousLockDigest:v(E(Oe(e.previousLock)))});return await Ln(u.journal,g),wc(t,g)}async function bc(e){let t=await lr(ye.resolve(e.projectRoot)),r=Mn(t,e.planId),n=await Au(r.journal);return n.state==="committed"?(await Mt(r.transactionLock)&&await fc(r.transactionLock),n.lock):(await Mt(r.transactionLock)||await yc(r.transactionLock,{planId:n.planId,transactionId:n.transactionId,createdAt:n.createdAt}),wc(t,n))}async function kc(e){let t=await lr(ye.resolve(e.projectRoot)),r=Mn(t,e.planId);if(!await Mt(r.journal))return null;let n=await Au(r.journal);return{planId:n.planId,state:n.state}}async function De(e){let t=await lr(ye.resolve(e)),r=ye.join(t,".dyyto","project-lock.json");return await Mt(r)?Oe(JSON.parse(await Vn(r,"utf8"))):null}import{lstat as Su,readFile as Nu,realpath as Du}from"node:fs/promises";import qt from"node:path";var it=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};function ju(e){return v(E(e))}async function kk(e,t){let r=qt.join(e,"assets",...t.split("/"));try{return await Su(r),r}catch(n){if(n.code!=="ENOENT"||qt.posix.basename(t)!==".gitignore")throw n}return qt.join(e,"assets",...qt.posix.dirname(t).split("/").filter(n=>n!=="."),"__dyyto_dotfiles__","gitignore")}async function me(e){let t=await Du(qt.resolve(e)),r;try{r=fu(JSON.parse(await Nu(qt.join(t,"release.json"),"utf8")))}catch(c){throw c instanceof it?c:new it("RELEASE_INVALID","Capability release metadata is invalid")}let{integrity:n,...a}=r;if(ju(a)!==n)throw new it("RELEASE_INTEGRITY_MISMATCH","Capability release integrity does not match metadata");let i=new Map,o=new Set,s="";for(let c of r.assets){try{Za(c.path)}catch{throw new it("RELEASE_ASSET_INVALID","Release asset path is unsafe",c.path)}if((c.path===".dyyto"||c.path.startsWith(".dyyto/"))&&c.path!==".dyyto/application-config-binding.json"||o.has(c.path)||c.path.localeCompare(s)<0)throw new it("RELEASE_ASSET_INVALID","Release assets must be unique, sorted and outside reserved .dyyto paths",c.path);o.add(c.path),s=c.path;let d=await kk(t,c.path),l=await Du(d),p=qt.join(t,"assets");if(!l.startsWith(`${p}${qt.sep}`))throw new it("RELEASE_ASSET_INVALID","Release asset escapes its bundle",c.path);let m=await Su(d);if(!m.isFile()||m.isSymbolicLink())throw new it("RELEASE_ASSET_INVALID","Release asset must be a regular file",c.path);let u=await Nu(d);if(v(u)!==c.digest)throw new it("RELEASE_ASSET_INTEGRITY_MISMATCH","Release asset digest does not match metadata",c.path);i.set(c.path,u)}if(r.exit.ownedAssets.length!==r.assets.length||r.exit.ownedAssets.some((c,d)=>c!==r.assets[d]?.path))throw new it("RELEASE_INVALID","Exit owned assets must exactly match release assets");return{release:r,contents:i}}import{link as _k,open as Ou,lstat as gt,mkdir as Cu,readFile as _c,readdir as gi,realpath as ht,rm as Ek,unlink as Ak}from"node:fs/promises";import ne from"node:path";var ge=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="ProjectBootstrapError"}},Rk={schemaVersion:1,profile:{id:"workspace-root",parameters:{}},capabilities:[{capabilityId:"foundation.workspace-root",version:"1.2.0"}]};function Pk(){return new TextEncoder().encode(`${JSON.stringify(Rk,null,2)}
20
+ `)}async function Nk(e,t=!1){let r=ne.resolve(e),n=await gt(r).catch(()=>null);if(n===null||!n.isDirectory()||n.isSymbolicLink())throw new ge("TARGET_INVALID","Workspace target must be a real existing directory");let a=await ht(r);for(let i of t?["AGENTS.md","README.md"]:["package.json","pnpm-workspace.yaml"]){let o=await gt(ne.join(a,i)).catch(()=>null);if(o===null||!o.isFile()||o.isSymbolicLink())throw new ge("WORKSPACE_MARKER_MISSING",`Existing workspace must contain a real ${i}`)}if(await gt(ne.join(a,"project-capabilities.json")).catch(()=>null))throw new ge("MANIFEST_EXISTS","Project manifest already exists");return a}async function Dk(e,t){let r=ne.resolve(e),n=await gt(r).catch(()=>null);if(n===null||!n.isDirectory()||n.isSymbolicLink())throw new ge("TARGET_INVALID","Project target must be a real existing directory");let a=await ht(r);for(let i of t){let o=await gt(ne.join(a,i)).catch(()=>null);if(o===null||!o.isFile()||o.isSymbolicLink())throw new ge("WORKSPACE_MARKER_MISSING",`Existing project must contain a real ${i}`)}if(await gt(ne.join(a,"project-capabilities.json")).catch(()=>null))throw new ge("MANIFEST_EXISTS","Project manifest already exists");return a}async function Tu(e){let t=await Dk(e.projectRoot,e.requiredMarkers??["package.json"]),r=W(e.manifest),n=new TextEncoder().encode(`${JSON.stringify(r,null,2)}
21
+ `),a=r.capabilities[0],i=Ne({action:"adopt",capability:{schemaVersion:1,capabilityId:a.capabilityId,version:a.version,integrity:e.capabilityIntegrity,assets:[],verifiers:[]},changes:[{path:"project-capabilities.json",kind:"create",ownership:"owned-file",desiredDigest:v(n)}],observedAssets:[{path:"project-capabilities.json",exists:!1}],generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{projectRoot:t,plan:i,desiredContents:new Map([["project-capabilities.json",n]])}}async function xu(e){let t=await Nk(e.projectRoot,e.documentationOnly===!0),r=Pk(),n=Ne({action:"adopt",capability:{schemaVersion:1,capabilityId:"foundation.workspace-root",version:"1.2.0",integrity:e.capabilityIntegrity,assets:[],verifiers:[]},changes:[{path:"project-capabilities.json",kind:"create",ownership:"owned-file",desiredDigest:v(r)}],observedAssets:[{path:"project-capabilities.json",exists:!1}],generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{projectRoot:t,plan:n,desiredContents:new Map([["project-capabilities.json",r]])}}async function Sk(e){let t=await Ou(e,"r");try{await t.sync()}finally{await t.close()}}async function Lu(e,t){let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`,n=await Ou(r,"wx",384);try{await n.writeFile(t,"utf8"),await n.sync()}finally{await n.close()}try{await _k(r,e),await Ak(r),await Sk(ne.dirname(e))}catch(a){throw await Ek(r,{force:!0}),a}}async function jk(e){let t=ne.resolve(e);try{let r=await gt(t);if(!r.isDirectory()||r.isSymbolicLink())throw new ge("TARGET_INVALID","Project target must be a real directory");if((await gi(t)).length!==0)throw new ge("TARGET_NOT_EMPTY","Project target must be empty")}catch(r){if(r.code!=="ENOENT")throw r;let n=ne.dirname(t),a=await gt(n).catch(()=>null);if(a===null||!a.isDirectory()||a.isSymbolicLink())throw new ge("TARGET_INVALID","Project target parent must be a real directory");await Cu(t)}return ht(t)}async function hi(e){let t=W(e.manifest),r=await jk(e.projectRoot),n=ne.join(r,"project-capabilities.json");try{await Lu(n,`${JSON.stringify(t,null,2)}
22
+ `)}catch(a){throw a.code==="EEXIST"?new ge("MANIFEST_EXISTS","Project manifest already exists"):a}return{projectRoot:r,manifest:t}}function qn(e){let{planId:t,...r}=e;if(Qa(r)!==e.planId)throw new ge("PLAN_INTEGRITY_INVALID","Saved plan integrity is invalid")}async function $k(e){let t=await ht(ne.resolve(e.projectRoot)),r=xt(e.plan);qn(r);let n=ne.join(t,".dyyto","plans");await Cu(n,{recursive:!0,mode:448});let a=ne.join(n,`${r.planId}.json`);try{await Lu(a,`${E(r)}
23
+ `)}catch(i){if(i.code!=="EEXIST")throw i;let o=xt(JSON.parse(await _c(a,"utf8")));if(qn(o),E(o)!==E(r))throw new ge("PLAN_INTEGRITY_INVALID","Plan ID content mismatch")}return a}function $u(e){return E({action:e.action,state:e.state,capability:e.capability,operations:e.operations,packageAdoption:e.packageAdoption})}async function dr(e){let t=await ht(ne.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await ht(ne.resolve(e.transactionRoot)),n=xt(e.plan);qn(n);let a=ne.join(t,".dyyto","plans"),i=await gi(a).catch(s=>{if(s.code==="ENOENT")return[];throw s}),o=[];for(let s of i.filter(c=>c.endsWith(".json")).sort()){let c=xt(JSON.parse(await _c(ne.join(a,s),"utf8")));qn(c),!await gt(ne.join(r,".dyyto","transactions",c.planId)).then(()=>!0).catch(l=>l.code==="ENOENT"?!1:Promise.reject(l))&&Date.parse(c.expiresAt)>Date.parse(e.now)&&$u(c)===$u(n)&&o.push(c)}return o.sort((s,c)=>s.generatedAt.localeCompare(c.generatedAt)),o[0]!==void 0?o[0]:(await $k({projectRoot:t,plan:n}),n)}async function Un(e){let t=await ht(ne.resolve(e.projectRoot)),r=ne.join(t,".dyyto","plans",`${e.planId}.json`);try{let n=xt(JSON.parse(await _c(r,"utf8")));if(qn(n),n.planId!==e.planId)throw new ge("PLAN_INTEGRITY_INVALID","Saved plan identity mismatch");return n}catch(n){throw n.code==="ENOENT"?new ge("PLAN_NOT_FOUND","Saved plan was not found"):n}}async function yi(e,t=[],r,n=[]){let a=await ht(ne.resolve(e)),i=r===void 0?a:await ht(ne.resolve(r)),o=ne.join(a,".dyyto","plans"),s=await gi(o).catch(l=>{if(l.code==="ENOENT")return[];throw l}),c=[];for(let l of s.filter(p=>p.endsWith(".json")).sort()){let p=l.slice(0,-5),m=await Un({projectRoot:a,planId:p}),u=await kt({projectRoot:i,planId:p}),f=await gt(ne.join(a,".dyyto","metadata-transactions",p)).then(()=>!0).catch(g=>g.code==="ENOENT"?!1:Promise.reject(g));u?.state==="applied"&&!f&&!t.includes(m.planId)&&(!n.includes(m.capability.capabilityId)||m.action==="upgrade"||m.action==="remove"||m.action==="adopt"&&m.operations.every(g=>g.disposition==="noop"))&&c.push(m)}let d=Ok(c);if(d===void 0)throw new ge("PLAN_NOT_FOUND",c.length===0?"No applied plan is available for verification":"More than one applied plan requires inspection before verification");return d}function Ok(e){if(e.length===1)return e[0];if(e.length===0)return;let t=e[0]?.capability.capabilityId;if(!(t===void 0||e.some(r=>r.capability.capabilityId!==t)))return[...e].sort((r,n)=>r.generatedAt.localeCompare(n.generatedAt)).at(-1)}async function Ec(e){let t=await ht(ne.resolve(e)),r=ne.join(t,".dyyto","plans"),n=await gi(r).catch(i=>{if(i.code==="ENOENT")return[];throw i}),a=[];for(let i of n.filter(o=>o.endsWith(".json")).sort())a.push(await Un({projectRoot:t,planId:i.slice(0,-5)}));return a}import{lstat as Vu,readFile as Ck,readdir as IP,realpath as Tk}from"node:fs/promises";import Me from"node:path";import{homedir as Mu}from"node:os";var yt=class extends Error{code;constructor(t){super(t),this.code=t,this.name="WorkspaceTopologyError"}};async function xk(e){let t=Me.resolve(e),r=await Vu(t).catch(()=>null);if(!r?.isDirectory()||r.isSymbolicLink()||t===Me.parse(t).root||t===Me.resolve(Mu()))throw new yt("WORKSPACE_PATH_UNSAFE");let n=await Tk(t);if(n!==t)throw new yt("WORKSPACE_PATH_UNSAFE");return n}async function Fn(e){let t=await Vu(e).catch(()=>null);if(t!==null){if(!t.isFile()||t.isSymbolicLink())throw new yt("WORKSPACE_PATH_UNSAFE");return Ck(e)}}function Lk(e){let t=e.split(/\r?\n/u),r=[],n=!1;for(let a of t){if(/^packages:\s*(?:#.*)?$/u.test(a)){n=!0;continue}if(!n)continue;let i=/^\s+-\s+["']?([^"'#]+?)["']?\s*(?:#.*)?$/u.exec(a);if(i){r.push(i[1].trim().replace(/^\.\//u,"").replace(/\/$/u,""));continue}if(a.trim()&&!/^\s/u.test(a))break}if(r.length===0)throw new yt("WORKSPACE_MANIFEST_INVALID");return r}function Vk(e,t){if(e.includes("**")){let r=e.split("**",1)[0].replace(/\/$/u,"");return t===r||t.startsWith(`${r}/`)}if(e.endsWith("/*")){let r=e.slice(0,-2);return t.startsWith(`${r}/`)&&!t.slice(r.length+1).includes("/")}return e===t}async function Wr(e){let t=await xk(e);if(await Fn(Me.join(t,"pnpm-lock.yaml")))return Object.freeze({schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"});if(await Fn(Me.join(t,"pnpm-workspace.yaml")))throw new yt("WORKSPACE_NESTED_UNSUPPORTED");let r=Me.dirname(t),n;for(;r!==Me.parse(r).root&&r!==Me.resolve(Mu());){let i=await Fn(Me.join(r,"pnpm-workspace.yaml"));if(i){if(n)throw new yt("WORKSPACE_NESTED_UNSUPPORTED");n={root:r,manifest:i};break}r=Me.dirname(r)}if(!n||!await Fn(Me.join(n.root,"pnpm-lock.yaml"))||!await Fn(Me.join(n.root,"project-capabilities.json")))throw new yt("WORKSPACE_OWNER_MISSING");let a=Me.relative(n.root,t).split(Me.sep).join("/");if(!a||a.startsWith("../")||Lk(n.manifest.toString("utf8")).filter(i=>Vk(i,a)).length!==1)throw new yt("WORKSPACE_UNIT_NOT_DECLARED");return Object.freeze({schemaVersion:1,mode:"pnpm-shared-lockfile",transactionRoot:n.root,unitRoot:t,unitRelativeRoot:a,unitImporterId:a,workspaceManifestPath:"pnpm-workspace.yaml",workspaceManifestDigest:v(n.manifest),lockfilePath:"pnpm-lock.yaml"})}var qu=new Set(["preparing","prepared","applying","recovery-required","recovering"]);async function Ac(e){let t=await Ec(e);for(let r of t){let n=await kt({projectRoot:e,planId:r.planId});if(n!==null&&qu.has(n.state))return{required:!0,kind:"filesystem",planId:r.planId,state:n.state}}for(let r of t){let n=await kc({projectRoot:e,planId:r.planId});if(n!==null&&n.state!=="committed")return{required:!0,kind:"metadata",planId:r.planId,state:n.state}}return{required:!1}}async function Mk(e){let t=await Ac(e.projectRoot);if(!t.required)return{kind:"none",state:"not-required"};if(t.kind==="filesystem"){let r=await Tn({projectRoot:e.projectRoot,planId:t.planId,now:e.now});return{kind:"filesystem",planId:t.planId,state:r.state}}return await bc({projectRoot:e.projectRoot,planId:t.planId}),{kind:"metadata",planId:t.planId,state:"committed"}}async function Uu(e){let t=await Mk(e);if(t.kind!=="none")return t;let r=await Wr(e.projectRoot).catch(()=>{});if(r?.mode!=="pnpm-shared-lockfile")return t;let n=new Set((await Ec(e.projectRoot)).map(c=>c.planId)),a=await import("node:fs/promises").then(({readFile:c})=>c(`${r.transactionRoot}/.dyyto/transaction-lock.json`,"utf8")).catch(c=>c.code==="ENOENT"?void 0:Promise.reject(c));if(!a)return t;let i;try{let c=JSON.parse(a);if(typeof c.planId!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.planId)||!n.has(c.planId))return t;i=c.planId}catch{return t}let o=await kt({projectRoot:r.transactionRoot,planId:i});if(!o||!qu.has(o.state))return t;let s=await Tn({projectRoot:r.transactionRoot,planId:i,now:e.now});return{kind:"filesystem",planId:i,state:s.state}}import{lstat as qk,readFile as Rc,realpath as Fu}from"node:fs/promises";import zn from"node:path";var Uk=new Set(["MIT","Apache-2.0","UNLICENSED"]),Fk=new Set(["public","restricted","private"]),zk=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Bk=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Jk(e){let t;try{t=new URL(e)}catch{throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL")}if(t.protocol!=="https:"||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname==="/"||t.pathname.includes(".."))throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL");t.pathname=t.pathname.replace(/\/$/,"").replace(/\.git$/,"");let r=t.href.replace(/\/$/,"");if(r!==e)throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository URL must already be canonical");return r}function pr(e){if(e.profile?.id!=="workspace-node-application"&&e.profile?.id!=="workspace-web-application"&&e.profile?.id!=="workspace-expo-application"&&e.profile?.id!=="nextjs-full-stack-application")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Manifest must select a workspace application profile");let t=Object.keys(e.profile.parameters),r=e.profile.parameters.name;if(t.length!==1||t[0]!=="name"||r===void 0||r.length>128||!/^[a-z0-9][a-z0-9._-]*$/.test(r))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Application parameters must contain one valid lowercase name");return{name:r}}function Ut(e,t="standalone-npm-package"){if(e.profile?.id!==t)throw new M("CONSUMER_PROFILE_UNSUPPORTED",`Manifest must select ${t} profile`);let r=e.profile.parameters,n=Object.keys(r).sort(),a=e.capabilities.find(m=>m.capabilityId===`foundation.${t}`)?.version,i=a==="1.1.0"||a==="1.2.0"||t==="react-component-library",o=i?["license","name","publishAccess","repository","version"]:["license","name","publishAccess","version"];if(n.length!==o.length||n.some((m,u)=>m!==o[u]))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Standalone npm profile parameters must be exact");let{name:s,version:c,license:d,publishAccess:l,repository:p}=r;if(s===void 0||s.length>214||!zk.test(s))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package name must be a valid lowercase name");if(c===void 0||!Bk.test(c))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package version must be a stable SemVer");if(d===void 0||!Uk.has(d))throw new M("CONSUMER_PROFILE_UNSUPPORTED","license must be MIT, Apache-2.0, or UNLICENSED");if(l===void 0||!Fk.has(l))throw new M("CONSUMER_PROFILE_UNSUPPORTED","publish access must be public, restricted, or private");if(l==="restricted"&&!s.startsWith("@"))throw new M("CONSUMER_PROFILE_UNSUPPORTED","restricted access requires a scoped package name");return{name:s,version:c,license:d,publishAccess:l,...i?{repository:Jk(p)}:{}}}function Pc(e){let t={name:e.name,version:e.version,...e.publishAccess==="private"?{private:!0}:{},license:e.license,...e.repository===void 0?{}:{repository:{type:"git",url:e.repository}},type:"module",sideEffects:!1,main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},files:["dist"],engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run",check:"corepack pnpm typecheck && corepack pnpm test",prepack:"corepack pnpm check && corepack pnpm build"},...e.publishAccess==="private"?{}:{publishConfig:{access:e.publishAccess}},devDependencies:{"@types/node":"24.10.13",typescript:"6.0.3",vitest:"4.1.10"}};return Buffer.from(`${JSON.stringify(t,null,2)}
23
24
  `)}function Nc(e){return Buffer.from(`${JSON.stringify({name:e.name,version:e.version,...e.publishAccess==="private"?{private:!0}:{},license:e.license,repository:{type:"git",url:e.repository},type:"module",sideEffects:["**/*.css"],files:["dist"],main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./style.css":"./dist/style.css"},engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"vite build && tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run","verify:bundle":"vite build && tsc -p tsconfig.build.json && node tooling/verify-bundle.mjs",check:"corepack pnpm typecheck && corepack pnpm test && corepack pnpm verify:bundle",prepack:"corepack pnpm check"},peerDependencies:{react:">=19.0.0 <20","react-dom":">=19.0.0 <20"},devDependencies:{"@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",jsdom:"30.0.1",react:"19.2.8","react-dom":"19.2.8",typescript:"6.0.3",vite:"8.2.1",vitest:"4.1.10"},...e.publishAccess==="private"?{}:{publishConfig:{access:e.publishAccess}}},null,2)}
24
- `)}function Bk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run",check:"pnpm typecheck && pnpm test && pnpm build",start:"node dist/index.js"},devDependencies:{"@types/node":"24.10.13",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
25
- `)}function Jk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"vite",build:"tsc -b && vite build",preview:"vite preview",typecheck:"tsc -b --pretty false",test:"vitest run",check:"pnpm typecheck && pnpm test && pnpm build"},dependencies:{react:"19.2.8","react-dom":"19.2.8"},devDependencies:{"@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",jsdom:"30.0.1",typescript:"6.0.3",vite:"8.2.1",vitest:"4.1.10"}},null,2)}
26
- `)}function Gk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"next dev",build:"next build",start:"node .artifacts/standalone/server.js",typecheck:"tsc --noEmit",lint:"eslint .","test:unit":"vitest run","test:e2e":"playwright test",test:"pnpm test:unit && pnpm test:e2e",package:"pnpm build && node tooling/package-standalone.mjs",check:"pnpm lint && pnpm typecheck && pnpm test:unit && pnpm build"},dependencies:{next:"16.2.11",react:"19.2.8","react-dom":"19.2.8","server-only":"0.0.1"},devDependencies:{"@playwright/test":"1.62.1","@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",eslint:"9.39.5","eslint-config-next":"16.2.11",jsdom:"30.0.1",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
27
- `)}function Wk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,main:"expo-router/entry",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"expo start",android:"expo start --android",ios:"expo start --ios",web:"expo start --web",build:"expo export --platform web --output-dir dist",package:"corepack pnpm build && node tooling/verify-expo-export.mjs",typecheck:"tsc --noEmit",test:"vitest run",check:"corepack pnpm typecheck && corepack pnpm test && corepack pnpm package"},dependencies:{expo:"~57.0.15","expo-router":"~57.0.15","expo-status-bar":"~57.0.1",react:"19.2.3","react-dom":"19.2.3","react-native":"0.86.2","react-native-safe-area-context":"5.9.1","react-native-screens":"4.27.0","react-native-web":"0.21.2"},devDependencies:{"@types/node":"24.10.13","@types/react":"19.2.14",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
28
- `)}async function Fu(e,t){let r=zn.join(e,...t.split("/"));try{let n=await Vk(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Managed target must be a regular file",t);return{path:t,exists:!0,digest:v(await Rc(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function ur(e,t){let r=K(e.manifest),n=t==="workspace-node-application"||t==="workspace-web-application"||t==="workspace-expo-application"||t==="nextjs-full-stack-application"?t==="workspace-web-application"?Jk(pr(r).name):t==="workspace-expo-application"?Wk(pr(r).name):t==="nextjs-full-stack-application"?Gk(pr(r).name):Bk(pr(r).name):t==="react-component-library"?Nc(qt(r,t)):Pc(qt(r,t));if(r.capabilities.filter(u=>u.capabilityId===e.release.release.capabilityId&&u.version===e.release.release.version).length!==1||e.release.release.consumerProfile!==t)throw new M("RELEASE_NOT_FOUND","Manifest must select exactly the loaded standalone npm release");let o=(e.currentLock===void 0?void 0:$e(e.currentLock))?.capabilities.find(u=>u.capabilityId===e.release.release.capabilityId);if(o!==void 0&&(o.version!==e.release.release.version||o.integrity!==e.release.release.integrity))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Changing locked npm profile parameters or release is not supported");let s=new Map(e.release.contents);s.set("package.json",n);let c=await Uu(zn.resolve(e.projectRoot)),d=[],l=[];for(let u of e.release.release.assets){if(s.get(u.path)===void 0)throw new M("RELEASE_NOT_FOUND","Release asset content is unavailable",u.path);let g=await Fu(c,u.path);if(g.exists&&o===void 0&&e.allowExistingWithoutLock!==!0&&u.ownership!=="seed-file")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Profile cannot adopt over an existing owned file without a lock",u.path);u.ownership==="seed-file"&&g.exists&&s.set(u.path,await Rc(zn.join(c,...u.path.split("/"))));let h=v(s.get(u.path));d.push(g),l.push({path:u.path,kind:"create",ownership:u.ownership,desiredDigest:h})}let p={schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:l.map(u=>({path:u.path,ownership:u.ownership,desiredDigest:u.desiredDigest})),verifiers:e.release.release.verifiers.map(({id:u})=>({id:u,kind:"command"}))},f=Oe({action:"adopt",capability:p,changes:l,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{manifest:r,release:e.release,plan:f,desiredContents:s}}function Bn(e){return ur(e,"standalone-npm-package")}function Jn(e){return ur(e,"react-component-library")}function Kr(e){return ur(e,"nextjs-full-stack-application")}async function Dc(e){let t=K(e.manifest);if(t.profile?.id!=="nextjs-full-stack-application"||e.release.release.consumerProfile!=="nextjs-full-stack-application"||e.release.release.assets.some(u=>u.ownership!=="seed-file"))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Historical adoption requires a seed-only Next.js Profile Release");let r=K({...t,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}),n=await Kr({...e,manifest:r}),a=await Uu(zn.resolve(e.projectRoot)),i="project-capabilities.json",o=await Rc(zn.join(a,i)),s=Buffer.from(`${JSON.stringify(r,null,2)}
29
- `),c=n.plan.operations.map(({disposition:u,conflictCode:m,...g})=>g);c.push({path:i,kind:"replace",ownership:"owned-file",baseDigest:v(o),desiredDigest:v(s)});let d=await Promise.all(c.map(u=>Fu(a,u.path))),l=Oe({action:"adopt",capability:{schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:c.filter(u=>u.path!==i).map(u=>({path:u.path,ownership:u.ownership,desiredDigest:u.desiredDigest})),verifiers:e.release.release.verifiers.map(({id:u})=>({id:u,kind:"command"}))},changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),p=new Map([...n.desiredContents,[i,s]]),f=new Map;for(let u of l.operations)u.disposition==="ready"&&u.kind!=="remove"&&f.set(u.path,p.get(u.path));return{...n,manifest:r,plan:l,desiredContents:f}}function Gn(e){return ur(e,"workspace-npm-package")}function Wn(e){return ur(e,"workspace-node-application")}function Kn(e){return ur(e,"workspace-web-application")}function Yn(e){return ur(e,"workspace-expo-application")}async function zu(e){if(e.currentLock!==void 0){let n=await Bn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Bn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Bu(e){if(e.currentLock!==void 0){let n=await Jn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Jn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Ju(e){if(e.currentLock!==void 0){let n=await Kr(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Kr({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Gu(e){if(e.currentLock!==void 0){let n=await Gn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Gn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Wu(e){if(e.currentLock!==void 0){let n=await Wn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Wn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Ku(e){if(e.currentLock!==void 0){let n=await Kn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Kn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Yu(e){if(e.currentLock!==void 0){let n=await Yn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Yn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}import{lstat as v_,readFile as Oi,realpath as I_}from"node:fs/promises";import Xn from"node:path";var ot=class extends Error{code;constructor(t,r){super(r),this.code=t}},fr=/^sha256:[a-f0-9]{64}$/,Kk=/^sha512-[A-Za-z0-9+/]{86}==$/,Yk=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/,Xu=/^registry\.[a-z0-9][a-z0-9.-]{1,126}$/,Hk=/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/,Hu=/^[a-z][a-z0-9._:-]{2,127}$/;function mr(e,t){let r=Object.keys(e).sort();return r.length===t.length&&r.every((n,a)=>n===[...t].sort()[a])}function Xk(e){if(!mr(e,["registryId","tenantId","origin","scopes","authentication","capabilities","status"])||!Xu.test(e.registryId)||!Hu.test(e.tenantId)||e.scopes.length===0||e.scopes.length>32||e.scopes.some((n,a)=>!/^@[a-z0-9][a-z0-9._-]*$/.test(n)||e.scopes.indexOf(n)!==a)||!mr(e.authentication,e.authentication.credentialRef===void 0?["kind"]:["kind","credentialRef"])||!mr(e.capabilities,["read","write","provenance","staging"])||!["workload-identity","short-lived-token","restricted-token","anonymous-test"].includes(e.authentication.kind)||e.authentication.kind==="anonymous-test"!=(e.authentication.credentialRef===void 0)||e.authentication.credentialRef!==void 0&&!Hu.test(e.authentication.credentialRef))return!1;let t;try{t=new URL(e.origin)}catch{return!1}if(t.username||t.password||t.search||t.hash||!t.pathname.endsWith("/")||t.pathname.includes("..")||/%2f|%5c/iu.test(t.pathname))return!1;let r=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]";return e.authentication.kind==="anonymous-test"&&(!r||t.protocol!=="http:")||e.authentication.kind!=="anonymous-test"&&t.protocol!=="https:"?!1:typeof e.capabilities.read=="boolean"&&typeof e.capabilities.write=="boolean"&&typeof e.capabilities.provenance=="boolean"&&typeof e.capabilities.staging=="boolean"&&(e.status==="enabled"||e.status==="disabled")}function Zk(e){if(!Xk(e))throw new ot("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,scopes:Object.freeze([...e.scopes]),authentication:Object.freeze({...e.authentication}),capabilities:Object.freeze({...e.capabilities}),revision:v(E(t))})}function wi(e){let t=e;if(typeof t!="object"||t===null||!mr(t,["schemaVersion","revision","registryId","tenantId","origin","scopes","authentication","capabilities","status"])||t.schemaVersion!==1||!fr.test(t.revision))throw new ot("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let{schemaVersion:r,revision:n,...a}=t;if(Zk(a).revision!==n)throw new ot("REGISTRY_CONFIG_INVALID","Registry configuration has been modified");return t}function Qk(e,t){let r,n;try{r=new URL(e.origin),n=new URL(t)}catch{return!1}return n.username||n.password||n.search||n.hash||n.pathname!==r.pathname||n.protocol!==r.protocol||n.hostname!==r.hostname?!1:e.authentication.kind==="anonymous-test"||n.port===r.port}function e_(e,t){let r=wi(t);if(!mr(e,["registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||e.registryId!==r.registryId||e.registryConfigRevision!==r.revision||!Qk(r,e.origin)||Number.isNaN(Date.parse(e.resolvedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.resolvedAt))throw new ot("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let n={schemaVersion:1,...e};return Object.freeze({...n,bindingDigest:v(E(n))})}function Zu(e,t){let r=e;if(typeof r!="object"||r===null||!mr(r,["schemaVersion","bindingDigest","registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||r.schemaVersion!==1||!fr.test(r.bindingDigest))throw new ot("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let{schemaVersion:n,bindingDigest:a,...i}=r;if(e_(i,t).bindingDigest!==a)throw new ot("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding has been modified");return r}function t_(e){let t=["registryId","registryConfigRevision","packageName","version","integrity","tarballDigest","access","provenance","sourceDeliveryReceiptId","verifiedAt",...e.verificationIdentityDigest===void 0?[]:["verificationIdentityDigest"]];return mr(e,t)&&Xu.test(e.registryId)&&fr.test(e.registryConfigRevision)&&Hk.test(e.packageName)&&Yk.test(e.version)&&Kk.test(e.integrity)&&fr.test(e.tarballDigest)&&fr.test(e.sourceDeliveryReceiptId)&&!Number.isNaN(Date.parse(e.verifiedAt))&&(e.access==="restricted"||e.access==="private")&&["registry-attested","external-attested","local-readback-verified","development-readback-verified","registry-verified-no-attestation"].includes(e.provenance)&&(e.provenance!=="registry-verified-no-attestation"?e.verificationIdentityDigest!==void 0&&fr.test(e.verificationIdentityDigest):e.verificationIdentityDigest===void 0)}function Qu(e){if(!t_(e))throw new ot("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,receiptId:v(E(t))})}function ef(e){let t=e;if(typeof t!="object"||t===null||t.schemaVersion!==1||!fr.test(t.receiptId))throw new ot("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let{schemaVersion:r,receiptId:n,...a}=t;if(Qu(a).receiptId!==n)throw new ot("PACKAGE_RECEIPT_INVALID","Package delivery receipt has been modified");return t}var De=class extends Error{code;constructor(t){super(t),this.code=t,this.name="ResolutionEvidenceError"}};function jc(e){return v(E(e))}var Sc=/^sha256:[a-f0-9]{64}$/u,r_=/^sha512-[A-Za-z0-9+/]{86}==$/u,n_=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,vi=/^[a-z0-9][a-z0-9._/-]{0,255}$/u,a_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,i_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@[0-9][a-zA-Z0-9.+()_@/-]*$/u;function Ii(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((a,i)=>a===n[i])}function o_(e){return v(E(e))}function s_(e){if(!Ii(e,["schemaVersion","jobId","workerReleaseId","workerStateRevision","requestDigest","pnpmVersion","desiredLockfile","desiredLockDigest","importerFacts","packageFacts","snapshotClosureDigest","networkObservationDigest","cacheObservation","commandDigest","completedAt","expiresAt"])||e.schemaVersion!==1||e.pnpmVersion!=="11.21.0")throw new De("RESOLUTION_EVIDENCE_INVALID");if(![e.jobId,e.workerStateRevision,e.requestDigest,e.desiredLockDigest,e.snapshotClosureDigest,e.networkObservationDigest,e.commandDigest,e.cacheObservation.preimageRevision,e.cacheObservation.desiredRevision,e.cacheObservation.writesDigest].every(a=>Sc.test(a)))throw new De("RESOLUTION_EVIDENCE_INVALID");if(!vi.test(e.workerReleaseId)||!vi.test(e.cacheObservation.namespace)||e.desiredLockfile.byteLength===0||v(e.desiredLockfile)!==e.desiredLockDigest||Number.isNaN(Date.parse(e.completedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.completedAt))throw new De("RESOLUTION_EVIDENCE_INVALID");if(!Ii(e.cacheObservation,["namespace","preimageRevision","desiredRevision","writesDigest"])||e.importerFacts.length===0||e.packageFacts.length===0)throw new De("RESOLUTION_EVIDENCE_INVALID");if(e.importerFacts.some(a=>!Ii(a,["importerId","manifestDigest","preimageDigest","desiredDigest"])||a.importerId!=="."&&!vi.test(a.importerId)||![a.manifestDigest,a.preimageDigest,a.desiredDigest].every(i=>Sc.test(i))))throw new De("RESOLUTION_EVIDENCE_INVALID");if(e.packageFacts.some(a=>!Ii(a,["identity","packageName","version","integrity","registryId","managed","edgesDigest"])||!i_.test(a.identity)||!a_.test(a.packageName)||!vi.test(a.registryId)||!n_.test(a.version)||!r_.test(a.integrity)||typeof a.managed!="boolean"||!Sc.test(a.edgesDigest)))throw new De("RESOLUTION_EVIDENCE_INVALID");if(new Set(e.importerFacts.map(a=>a.importerId)).size!==e.importerFacts.length||new Set(e.packageFacts.map(a=>a.identity)).size!==e.packageFacts.length)throw new De("RESOLUTION_EVIDENCE_INVALID");let{jobId:t,desiredLockfile:r,...n}=e;if(o_(n)!==e.jobId)throw new De("RESOLUTION_EVIDENCE_INVALID")}function $c(e,t){if(s_(e),Date.parse(t.now)>Date.parse(e.expiresAt))throw new De("RESOLUTION_EVIDENCE_EXPIRED");if(e.requestDigest!==t.requestDigest||e.pnpmVersion!==t.pnpmVersion||e.workerReleaseId!==t.workerReleaseId)throw new De("RESOLUTION_EVIDENCE_INVALID");let r=e.importerFacts.find(n=>n.importerId===t.targetImporterId);if(!r||r.manifestDigest!==t.targetManifestDigest)throw new De("RESOLUTION_EVIDENCE_IMPORTER_DRIFT");for(let n of t.preservedImporterDigests){let a=e.importerFacts.find(i=>i.importerId===n.importerId);if(!a||a.preimageDigest!==n.preimageDigest||a.desiredDigest!==n.preimageDigest)throw new De("RESOLUTION_EVIDENCE_IMPORTER_DRIFT")}for(let n of t.managedSources){let a=e.packageFacts.filter(i=>i.managed&&i.packageName===n.packageName);if(a.length!==1||a[0].registryId!==n.registryId||a[0].version!==n.version||a[0].integrity!==n.integrity)throw new De("RESOLUTION_EVIDENCE_SOURCE_MISMATCH")}if(e.packageFacts.filter(n=>n.managed).length!==t.managedSources.length)throw new De("RESOLUTION_EVIDENCE_SOURCE_MISMATCH");return e}var Y=class extends Error{code;constructor(t,r){super(t,r),this.code=t,this.name="PackageAdoptionError"}};function _i(e){let t={sourceChannel:e.sourceChannel,packageJsonPreimageDigest:e.packageJsonPreimageDigest,desiredPackageJsonDigest:e.desiredPackageJsonDigest,lockfilePreimage:{...e.lockfilePreimage},desiredLockfileDigest:e.desiredLockfileDigest,registryRevisions:e.registryRevisions.map(r=>({...r})),endpointBindings:e.endpointBindings.map(({registryId:r,registryConfigRevision:n,bindingDigest:a,expiresAt:i})=>({registryId:r,registryConfigRevision:n,bindingDigest:a,expiresAt:i})),sources:e.sources.map(r=>({...r})),installPolicy:{...e.installPolicy}};if(e.schemaVersion===1)return{schemaVersion:1,...t};if(!e.topology||!e.preservedDependencies||!e.preservedImporterDigests)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");return{schemaVersion:2,...t,topology:{...e.topology},preservedDependencies:e.preservedDependencies.map(r=>({...r})),preservedImporterDigests:e.preservedImporterDigests.map(r=>({...r}))}}var bi=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u,tf=/^(?:workspace:|file:|link:|git(?:\+|:)|https?:|npm:)|[~^*<>=|]/u;function Oc(e){return Array.isArray(e)?`[${e.map(Oc).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Oc(r)}`).join(",")}}`:JSON.stringify(e)}function _t(e){let t;try{t=JSON.parse(Buffer.from(e).toString("utf8"))}catch{throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}if(!t||typeof t!="object"||Array.isArray(t))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");return t}function Ze(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let t=Object.entries(e);if(t.some(([,r])=>typeof r!="string"))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");return Object.fromEntries(t)}function ki(e){for(let t of[Ze(e.dependencies),Ze(e.devDependencies),Ze(e.optionalDependencies)])for(let[r,n]of Object.entries(t))if(r.startsWith("@aipt/")&&(!bi.test(n)||tf.test(n)))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}var c_=["dependencies","devDependencies","optionalDependencies"];function Ei(e,t){let r=[];for(let n of c_)for(let[a,i]of Object.entries(Ze(e[n]))){if(t.has(a)){if(!bi.test(i))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");continue}if(/^(?:file:|link:|git(?:\+|:)|https?:|npm:)/u.test(i))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");r.push({section:n,packageName:a,specifier:i})}return r.sort((n,a)=>`${n.section}:${n.packageName}`.localeCompare(`${a.section}:${a.packageName}`))}function Cc(e){let t=_t(e.packageJson);ki(t);let r=Object.fromEntries(e.release.packageSources.filter(({usage:i})=>i==="runtime").map(({packageName:i,version:o})=>[i,o])),n=Object.fromEntries(e.release.packageSources.filter(({usage:i})=>i==="development").map(({packageName:i,version:o})=>[i,o])),a={...t,...Object.keys(r).length?{dependencies:{...Ze(t.dependencies),...r}}:{},...Object.keys(n).length?{devDependencies:{...Ze(t.devDependencies),...n}}:{}};return Buffer.from(`${JSON.stringify(a,null,2)}
30
- `)}function Hn(e){let t=_t(e.packageJson);Ei(t,new Set(e.release.packageSources.map(a=>a.packageName)));let r=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="runtime").map(({packageName:a,version:i})=>[a,i])),n=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="development").map(({packageName:a,version:i})=>[a,i]));return Buffer.from(`${JSON.stringify({...t,...Object.keys(r).length?{dependencies:{...Ze(t.dependencies),...r}}:{},...Object.keys(n).length?{devDependencies:{...Ze(t.devDependencies),...n}}:{}},null,2)}
31
- `)}function Tc(e){let t=_t(e.packageJson);ki(t);let r=Ze(t.dependencies),n=Ze(t.devDependencies);for(let i of e.remove)delete(i.usage==="runtime"?r:n)[i.packageName];let a={...t};return Object.keys(r).length===0?delete a.dependencies:a.dependencies=r,Object.keys(n).length===0?delete a.devDependencies:a.devDependencies=n,Buffer.from(`${JSON.stringify(a,null,2)}
32
- `)}function xc(e){let t=_t(e.packageJson);Ei(t,new Set(e.remove.map(i=>i.packageName)));let r=Ze(t.dependencies),n=Ze(t.devDependencies);for(let i of e.remove)delete(i.usage==="runtime"?r:n)[i.packageName];let a={...t};return Object.keys(r).length===0?delete a.dependencies:a.dependencies=r,Object.keys(n).length===0?delete a.devDependencies:a.devDependencies=n,Buffer.from(`${JSON.stringify(a,null,2)}
33
- `)}function rf(e){let t=e.currentLock.capabilities.find(p=>p.capabilityId===e.release.capabilityId&&p.version===e.release.version);if(!t?.packageAdoption)throw new Y("PACKAGE_SOURCE_NOT_FOUND");let r=new Set(e.currentLock.capabilities.filter(p=>p!==t).flatMap(p=>p.packageAdoption?.sources.map(f=>f.packageName)??[])),n=t.packageAdoption.sources.filter(p=>!r.has(p.packageName)),a=Tc({packageJson:e.packageJson,remove:n}),i=_t(e.projectManifest),o=Array.isArray(i.capabilities)?i.capabilities:[],s=Buffer.from(`${JSON.stringify({...i,capabilities:o.filter(p=>p.capabilityId!==e.release.capabilityId||p.version!==e.release.version)},null,2)}
34
- `),c=e.endpointBindings.filter(p=>n.some(f=>f.registryId===p.registryId)),d=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(s)},{path:"package.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(a)},{path:"pnpm-lock.yaml",kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:v(e.desiredLockfile)},...t.assets.map(p=>({path:p.path,kind:"remove",ownership:p.ownership??"owned-file",baseDigest:p.digest}))];return{plan:Oe({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(p=>({path:p.path,ownership:p.ownership??"owned-file",desiredDigest:p.digest})),verifiers:e.release.verifiers.map(p=>({id:p.id,kind:"file-digest"}))},changes:d,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:1,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(a),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:v(e.desiredLockfile),registryRevisions:t.packageAdoption.registryRevisions.map(p=>({...p})),endpointBindings:c.map(({registryId:p,registryConfigRevision:f,bindingDigest:u,expiresAt:m})=>({registryId:p,registryConfigRevision:f,bindingDigest:u,expiresAt:m})),sources:n.map(p=>({...p})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}}}),desiredContents:new Map([["project-capabilities.json",s],["package.json",a],["pnpm-lock.yaml",e.desiredLockfile]]),removedSources:n}}function nf(e){let t=e.currentLock.capabilities.find(g=>g.capabilityId===e.release.capabilityId&&g.version===e.release.version);if(!t?.packageAdoption||e.topology.mode!=="pnpm-shared-lockfile")throw new Y("PACKAGE_SOURCE_NOT_FOUND");let r=new Set(e.currentLock.capabilities.filter(g=>g!==t).flatMap(g=>g.packageAdoption?.sources.map(h=>h.packageName)??[])),n=t.packageAdoption.sources.filter(g=>!r.has(g.packageName)),a=xc({packageJson:e.packageJson,remove:n}),i=e.remainingSources.map(({registryId:g,packageName:h,version:w,integrity:_})=>({registryId:g,packageName:h,version:w,integrity:_})),o={mode:e.topology.mode,unitRelativeRoot:e.topology.unitRelativeRoot,unitImporterId:e.topology.unitImporterId,lockfilePath:e.topology.lockfilePath,...e.topology.workspaceManifestPath?{workspaceManifestPath:e.topology.workspaceManifestPath,workspaceManifestDigest:e.topology.workspaceManifestDigest}:{}},s=$c(e.resolutionEvidence,{requestDigest:jc({schemaVersion:1,pnpmVersion:"11.21.0",topology:o,currentLockfileDigest:v(e.currentLockfile),desiredPackageJsonDigest:v(a),sources:i,preservedImporterDigests:e.preservedImporterDigests.map(({importerId:g,preimageDigest:h})=>({importerId:g,preimageDigest:h}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(a),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:g,preimageDigest:h})=>({importerId:g,preimageDigest:h})),managedSources:i,now:e.generatedAt}),c=_t(e.projectManifest),d=Array.isArray(c.capabilities)?c.capabilities:[],l=Buffer.from(`${JSON.stringify({...c,capabilities:d.filter(g=>g.capabilityId!==e.release.capabilityId||g.version!==e.release.version)},null,2)}
35
- `),p=g=>`${e.topology.unitRelativeRoot}/${g}`,f=e.endpointBindings.filter(g=>n.some(h=>h.registryId===g.registryId)),u=[{path:p("project-capabilities.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(l)},{path:p("package.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(a)},{path:e.topology.lockfilePath,kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:s.desiredLockDigest},...t.assets.map(g=>({path:p(g.path),kind:"remove",ownership:g.ownership??"owned-file",baseDigest:g.digest}))];return{plan:Oe({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(g=>({path:g.path,ownership:g.ownership??"owned-file",desiredDigest:g.digest})),verifiers:e.release.verifiers.map(g=>({id:g.id,kind:"file-digest"}))},changes:u,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:2,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(a),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:s.desiredLockDigest,registryRevisions:t.packageAdoption.registryRevisions.map(g=>({...g})),endpointBindings:f.map(({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})=>({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})),sources:n.map(g=>({...g})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1},topology:o,preservedDependencies:Ei(_t(a),new Set(e.remainingSources.map(g=>g.packageName))),preservedImporterDigests:e.preservedImporterDigests.map(g=>({...g}))}}),desiredContents:new Map([[p("project-capabilities.json"),l],[p("package.json"),a],[e.topology.lockfilePath,s.desiredLockfile]]),removedSources:n,transactionRoot:e.transactionRoot}}function Ai(e,t){let r=e.release.availability,n=r.maturity==="available"&&r.visibility==="catalog-consumers"&&r.sourceState==="registry-verified",a=r.maturity==="candidate"&&r.visibility==="maintainers-only"&&r.sourceState==="development-registry";if((t==="production"?!n:!a)||e.release.packageSources.length===0)throw new Y("PACKAGE_SOURCE_NOT_FOUND");let i=_t(e.packageJson),o=e.desiredBasePackageJson??e.packageJson,s=_t(o),c="topology"in e,d=c?Ei(s,new Set(e.release.packageSources.map(y=>y.packageName))):void 0;c||ki(i),c||ki(s);let l=new Map(e.registryConfigs.map(y=>{let k=wi(y);return[k.registryId,k]})),p=new Map(e.endpointBindings.map(y=>{let k=l.get(y.registryId);if(k===void 0)throw new Y("PACKAGE_SOURCE_NOT_FOUND");let S=Zu(y,k);return[S.registryId,S]})),f=new Map(e.receipts.map(y=>{let k=ef(y);return[k.receiptId,k]})),u=new Map(e.inspections.map(y=>[`${y.registryId}:${y.packageName}@${y.version}`,y])),m=new Map(e.release.packageSources.map(y=>[y.packageName,y])),g=c?$c(e.resolutionEvidence,{requestDigest:jc({schemaVersion:1,pnpmVersion:"11.21.0",topology:e.topology,currentLockfileDigest:e.currentLockfile===void 0?null:v(e.currentLockfile),desiredPackageJsonDigest:v(Hn({release:e.release,packageJson:o})),sources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(Hn({release:e.release,packageJson:o})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k})),managedSources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),now:e.generatedAt}):void 0,h=c?{lockfile:g.desiredLockfile,packages:g.packageFacts.filter(y=>y.managed).map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O}))}:e.lockResolution;if(h.lockfile.byteLength===0||h.packages.length!==e.release.packageSources.length)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`managed resolution count ${h.packages.length}/${e.release.packageSources.length}`)});let w=new Map(h.packages.map(y=>[y.packageName,y]));for(let y of e.release.packageSources){let k=l.get(y.registryId),S=p.get(y.registryId),O=f.get(y.deliveryReceiptId),ae=u.get(`${y.registryId}:${y.packageName}@${y.version}`),$=w.get(y.packageName);if(O!==void 0&&(t==="production"&&O.provenance==="development-readback-verified"||t==="development"&&O.provenance!=="development-readback-verified"))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");if(!k||!S||Date.parse(S.expiresAt)<=Date.parse(e.expiresAt)||k.status!=="enabled"||!k.scopes.some(P=>y.packageName.startsWith(`${P}/`))||!O||!ae||!$)throw new Y("PACKAGE_SOURCE_NOT_FOUND");if(O.registryId!==y.registryId||O.registryConfigRevision!==k.revision||O.packageName!==y.packageName||O.version!==y.version||O.integrity!==y.integrity||O.tarballDigest!==y.tarballDigest||ae.integrity!==y.integrity||ae.tarballDigest!==y.tarballDigest||ae.deliveryReceiptId!==y.deliveryReceiptId||$.registryId!==y.registryId||$.version!==y.version||$.integrity!==y.integrity)throw new Y("PACKAGE_SOURCE_INTEGRITY_MISMATCH");if(!bi.test(y.version)||ae.lifecycleScripts.length>0)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");for(let[P,W]of Object.entries(ae.dependencies)){let re=m.get(P);if(P.startsWith("@aipt/")&&(!re||re.version!==W||!bi.test(W)))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`undeclared internal dependency ${y.packageName}->${P}@${W}`)});if(tf.test(W))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}}let _=c?Hn({release:e.release,packageJson:o}):Cc({release:e.release,packageJson:o}),I={schemaVersion:c?2:1,sourceChannel:t,capabilityId:e.release.capabilityId,capabilityVersion:e.release.version,capabilityIntegrity:e.release.integrity,consumerProfile:e.consumerProfile,generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(_),lockfilePreimage:Object.freeze(e.currentLockfile===void 0?{kind:"absent"}:{kind:"present",digest:v(e.currentLockfile)}),desiredLockfileDigest:v(h.lockfile),registryRevisions:Object.freeze([...l.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,revision:k})=>Object.freeze({registryId:y,revision:k})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),endpointBindings:Object.freeze([...p.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})=>Object.freeze({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),sources:Object.freeze(e.release.packageSources.map(y=>Object.freeze({...y}))),installPolicy:Object.freeze({ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}),...c?{topology:Object.freeze({...e.topology}),preservedDependencies:Object.freeze(d.map(y=>Object.freeze({...y}))),preservedImporterDigests:Object.freeze(e.preservedImporterDigests.map(y=>Object.freeze({...y})))}:{}},A=v(Oc(I));return Object.freeze({...I,planId:A,desiredPackageJson:_,desiredLockfile:h.lockfile})}function Ri(e){return Ai(e,"production")}function Pi(e){return Ai(e,"development")}function Ni(e){return Ai(e,"production")}function Di(e){return Ai(e,"development")}function l_(e){let t=e.packageAdoption;if(t===void 0)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let r=t.schemaVersion===2&&t.topology.mode==="pnpm-shared-lockfile"?`${t.topology.unitRelativeRoot}/package.json`:"package.json",n=t.schemaVersion===2?t.topology.lockfilePath:"pnpm-lock.yaml",a=e.operations.filter(({path:l})=>l===r),i=e.operations.filter(({path:l})=>l===n);if(a.length!==1||i.length!==1)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let o=a[0],s=i[0],c=o.kind==="replace"&&o.baseDigest===t.packageJsonPreimageDigest&&o.desiredDigest===t.desiredPackageJsonDigest&&o.disposition==="ready",d=s.kind===(t.lockfilePreimage.kind==="absent"?"create":"replace")&&(t.lockfilePreimage.kind==="absent"?s.baseDigest===void 0:s.baseDigest===t.lockfilePreimage.digest)&&s.desiredDigest===t.desiredLockfileDigest&&s.disposition==="ready";if(!c||!d)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}async function af(e){l_(e.plan);let t=!1;try{await e.packageManager.prepare({projectRoot:e.projectRoot,plan:e.plan});let r=await Br({projectRoot:e.projectRoot,plan:e.plan,approvedPlanId:e.approvedPlanId,desiredContents:e.desiredContents,now:e.now}),n=await Jr(r);return t=!0,await e.packageManager.install({projectRoot:e.projectRoot,plan:e.plan}),await e.packageManager.verify({projectRoot:e.projectRoot,plan:e.plan}),n}catch(r){if(t){await uc({projectRoot:e.projectRoot,planId:e.plan.planId,now:new Date().toISOString(),failureCode:"PACKAGE_INSTALL_FAILED"});try{await e.packageManager.restore({projectRoot:e.projectRoot,plan:e.plan})}catch(n){throw new Y("PACKAGE_INSTALL_RECOVERY_REQUIRED",{cause:n})}}throw r}finally{await e.packageManager.cleanup({projectRoot:e.projectRoot,plan:e.plan})}}var lf=Ir(tr(),1);var df=["workspace-node-application","workspace-web-application","nextjs-full-stack-application"],pf="^[a-z0-9][a-z0-9._-]{0,127}$",Lc="^[A-Z][A-Z0-9_]{0,127}$",of="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)\\.(?:/|$))(?!.*\\\\)(?!.*[\\u0000-\\u001f]).+$",d_={$id:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","kind","application","configDirectory","bindings"],properties:{$schema:{const:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json"},schemaVersion:{const:1},kind:{const:"ApplicationConfigContract"},application:{type:"object",additionalProperties:!1,required:["id","profile"],properties:{id:{type:"string",pattern:pf},profile:{enum:df}}},configDirectory:{type:"object",additionalProperties:!1,required:["rootEnvironmentVariable","relativeDirectory","environmentFile","materializationOwner"],properties:{rootEnvironmentVariable:{const:"IDP_CONFIG_DIR"},relativeDirectory:{type:"string",pattern:"^applications/[a-z0-9][a-z0-9._-]{0,127}$"},environmentFile:{const:".env"},materializationOwner:{const:"external-deployment-control-plane"}}},bindings:{type:"array",maxItems:128,items:{oneOf:[{type:"object",additionalProperties:!1,required:["name","kind","required"],properties:{name:{type:"string",pattern:Lc},kind:{const:"value"},required:{type:"boolean"},default:{type:"string",maxLength:1024}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Lc},kind:{const:"secret-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:of}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Lc},kind:{const:"certificate-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:of}}}]}}}},sf=new lf.Ajv2020({allErrors:!0,strict:!0}).compile(d_),cf=/(?:^|_)(?:PASSWORD|PASSWD|TOKEN|SECRET|PRIVATE_KEY|ACCESS_KEY|API_KEY|DATABASE_URL|CONNECTION_STRING|DSN|AUTHORIZATION|CREDENTIALS?)(?:_|$)/u,p_=/(?:^|_)(?:PRIVATE_KEY|PRIVATE|KEYPAIR|KEYSTORE|PKCS12|P12|PFX|KEY)(?:_|$)/u,qe=class extends Error{code;issues;constructor(t,r,n=[]){super(r),this.code=t,this.issues=n}};function uf(e){let t=K(e),r=t.profile?.id;if(!df.includes(r))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","\u73AF\u5883\u914D\u7F6E\u5951\u7EA6\u53EA\u652F\u6301\u53EF\u90E8\u7F72 Application Profile\u3002");let n=t.profile?.parameters??{},a=n.name;if(Object.keys(n).length!==1||typeof a!="string"||!new RegExp(pf,"u").test(a))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","Application Manifest \u5FC5\u987B\u5305\u542B\u552F\u4E00\u4E14\u5408\u6CD5\u7684 name \u53C2\u6570\u3002");return{id:a,profile:r}}function Vc(e,t){if(!sf(e))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","Application ConfigContract \u4E0D\u7B26\u5408 v1 Schema\u3002",sf.errors??[]);let r=e;if(r.configDirectory.relativeDirectory!==`applications/${r.application.id}`)throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","Config Dir \u76F8\u5BF9\u76EE\u5F55\u5FC5\u987B\u7531 Application identity \u552F\u4E00\u786E\u5B9A\u3002");let n=new Set,a=new Set;for(let i of r.bindings){if(n.has(i.name))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`\u73AF\u5883 Binding \u540D\u79F0\u91CD\u590D\uFF1A${i.name}`);if(n.add(i.name),i.kind==="value"){if(cf.test(i.name))throw new qe("APPLICATION_CONFIG_SECRET_LITERAL_FORBIDDEN",`\u654F\u611F\u914D\u7F6E ${i.name} \u5FC5\u987B\u4F7F\u7528\u6587\u4EF6 Binding\uFF0C\u7981\u6B62\u5728\u4ED3\u5E93\u4E2D\u58F0\u660E\u503C\u3002`);continue}if(!i.name.endsWith("_FILE"))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6587\u4EF6 Binding ${i.name} \u5FC5\u987B\u4EE5 _FILE \u7ED3\u5C3E\u3002`);let o=i.kind==="secret-file"?"secrets/":"certs/";if(i.kind==="certificate-file"&&(cf.test(i.name)||p_.test(i.name)))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`${i.name} \u5305\u542B\u79C1\u5BC6\u6750\u6599\u8BED\u4E49\uFF0C\u5FC5\u987B\u4F7F\u7528 secret-file \u5E76\u653E\u5165 secrets/\uFF1Bcertificate-file \u53EA\u5141\u8BB8\u516C\u5F00\u8BC1\u4E66\u3002`);let s=i.file.split("/");if(!i.file.startsWith(o)||s.some(c=>c===""||c==="."||c===".."))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`${i.name} \u5FC5\u987B\u4F4D\u4E8E ${o} \u4E0B\u7684\u5177\u4F53\u6587\u4EF6\u3002`);if(a.has(i.file))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`\u914D\u7F6E\u6587\u4EF6 Binding \u8DEF\u5F84\u91CD\u590D\uFF1A${i.file}`);a.add(i.file)}if(t!==void 0){let i=uf(t);if(r.application.id!==i.id||r.application.profile!==i.profile)throw new qe("APPLICATION_CONFIG_IDENTITY_MISMATCH","ConfigContract \u7684\u5E94\u7528\u8EAB\u4EFD\u6216 Profile \u4E0E Project Manifest \u4E0D\u4E00\u81F4\u3002")}return r}function Si(e){let t=uf(e),r=t.profile==="workspace-web-application"?[]:[{name:"PORT",kind:"value",required:!1,default:"3000"}],n={$schema:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",schemaVersion:1,kind:"ApplicationConfigContract",application:t,configDirectory:{rootEnvironmentVariable:"IDP_CONFIG_DIR",relativeDirectory:`applications/${t.id}`,environmentFile:".env",materializationOwner:"external-deployment-control-plane"},bindings:r};return Vc(n,e),Buffer.from(`${JSON.stringify(n,null,2)}
36
- `)}import{createHash as u_,X509Certificate as f_}from"node:crypto";import{lstat as Mc,readFile as gr,realpath as ff}from"node:fs/promises";import pe from"node:path";var ge=class extends Error{code;constructor(t,r){super(r),this.code=t}};function hf(e){let t=K(e),r=t.profile?.parameters?.name;if(typeof r!="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(r))throw new ge("APPLICATION_CONFIG_BINDING_IDENTITY_INVALID","\u9879\u76EE\u7F3A\u5C11\u5408\u6CD5Application identity\u3002");return{id:r,profile:t.profile.id}}function ji(e){let t=hf(e);return Buffer.from(`${JSON.stringify({$schema:"https://schemas.dyyto.dev/platform/application-config-binding-v1.json",schemaVersion:1,kind:"ApplicationConfigBinding",application:t,environment:{name:"local"},configDirectory:{rootEnvironmentVariable:"APP_CONFIG_DIR",scope:"application-environment"},contract:{path:"config/application-config.json"},materializationOwner:"external-deployment-control-plane"},null,2)}
37
- `)}function m_(e,t){let r=e;if(r?.$schema!=="https://schemas.dyyto.dev/platform/application-config-binding-v1.json"||r.schemaVersion!==1||r.kind!=="ApplicationConfigBinding"||r.environment?.name!=="local"||r.configDirectory?.rootEnvironmentVariable!=="APP_CONFIG_DIR"||r.configDirectory.scope!=="application-environment"||r.contract?.path!=="config/application-config.json"||r.materializationOwner!=="external-deployment-control-plane")throw new ge("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u4E0D\u7B26\u5408v1\u5408\u540C\u3002");if(!r.application||typeof r.application.id!="string"||typeof r.application.profile!="string")throw new ge("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u5E94\u7528\u8EAB\u4EFD\u65E0\u6548\u3002");if(t!==void 0){let n=hf(t);if(r.application.id!==n.id||r.application.profile!==n.profile)throw new ge("APPLICATION_CONFIG_BINDING_IDENTITY_MISMATCH","ApplicationConfigBinding\u4E0EProject Manifest\u8EAB\u4EFD\u4E0D\u4E00\u81F4\u3002")}return r}function g_(e){let t={};for(let[r,n]of e.split(/\r?\n/u).entries()){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(a),o=i?.[1],s=i?.[2];if(!o||s===void 0||o in t)throw new ge("APPLICATION_CONFIG_ENV_INVALID",`.env:${r+1}\u683C\u5F0F\u65E0\u6548\u6216\u53D8\u91CF\u91CD\u590D\u3002`);t[o]=s.trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/u,"$1$2")}return t}function mf(e){return`sha256:${u_("sha256").update(e).digest("hex")}`}function h_(e){return e?e.length<=4?"\u2022\u2022\u2022\u2022":`${e.slice(0,2)}\u2022\u2022\u2022\u2022${e.slice(-2)}`:""}async function gf(e,t,r){let n=await Mc(e).catch(()=>null);if(!n||!n.isFile()||n.isSymbolicLink()||n.nlink!==1||!r&&n.size===0||(n.mode&511&-385)!==0)throw new ge("APPLICATION_CONFIG_FILE_INVALID",`${t}\u4E0D\u5B58\u5728\u3001\u4E3A\u7A7A\u3001\u4E0D\u662F\u5B89\u5168\u666E\u901A\u6587\u4EF6\u6216\u6743\u9650\u8D85\u8FC70600\u3002`);return n}async function y_(e,t,r){let n=pe.dirname(e);for(;n!==pe.dirname(n);){try{if(JSON.parse(await gr(pe.join(n,"project-capabilities.json"),"utf8")).profile?.id==="workspace-root"){let i=pe.relative(n,e);if(!/^(?:apps|packages)[/\\][a-z0-9][a-z0-9._-]*$/u.test(i))throw new ge("APPLICATION_CONFIG_WORKSPACE_UNIT_INVALID","Workspace\u5E94\u7528\u5FC5\u987B\u4F4D\u4E8Eapps/<name>\u6216packages/<name>\u3002");return pe.join(pe.basename(n),i,r)}}catch(a){if(a instanceof ge)throw a}n=pe.dirname(n)}return pe.join(t,r)}async function w_(e,t,r){let n=r.DYYTO_WORKBENCH_PROJECT_BINDINGS_FILE;if(n){if(!pe.isAbsolute(n))throw new ge("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let i=await Mc(n).catch(()=>null);if(!i?.isFile()||i.isSymbolicLink()||i.nlink!==1||(i.mode&511&-385)!==0)throw new ge("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u4E0D\u5B89\u5168\u3002");let o=JSON.parse(await gr(n,"utf8"));if(o.schemaVersion!==1||!Array.isArray(o.projects))throw new ge("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u7248\u672C\u65E0\u6548\u3002");let s=o.projects.filter(c=>typeof c.containerPath=="string"&&typeof c.configDirectory=="string"&&(e===c.containerPath||e.startsWith(`${c.containerPath}${pe.sep}`))).sort((c,d)=>d.containerPath.length-c.containerPath.length);if(s[0])return s[0].configDirectory}let a=r.APP_CONFIG_DIR;if(a){if(!pe.isAbsolute(a))throw new ge("APP_CONFIG_DIR_REQUIRED","APP_CONFIG_DIR\u5FC5\u987B\u662F\u7EDD\u5BF9\u4E1A\u52A1\u914D\u7F6E\u603B\u6839\u3002");return pe.join(a,await y_(e,t,r.DYYTO_APPLICATION_ENVIRONMENT??"local"))}}async function $i({projectRoot:e,environment:t=process.env}){let r=await ff(pe.resolve(e)),[n,a,i]=await Promise.all([gr(pe.join(r,"project-capabilities.json")),gr(pe.join(r,".dyyto/application-config-binding.json")),gr(pe.join(r,"config/application-config.json"))]),o=JSON.parse(n.toString("utf8")),s=m_(JSON.parse(a.toString("utf8")),o),c=Vc(JSON.parse(i.toString("utf8")),o),d=await w_(r,s.application.id,t);if(!d||!pe.isAbsolute(d))throw new ge("APP_CONFIG_DIR_REQUIRED","\u8BF7\u4E3A\u5F53\u524D\u9879\u76EE\u8BBE\u7F6E\u7EDD\u5BF9APP_CONFIG_DIR\u3002");let l=await ff(d),p=await Mc(l);if(!p.isDirectory()||p.isSymbolicLink()||(p.mode&511&-449)!==0)throw new ge("APP_CONFIG_DIR_INVALID","APP_CONFIG_DIR\u5FC5\u987B\u662F\u6743\u9650\u4E0D\u8D85\u8FC70700\u7684\u666E\u901A\u76EE\u5F55\u3002");let f=pe.relative(r,l);if(f===""||!f.startsWith("..")&&!pe.isAbsolute(f))throw new ge("APP_CONFIG_DIR_INSIDE_PROJECT","APP_CONFIG_DIR\u4E0D\u80FD\u4F4D\u4E8E\u9879\u76EE\u4ED3\u5E93\u5185\u3002");let u=pe.join(l,".env");await gf(u,"\u5E94\u7528.env",c.bindings.length===0);let m=g_(await gr(u,"utf8")),g=[];for(let h of c.bindings){if(h.kind==="value"){let O=m[h.name]??"";g.push({name:h.name,kind:h.kind,required:h.required,configured:O.length>0,source:"APP_CONFIG_DIR",display:h_(O)});continue}if(m[h.name]!==h.file)throw new ge("APPLICATION_CONFIG_REFERENCE_CHANGED",`${h.name}\u672A\u4FDD\u6301\u5408\u540C\u6587\u4EF6\u5F15\u7528\u3002`);let _=pe.resolve(l,h.file),I=pe.relative(l,_);if(!I||I.startsWith("..")||pe.isAbsolute(I))throw new ge("APPLICATION_CONFIG_REFERENCE_ESCAPE",`${h.name}\u9003\u9038APP_CONFIG_DIR\u3002`);let A=await gf(_,h.name,!h.required),y=await gr(_),k=y.length>0,S;if(k&&h.kind==="certificate-file")try{let O=new f_(y);S={subject:O.subject,issuer:O.issuer,validFrom:O.validFrom,validTo:O.validTo}}catch{throw new ge("APPLICATION_CERTIFICATE_INVALID",`${h.name}\u4E0D\u662F\u6709\u6548X.509\u8BC1\u4E66\u3002`)}g.push({name:h.name,kind:h.kind,required:h.required,configured:k,source:"APP_CONFIG_DIR",display:k?"\u5DF2\u914D\u7F6E":"\u672A\u914D\u7F6E",...k?{fingerprint:mf(y),updatedAt:A.mtime.toISOString()}:{},...S?{certificate:S}:{}})}return{application:s.application.id,environment:"local",configDirectory:l,contractDigest:mf(i),entries:g}}var hr="project-capabilities.json",yf=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function b_(e,t){if(!yf.test(e)||!yf.test(t))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade requires stable SemVer releases");let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let a=0;a<3;a+=1)if(r[a]!==n[a])return r[a]-n[a];return 0}async function k_(e,t){let r=Xn.join(e,...t.split("/"));try{let n=await v_(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Managed upgrade target must be a regular file",t);return{path:t,exists:!0,digest:v(await Oi(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}function Ci(e,t){let r=K(e),n=t.release,a=n.assets.find(o=>o.path==="package.json");if((n.consumerProfile==="standalone-npm-package"||n.consumerProfile==="workspace-npm-package")&&a?.renderer?.startsWith("npm-package-json-")===!0)return Pc(qt(r,n.consumerProfile));if(n.consumerProfile==="react-component-library"&&a?.renderer==="react-component-package-json-v1")return Nc(qt(r,n.consumerProfile));let i=t.contents.get("package.json");if(i===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");return i}async function qc(e){let t=K(e.manifest),r=$e(e.currentLock),n=e.sourceRelease.release,a=e.targetRelease.release,i=t.capabilities.find(P=>P.capabilityId===n.capabilityId),o=r.capabilities.find(P=>P.capabilityId===n.capabilityId),s=a.capabilityId!==n.capabilityId&&a.dependencies?.capabilities?.includes(n.capabilityId)===!0;if(i===void 0||o===void 0||i.capabilityId!==o.capabilityId||i.version!==o.version||n.capabilityId!==o.capabilityId||n.version!==o.version||n.integrity!==o.integrity||!s&&a.capabilityId!==o.capabilityId||a.consumerProfile!==o.consumerProfile||n.consumerProfile!==a.consumerProfile)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade source, target, Manifest, and Lock must describe one compatible capability");if(!s&&b_(a.version,n.version)<=0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade target must be newer than the locked release");let c=await I_(Xn.resolve(e.projectRoot)),d={...t,...e.targetTemplate===void 0?{}:{template:e.targetTemplate},capabilities:t.capabilities.map(P=>P.capabilityId===n.capabilityId?{capabilityId:a.capabilityId,version:a.version}:P)},l=new Map(e.targetRelease.contents);a.assets.some(P=>P.path==="package.json")&&l.set("package.json",Ci(d,e.targetRelease));for(let P of a.assets)P.renderer==="application-config-contract-v1"&&l.set(P.path,Si(d)),P.renderer==="application-config-binding-v1"&&l.set(P.path,ji(d));let p,f=c,u="package.json",m;if(a.schemaVersion===2&&a.availability.maturity!=="withdrawn"&&(a.packageSources?.length??0)>0){if(e.packageSource===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Profile transition requires verified Package Source facts");let P=l.get("package.json");if(P===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");let W=await Oi(Xn.join(c,"package.json")),re=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:c,unitRoot:c,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"};f=re.transactionRoot,u=re.mode==="pnpm-shared-lockfile"?`${re.unitRelativeRoot}/package.json`:"package.json",m=re.lockfilePath;let Be={release:a,registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections,consumerProfile:a.consumerProfile,packageJson:W,desiredBasePackageJson:P,...e.packageSource.currentLockfile===void 0?{}:{currentLockfile:e.packageSource.currentLockfile},generatedAt:e.generatedAt,expiresAt:e.expiresAt};try{let Qe=re.mode==="pnpm-shared-lockfile"?(e.packageChannel==="development"?Di:Ni)({...Be,topology:{mode:re.mode,unitRelativeRoot:re.unitRelativeRoot,unitImporterId:re.unitImporterId,lockfilePath:re.lockfilePath,workspaceManifestPath:re.workspaceManifestPath,workspaceManifestDigest:re.workspaceManifestDigest},preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Pi:Ri)({...Be,lockResolution:e.packageSource.lockResolution});p=_i(Qe),l.set("package.json",Qe.desiredPackageJson),l.set(m,Qe.desiredLockfile)}catch(Qe){throw Qe instanceof Y?new M("CONSUMER_PROFILE_UNSUPPORTED",Qe.code):Qe}}let g=new Map(o.assets.filter(P=>P.path!==hr).map(P=>[P.path,P.digest])),h=new Map(a.assets.filter(P=>P.path!==hr).map(P=>{let W=l.get(P.path);if(W===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade target asset content is unavailable",P.path);return[P.path,v(W)]})),w=[...new Set([...g.keys(),...h.keys()])].sort(),_=[],I=[];for(let P of w){let W=await k_(c,P);_.push(W);let re=g.get(P),Be=h.get(P),Qe=a.assets.find(Km=>Km.path===P);if(Qe?.ownership==="seed-file"&&W.exists&&W.digest!==void 0){h.set(P,W.digest),l.set(P,await Oi(Xn.join(c,...P.split("/")))),I.push({path:P,kind:"replace",ownership:"seed-file",baseDigest:W.digest,desiredDigest:W.digest});continue}if(re===void 0){if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Target asset digest is unavailable",P);I.push({path:P,kind:"create",ownership:Qe?.ownership??"owned-file",desiredDigest:Be})}else Be===void 0?I.push({path:P,kind:"remove",ownership:"owned-file",baseDigest:re}):I.push({path:P,kind:"replace",ownership:Qe?.ownership??"owned-file",baseDigest:re,desiredDigest:Be})}if(p!==void 0&&m!==void 0){let P=e.packageSource?.currentLockfile;if(P===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Transition lockfile preimage is unavailable");let W=l.get(m);_.push({path:m,exists:!0,digest:v(P)}),I.push({path:m,kind:"replace",ownership:"owned-file",baseDigest:v(P),desiredDigest:v(W)})}let A=await Oi(Xn.join(c,hr)),y=Buffer.from(`${JSON.stringify(d,null,2)}
38
- `);_.push({path:hr,exists:!0,digest:v(A)}),I.push({path:hr,kind:"replace",ownership:"owned-file",baseDigest:v(A),desiredDigest:v(y)});let k={schemaVersion:1,capabilityId:a.capabilityId,version:a.version,integrity:a.integrity,assets:a.assets.filter(P=>P.path!==hr).map(P=>({path:P.path,ownership:P.ownership,desiredDigest:h.get(P.path)})),verifiers:a.verifiers.map(({id:P})=>({id:P,kind:"command"}))},S=f===c?I:I.map(P=>P.path===m?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),O=f===c?_:_.map(P=>P.path===m?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),ae=Oe({action:"upgrade",capability:k,changes:S,observedAssets:O,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...p===void 0?{}:{packageAdoption:p}});l.set(hr,y);let $=new Map;for(let P of ae.operations){if(P.disposition!=="ready"||P.kind==="remove")continue;let W=f===c?"":`${e.packageSource.topology.unitRelativeRoot}/`,re=P.path===m?P.path:P.path.startsWith(W)?P.path.slice(W.length):P.path,Be=l.get(re);if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade desired content is unavailable",P.path);$.set(P.path,Be)}return{sourceLock:r,targetManifest:d,release:e.targetRelease,plan:ae,desiredContents:$,transactionRoot:f}}import{link as __,mkdir as E_,open as wf,readFile as st,readdir as A_,realpath as ct,rm as R_,unlink as P_}from"node:fs/promises";import ce from"node:path";var j=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="DeliveryError"}};function _e(e){return/^sha256:[a-f0-9]{64}$/.test(e)}function vf(e){return v(E(e))}function Jc(e){if(!_e(e.project.lockDigest)||!_e(e.project.appliedPlanId)||!_e(e.artifact.digest))throw new j("DELIVERY_PRECONDITION_FAILED","Delivery identities must use canonical SHA-256 digests");if(Date.parse(e.expiresAt)<=Date.parse(e.createdAt)||Number.isNaN(Date.parse(e.createdAt)))throw new j("DELIVERY_PRECONDITION_FAILED","Delivery plan expiry must follow creation time");if(e.kind==="npm-publish"&&(e.artifact.type!=="npm-package"||e.target.adapterId!=="registry.npmjs"||e.risk!=="irreversible-publish")||e.kind==="application-deploy"&&(e.artifact.type!=="node-application"&&e.artifact.type!=="web-application"||e.target.adapterId!=="deployment.local-docker"||e.risk!=="local-reversible-deployment")||e.kind==="artifact-publication"&&(e.artifact.type!=="published-package"||e.target.adapterId!=="publication.offline-web"&&e.target.adapterId!=="publication.hosted-static"||(e.target.adapterId==="publication.offline-web"?e.risk!=="local-reversible-publication":e.risk!=="external-reversible-publication"))||e.kind==="hosted-static"&&(e.artifact.type!=="web-bundle"||e.target.adapterId!=="publication.hosted-static"||e.risk!=="external-reversible-publication"))throw new j("DELIVERY_PROJECT_UNSUPPORTED","Delivery kind, artifact, target, and risk must be compatible");if(e.kind==="npm-publish"&&e.publication!==void 0){let r=e.publication,n=r.execution;if(r.mode!=="staged"||r.access!=="public"||r.authentication!=="trusted-publishing"||r.trustedAction!=="stage-only"||r.provenance!=="required"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.tag)||n?.provider!=="github-actions"&&n?.provider!=="gitlab-ci"||!n.repository||!n.workflow||!n.ref||Object.values(n).some(a=>typeof a!="string"||a.length>512||/[\u0000-\u001f\u007f]/.test(a)))throw new j("DELIVERY_PRECONDITION_FAILED","npm publication policy is invalid")}if(e.kind!=="npm-publish"&&e.publication!==void 0)throw new j("DELIVERY_PRECONDITION_FAILED","Publication policy is only valid for npm delivery");let t={schemaVersion:e.kind==="npm-publish"&&e.publication!==void 0?2:1,...e,state:"reviewable"};return{...t,planId:vf(t)}}function Uc(e){let t=e;if(t?.schemaVersion!==1&&t?.schemaVersion!==2||t.state!=="reviewable")throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan is invalid or has been modified");if(t.schemaVersion===2&&(t.kind!=="npm-publish"||t.publication===void 0)||t.schemaVersion===1&&t.publication!==void 0)throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan schema and publication policy do not match");let{planId:r,...n}=t;if(vf(n)!==r)throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan is invalid or has been modified");return Jc({kind:t.kind,project:t.project,artifact:t.artifact,target:t.target,risk:t.risk,createdAt:t.createdAt,expiresAt:t.expiresAt,...t.publication===void 0?{}:{publication:t.publication}})}function If(e){if(!_e(e.planId)||!_e(e.artifactDigest)||!/^[A-Za-z0-9._:-]{1,256}$/.test(e.stageId)||Number.isNaN(Date.parse(e.createdAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record identities are invalid");let t={schemaVersion:1,...e,status:"registry-accepted"};return{...t,recordId:v(E(t))}}function bf(e){if(!_e(e.planId)||!_e(e.artifactDigest)||Number.isNaN(Date.parse(e.startedAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record identities are invalid");let t={schemaVersion:1,...e,status:"remote-write-started"};return{...t,recordId:v(E(t))}}function Ti(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="remote-write-started"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record is invalid or has been modified");return t}function Fc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="registry-accepted"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record is invalid or has been modified");return t}function kf(e){if(!_e(e.planId)||!_e(e.artifactDigest)||!/^[A-Za-z0-9._:-]{1,256}$/.test(e.stageId)||Number.isNaN(Date.parse(e.reviewedAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record identities are invalid");let t={schemaVersion:1,...e,status:"artifact-digest-verified"};return{...t,recordId:v(E(t))}}function zc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="artifact-digest-verified"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record is invalid or has been modified");return t}function xi(e){if(!_e(e.planId)||!_e(e.artifactDigest)||e.externalIdentity.length===0)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt identities are invalid");if("npm"in e){let r=e.npm;if(e.adapterId!=="registry.npmjs"||r===void 0||r.stageId.length===0||r.registry!=="https://registry.npmjs.org"||r.tarballDigest!==e.artifactDigest||r.access!=="public"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.tag)||r.provenance!=="registry-attested"||!_e(r.attestationUrlDigest))throw new j("DELIVERY_RECEIPT_INVALID","Verified npm Receipt facts are incomplete or inconsistent");let n={schemaVersion:2,...e,status:"verified"};return{...n,receiptId:v(E(n))}}if(e.kind==="npm-publish"||e.kind==="application-deploy"&&e.adapterId!=="deployment.local-docker"||e.kind==="artifact-publication"&&e.adapterId!=="publication.offline-web"&&e.adapterId!=="publication.hosted-static"||e.kind==="hosted-static"&&(e.adapterId!=="publication.hosted-static"||e.details.renderMode!=="csr"))throw new j("DELIVERY_RECEIPT_INVALID","Application or artifact Delivery Receipt facts are invalid");let t={schemaVersion:1,...e,status:"verified"};return{...t,receiptId:v(E(t))}}function Bc(e){let t=e,{receiptId:r,...n}=t??{};if(t?.schemaVersion!==1&&t?.schemaVersion!==2||t.status!=="verified"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt is invalid or has been modified");let{receiptId:a,schemaVersion:i,status:o,...s}=t;return xi(s)}async function N_(e){let t=await wf(e,"r");try{await t.sync()}finally{await t.close()}}async function Zn(e,t){let r=ce.dirname(e);await E_(r,{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`,a=await wf(n,"wx",384);try{await a.writeFile(`${E(t)}
39
- `,"utf8"),await a.sync()}finally{await a.close()}try{await __(n,e),await P_(n),await N_(r)}catch(i){throw await R_(n,{force:!0}),i}}async function _f(e){let t=await ct(ce.resolve(e.projectRoot)),r=Uc(e.plan),n=ce.join(t,".dyyto","delivery","plans",`${r.planId}.json`);try{await Zn(n,r)}catch(a){if(a.code!=="EEXIST")throw a;if(E(Uc(JSON.parse(await st(n,"utf8"))))!==E(r))throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan content does not match its identity")}return r}async function Ut(e){if(!_e(e.planId))throw new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan identity is invalid");let t=await ct(ce.resolve(e.projectRoot));try{let r=Uc(JSON.parse(await st(ce.join(t,".dyyto","delivery","plans",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan identity does not match its path");return r}catch(r){throw r.code==="ENOENT"?new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan was not found"):r}}async function Gc(e){let t=await ct(ce.resolve(e.projectRoot)),r=Bc(e.receipt),n=await Ut({projectRoot:t,planId:r.planId});if(r.kind!==n.kind||r.adapterId!==n.target.adapterId||r.artifactDigest!==n.artifact.digest||r.target!==n.target.location)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt does not match its immutable Plan");if(r.schemaVersion===2){let i=await Yr({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.publication===void 0||i===null||r.npm.stageId!==i.stageId||r.npm.tarballDigest!==i.artifactDigest||r.npm.tag!==n.publication.tag||r.npm.access!==n.publication.access)throw new j("DELIVERY_RECEIPT_INVALID","Verified npm Receipt does not match its Plan and Stage Record")}let a=ce.join(t,".dyyto","delivery","receipts",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=Bc(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Receipt already exists for this Plan");return o}return r}async function Qn(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt Plan identity is invalid");let t=await ct(ce.resolve(e.projectRoot));try{let r=Bc(JSON.parse(await st(ce.join(t,".dyyto","delivery","receipts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Receipt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ef(e){let t=await ct(ce.resolve(e.projectRoot)),r=Ti(e.record),n=await Ut({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record does not match an npm Plan v2");let a=ce.join(t,".dyyto","delivery","attempts",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=Ti(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Attempt Record already exists for this Plan");return o}return r}async function Af(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Plan identity is invalid");let t=await ct(ce.resolve(e.projectRoot));try{let r=Ti(JSON.parse(await st(ce.join(t,".dyyto","delivery","attempts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Attempt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Rf(e){let t=await ct(ce.resolve(e.projectRoot)),r=ce.join(t,".dyyto","delivery","attempts"),n;try{n=await A_(r)}catch(a){if(a.code==="ENOENT")return null;throw a}for(let a of n.sort()){if(!a.endsWith(".json"))continue;let i=Ti(JSON.parse(await st(ce.join(r,a),"utf8")));if((await Ut({projectRoot:t,planId:i.planId})).artifact.identity!==e.artifactIdentity)continue;let[s,c]=await Promise.all([Yr({projectRoot:t,planId:i.planId}),Qn({projectRoot:t,planId:i.planId})]);if(s===null&&c===null)return i}return null}async function Pf(e){let t=await ct(ce.resolve(e.projectRoot)),r=Fc(e.record),n=await Ut({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||n.publication===void 0||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record does not match an npm Plan v2");let a=ce.join(t,".dyyto","delivery","stages",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=Fc(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Record already exists for this Plan");return o}return r}async function Yr(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Plan identity is invalid");let t=await ct(ce.resolve(e.projectRoot));try{let r=Fc(JSON.parse(await st(ce.join(t,".dyyto","delivery","stages",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Nf(e){let t=await ct(ce.resolve(e.projectRoot)),r=zc(e.record),n=await Yr({projectRoot:t,planId:r.planId});if(n===null||r.stageId!==n.stageId||r.artifactDigest!==n.artifactDigest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record does not match its immutable Stage Record");let a=ce.join(t,".dyyto","delivery","stage-reviews",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=zc(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Review Record already exists for this Plan");return o}return r}async function Df(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Plan identity is invalid");let t=await ct(ce.resolve(e.projectRoot));try{let r=zc(JSON.parse(await st(ce.join(t,".dyyto","delivery","stage-reviews",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage Review identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}import{readFile as Wf,readdir as fE}from"node:fs/promises";import Yc from"node:path";import{mkdir as Wc,open as qi,readFile as ta,readdir as Bf,rename as Ui,rm as Jf}from"node:fs/promises";import we from"node:path";var D_=44;var Sf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",S_=new Uint8Array(64),$f=new Uint8Array(128);for(let e=0;e<Sf.length;e++){let t=Sf.charCodeAt(e);S_[e]=t,$f[t]=e}function ea(e,t){let r=0,n=0,a=0;do{let o=e.next();a=$f[o],r|=(a&31)<<n,n+=5}while(a&32);let i=r&1;return r>>>=1,i&&(r=-2147483648|-r),t+r}function jf(e,t){return e.pos>=t?!1:e.peek()!==D_}var IN=1024*16;var j_=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:r}=this,n=t.indexOf(e,r);return n===-1?t.length:n}};function Of(e){let{length:t}=e,r=new j_(e),n=[],a=0,i=0,o=0,s=0,c=0;do{let d=r.indexOf(";"),l=[],p=!0,f=0;for(a=0;r.pos<d;){let u;a=ea(r,a),a<f&&(p=!1),f=a,jf(r,d)?(i=ea(r,i),o=ea(r,o),s=ea(r,s),jf(r,d)?(c=ea(r,c),u=[a,i,o,s,c]):u=[a,i,o,s]):u=[a],l.push(u),r.pos++}p||$_(l),n.push(l),r.pos=d+1}while(r.pos<=t);return n}function $_(e){e.sort(O_)}function O_(e,t){return e[0]-t[0]}var C_=/^[\w+.-]+:\/\//,T_=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,x_=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function L_(e){return C_.test(e)}function V_(e){return e.startsWith("//")}function xf(e){return e.startsWith("/")}function M_(e){return e.startsWith("file:")}function Cf(e){return/^[.?#]/.test(e)}function Li(e){let t=T_.exec(e);return Lf(t[1],t[2]||"",t[3],t[4]||"",t[5]||"/",t[6]||"",t[7]||"")}function q_(e){let t=x_.exec(e),r=t[2];return Lf("file:","",t[1]||"","",xf(r)?r:"/"+r,t[3]||"",t[4]||"")}function Lf(e,t,r,n,a,i,o){return{scheme:e,user:t,host:r,port:n,path:a,query:i,hash:o,type:7}}function Tf(e){if(V_(e)){let r=Li("http:"+e);return r.scheme="",r.type=6,r}if(xf(e)){let r=Li("http://foo.com"+e);return r.scheme="",r.host="",r.type=5,r}if(M_(e))return q_(e);if(L_(e))return Li(e);let t=Li("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function U_(e){if(e.endsWith("/.."))return e;let t=e.lastIndexOf("/");return e.slice(0,t+1)}function F_(e,t){Vf(t,t.type),e.path==="/"?e.path=t.path:e.path=U_(t.path)+e.path}function Vf(e,t){let r=t<=4,n=e.path.split("/"),a=1,i=0,o=!1;for(let c=1;c<n.length;c++){let d=n[c];if(!d){o=!0;continue}if(o=!1,d!=="."){if(d===".."){i?(o=!0,i--,a--):r&&(n[a++]=d);continue}n[a++]=d,i++}}let s="";for(let c=1;c<a;c++)s+="/"+n[c];(!s||o&&!s.endsWith("/.."))&&(s+="/"),e.path=s}function Mf(e,t){if(!e&&!t)return"";let r=Tf(e),n=r.type;if(t&&n!==7){let i=Tf(t),o=i.type;switch(n){case 1:r.hash=i.hash;case 2:r.query=i.query;case 3:case 4:F_(r,i);case 5:r.user=i.user,r.host=i.host,r.port=i.port;case 6:r.scheme=i.scheme}o>n&&(n=o)}Vf(r,n);let a=r.query+r.hash;switch(n){case 2:case 3:return a;case 4:{let i=r.path.slice(1);return i?Cf(t||e)&&!Cf(i)?"./"+i+a:i+a:a||"."}case 5:return r.path+a;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+a}}function z_(e){if(!e)return"";let t=e.lastIndexOf("/");return e.slice(0,t+1)}function B_(e,t){let r=z_(e),n=t?t+"/":"";return a=>Mf(n+(a||""),r)}var Ft=0,J_=1,G_=2,W_=3,K_=4;function Y_(e,t){let r=qf(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n<e.length;n=qf(e,n+1))e[n]=X_(e[n],t);return e}function qf(e,t){for(let r=t;r<e.length;r++)if(!H_(e[r]))return r;return e.length}function H_(e){for(let t=1;t<e.length;t++)if(e[t][Ft]<e[t-1][Ft])return!1;return!0}function X_(e,t){return t||(e=e.slice()),e.sort(Z_)}function Z_(e,t){return e[Ft]-t[Ft]}var Mi=!1;function Q_(e,t,r,n){for(;r<=n;){let a=r+(n-r>>1),i=e[a][Ft]-t;if(i===0)return Mi=!0,a;i<0?r=a+1:n=a-1}return Mi=!1,r-1}function eE(e,t,r){for(let n=r+1;n<e.length&&e[n][Ft]===t;r=n++);return r}function tE(e,t,r){for(let n=r-1;n>=0&&e[n][Ft]===t;r=n--);return r}function rE(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function nE(e,t,r,n){let{lastKey:a,lastNeedle:i,lastIndex:o}=r,s=0,c=e.length-1;if(n===a){if(t===i)return Mi=o!==-1&&e[o][Ft]===t,o;t>=i?s=o===-1?0:o:c=o}return r.lastKey=n,r.lastNeedle=t,r.lastIndex=Q_(e,t,s,c)}function aE(e){return typeof e=="string"?JSON.parse(e):e}var iE="`line` must be greater than 0 (lines start at line 1)",oE="`column` must be greater than or equal to 0 (columns start at column 0)",Uf=-1,sE=1,Ff=class{constructor(e,t){let r=typeof e=="string";if(!r&&e._decodedMemo)return e;let n=aE(e),{version:a,file:i,names:o,sourceRoot:s,sources:c,sourcesContent:d}=n;this.version=a,this.file=i,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=d,this.ignoreList=n.ignoreList||n.x_google_ignoreList||void 0;let l=B_(t,s);this.resolvedSources=c.map(l);let{mappings:p}=n;if(typeof p=="string")this._encoded=p,this._decoded=void 0;else if(Array.isArray(p))this._encoded=void 0,this._decoded=Y_(p,r);else throw n.sections?new Error("TraceMap passed sectioned source map, please use FlattenMap export instead"):new Error(`invalid source map: ${JSON.stringify(n)}`);this._decodedMemo=rE(),this._bySources=void 0,this._bySourceMemos=void 0}};function cE(e){var t;return(t=e)._decoded||(t._decoded=Of(e._encoded))}function zf(e,t){let{line:r,column:n,bias:a}=t;if(r--,r<0)throw new Error(iE);if(n<0)throw new Error(oE);let i=cE(e);if(r>=i.length)return Vi(null,null,null,null);let o=i[r],s=lE(o,e._decodedMemo,r,n,a||sE);if(s===-1)return Vi(null,null,null,null);let c=o[s];if(c.length===1)return Vi(null,null,null,null);let{names:d,resolvedSources:l}=e;return Vi(l[c[J_]],c[G_]+1,c[W_],c.length===5?d[c[K_]]:null)}function Vi(e,t,r,n){return{source:e,line:t,column:r,name:n}}function lE(e,t,r,n,a){let i=nE(e,n,t,r);return Mi?i=(a===Uf?eE:tE)(e,n,i):a===Uf&&i++,i===-1||i===e.length?-1:i}var fe=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="RuntimeObservabilityError"}},Kc=/^sha256:[a-f0-9]{64}$/,Gf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,dE=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/,Fi=(e,t)=>Object.keys(e).every(r=>t.includes(r)),ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hr=(e,t)=>e.replace(/[\u0000-\u001f\u007f]/g," ").replace(/([a-z]+:\/\/)[^/@\s]+@/gi,"$1").slice(0,t);function pE(e){if(!ra(e)||!Fi(e,["schemaVersion","eventId","occurredAt","applicationId","releaseId","deploymentId","kind","error","page","traceparent"]))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error Envelope contains unknown fields");if(!ra(e.error)||!ra(e.page)||!Fi(e.error,["type","message","frames"])||!Fi(e.page,["origin","path"]))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error Envelope structure is invalid");if(e.schemaVersion!==1||typeof e.eventId!="string"||!Gf.test(e.eventId)||typeof e.occurredAt!="string"||Number.isNaN(Date.parse(e.occurredAt))||typeof e.applicationId!="string"||e.applicationId.length<1||e.applicationId.length>128)throw new fe("RUNTIME_ERROR_INVALID","Runtime Error Envelope identity is invalid");if(!["uncaught-error","unhandled-rejection","reported-error"].includes(e.kind))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error kind is invalid");for(let n of[e.releaseId,e.deploymentId])if(n!==void 0&&(typeof n!="string"||!Kc.test(n)))throw new fe("RUNTIME_ERROR_IDENTITY_UNKNOWN","Runtime Error correlation identity is invalid");if(e.traceparent!==void 0&&(typeof e.traceparent!="string"||!dE.test(e.traceparent)))throw new fe("RUNTIME_ERROR_INVALID","traceparent is invalid");if(typeof e.error.type!="string"||typeof e.error.message!="string"||!Array.isArray(e.error.frames)||e.error.frames.length>50||typeof e.page.origin!="string"||typeof e.page.path!="string")throw new fe("RUNTIME_ERROR_INVALID","Runtime Error content is invalid");if(e.error.message.length>4096||e.error.type.length>256||e.page.path.length>2048)throw new fe("RUNTIME_ERROR_TOO_LARGE","Runtime Error content exceeds a hard limit");let t=e.error.frames.map(n=>{if(!ra(n)||!Fi(n,["file","line","column","function"])||typeof n.file!="string"||n.file.length>2048)throw new fe("RUNTIME_ERROR_INVALID","Runtime Error stack frame is invalid");for(let a of[n.line,n.column])if(a!==void 0&&(!Number.isSafeInteger(a)||Number(a)<1))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error stack location is invalid");if(n.function!==void 0&&(typeof n.function!="string"||n.function.length>256))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error stack function is invalid");return n}),r;try{r=new URL(e.page.origin)}catch{throw new fe("RUNTIME_ERROR_INVALID","Runtime Error page origin is invalid")}if(r.origin!==e.page.origin||!e.page.path.startsWith("/")||e.page.path.includes("?")||e.page.path.includes("#"))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error page must contain only origin and path");return{...e,error:{...e.error,frames:t}}}function uE(e,t,r="unknown"){let n=e.error.frames.map(o=>({file:Hr(o.file,2048),...o.line===void 0?{}:{line:o.line},...o.column===void 0?{}:{column:o.column},...o.function===void 0?{}:{function:Hr(o.function,256)}})),a={type:Hr(e.error.type,256),message:Hr(e.error.message,4096),frames:n},i=v(E({type:a.type,message:a.message,frames:n.slice(0,5).map(({file:o,line:s,column:c})=>({file:o,line:s,column:c}))}));return{schemaVersion:1,eventId:e.eventId,occurredAt:e.occurredAt,receivedAt:t,applicationId:Hr(e.applicationId,128),...e.releaseId===void 0?{}:{releaseId:e.releaseId},...e.deploymentId===void 0?{}:{deploymentId:e.deploymentId},kind:e.kind,error:a,page:{origin:e.page.origin,path:Hr(e.page.path,2048)},...e.traceparent===void 0?{}:{traceparent:e.traceparent},fingerprint:i,state:e.releaseId===void 0?"persisted":"map-missing",correlation:r}}var yr=class{workspaceRoot;adapterId="observability.local";#e=Promise.resolve();constructor(t){this.workspaceRoot=t}directory(){return we.join(we.resolve(this.workspaceRoot),".dyyto","observability","events")}releases(){return we.join(we.resolve(this.workspaceRoot),".dyyto","observability","releases")}async accept(t,r){let n=pE(t);if(!r.allowedOrigins.includes(n.page.origin))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error origin is not registered");let a=r.resolveCorrelation===void 0?"unknown":await r.resolveCorrelation(n),i=uE(n,r.receivedAt,a);return this.#t(async()=>{let o=this.directory();await Wc(o,{recursive:!0,mode:448});let s=we.join(o,`${i.eventId}.json`);try{let f=JSON.parse(await ta(s,"utf8")),u={...f,correlation:f.correlation??"unknown"};if(E({...u,receivedAt:i.receivedAt})!==E(i))throw new fe("RUNTIME_ERROR_INVALID","eventId is already used for different content");return{eventId:i.eventId,state:u.state,duplicate:!0}}catch(f){if(f.code!=="ENOENT")throw f}let c=`${s}.tmp-${process.pid}-${crypto.randomUUID()}`,d=await qi(c,"wx",384);try{await d.writeFile(`${E(i)}
40
- `,"utf8"),await d.sync()}finally{await d.close()}await Ui(c,s);let l=await qi(o,"r");try{await l.sync()}finally{await l.close()}await this.rotate(),i.releaseId!==void 0&&await this.resymbolicate(i.releaseId);let p=JSON.parse(await ta(s,"utf8"));return{eventId:i.eventId,state:p.state,duplicate:!1}})}#t(t){let r=this.#e.then(t,t);return this.#e=r.catch(()=>{}),r}async quarantine(t){let r=we.join(this.directory(),t),n=we.join(we.resolve(this.workspaceRoot),".dyyto","observability","quarantine");await Wc(n,{recursive:!0,mode:448}),await Ui(r,we.join(n,`${Date.now()}-${t}`))}async all(){let t=await Bf(this.directory()).catch(()=>[]),r=[];for(let n of t){if(!n.endsWith(".json")){n.includes(".tmp-")&&await this.quarantine(n).catch(()=>{});continue}try{let a=JSON.parse(await ta(we.join(this.directory(),n),"utf8"));if(a.eventId!==n.slice(0,-5))throw new Error("identity mismatch");r.push({...a,correlation:a.correlation??"unknown"})}catch{await this.quarantine(n).catch(()=>{})}}return r.sort((n,a)=>a.occurredAt.localeCompare(n.occurredAt)||n.eventId.localeCompare(a.eventId))}selected(t,r){return t.filter(n=>(!r.applicationId||n.applicationId===r.applicationId)&&(!r.releaseId||n.releaseId===r.releaseId)&&(!r.deploymentId||n.deploymentId===r.deploymentId))}cursor(t,r){let n=E({v:1,offset:t,snapshot:r});return Buffer.from(E({content:n,digest:v(n)})).toString("base64url")}parseCursor(t,r){try{let n=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(typeof n.content!="string"||n.digest!==v(n.content))throw new Error("tampered");let a=JSON.parse(n.content);if(a.v!==1||!Number.isSafeInteger(a.offset)||a.offset<0||a.snapshot!==r)throw new Error("expired");return a.offset}catch{throw new fe("OBSERVABILITY_CURSOR_EXPIRED","Runtime Error query cursor is invalid or expired")}}async list(t){let r=Math.max(1,Math.min(t.limit??100,100)),n=this.selected(await this.all(),t),a=v(E(n.map(s=>s.eventId))),i=t.cursor===void 0?0:this.parseCursor(t.cursor,a),o=n.slice(i,i+r);return{events:o,...i+o.length<n.length?{nextCursor:this.cursor(i+o.length,a)}:{}}}async get(t){if(!Gf.test(t))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error eventId is invalid");let r=`${t}.json`;try{let n=JSON.parse(await ta(we.join(this.directory(),r),"utf8"));if(n.eventId!==t)throw new Error("identity mismatch");return{...n,correlation:n.correlation??"unknown"}}catch(n){if(n.code==="ENOENT")return null;throw await this.quarantine(r).catch(()=>{}),new fe("OBSERVABILITY_STORE_DAMAGED","Runtime Error record is damaged and has been quarantined")}}async summary(t){let r=this.selected(await this.all(),t),n=new Map;for(let a of r){let i=n.get(a.fingerprint);i?i.count+=1:n.set(a.fingerprint,{count:1,latestAt:a.occurredAt,event:a})}return{total:r.length,groups:[...n.entries()].map(([a,i])=>({fingerprint:a,...i}))}}async rotate(){let t=await this.all(),n=t.reduce((a,i)=>Math.max(a,Date.parse(i.receivedAt)),0)-10080*60*1e3;for(let a of t.slice(1e4))await Jf(we.join(this.directory(),`${a.eventId}.json`),{force:!0});for(let a of t.slice(0,1e4))Date.parse(a.receivedAt)<n&&await Jf(we.join(this.directory(),`${a.eventId}.json`),{force:!0})}async registerSourceMap(t){if(!Kc.test(t.releaseId)||!Kc.test(t.assetDigest)||!/^[A-Za-z0-9._/-]+\.js$/.test(t.asset)||t.asset.includes("..")||!ra(t.map)||"sourcesContent"in t.map)throw new fe("RUNTIME_ERROR_INVALID","Source Map registration is invalid or contains sourcesContent");let r=Buffer.from(E(t.map)),n=v(r),a=we.join(this.releases(),t.releaseId);await Wc(a,{recursive:!0,mode:448});let i=v(t.asset),o=we.join(a,`${i}.json`),s={releaseId:t.releaseId,asset:t.asset,assetDigest:t.assetDigest,mapDigest:n,registeredAt:t.registeredAt},c=await qi(`${o}.tmp`,"w",384);try{await c.writeFile(`${E({registration:s,map:t.map})}
41
- `),await c.sync()}finally{await c.close()}return await Ui(`${o}.tmp`,o),await this.resymbolicate(t.releaseId),s}async resymbolicate(t){let r=await Bf(we.join(this.releases(),t)).catch(()=>[]),n=[];for(let a of r)try{n.push(JSON.parse(await ta(we.join(this.releases(),t,a),"utf8")))}catch{}for(let a of(await this.all()).filter(i=>i.releaseId===t&&i.state==="map-missing")){let i=!1,o=a.error.frames.map(l=>{let p=n.find(f=>new URL(l.file,"http://local").pathname.endsWith(`/${f.registration.asset}`));if(!p||l.line===void 0||l.column===void 0)return l;try{let f=zf(new Ff(p.map),{line:l.line,column:Math.max(0,l.column-1)});return f.source===null||f.line===null||f.column===null?l:(i=!0,{...l,source:f.source.replace(/^file:\/\//,""),sourceLine:f.line,sourceColumn:f.column+1})}catch{return l}});if(!i)continue;let s={...a,error:{...a.error,frames:o},state:"symbolicated"},c=we.join(this.directory(),`${a.eventId}.json`),d=await qi(`${c}.tmp`,"w",384);try{await d.writeFile(`${E(s)}
42
- `),await d.sync()}finally{await d.close()}await Ui(`${c}.tmp`,c)}}};var Ue=(e,t,r,n,a)=>({code:e,severity:t,fact:r,message:n,...a===void 0?{}:{action:a}});async function na(e){if(e.lock.capabilities.length===0||e.lock.capabilities.some(r=>r.evidenceIds.length===0))return[Ue("EVIDENCE_INVALID","critical","evidence","\u5DF2\u9A8C\u8BC1\u9501\u7F3A\u5C11\u5B8C\u6574\u8BC1\u636E\u5F15\u7528\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u4E8B\u52A1\u672A\u5B8C\u6210\uFF0C\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\u3002")];for(let r of e.lock.capabilities)for(let n of r.evidenceIds)try{let a=$n(JSON.parse(await Wf(Yc.join(e.projectRoot,".dyyto","evidence",`${n}.json`),"utf8")));if(a.evidenceId!==n||a.capabilityId!==r.capabilityId||a.capabilityVersion!==r.version||a.capabilityIntegrity!==r.integrity||a.projectStateDigest!==r.projectStateDigest||a.result!=="passed")return[Ue("EVIDENCE_INVALID","critical","evidence","\u91C7\u7528\u8BC1\u636E\u4E0E\u5DF2\u9A8C\u8BC1\u9501\u7684\u8EAB\u4EFD\u6216\u5DE5\u7A0B\u72B6\u6001\u4E0D\u4E00\u81F4\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u73B0\u573A\u5DF2\u53D8\u5316\uFF0C\u5148\u68C0\u67E5\u5E76\u91CD\u65B0\u89C4\u5212\u3002")]}catch{return[Ue("EVIDENCE_INVALID","critical","evidence","\u91C7\u7528\u8BC1\u636E\u7F3A\u5931\u3001\u635F\u574F\u6216\u4E0D\u7B26\u5408\u5951\u7EA6\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u4E8B\u52A1\u672A\u5B8C\u6210\uFF0C\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\u3002")]}let t=e.lock.capabilities.reduce((r,n)=>r+n.evidenceIds.length,0);return[Ue("EVIDENCE_VALID","info","evidence",`\u5DF2\u6838\u9A8C ${e.lock.capabilities.length} \u9879\u80FD\u529B\u7684 ${t} \u6761\u91C7\u7528\u8BC1\u636E\u3002`)]}function Hc(e){return e==="adopted"?[]:e==="planned"?[Ue("ADOPTION_PLANNED","warning","lock","\u80FD\u529B\u91C7\u7528\u4ECD\u5904\u4E8E\u8BA1\u5212\u9636\u6BB5\u3002","\u5BA1\u9605\u5E76\u6279\u51C6\u7CBE\u786E Plan\u3002")]:e==="applied-unverified"?[Ue("VERIFICATION_REQUIRED","warning","evidence","\u53D8\u66F4\u5DF2\u5E94\u7528\u4F46\u5C1A\u672A\u5F62\u6210\u9A8C\u8BC1\u8BC1\u636E\u3002","\u8FD0\u884C\u9A8C\u8BC1\u5E76\u63D0\u4EA4\u91C7\u7528\u9501\u3002")]:e==="drifted"?[Ue("REPOSITORY_DRIFT","warning","repository","\u5DE5\u7A0B\u73B0\u573A\u4E0E\u5DF2\u9501\u5B9A\u4E8B\u5B9E\u4E0D\u4E00\u81F4\u3002","\u68C0\u67E5\u5DEE\u5F02\u5E76\u91CD\u65B0\u89C4\u5212\uFF0C\u5E73\u53F0\u4E0D\u4F1A\u8986\u76D6\u7528\u6237\u4FEE\u6539\u3002")]:e==="recovery-required"?[Ue("RECOVERY_REQUIRED","critical","recovery","\u68C0\u6D4B\u5230\u672A\u5B8C\u6210\u7684\u6301\u4E45\u5316\u4E8B\u52A1\u3002","\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\uFF0C\u518D\u7EE7\u7EED\u5176\u4ED6\u64CD\u4F5C\u3002")]:[Ue("FACT_INVALID","critical","manifest","\u5DE5\u7A0B\u5355\u5143\u4E8B\u5B9E\u65E0\u6CD5\u5B89\u5168\u8BFB\u53D6\u3002","\u4FEE\u590D\u8BE5\u5355\u5143\u7684 Manifest \u6216\u5143\u6570\u636E\u540E\u91CD\u65B0\u8BCA\u65AD\u3002")]}async function Kf(e){try{let r=JSON.parse(await Wf(Yc.join(e.workspaceRoot,".dyyto","observability","config.json"),"utf8"));if(!Array.isArray(r.applications)||!r.applications.includes(e.applicationId))return[Ue("OBSERVABILITY_NOT_CONFIGURED","warning","repository","\u5F53\u524D Web \u5E94\u7528\u5C1A\u672A\u914D\u7F6E\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u3002","\u767B\u8BB0\u5E94\u7528 Origin\uFF0C\u5E76\u542F\u52A8\u672C\u5730\u91C7\u96C6\u7AEF\u3002")]}catch{return[Ue("OBSERVABILITY_NOT_CONFIGURED","warning","repository","\u5F53\u524D Web \u5E94\u7528\u5C1A\u672A\u914D\u7F6E\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u3002","\u767B\u8BB0\u5E94\u7528 Origin\uFF0C\u5E76\u542F\u52A8\u672C\u5730\u91C7\u96C6\u7AEF\u3002")]}await new yr(e.workspaceRoot).list({applicationId:e.applicationId});let t=(await fE(Yc.join(e.workspaceRoot,".dyyto","observability","quarantine")).catch(()=>[])).length;return t>0?[Ue("OBSERVABILITY_STORE_DAMAGED","critical","repository",`\u8FD0\u884C\u65F6\u9519\u8BEF\u672C\u5730\u5B58\u50A8\u5DF2\u9694\u79BB ${t} \u6761\u635F\u574F\u8BB0\u5F55\uFF0C\u5065\u5EB7\u4E8B\u4EF6\u4ECD\u53EF\u67E5\u8BE2\u3002`,"\u68C0\u67E5\u672C\u673A\u78C1\u76D8\u72B6\u6001\uFF0C\u5E76\u663E\u5F0F\u5904\u7406\u9694\u79BB\u8BB0\u5F55\u3002")]:[Ue("OBSERVABILITY_CONFIGURED","info","repository","\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u914D\u7F6E\u4E0E\u672C\u5730\u5B58\u50A8\u53EF\u8BFB\u53D6\u3002")]}function Yf(e){let t=e.units.map(n=>{let a=n.findings.some(i=>i.severity==="critical")?"blocked":n.findings.some(i=>i.severity==="warning")?"attention":"healthy";return{...n,status:a}}),r={total:t.length,healthy:t.filter(n=>n.status==="healthy").length,attention:t.filter(n=>n.status==="attention").length,blocked:t.filter(n=>n.status==="blocked").length};return{schemaVersion:1,workspace:e.workspace,generatedAt:e.generatedAt,status:r.blocked>0?"blocked":r.attention>0?"attention":"healthy",summary:r,units:t}}import{readFile as aa,realpath as Hf}from"node:fs/promises";import wr from"node:path";var ne=class extends Error{code;constructor(t,r){super(r),this.code=t}};async function Xf(e){let t=await Hf(wr.resolve(e.projectRoot)),r=K(e.manifest),n=e.release.release,a=e.currentLock.capabilities.find(f=>f.capabilityId===n.capabilityId&&f.version===n.version);if(!a||a.packageAdoption!==void 0)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Asset-only removal requires an adopted Capability without package ownership");let i=K({...r,capabilities:r.capabilities.filter(f=>f.capabilityId!==n.capabilityId)}),o=Buffer.from(`${JSON.stringify(i,null,2)}
43
- `),s=await ia(t,"project-capabilities.json");if(!s.exists||s.digest===void 0)throw new ne("CAPABILITY_DEPENDENCY_UNSATISFIED","Project manifest is unavailable");let c=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:s.digest,desiredDigest:v(o)},...a.assets.map(f=>({path:f.path,kind:"remove",ownership:f.ownership??"owned-file",baseDigest:f.digest}))],d=await Promise.all(c.map(f=>ia(t,f.path))),l={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:a.assets.map(f=>({path:f.path,ownership:f.ownership??"owned-file",desiredDigest:f.digest})),verifiers:n.verifiers.map(f=>({id:f.id,kind:"file-digest"}))};return{plan:Oe({action:"remove",capability:l,changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),manifest:i,desiredContents:new Map([["project-capabilities.json",o]]),transactionRoot:t,removedSources:[]}}async function ia(e,t){try{let r=await aa(wr.join(e,...t.split("/")));return{path:t,exists:!0,digest:v(r)}}catch(r){if(r.code==="ENOENT")return{path:t,exists:!1};throw r}}async function Xc(e){if(e.release.release.schemaVersion===2&&e.release.release.packageSources.length>0&&e.packageSource===void 0)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires verified package source facts");let t=await Hf(wr.resolve(e.projectRoot)),r=K(e.manifest),n=e.release.release,a=e.packageSource?.topology,i=a?.transactionRoot??t,o=k=>a?.mode==="pnpm-shared-lockfile"?`${a.unitRelativeRoot}/${k}`:k;if(n.kind!=="engineering-feature"||n.consumerProfile!=="any-project")throw new ne("CAPABILITY_KIND_UNSUPPORTED","Only an addable engineering feature can use this lifecycle");if(r.capabilities.some(k=>k.capabilityId===n.capabilityId))throw new ne("CAPABILITY_ALREADY_SELECTED","The capability is already selected by this project");let s=r.profile?.id,c=s==="typescript-library"?"blank-typescript-library":s,d=n.dependencies?.profiles??[],l=e.currentLock.capabilities.find(k=>k.consumerProfile===c);if(c===void 0||!d.includes(c)||l===void 0)throw new ne("CAPABILITY_DEPENDENCY_UNSATISFIED","The project profile does not satisfy this capability dependency");if((n.dependencies?.capabilities??[]).some(k=>!r.capabilities.some(S=>S.capabilityId===k)||!e.currentLock.capabilities.some(S=>S.capabilityId===k)))throw new ne("CAPABILITY_DEPENDENCY_UNSATISFIED","A required project capability is not adopted and verified");let f=K({...r,capabilities:[...r.capabilities,{capabilityId:n.capabilityId,version:n.version}]}),u=o("project-capabilities.json"),m=Buffer.from(`${JSON.stringify(f,null,2)}
44
- `),g=await ia(i,u);if(!g.exists||g.digest===void 0)throw new ne("CAPABILITY_DEPENDENCY_UNSATISFIED","The project manifest is unavailable");let h=[{path:u,kind:"replace",ownership:"owned-file",baseDigest:g.digest,desiredDigest:v(m)}],w=new Map([[u,m]]),_;if(n.schemaVersion===2&&n.packageSources.length>0){if(e.packageSource===void 0)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires verified package source facts");let k;try{k=await aa(wr.join(t,"package.json"))}catch{throw new ne("CAPABILITY_PACKAGE_SOURCE_INVALID","\u9879\u76EE package.json \u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u751F\u6210\u5305\u91C7\u7528\u8BA1\u5212")}try{let S=e.packageSource.currentLockfile??await aa(wr.join(t,"pnpm-lock.yaml")).catch(re=>re.code==="ENOENT"?void 0:Promise.reject(re)),O=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"},ae=O.mode==="pnpm-shared-lockfile",$={mode:O.mode,unitRelativeRoot:O.unitRelativeRoot,unitImporterId:O.unitImporterId,lockfilePath:O.lockfilePath,...O.workspaceManifestPath?{workspaceManifestPath:O.workspaceManifestPath,workspaceManifestDigest:O.workspaceManifestDigest}:{}},P={registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections};if(ae&&(!e.packageSource.resolutionEvidence||!e.packageSource.resolutionWorkerReleaseId))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let W=ae?(e.packageChannel==="development"?Di:Ni)({release:n,...P,consumerProfile:c,packageJson:k,currentLockfile:S,generatedAt:e.generatedAt,expiresAt:e.expiresAt,topology:$,preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Pi:Ri)({release:n,...P,lockResolution:e.packageSource.lockResolution,consumerProfile:c,packageJson:k,...S===void 0?{}:{currentLockfile:S},generatedAt:e.generatedAt,expiresAt:e.expiresAt});_=_i(W),h.push({path:o("package.json"),kind:"replace",ownership:"owned-file",baseDigest:W.packageJsonPreimageDigest,desiredDigest:W.desiredPackageJsonDigest}),w.set(o("package.json"),W.desiredPackageJson),h.push({path:O.lockfilePath,kind:S===void 0?"create":"replace",ownership:"owned-file",...S===void 0?{}:{baseDigest:v(S)},desiredDigest:W.desiredLockfileDigest}),w.set(O.lockfilePath,W.desiredLockfile)}catch(S){throw S instanceof Y?new ne("CAPABILITY_PACKAGE_SOURCE_INVALID",S.code):S}}for(let k of n.assets){let S=e.release.contents.get(k.path);if(S===void 0)throw new ne("CAPABILITY_KIND_UNSUPPORTED","Capability asset content is unavailable");let O=k.renderer==="application-config-contract-v1"?Si(r):k.renderer==="application-config-binding-v1"?ji(r):S;if(k.ownership==="managed-region"){if(k.regionId===void 0)throw new ne("CAPABILITY_KIND_UNSUPPORTED","Managed region identity is unavailable");let ae;try{ae=await aa(wr.join(t,...k.path.split("/")))}catch{throw new ne("CAPABILITY_DEPENDENCY_UNSATISFIED","The managed shared file is unavailable")}let $=Buffer.from(hu({source:ae.toString("utf8"),regionId:k.regionId,content:Buffer.from(O).toString("utf8")}));h.push({path:o(k.path),kind:"merge",ownership:"managed-region",regionId:k.regionId,baseDigest:v(ae),desiredDigest:v($)}),w.set(o(k.path),$)}else{let ae=await ia(t,k.path);if(k.ownership==="seed-file"&&ae.exists){let $=await aa(wr.join(t,...k.path.split("/")));h.push({path:o(k.path),kind:"create",ownership:"seed-file",desiredDigest:v($)}),w.set(o(k.path),$)}else h.push({path:o(k.path),kind:"create",ownership:k.ownership,desiredDigest:v(O)}),w.set(o(k.path),O)}}let I=await Promise.all(h.map(k=>ia(i,k.path))),A={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:h.filter(k=>k.path!==u&&k.path!==a?.lockfilePath).map(k=>({path:a?.mode==="pnpm-shared-lockfile"?k.path.slice(a.unitRelativeRoot.length+1):k.path,ownership:k.ownership,desiredDigest:k.desiredDigest})),verifiers:n.verifiers.map(k=>({id:k.id,kind:"file-digest"}))};return{plan:Oe({action:"adopt",capability:A,changes:h,observedAssets:I,generatedAt:e.generatedAt,expiresAt:e.expiresAt,..._===void 0?{}:{packageAdoption:_}}),manifest:f,desiredContents:w,transactionRoot:i,dependency:{profile:c,satisfied:!0}}}var Zf=Ir(tr(),1);var mE={$id:"https://schemas.dyyto.dev/platform/solution-catalog-entry-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","solutionId","version","integrity","title","summary","maturity","members","integration","exit"],properties:{schemaVersion:{const:1},solutionId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:dt},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},maturity:{enum:["guided","automated"]},members:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","role","required"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},role:{type:"string",minLength:1,maxLength:80},required:{type:"boolean"}}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","steps","verification","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},steps:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["label","command"],properties:{label:{type:"string",minLength:1,maxLength:80},command:{type:"string",minLength:1,maxLength:2e3}}}},verification:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:1e3}},result:{type:"string",minLength:1,maxLength:400}}},exit:{type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string",minLength:1,maxLength:400}}}}},ZN=new Zf.Ajv2020({allErrors:!0,strict:!0}).compile(mE);var nm=Ir(tr(),1);import{readFile as gE,realpath as hE}from"node:fs/promises";import Qf from"node:path";var em="^[a-z0-9]+(?:[.-][a-z0-9]+)*$",tm="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)[^\\u0000]+$",yE={$id:"https://schemas.dyyto.dev/platform/example-recipe-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","recipeId","version","integrity","title","locale","rootProfile","capabilities","expectedEntrypoint","verifiers","manualAcceptance","cleanup"],properties:{schemaVersion:{const:1},recipeId:{type:"string",pattern:em},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:dt},title:{type:"string",minLength:1,maxLength:80},locale:{const:"zh-CN"},rootProfile:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128}}},capabilities:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","channel"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},channel:{const:"development"}}}},expectedEntrypoint:{type:"string",pattern:tm,maxLength:240},verifiers:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",pattern:em}},manualAcceptance:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:240}},cleanup:{type:"object",additionalProperties:!1,required:["ownedStateDirectories"],properties:{ownedStateDirectories:{type:"array",maxItems:8,uniqueItems:!0,items:{type:"string",pattern:tm,maxLength:240}}}}}},rm=new nm.Ajv2020({allErrors:!0,strict:!0}).compile(yE),vr=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function wE(e){return v(E(e))}function vE(e){if(!rm(e))throw new vr("EXAMPLE_RECIPE_INVALID",rm.errors??[]);let t=e,r=[t.rootProfile.capabilityId,...t.capabilities.map(n=>n.capabilityId)];if(new Set(r).size!==r.length||t.capabilities.some(n=>n.version.includes("workspace:")||n.capabilityId.includes("ai-education-poc")))throw new vr("EXAMPLE_RECIPE_INVALID");return t}async function am(e){let t=await hE(Qf.resolve(e)),r;try{r=vE(JSON.parse(await gE(Qf.join(t,"recipe.json"),"utf8")))}catch(i){throw i instanceof vr?i:new vr("EXAMPLE_RECIPE_INVALID")}let{integrity:n,...a}=r;if(wE(a)!==n)throw new vr("EXAMPLE_RECIPE_INTEGRITY_MISMATCH");return r}var sm=Ir(tr(),1);import{readFile as IE,realpath as bE}from"node:fs/promises";import im from"node:path";var kE={$id:"https://schemas.dyyto.dev/platform/engineering-template-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","templateId","version","integrity","title","summary","status","profile","parameters","commands","technology","support","integration","metrics"],properties:{schemaVersion:{const:1},templateId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:dt},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},status:{enum:["candidate","recommended","deprecated"]},profile:{type:"object",additionalProperties:!1,required:["id","capability"],properties:{id:{type:"string",pattern:H},capability:{type:"string",pattern:`${H.slice(1,-1)}@[0-9]+\\.[0-9]+\\.[0-9]+$`}}},parameters:{type:"array",minItems:0,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","required","description"],properties:{id:{type:"string",pattern:"^[a-z][A-Za-z0-9]*$"},required:{type:"boolean"},description:{type:"string",minLength:1,maxLength:160}}}},commands:{type:"object",minProperties:1,additionalProperties:!1,properties:{dev:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},build:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},test:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},package:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"}}},technology:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","version","policy","verifiedAt","rationale","alternative","exit"],properties:{id:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:64},policy:{enum:["recommended","allowed"]},verifiedAt:{type:"string",format:"date"},rationale:{type:"string",minLength:1,maxLength:240},alternative:{type:"string",minLength:1,maxLength:160},exit:{type:"string",minLength:1,maxLength:240}}}},support:{type:"object",additionalProperties:!1,required:["owner","tier","supportedFrom","supportedUntil","upgradeCadence","eolNoticeDays"],properties:{owner:{type:"string",pattern:H},tier:{const:"production"},supportedFrom:{type:"string",format:"date"},supportedUntil:{type:"string",format:"date"},upgradeCadence:{type:"string",minLength:1,maxLength:80},eolNoticeDays:{type:"integer",minimum:30,maximum:730}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","createCommand","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},createCommand:{type:"string",minLength:1,maxLength:2e3},result:{type:"string",minLength:1,maxLength:400}}},metrics:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["time-to-green-build","time-to-first-business-commit","manual-engineering-edits","upgrade-conflicts"]}}}},om=new sm.Ajv2020({allErrors:!0,strict:!0,formats:{date:/^\d{4}-\d{2}-\d{2}$/}}).compile(kE),Et=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function _E(e){return v(E(e))}function EE(e){if(!om(e))throw new Et("TEMPLATE_INVALID",om.errors??[]);let t=e;if(new Set(t.parameters.map(r=>r.id)).size!==t.parameters.length||new Set(t.technology.map(r=>r.id)).size!==t.technology.length)throw new Et("TEMPLATE_INVALID");if(Date.parse(t.support.supportedUntil)<=Date.parse(t.support.supportedFrom))throw new Et("TEMPLATE_INVALID");return t}async function oa(e,t=new Date){let r=await bE(im.resolve(e)),n;try{n=EE(JSON.parse(await IE(im.join(r,"template.json"),"utf8")))}catch(o){throw o instanceof Et?o:new Et("TEMPLATE_INVALID")}let{integrity:a,...i}=n;if(_E(i)!==a)throw new Et("TEMPLATE_INTEGRITY_MISMATCH");if(n.status==="recommended"&&Date.parse(n.support.supportedUntil)<t.getTime())throw new Et("TEMPLATE_SUPPORT_EXPIRED");return n}import{readFile as cm}from"node:fs/promises";import lm from"node:path";var AE=/^[A-Z][A-Z0-9_]*$/u,RE=/(?:API_KEY|ACCESS_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|DATABASE_URL|POSTGRES_URL)$/u;function PE(e){let t=new Map;for(let r of e.split(/\r?\n/u)){let n=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(r.trim());if(!n||!AE.test(n[1]))continue;let a=n[1],i=n[2].trim();t.set(a,{name:a,requirement:i.length===0?"conditional":"optional",secret:RE.test(a),configured:!1,source:".env.example",configuredSource:null})}return[...t.values()]}async function dm(e){let t=await cm(lm.join(e.projectRoot,".env.example"),"utf8").then(()=>".env.example").catch(()=>null),r=t?await cm(lm.join(e.projectRoot,t),"utf8"):"",n=await $i({projectRoot:e.projectRoot}).catch(()=>null);return{commands:["dev","build","test","package"].flatMap(i=>e.commands[i]?[{id:i,script:e.commands[i],mode:i==="dev"?"managed-process":"foreground-task"}]:[]),environment:n?n.entries.map(i=>({name:i.name,requirement:i.required?"conditional":"optional",secret:i.kind!=="value",configured:i.configured,source:"application-config-contract",configuredSource:"APP_CONFIG_DIR",display:i.display,...i.fingerprint?{fingerprint:i.fingerprint}:{}})):PE(r),environmentExample:t,productionValidation:{contract:!0,live:["provider-read","oss-write-read-delete"]}}}var pm={change:new Set(["plan","apply","upgrade","recover","baseline-next","add-package","add-application","add-feature"]),quality:new Set(["inspect","verify","doctor","maintenance","test","build"]),delivery:new Set(["package","delivery-plan","delivery-apply","delivery-inspect"])},um=new Set(["queued","running","succeeded","failed","outcome-unknown","cancelled"]);function fm(e,t){if(!pm[t.plane]||t.state&&!um.has(t.state)||t.limit!==void 0&&(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>200))throw new Error("OPERATION_FILTER_INVALID");let r=pm[t.plane],n=t.from?Date.parse(t.from):null,a=t.to?Date.parse(t.to):null;if(n!==null&&Number.isNaN(n)||a!==null&&Number.isNaN(a)||n!==null&&a!==null&&n>a)throw new Error("OPERATION_FILTER_INVALID");let i=e.filter(d=>r.has(d.operation)),o=[...new Map(i.map(d=>[d.projectId,{id:d.projectId,name:d.projectName}])).values()].sort((d,l)=>d.name.localeCompare(l.name)),s=i.filter(d=>(!t.projectId||d.projectId===t.projectId)&&(!t.state||d.state===t.state)&&(!t.kind||d.operation===t.kind)&&(n===null||Date.parse(d.createdAt)>=n)&&(a===null||Date.parse(d.createdAt)<=a)).sort((d,l)=>l.updatedAt.localeCompare(d.updatedAt)),c={total:s.length,running:s.filter(d=>d.state==="running"||d.state==="queued").length,succeeded:s.filter(d=>d.state==="succeeded").length,attention:s.filter(d=>d.state==="failed"||d.state==="outcome-unknown").length};return Object.freeze({schemaVersion:1,plane:t.plane,summary:Object.freeze(c),facets:Object.freeze({projects:Object.freeze(o),states:Object.freeze([...um]),kinds:Object.freeze([...r])}),items:Object.freeze(s.slice(0,t.limit??50).map(Object.freeze)),hasMore:s.length>(t.limit??50)})}var sa=class extends Error{code;constructor(t,r){super(r),this.code=t}},Qc=/^sha256:[a-f0-9]{64}$/u,NE=/^sha512-[A-Za-z0-9+/]{86}==$/u,DE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,SE=/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?$/u,jE=/[\u0000-\u001f\u007f]/u;function Xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Zr(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((a,i)=>a===n[i])}function At(e,t=500){return typeof e=="string"&&e.length>0&&e.length<=t&&!jE.test(e)}function Zc(e){return At(e,500)&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")}function mm(e,t=128){return Array.isArray(e)&&e.length<=t&&e.every(r=>At(r,500))&&e.every((r,n)=>n===0||e[n-1]<r)}function $E(e){return e===null?!0:!Xr(e)||!Zr(e,["fileName","digest","integrity","fileCount","unpackedBytes"])?!1:Zc(e.fileName)&&Qc.test(String(e.digest))&&NE.test(String(e.integrity))&&Number.isSafeInteger(e.fileCount)&&Number(e.fileCount)>0&&Number.isSafeInteger(e.unpackedBytes)&&Number(e.unpackedBytes)>0}function OE(e){if(!Xr(e)||!Zr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence"])||e.schemaVersion!==1||e.kind!=="PackageRelease"||!DE.test(e.packageName)||!SE.test(e.version)||!At(e.title,120)||!At(e.summary,1e3)||!["candidate","stable","deprecated"].includes(e.maturity)||!Xr(e.source)||!Zr(e.source,["repository","path","revision","treeDigest"])||!At(e.source.repository)||!Zc(e.source.path)||!At(e.source.revision,200)||!Qc.test(String(e.source.treeDigest))||!$E(e.artifact)||!Xr(e.compatibility)||!Zr(e.compatibility,["node","packageManager"])||!At(e.compatibility.node,100)||!At(e.compatibility.packageManager,100)||!mm(e.exports)||!mm(e.consumerEvidence)||!Xr(e.documentation))return!1;let t=e.documentation.knowledgeRef===void 0?["readme"]:["readme","knowledgeRef"];return!Zr(e.documentation,t)||!Zc(e.documentation.readme)||e.documentation.knowledgeRef!==void 0&&!At(e.documentation.knowledgeRef,500)?!1:e.artifact!==null||e.maturity!=="stable"}function CE(e){let t={schemaVersion:1,kind:"PackageRelease",...e,source:Object.freeze({...e.source}),artifact:e.artifact===null?null:Object.freeze({...e.artifact}),compatibility:Object.freeze({...e.compatibility}),exports:Object.freeze([...e.exports]),documentation:Object.freeze({...e.documentation}),consumerEvidence:Object.freeze([...e.consumerEvidence])};if(!OE(t))throw new sa("PACKAGE_RELEASE_INVALID","PackageRelease \u5185\u5BB9\u65E0\u6548");return Object.freeze({...t,releaseDigest:v(E(t))})}function gm(e){if(!Xr(e)||!Zr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence","releaseDigest"])||!Qc.test(String(e.releaseDigest)))throw new sa("PACKAGE_RELEASE_INVALID","PackageRelease \u7ED3\u6784\u65E0\u6548");let{releaseDigest:t,schemaVersion:r,kind:n,...a}=e,i=CE(a);if(i.releaseDigest!==t)throw new sa("PACKAGE_RELEASE_MODIFIED","PackageRelease \u5DF2\u88AB\u4FEE\u6539");return i}import{lstat as TE,readFile as xE,realpath as LE}from"node:fs/promises";import hm from"node:path";async function ym(e){let t=await LE(hm.resolve(e.projectRoot)),r=new Set(e.excludeCapabilityIds??[]),n=new Map,a=[...e.lock.capabilities].sort((o,s)=>o.committedAt.localeCompare(s.committedAt)||o.capabilityId.localeCompare(s.capabilityId));for(let o of a)if(!r.has(o.capabilityId))for(let s of o.assets){let c=s.ownership??"owned-file",d=`${s.path}\0`;if(c==="managed-region")n.delete(d);else for(let p of n.keys())p.startsWith(d)&&n.delete(p);let l=c==="managed-region"?`${d}${s.regionId??""}`:d;n.set(l,{capabilityId:o.capabilityId,path:s.path,digest:s.digest,ownership:c,...s.regionId===void 0?{}:{regionId:s.regionId}})}let i=[];for(let o of[...n.values()].sort((s,c)=>s.path.localeCompare(c.path)||(s.regionId??"").localeCompare(c.regionId??"")||s.capabilityId.localeCompare(c.capabilityId))){let s=hm.join(t,...o.path.split("/")),d=await TE(s).then(async l=>{if(!l.isFile()||l.isSymbolicLink())return;let p=await xE(s);if(o.ownership!=="managed-region")return v(p);if(o.regionId!==void 0)try{return v(Xa(p.toString("utf8"),o.regionId))}catch{return}}).catch(l=>l.code==="ENOENT"?void 0:Promise.reject(l))===o.digest;i.push({capabilityId:o.capabilityId,path:o.path,kind:"create",ownership:o.ownership,...o.regionId===void 0?{}:{regionId:o.regionId},desiredDigest:o.digest,disposition:d?"noop":"conflict",...d?{}:{conflictCode:"BASE_DIGEST_MISMATCH"}})}return i}var el="0.1.18",ca={DEPENDENCIES_NOT_INSTALLED:4,VERIFIER_RUNTIME_INVALID:4},VE=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/u;function wm(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!VE.test(e)}function ME(e){let t={schemaVersion:1,kind:"dyyto-cli-domain-error",code:e.code,message:e.message,exitCode:ca[e.code],...e.nextStep===void 0?{}:{nextStep:e.nextStep}},r=qE(t);if(r===null)throw new TypeError("CLI domain error input is invalid");return r}function qE(e){try{if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype)return null;let t=Object.getOwnPropertyDescriptors(e);if(Reflect.ownKeys(t).some(s=>typeof s=="symbol"))return null;let r=Object.keys(t).sort(),n="nextStep"in t?["code","exitCode","kind","message","nextStep","schemaVersion"]:["code","exitCode","kind","message","schemaVersion"];if(r.length!==n.length||r.some((s,c)=>s!==n[c])||Object.values(t).some(s=>!("value"in s)))return null;let a=s=>t[s]?.value,i=a("code");if(a("schemaVersion")!==1||a("kind")!=="dyyto-cli-domain-error"||typeof i!="string"||!(i in ca)||a("exitCode")!==ca[i]||!wm(a("message"),500))return null;let o=a("nextStep");return o!==void 0&&!wm(o,500)?null:Object.freeze({schemaVersion:1,kind:"dyyto-cli-domain-error",code:i,message:a("message"),exitCode:4,...o===void 0?{}:{nextStep:o}})}catch{return null}}var Ce=class extends Error{code;exitCode;nextStep;domainError;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.exitCode=t.exitCode,this.nextStep=t.nextStep,this.domainError=t.code in ca&&t.exitCode===ca[t.code]?ME({code:t.code,message:t.message,...t.nextStep===void 0?{}:{nextStep:t.nextStep}}):void 0}};var vm=`Dyyto Engineering Platform CLI
25
+ `)}function Gk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run",check:"pnpm typecheck && pnpm test && pnpm build",start:"node dist/index.js"},devDependencies:{"@types/node":"24.10.13",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
26
+ `)}function Wk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"vite",build:"tsc -b && vite build",preview:"vite preview",typecheck:"tsc -b --pretty false",test:"vitest run",check:"pnpm typecheck && pnpm test && pnpm build"},dependencies:{react:"19.2.8","react-dom":"19.2.8"},devDependencies:{"@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",jsdom:"30.0.1",typescript:"6.0.3",vite:"8.2.1",vitest:"4.1.10"}},null,2)}
27
+ `)}function Kk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"next dev",build:"next build",start:"node .artifacts/standalone/server.js",typecheck:"tsc --noEmit",lint:"eslint .","test:unit":"vitest run","test:e2e":"playwright test",test:"pnpm test:unit && pnpm test:e2e",package:"pnpm build && node tooling/package-standalone.mjs",check:"pnpm lint && pnpm typecheck && pnpm test:unit && pnpm build"},dependencies:{next:"16.2.11",react:"19.2.8","react-dom":"19.2.8","server-only":"0.0.1"},devDependencies:{"@playwright/test":"1.62.1","@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",eslint:"9.39.5","eslint-config-next":"16.2.11",jsdom:"30.0.1",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
28
+ `)}function Yk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,main:"expo-router/entry",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"expo start",android:"expo start --android",ios:"expo start --ios",web:"expo start --web",build:"expo export --platform web --output-dir dist",package:"corepack pnpm build && node tooling/verify-expo-export.mjs",typecheck:"tsc --noEmit",test:"vitest run",check:"corepack pnpm typecheck && corepack pnpm test && corepack pnpm package"},dependencies:{expo:"~57.0.15","expo-router":"~57.0.15","expo-status-bar":"~57.0.1",react:"19.2.3","react-dom":"19.2.3","react-native":"0.86.2","react-native-safe-area-context":"5.9.1","react-native-screens":"4.27.0","react-native-web":"0.21.2"},devDependencies:{"@types/node":"24.10.13","@types/react":"19.2.14",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
29
+ `)}async function zu(e,t){let r=zn.join(e,...t.split("/"));try{let n=await qk(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Managed target must be a regular file",t);return{path:t,exists:!0,digest:v(await Rc(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function ur(e,t){let r=W(e.manifest),n=t==="workspace-node-application"||t==="workspace-web-application"||t==="workspace-expo-application"||t==="nextjs-full-stack-application"?t==="workspace-web-application"?Wk(pr(r).name):t==="workspace-expo-application"?Yk(pr(r).name):t==="nextjs-full-stack-application"?Kk(pr(r).name):Gk(pr(r).name):t==="react-component-library"?Nc(Ut(r,t)):Pc(Ut(r,t));if(r.capabilities.filter(u=>u.capabilityId===e.release.release.capabilityId&&u.version===e.release.release.version).length!==1||e.release.release.consumerProfile!==t)throw new M("RELEASE_NOT_FOUND","Manifest must select exactly the loaded standalone npm release");let o=(e.currentLock===void 0?void 0:Oe(e.currentLock))?.capabilities.find(u=>u.capabilityId===e.release.release.capabilityId);if(o!==void 0&&(o.version!==e.release.release.version||o.integrity!==e.release.release.integrity))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Changing locked npm profile parameters or release is not supported");let s=new Map(e.release.contents);s.set("package.json",n);let c=await Fu(zn.resolve(e.projectRoot)),d=[],l=[];for(let u of e.release.release.assets){if(s.get(u.path)===void 0)throw new M("RELEASE_NOT_FOUND","Release asset content is unavailable",u.path);let g=await zu(c,u.path);if(g.exists&&o===void 0&&e.allowExistingWithoutLock!==!0&&u.ownership!=="seed-file")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Profile cannot adopt over an existing owned file without a lock",u.path);u.ownership==="seed-file"&&g.exists&&s.set(u.path,await Rc(zn.join(c,...u.path.split("/"))));let h=v(s.get(u.path));d.push(g),l.push({path:u.path,kind:"create",ownership:u.ownership,desiredDigest:h})}let p={schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:l.map(u=>({path:u.path,ownership:u.ownership,desiredDigest:u.desiredDigest})),verifiers:e.release.release.verifiers.map(({id:u})=>({id:u,kind:"command"}))},m=Ne({action:"adopt",capability:p,changes:l,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{manifest:r,release:e.release,plan:m,desiredContents:s}}function Bn(e){return ur(e,"standalone-npm-package")}function Jn(e){return ur(e,"react-component-library")}function Kr(e){return ur(e,"nextjs-full-stack-application")}async function Dc(e){let t=W(e.manifest);if(t.profile?.id!=="nextjs-full-stack-application"||e.release.release.consumerProfile!=="nextjs-full-stack-application"||e.release.release.assets.some(u=>u.ownership!=="seed-file"))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Historical adoption requires a seed-only Next.js Profile Release");let r=W({...t,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}),n=await Kr({...e,manifest:r}),a=await Fu(zn.resolve(e.projectRoot)),i="project-capabilities.json",o=await Rc(zn.join(a,i)),s=Buffer.from(`${JSON.stringify(r,null,2)}
30
+ `),c=n.plan.operations.map(({disposition:u,conflictCode:f,...g})=>g);c.push({path:i,kind:"replace",ownership:"owned-file",baseDigest:v(o),desiredDigest:v(s)});let d=await Promise.all(c.map(u=>zu(a,u.path))),l=Ne({action:"adopt",capability:{schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:c.filter(u=>u.path!==i).map(u=>({path:u.path,ownership:u.ownership,desiredDigest:u.desiredDigest})),verifiers:e.release.release.verifiers.map(({id:u})=>({id:u,kind:"command"}))},changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),p=new Map([...n.desiredContents,[i,s]]),m=new Map;for(let u of l.operations)u.disposition==="ready"&&u.kind!=="remove"&&m.set(u.path,p.get(u.path));return{...n,manifest:r,plan:l,desiredContents:m}}function Gn(e){return ur(e,"workspace-npm-package")}function Wn(e){return ur(e,"workspace-node-application")}function Kn(e){return ur(e,"workspace-web-application")}function Yn(e){return ur(e,"workspace-expo-application")}async function Bu(e){if(e.currentLock!==void 0){let n=await Bn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Bn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Ju(e){if(e.currentLock!==void 0){let n=await Jn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Jn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Gu(e){if(e.currentLock!==void 0){let n=await Kr(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Kr({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Wu(e){if(e.currentLock!==void 0){let n=await Gn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Gn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Ku(e){if(e.currentLock!==void 0){let n=await Wn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Wn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Yu(e){if(e.currentLock!==void 0){let n=await Kn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Kn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Hu(e){if(e.currentLock!==void 0){let n=await Yn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Yn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}import{lstat as b_,readFile as Oi,realpath as k_}from"node:fs/promises";import Xn from"node:path";var ot=class extends Error{code;constructor(t,r){super(r),this.code=t}},fr=/^sha256:[a-f0-9]{64}$/,Hk=/^sha512-[A-Za-z0-9+/]{86}==$/,Xk=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/,Zu=/^registry\.[a-z0-9][a-z0-9.-]{1,126}$/,Zk=/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/,Xu=/^[a-z][a-z0-9._:-]{2,127}$/;function mr(e,t){let r=Object.keys(e).sort();return r.length===t.length&&r.every((n,a)=>n===[...t].sort()[a])}function Qk(e){if(!mr(e,["registryId","tenantId","origin","scopes","authentication","capabilities","status"])||!Zu.test(e.registryId)||!Xu.test(e.tenantId)||e.scopes.length===0||e.scopes.length>32||e.scopes.some((n,a)=>!/^@[a-z0-9][a-z0-9._-]*$/.test(n)||e.scopes.indexOf(n)!==a)||!mr(e.authentication,e.authentication.credentialRef===void 0?["kind"]:["kind","credentialRef"])||!mr(e.capabilities,["read","write","provenance","staging"])||!["workload-identity","short-lived-token","restricted-token","anonymous-test"].includes(e.authentication.kind)||e.authentication.kind==="anonymous-test"!=(e.authentication.credentialRef===void 0)||e.authentication.credentialRef!==void 0&&!Xu.test(e.authentication.credentialRef))return!1;let t;try{t=new URL(e.origin)}catch{return!1}if(t.username||t.password||t.search||t.hash||!t.pathname.endsWith("/")||t.pathname.includes("..")||/%2f|%5c/iu.test(t.pathname))return!1;let r=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]";return e.authentication.kind==="anonymous-test"&&(!r||t.protocol!=="http:")||e.authentication.kind!=="anonymous-test"&&t.protocol!=="https:"?!1:typeof e.capabilities.read=="boolean"&&typeof e.capabilities.write=="boolean"&&typeof e.capabilities.provenance=="boolean"&&typeof e.capabilities.staging=="boolean"&&(e.status==="enabled"||e.status==="disabled")}function e_(e){if(!Qk(e))throw new ot("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,scopes:Object.freeze([...e.scopes]),authentication:Object.freeze({...e.authentication}),capabilities:Object.freeze({...e.capabilities}),revision:v(E(t))})}function wi(e){let t=e;if(typeof t!="object"||t===null||!mr(t,["schemaVersion","revision","registryId","tenantId","origin","scopes","authentication","capabilities","status"])||t.schemaVersion!==1||!fr.test(t.revision))throw new ot("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let{schemaVersion:r,revision:n,...a}=t;if(e_(a).revision!==n)throw new ot("REGISTRY_CONFIG_INVALID","Registry configuration has been modified");return t}function t_(e,t){let r,n;try{r=new URL(e.origin),n=new URL(t)}catch{return!1}return n.username||n.password||n.search||n.hash||n.pathname!==r.pathname||n.protocol!==r.protocol||n.hostname!==r.hostname?!1:e.authentication.kind==="anonymous-test"||n.port===r.port}function r_(e,t){let r=wi(t);if(!mr(e,["registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||e.registryId!==r.registryId||e.registryConfigRevision!==r.revision||!t_(r,e.origin)||Number.isNaN(Date.parse(e.resolvedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.resolvedAt))throw new ot("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let n={schemaVersion:1,...e};return Object.freeze({...n,bindingDigest:v(E(n))})}function Qu(e,t){let r=e;if(typeof r!="object"||r===null||!mr(r,["schemaVersion","bindingDigest","registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||r.schemaVersion!==1||!fr.test(r.bindingDigest))throw new ot("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let{schemaVersion:n,bindingDigest:a,...i}=r;if(r_(i,t).bindingDigest!==a)throw new ot("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding has been modified");return r}function n_(e){let t=["registryId","registryConfigRevision","packageName","version","integrity","tarballDigest","access","provenance","sourceDeliveryReceiptId","verifiedAt",...e.verificationIdentityDigest===void 0?[]:["verificationIdentityDigest"]];return mr(e,t)&&Zu.test(e.registryId)&&fr.test(e.registryConfigRevision)&&Zk.test(e.packageName)&&Xk.test(e.version)&&Hk.test(e.integrity)&&fr.test(e.tarballDigest)&&fr.test(e.sourceDeliveryReceiptId)&&!Number.isNaN(Date.parse(e.verifiedAt))&&(e.access==="restricted"||e.access==="private")&&["registry-attested","external-attested","local-readback-verified","development-readback-verified","registry-verified-no-attestation"].includes(e.provenance)&&(e.provenance!=="registry-verified-no-attestation"?e.verificationIdentityDigest!==void 0&&fr.test(e.verificationIdentityDigest):e.verificationIdentityDigest===void 0)}function ef(e){if(!n_(e))throw new ot("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,receiptId:v(E(t))})}function tf(e){let t=e;if(typeof t!="object"||t===null||t.schemaVersion!==1||!fr.test(t.receiptId))throw new ot("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let{schemaVersion:r,receiptId:n,...a}=t;if(ef(a).receiptId!==n)throw new ot("PACKAGE_RECEIPT_INVALID","Package delivery receipt has been modified");return t}var Se=class extends Error{code;constructor(t){super(t),this.code=t,this.name="ResolutionEvidenceError"}};function jc(e){return v(E(e))}var Sc=/^sha256:[a-f0-9]{64}$/u,a_=/^sha512-[A-Za-z0-9+/]{86}==$/u,i_=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,vi=/^[a-z0-9][a-z0-9._/-]{0,255}$/u,o_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,s_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@[0-9][a-zA-Z0-9.+()_@/-]*$/u;function Ii(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((a,i)=>a===n[i])}function c_(e){return v(E(e))}function l_(e){if(!Ii(e,["schemaVersion","jobId","workerReleaseId","workerStateRevision","requestDigest","pnpmVersion","desiredLockfile","desiredLockDigest","importerFacts","packageFacts","snapshotClosureDigest","networkObservationDigest","cacheObservation","commandDigest","completedAt","expiresAt"])||e.schemaVersion!==1||e.pnpmVersion!=="11.21.0")throw new Se("RESOLUTION_EVIDENCE_INVALID");if(![e.jobId,e.workerStateRevision,e.requestDigest,e.desiredLockDigest,e.snapshotClosureDigest,e.networkObservationDigest,e.commandDigest,e.cacheObservation.preimageRevision,e.cacheObservation.desiredRevision,e.cacheObservation.writesDigest].every(a=>Sc.test(a)))throw new Se("RESOLUTION_EVIDENCE_INVALID");if(!vi.test(e.workerReleaseId)||!vi.test(e.cacheObservation.namespace)||e.desiredLockfile.byteLength===0||v(e.desiredLockfile)!==e.desiredLockDigest||Number.isNaN(Date.parse(e.completedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.completedAt))throw new Se("RESOLUTION_EVIDENCE_INVALID");if(!Ii(e.cacheObservation,["namespace","preimageRevision","desiredRevision","writesDigest"])||e.importerFacts.length===0||e.packageFacts.length===0)throw new Se("RESOLUTION_EVIDENCE_INVALID");if(e.importerFacts.some(a=>!Ii(a,["importerId","manifestDigest","preimageDigest","desiredDigest"])||a.importerId!=="."&&!vi.test(a.importerId)||![a.manifestDigest,a.preimageDigest,a.desiredDigest].every(i=>Sc.test(i))))throw new Se("RESOLUTION_EVIDENCE_INVALID");if(e.packageFacts.some(a=>!Ii(a,["identity","packageName","version","integrity","registryId","managed","edgesDigest"])||!s_.test(a.identity)||!o_.test(a.packageName)||!vi.test(a.registryId)||!i_.test(a.version)||!a_.test(a.integrity)||typeof a.managed!="boolean"||!Sc.test(a.edgesDigest)))throw new Se("RESOLUTION_EVIDENCE_INVALID");if(new Set(e.importerFacts.map(a=>a.importerId)).size!==e.importerFacts.length||new Set(e.packageFacts.map(a=>a.identity)).size!==e.packageFacts.length)throw new Se("RESOLUTION_EVIDENCE_INVALID");let{jobId:t,desiredLockfile:r,...n}=e;if(c_(n)!==e.jobId)throw new Se("RESOLUTION_EVIDENCE_INVALID")}function $c(e,t){if(l_(e),Date.parse(t.now)>Date.parse(e.expiresAt))throw new Se("RESOLUTION_EVIDENCE_EXPIRED");if(e.requestDigest!==t.requestDigest||e.pnpmVersion!==t.pnpmVersion||e.workerReleaseId!==t.workerReleaseId)throw new Se("RESOLUTION_EVIDENCE_INVALID");let r=e.importerFacts.find(n=>n.importerId===t.targetImporterId);if(!r||r.manifestDigest!==t.targetManifestDigest)throw new Se("RESOLUTION_EVIDENCE_IMPORTER_DRIFT");for(let n of t.preservedImporterDigests){let a=e.importerFacts.find(i=>i.importerId===n.importerId);if(!a||a.preimageDigest!==n.preimageDigest||a.desiredDigest!==n.preimageDigest)throw new Se("RESOLUTION_EVIDENCE_IMPORTER_DRIFT")}for(let n of t.managedSources){let a=e.packageFacts.filter(i=>i.managed&&i.packageName===n.packageName);if(a.length!==1||a[0].registryId!==n.registryId||a[0].version!==n.version||a[0].integrity!==n.integrity)throw new Se("RESOLUTION_EVIDENCE_SOURCE_MISMATCH")}if(e.packageFacts.filter(n=>n.managed).length!==t.managedSources.length)throw new Se("RESOLUTION_EVIDENCE_SOURCE_MISMATCH");return e}var Y=class extends Error{code;constructor(t,r){super(t,r),this.code=t,this.name="PackageAdoptionError"}};function _i(e){let t={sourceChannel:e.sourceChannel,packageJsonPreimageDigest:e.packageJsonPreimageDigest,desiredPackageJsonDigest:e.desiredPackageJsonDigest,lockfilePreimage:{...e.lockfilePreimage},desiredLockfileDigest:e.desiredLockfileDigest,registryRevisions:e.registryRevisions.map(r=>({...r})),endpointBindings:e.endpointBindings.map(({registryId:r,registryConfigRevision:n,bindingDigest:a,expiresAt:i})=>({registryId:r,registryConfigRevision:n,bindingDigest:a,expiresAt:i})),sources:e.sources.map(r=>({...r})),installPolicy:{...e.installPolicy}};if(e.schemaVersion===1)return{schemaVersion:1,...t};if(!e.topology||!e.preservedDependencies||!e.preservedImporterDigests)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");return{schemaVersion:2,...t,topology:{...e.topology},preservedDependencies:e.preservedDependencies.map(r=>({...r})),preservedImporterDigests:e.preservedImporterDigests.map(r=>({...r}))}}var bi=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u,rf=/^(?:workspace:|file:|link:|git(?:\+|:)|https?:|npm:)|[~^*<>=|]/u;function Oc(e){return Array.isArray(e)?`[${e.map(Oc).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Oc(r)}`).join(",")}}`:JSON.stringify(e)}function Et(e){let t;try{t=JSON.parse(Buffer.from(e).toString("utf8"))}catch{throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}if(!t||typeof t!="object"||Array.isArray(t))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");return t}function Ze(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let t=Object.entries(e);if(t.some(([,r])=>typeof r!="string"))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");return Object.fromEntries(t)}function ki(e){for(let t of[Ze(e.dependencies),Ze(e.devDependencies),Ze(e.optionalDependencies)])for(let[r,n]of Object.entries(t))if(r.startsWith("@aipt/")&&(!bi.test(n)||rf.test(n)))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}var d_=["dependencies","devDependencies","optionalDependencies"];function Ei(e,t){let r=[];for(let n of d_)for(let[a,i]of Object.entries(Ze(e[n]))){if(t.has(a)){if(!bi.test(i))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");continue}if(/^(?:file:|link:|git(?:\+|:)|https?:|npm:)/u.test(i))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");r.push({section:n,packageName:a,specifier:i})}return r.sort((n,a)=>`${n.section}:${n.packageName}`.localeCompare(`${a.section}:${a.packageName}`))}function Cc(e){let t=Et(e.packageJson);ki(t);let r=Object.fromEntries(e.release.packageSources.filter(({usage:i})=>i==="runtime").map(({packageName:i,version:o})=>[i,o])),n=Object.fromEntries(e.release.packageSources.filter(({usage:i})=>i==="development").map(({packageName:i,version:o})=>[i,o])),a={...t,...Object.keys(r).length?{dependencies:{...Ze(t.dependencies),...r}}:{},...Object.keys(n).length?{devDependencies:{...Ze(t.devDependencies),...n}}:{}};return Buffer.from(`${JSON.stringify(a,null,2)}
31
+ `)}function Hn(e){let t=Et(e.packageJson);Ei(t,new Set(e.release.packageSources.map(a=>a.packageName)));let r=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="runtime").map(({packageName:a,version:i})=>[a,i])),n=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="development").map(({packageName:a,version:i})=>[a,i]));return Buffer.from(`${JSON.stringify({...t,...Object.keys(r).length?{dependencies:{...Ze(t.dependencies),...r}}:{},...Object.keys(n).length?{devDependencies:{...Ze(t.devDependencies),...n}}:{}},null,2)}
32
+ `)}function Tc(e){let t=Et(e.packageJson);ki(t);let r=Ze(t.dependencies),n=Ze(t.devDependencies);for(let i of e.remove)delete(i.usage==="runtime"?r:n)[i.packageName];let a={...t};return Object.keys(r).length===0?delete a.dependencies:a.dependencies=r,Object.keys(n).length===0?delete a.devDependencies:a.devDependencies=n,Buffer.from(`${JSON.stringify(a,null,2)}
33
+ `)}function xc(e){let t=Et(e.packageJson);Ei(t,new Set(e.remove.map(i=>i.packageName)));let r=Ze(t.dependencies),n=Ze(t.devDependencies);for(let i of e.remove)delete(i.usage==="runtime"?r:n)[i.packageName];let a={...t};return Object.keys(r).length===0?delete a.dependencies:a.dependencies=r,Object.keys(n).length===0?delete a.devDependencies:a.devDependencies=n,Buffer.from(`${JSON.stringify(a,null,2)}
34
+ `)}function nf(e){let t=e.currentLock.capabilities.find(p=>p.capabilityId===e.release.capabilityId&&p.version===e.release.version);if(!t?.packageAdoption)throw new Y("PACKAGE_SOURCE_NOT_FOUND");let r=new Set(e.currentLock.capabilities.filter(p=>p!==t).flatMap(p=>p.packageAdoption?.sources.map(m=>m.packageName)??[])),n=t.packageAdoption.sources.filter(p=>!r.has(p.packageName)),a=Tc({packageJson:e.packageJson,remove:n}),i=Et(e.projectManifest),o=Array.isArray(i.capabilities)?i.capabilities:[],s=Buffer.from(`${JSON.stringify({...i,capabilities:o.filter(p=>p.capabilityId!==e.release.capabilityId||p.version!==e.release.version)},null,2)}
35
+ `),c=e.endpointBindings.filter(p=>n.some(m=>m.registryId===p.registryId)),d=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(s)},{path:"package.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(a)},{path:"pnpm-lock.yaml",kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:v(e.desiredLockfile)},...t.assets.map(p=>({path:p.path,kind:"remove",ownership:p.ownership??"owned-file",baseDigest:p.digest}))];return{plan:Ne({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(p=>({path:p.path,ownership:p.ownership??"owned-file",desiredDigest:p.digest})),verifiers:e.release.verifiers.map(p=>({id:p.id,kind:"file-digest"}))},changes:d,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:1,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(a),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:v(e.desiredLockfile),registryRevisions:t.packageAdoption.registryRevisions.map(p=>({...p})),endpointBindings:c.map(({registryId:p,registryConfigRevision:m,bindingDigest:u,expiresAt:f})=>({registryId:p,registryConfigRevision:m,bindingDigest:u,expiresAt:f})),sources:n.map(p=>({...p})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}}}),desiredContents:new Map([["project-capabilities.json",s],["package.json",a],["pnpm-lock.yaml",e.desiredLockfile]]),removedSources:n}}function af(e){let t=e.currentLock.capabilities.find(g=>g.capabilityId===e.release.capabilityId&&g.version===e.release.version);if(!t?.packageAdoption||e.topology.mode!=="pnpm-shared-lockfile")throw new Y("PACKAGE_SOURCE_NOT_FOUND");let r=new Set(e.currentLock.capabilities.filter(g=>g!==t).flatMap(g=>g.packageAdoption?.sources.map(h=>h.packageName)??[])),n=t.packageAdoption.sources.filter(g=>!r.has(g.packageName)),a=xc({packageJson:e.packageJson,remove:n}),i=e.remainingSources.map(({registryId:g,packageName:h,version:w,integrity:_})=>({registryId:g,packageName:h,version:w,integrity:_})),o={mode:e.topology.mode,unitRelativeRoot:e.topology.unitRelativeRoot,unitImporterId:e.topology.unitImporterId,lockfilePath:e.topology.lockfilePath,...e.topology.workspaceManifestPath?{workspaceManifestPath:e.topology.workspaceManifestPath,workspaceManifestDigest:e.topology.workspaceManifestDigest}:{}},s=$c(e.resolutionEvidence,{requestDigest:jc({schemaVersion:1,pnpmVersion:"11.21.0",topology:o,currentLockfileDigest:v(e.currentLockfile),desiredPackageJsonDigest:v(a),sources:i,preservedImporterDigests:e.preservedImporterDigests.map(({importerId:g,preimageDigest:h})=>({importerId:g,preimageDigest:h}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(a),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:g,preimageDigest:h})=>({importerId:g,preimageDigest:h})),managedSources:i,now:e.generatedAt}),c=Et(e.projectManifest),d=Array.isArray(c.capabilities)?c.capabilities:[],l=Buffer.from(`${JSON.stringify({...c,capabilities:d.filter(g=>g.capabilityId!==e.release.capabilityId||g.version!==e.release.version)},null,2)}
36
+ `),p=g=>`${e.topology.unitRelativeRoot}/${g}`,m=e.endpointBindings.filter(g=>n.some(h=>h.registryId===g.registryId)),u=[{path:p("project-capabilities.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(l)},{path:p("package.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(a)},{path:e.topology.lockfilePath,kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:s.desiredLockDigest},...t.assets.map(g=>({path:p(g.path),kind:"remove",ownership:g.ownership??"owned-file",baseDigest:g.digest}))];return{plan:Ne({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(g=>({path:g.path,ownership:g.ownership??"owned-file",desiredDigest:g.digest})),verifiers:e.release.verifiers.map(g=>({id:g.id,kind:"file-digest"}))},changes:u,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:2,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(a),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:s.desiredLockDigest,registryRevisions:t.packageAdoption.registryRevisions.map(g=>({...g})),endpointBindings:m.map(({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})=>({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})),sources:n.map(g=>({...g})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1},topology:o,preservedDependencies:Ei(Et(a),new Set(e.remainingSources.map(g=>g.packageName))),preservedImporterDigests:e.preservedImporterDigests.map(g=>({...g}))}}),desiredContents:new Map([[p("project-capabilities.json"),l],[p("package.json"),a],[e.topology.lockfilePath,s.desiredLockfile]]),removedSources:n,transactionRoot:e.transactionRoot}}function Ai(e,t){let r=e.release.availability,n=r.maturity==="available"&&r.visibility==="catalog-consumers"&&r.sourceState==="registry-verified",a=r.maturity==="candidate"&&r.visibility==="maintainers-only"&&r.sourceState==="development-registry";if((t==="production"?!n:!a)||e.release.packageSources.length===0)throw new Y("PACKAGE_SOURCE_NOT_FOUND");let i=Et(e.packageJson),o=e.desiredBasePackageJson??e.packageJson,s=Et(o),c="topology"in e,d=c?Ei(s,new Set(e.release.packageSources.map(y=>y.packageName))):void 0;c||ki(i),c||ki(s);let l=new Map(e.registryConfigs.map(y=>{let k=wi(y);return[k.registryId,k]})),p=new Map(e.endpointBindings.map(y=>{let k=l.get(y.registryId);if(k===void 0)throw new Y("PACKAGE_SOURCE_NOT_FOUND");let S=Qu(y,k);return[S.registryId,S]})),m=new Map(e.receipts.map(y=>{let k=tf(y);return[k.receiptId,k]})),u=new Map(e.inspections.map(y=>[`${y.registryId}:${y.packageName}@${y.version}`,y])),f=new Map(e.release.packageSources.map(y=>[y.packageName,y])),g=c?$c(e.resolutionEvidence,{requestDigest:jc({schemaVersion:1,pnpmVersion:"11.21.0",topology:e.topology,currentLockfileDigest:e.currentLockfile===void 0?null:v(e.currentLockfile),desiredPackageJsonDigest:v(Hn({release:e.release,packageJson:o})),sources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(Hn({release:e.release,packageJson:o})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k})),managedSources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),now:e.generatedAt}):void 0,h=c?{lockfile:g.desiredLockfile,packages:g.packageFacts.filter(y=>y.managed).map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O}))}:e.lockResolution;if(h.lockfile.byteLength===0||h.packages.length!==e.release.packageSources.length)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`managed resolution count ${h.packages.length}/${e.release.packageSources.length}`)});let w=new Map(h.packages.map(y=>[y.packageName,y]));for(let y of e.release.packageSources){let k=l.get(y.registryId),S=p.get(y.registryId),O=m.get(y.deliveryReceiptId),ie=u.get(`${y.registryId}:${y.packageName}@${y.version}`),$=w.get(y.packageName);if(O!==void 0&&(t==="production"&&O.provenance==="development-readback-verified"||t==="development"&&O.provenance!=="development-readback-verified"))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");if(!k||!S||Date.parse(S.expiresAt)<=Date.parse(e.expiresAt)||k.status!=="enabled"||!k.scopes.some(P=>y.packageName.startsWith(`${P}/`))||!O||!ie||!$)throw new Y("PACKAGE_SOURCE_NOT_FOUND");if(O.registryId!==y.registryId||O.registryConfigRevision!==k.revision||O.packageName!==y.packageName||O.version!==y.version||O.integrity!==y.integrity||O.tarballDigest!==y.tarballDigest||ie.integrity!==y.integrity||ie.tarballDigest!==y.tarballDigest||ie.deliveryReceiptId!==y.deliveryReceiptId||$.registryId!==y.registryId||$.version!==y.version||$.integrity!==y.integrity)throw new Y("PACKAGE_SOURCE_INTEGRITY_MISMATCH");if(!bi.test(y.version)||ie.lifecycleScripts.length>0)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");for(let[P,K]of Object.entries(ie.dependencies)){let re=f.get(P);if(P.startsWith("@aipt/")&&(!re||re.version!==K||!bi.test(K)))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`undeclared internal dependency ${y.packageName}->${P}@${K}`)});if(rf.test(K))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}}let _=c?Hn({release:e.release,packageJson:o}):Cc({release:e.release,packageJson:o}),b={schemaVersion:c?2:1,sourceChannel:t,capabilityId:e.release.capabilityId,capabilityVersion:e.release.version,capabilityIntegrity:e.release.integrity,consumerProfile:e.consumerProfile,generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(_),lockfilePreimage:Object.freeze(e.currentLockfile===void 0?{kind:"absent"}:{kind:"present",digest:v(e.currentLockfile)}),desiredLockfileDigest:v(h.lockfile),registryRevisions:Object.freeze([...l.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,revision:k})=>Object.freeze({registryId:y,revision:k})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),endpointBindings:Object.freeze([...p.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})=>Object.freeze({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),sources:Object.freeze(e.release.packageSources.map(y=>Object.freeze({...y}))),installPolicy:Object.freeze({ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}),...c?{topology:Object.freeze({...e.topology}),preservedDependencies:Object.freeze(d.map(y=>Object.freeze({...y}))),preservedImporterDigests:Object.freeze(e.preservedImporterDigests.map(y=>Object.freeze({...y})))}:{}},A=v(Oc(b));return Object.freeze({...b,planId:A,desiredPackageJson:_,desiredLockfile:h.lockfile})}function Ri(e){return Ai(e,"production")}function Pi(e){return Ai(e,"development")}function Ni(e){return Ai(e,"production")}function Di(e){return Ai(e,"development")}function p_(e){let t=e.packageAdoption;if(t===void 0)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let r=t.schemaVersion===2&&t.topology.mode==="pnpm-shared-lockfile"?`${t.topology.unitRelativeRoot}/package.json`:"package.json",n=t.schemaVersion===2?t.topology.lockfilePath:"pnpm-lock.yaml",a=e.operations.filter(({path:l})=>l===r),i=e.operations.filter(({path:l})=>l===n);if(a.length!==1||i.length!==1)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let o=a[0],s=i[0],c=o.kind==="replace"&&o.baseDigest===t.packageJsonPreimageDigest&&o.desiredDigest===t.desiredPackageJsonDigest&&o.disposition==="ready",d=s.kind===(t.lockfilePreimage.kind==="absent"?"create":"replace")&&(t.lockfilePreimage.kind==="absent"?s.baseDigest===void 0:s.baseDigest===t.lockfilePreimage.digest)&&s.desiredDigest===t.desiredLockfileDigest&&s.disposition==="ready";if(!c||!d)throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION")}async function of(e){p_(e.plan);let t=!1;try{await e.packageManager.prepare({projectRoot:e.projectRoot,plan:e.plan});let r=await Br({projectRoot:e.projectRoot,plan:e.plan,approvedPlanId:e.approvedPlanId,desiredContents:e.desiredContents,now:e.now}),n=await Jr(r);return t=!0,await e.packageManager.install({projectRoot:e.projectRoot,plan:e.plan}),await e.packageManager.verify({projectRoot:e.projectRoot,plan:e.plan}),n}catch(r){if(t){await uc({projectRoot:e.projectRoot,planId:e.plan.planId,now:new Date().toISOString(),failureCode:"PACKAGE_INSTALL_FAILED"});try{await e.packageManager.restore({projectRoot:e.projectRoot,plan:e.plan})}catch(n){throw new Y("PACKAGE_INSTALL_RECOVERY_REQUIRED",{cause:n})}}throw r}finally{await e.packageManager.cleanup({projectRoot:e.projectRoot,plan:e.plan})}}var df=Ir(rr(),1);var pf=["workspace-node-application","workspace-web-application","nextjs-full-stack-application"],uf="^[a-z0-9][a-z0-9._-]{0,127}$",Lc="^[A-Z][A-Z0-9_]{0,127}$",sf="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)\\.(?:/|$))(?!.*\\\\)(?!.*[\\u0000-\\u001f]).+$",u_={$id:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","kind","application","configDirectory","bindings"],properties:{$schema:{const:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json"},schemaVersion:{const:1},kind:{const:"ApplicationConfigContract"},application:{type:"object",additionalProperties:!1,required:["id","profile"],properties:{id:{type:"string",pattern:uf},profile:{enum:pf}}},configDirectory:{type:"object",additionalProperties:!1,required:["rootEnvironmentVariable","relativeDirectory","environmentFile","materializationOwner"],properties:{rootEnvironmentVariable:{const:"IDP_CONFIG_DIR"},relativeDirectory:{type:"string",pattern:"^applications/[a-z0-9][a-z0-9._-]{0,127}$"},environmentFile:{const:".env"},materializationOwner:{const:"external-deployment-control-plane"}}},bindings:{type:"array",maxItems:128,items:{oneOf:[{type:"object",additionalProperties:!1,required:["name","kind","required"],properties:{name:{type:"string",pattern:Lc},kind:{const:"value"},required:{type:"boolean"},default:{type:"string",maxLength:1024}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Lc},kind:{const:"secret-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:sf}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Lc},kind:{const:"certificate-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:sf}}}]}}}},cf=new df.Ajv2020({allErrors:!0,strict:!0}).compile(u_),lf=/(?:^|_)(?:PASSWORD|PASSWD|TOKEN|SECRET|PRIVATE_KEY|ACCESS_KEY|API_KEY|DATABASE_URL|CONNECTION_STRING|DSN|AUTHORIZATION|CREDENTIALS?)(?:_|$)/u,f_=/(?:^|_)(?:PRIVATE_KEY|PRIVATE|KEYPAIR|KEYSTORE|PKCS12|P12|PFX|KEY)(?:_|$)/u,qe=class extends Error{code;issues;constructor(t,r,n=[]){super(r),this.code=t,this.issues=n}};function ff(e){let t=W(e),r=t.profile?.id;if(!pf.includes(r))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","\u73AF\u5883\u914D\u7F6E\u5951\u7EA6\u53EA\u652F\u6301\u53EF\u90E8\u7F72 Application Profile\u3002");let n=t.profile?.parameters??{},a=n.name;if(Object.keys(n).length!==1||typeof a!="string"||!new RegExp(uf,"u").test(a))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","Application Manifest \u5FC5\u987B\u5305\u542B\u552F\u4E00\u4E14\u5408\u6CD5\u7684 name \u53C2\u6570\u3002");return{id:a,profile:r}}function Vc(e,t){if(!cf(e))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","Application ConfigContract \u4E0D\u7B26\u5408 v1 Schema\u3002",cf.errors??[]);let r=e;if(r.configDirectory.relativeDirectory!==`applications/${r.application.id}`)throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID","Config Dir \u76F8\u5BF9\u76EE\u5F55\u5FC5\u987B\u7531 Application identity \u552F\u4E00\u786E\u5B9A\u3002");let n=new Set,a=new Set;for(let i of r.bindings){if(n.has(i.name))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`\u73AF\u5883 Binding \u540D\u79F0\u91CD\u590D\uFF1A${i.name}`);if(n.add(i.name),i.kind==="value"){if(lf.test(i.name))throw new qe("APPLICATION_CONFIG_SECRET_LITERAL_FORBIDDEN",`\u654F\u611F\u914D\u7F6E ${i.name} \u5FC5\u987B\u4F7F\u7528\u6587\u4EF6 Binding\uFF0C\u7981\u6B62\u5728\u4ED3\u5E93\u4E2D\u58F0\u660E\u503C\u3002`);continue}if(!i.name.endsWith("_FILE"))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6587\u4EF6 Binding ${i.name} \u5FC5\u987B\u4EE5 _FILE \u7ED3\u5C3E\u3002`);let o=i.kind==="secret-file"?"secrets/":"certs/";if(i.kind==="certificate-file"&&(lf.test(i.name)||f_.test(i.name)))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`${i.name} \u5305\u542B\u79C1\u5BC6\u6750\u6599\u8BED\u4E49\uFF0C\u5FC5\u987B\u4F7F\u7528 secret-file \u5E76\u653E\u5165 secrets/\uFF1Bcertificate-file \u53EA\u5141\u8BB8\u516C\u5F00\u8BC1\u4E66\u3002`);let s=i.file.split("/");if(!i.file.startsWith(o)||s.some(c=>c===""||c==="."||c===".."))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`${i.name} \u5FC5\u987B\u4F4D\u4E8E ${o} \u4E0B\u7684\u5177\u4F53\u6587\u4EF6\u3002`);if(a.has(i.file))throw new qe("APPLICATION_CONFIG_CONTRACT_INVALID",`\u914D\u7F6E\u6587\u4EF6 Binding \u8DEF\u5F84\u91CD\u590D\uFF1A${i.file}`);a.add(i.file)}if(t!==void 0){let i=ff(t);if(r.application.id!==i.id||r.application.profile!==i.profile)throw new qe("APPLICATION_CONFIG_IDENTITY_MISMATCH","ConfigContract \u7684\u5E94\u7528\u8EAB\u4EFD\u6216 Profile \u4E0E Project Manifest \u4E0D\u4E00\u81F4\u3002")}return r}function Si(e){let t=ff(e),r=t.profile==="workspace-web-application"?[]:[{name:"PORT",kind:"value",required:!1,default:"3000"}],n={$schema:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",schemaVersion:1,kind:"ApplicationConfigContract",application:t,configDirectory:{rootEnvironmentVariable:"IDP_CONFIG_DIR",relativeDirectory:`applications/${t.id}`,environmentFile:".env",materializationOwner:"external-deployment-control-plane"},bindings:r};return Vc(n,e),Buffer.from(`${JSON.stringify(n,null,2)}
37
+ `)}import{createHash as m_,X509Certificate as g_}from"node:crypto";import{lstat as Mc,readFile as gr,realpath as mf}from"node:fs/promises";import pe from"node:path";var he=class extends Error{code;constructor(t,r){super(r),this.code=t}};function yf(e){let t=W(e),r=t.profile?.parameters?.name;if(typeof r!="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(r))throw new he("APPLICATION_CONFIG_BINDING_IDENTITY_INVALID","\u9879\u76EE\u7F3A\u5C11\u5408\u6CD5Application identity\u3002");return{id:r,profile:t.profile.id}}function ji(e){let t=yf(e);return Buffer.from(`${JSON.stringify({$schema:"https://schemas.dyyto.dev/platform/application-config-binding-v1.json",schemaVersion:1,kind:"ApplicationConfigBinding",application:t,environment:{name:"local"},configDirectory:{rootEnvironmentVariable:"APP_CONFIG_DIR",scope:"application-environment"},contract:{path:"config/application-config.json"},materializationOwner:"external-deployment-control-plane"},null,2)}
38
+ `)}function h_(e,t){let r=e;if(r?.$schema!=="https://schemas.dyyto.dev/platform/application-config-binding-v1.json"||r.schemaVersion!==1||r.kind!=="ApplicationConfigBinding"||r.environment?.name!=="local"||r.configDirectory?.rootEnvironmentVariable!=="APP_CONFIG_DIR"||r.configDirectory.scope!=="application-environment"||r.contract?.path!=="config/application-config.json"||r.materializationOwner!=="external-deployment-control-plane")throw new he("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u4E0D\u7B26\u5408v1\u5408\u540C\u3002");if(!r.application||typeof r.application.id!="string"||typeof r.application.profile!="string")throw new he("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u5E94\u7528\u8EAB\u4EFD\u65E0\u6548\u3002");if(t!==void 0){let n=yf(t);if(r.application.id!==n.id||r.application.profile!==n.profile)throw new he("APPLICATION_CONFIG_BINDING_IDENTITY_MISMATCH","ApplicationConfigBinding\u4E0EProject Manifest\u8EAB\u4EFD\u4E0D\u4E00\u81F4\u3002")}return r}function y_(e){let t={};for(let[r,n]of e.split(/\r?\n/u).entries()){let a=n.trim();if(!a||a.startsWith("#"))continue;let i=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(a),o=i?.[1],s=i?.[2];if(!o||s===void 0||o in t)throw new he("APPLICATION_CONFIG_ENV_INVALID",`.env:${r+1}\u683C\u5F0F\u65E0\u6548\u6216\u53D8\u91CF\u91CD\u590D\u3002`);t[o]=s.trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/u,"$1$2")}return t}function gf(e){return`sha256:${m_("sha256").update(e).digest("hex")}`}function w_(e){return e?e.length<=4?"\u2022\u2022\u2022\u2022":`${e.slice(0,2)}\u2022\u2022\u2022\u2022${e.slice(-2)}`:""}async function hf(e,t,r){let n=await Mc(e).catch(()=>null);if(!n||!n.isFile()||n.isSymbolicLink()||n.nlink!==1||!r&&n.size===0||(n.mode&511&-385)!==0)throw new he("APPLICATION_CONFIG_FILE_INVALID",`${t}\u4E0D\u5B58\u5728\u3001\u4E3A\u7A7A\u3001\u4E0D\u662F\u5B89\u5168\u666E\u901A\u6587\u4EF6\u6216\u6743\u9650\u8D85\u8FC70600\u3002`);return n}async function v_(e,t,r){let n=pe.dirname(e);for(;n!==pe.dirname(n);){try{if(JSON.parse(await gr(pe.join(n,"project-capabilities.json"),"utf8")).profile?.id==="workspace-root"){let i=pe.relative(n,e);if(!/^(?:apps|packages)[/\\][a-z0-9][a-z0-9._-]*$/u.test(i))throw new he("APPLICATION_CONFIG_WORKSPACE_UNIT_INVALID","Workspace\u5E94\u7528\u5FC5\u987B\u4F4D\u4E8Eapps/<name>\u6216packages/<name>\u3002");return pe.join(pe.basename(n),i,r)}}catch(a){if(a instanceof he)throw a}n=pe.dirname(n)}return pe.join(t,r)}async function I_(e,t,r){let n=r.DYYTO_WORKBENCH_PROJECT_BINDINGS_FILE;if(n){if(!pe.isAbsolute(n))throw new he("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let i=await Mc(n).catch(()=>null);if(!i?.isFile()||i.isSymbolicLink()||i.nlink!==1||(i.mode&511&-385)!==0)throw new he("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u4E0D\u5B89\u5168\u3002");let o=JSON.parse(await gr(n,"utf8"));if(o.schemaVersion!==1||!Array.isArray(o.projects))throw new he("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u7248\u672C\u65E0\u6548\u3002");let s=o.projects.filter(c=>typeof c.containerPath=="string"&&typeof c.configDirectory=="string"&&(e===c.containerPath||e.startsWith(`${c.containerPath}${pe.sep}`))).sort((c,d)=>d.containerPath.length-c.containerPath.length);if(s[0])return s[0].configDirectory}let a=r.APP_CONFIG_DIR;if(a){if(!pe.isAbsolute(a))throw new he("APP_CONFIG_DIR_REQUIRED","APP_CONFIG_DIR\u5FC5\u987B\u662F\u7EDD\u5BF9\u4E1A\u52A1\u914D\u7F6E\u603B\u6839\u3002");return pe.join(a,await v_(e,t,r.DYYTO_APPLICATION_ENVIRONMENT??"local"))}}async function $i({projectRoot:e,environment:t=process.env}){let r=await mf(pe.resolve(e)),[n,a,i]=await Promise.all([gr(pe.join(r,"project-capabilities.json")),gr(pe.join(r,".dyyto/application-config-binding.json")),gr(pe.join(r,"config/application-config.json"))]),o=JSON.parse(n.toString("utf8")),s=h_(JSON.parse(a.toString("utf8")),o),c=Vc(JSON.parse(i.toString("utf8")),o),d=await I_(r,s.application.id,t);if(!d||!pe.isAbsolute(d))throw new he("APP_CONFIG_DIR_REQUIRED","\u8BF7\u4E3A\u5F53\u524D\u9879\u76EE\u8BBE\u7F6E\u7EDD\u5BF9APP_CONFIG_DIR\u3002");let l=await mf(d),p=await Mc(l);if(!p.isDirectory()||p.isSymbolicLink()||(p.mode&511&-449)!==0)throw new he("APP_CONFIG_DIR_INVALID","APP_CONFIG_DIR\u5FC5\u987B\u662F\u6743\u9650\u4E0D\u8D85\u8FC70700\u7684\u666E\u901A\u76EE\u5F55\u3002");let m=pe.relative(r,l);if(m===""||!m.startsWith("..")&&!pe.isAbsolute(m))throw new he("APP_CONFIG_DIR_INSIDE_PROJECT","APP_CONFIG_DIR\u4E0D\u80FD\u4F4D\u4E8E\u9879\u76EE\u4ED3\u5E93\u5185\u3002");let u=pe.join(l,".env");await hf(u,"\u5E94\u7528.env",c.bindings.length===0);let f=y_(await gr(u,"utf8")),g=[];for(let h of c.bindings){if(h.kind==="value"){let O=f[h.name]??"";g.push({name:h.name,kind:h.kind,required:h.required,configured:O.length>0,source:"APP_CONFIG_DIR",display:w_(O)});continue}if(f[h.name]!==h.file)throw new he("APPLICATION_CONFIG_REFERENCE_CHANGED",`${h.name}\u672A\u4FDD\u6301\u5408\u540C\u6587\u4EF6\u5F15\u7528\u3002`);let _=pe.resolve(l,h.file),b=pe.relative(l,_);if(!b||b.startsWith("..")||pe.isAbsolute(b))throw new he("APPLICATION_CONFIG_REFERENCE_ESCAPE",`${h.name}\u9003\u9038APP_CONFIG_DIR\u3002`);let A=await hf(_,h.name,!h.required),y=await gr(_),k=y.length>0,S;if(k&&h.kind==="certificate-file")try{let O=new g_(y);S={subject:O.subject,issuer:O.issuer,validFrom:O.validFrom,validTo:O.validTo}}catch{throw new he("APPLICATION_CERTIFICATE_INVALID",`${h.name}\u4E0D\u662F\u6709\u6548X.509\u8BC1\u4E66\u3002`)}g.push({name:h.name,kind:h.kind,required:h.required,configured:k,source:"APP_CONFIG_DIR",display:k?"\u5DF2\u914D\u7F6E":"\u672A\u914D\u7F6E",...k?{fingerprint:gf(y),updatedAt:A.mtime.toISOString()}:{},...S?{certificate:S}:{}})}return{application:s.application.id,environment:"local",configDirectory:l,contractDigest:gf(i),entries:g}}var hr="project-capabilities.json",wf=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function __(e,t){if(!wf.test(e)||!wf.test(t))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade requires stable SemVer releases");let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let a=0;a<3;a+=1)if(r[a]!==n[a])return r[a]-n[a];return 0}async function E_(e,t){let r=Xn.join(e,...t.split("/"));try{let n=await b_(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Managed upgrade target must be a regular file",t);return{path:t,exists:!0,digest:v(await Oi(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}function Ci(e,t){let r=W(e),n=t.release,a=n.assets.find(o=>o.path==="package.json");if((n.consumerProfile==="standalone-npm-package"||n.consumerProfile==="workspace-npm-package")&&a?.renderer?.startsWith("npm-package-json-")===!0)return Pc(Ut(r,n.consumerProfile));if(n.consumerProfile==="react-component-library"&&a?.renderer==="react-component-package-json-v1")return Nc(Ut(r,n.consumerProfile));let i=t.contents.get("package.json");if(i===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");return i}async function qc(e){let t=W(e.manifest),r=Oe(e.currentLock),n=e.sourceRelease.release,a=e.targetRelease.release,i=t.capabilities.find(P=>P.capabilityId===n.capabilityId),o=r.capabilities.find(P=>P.capabilityId===n.capabilityId),s=a.capabilityId!==n.capabilityId&&a.dependencies?.capabilities?.includes(n.capabilityId)===!0;if(i===void 0||o===void 0||i.capabilityId!==o.capabilityId||i.version!==o.version||n.capabilityId!==o.capabilityId||n.version!==o.version||n.integrity!==o.integrity||!s&&a.capabilityId!==o.capabilityId||a.consumerProfile!==o.consumerProfile||n.consumerProfile!==a.consumerProfile)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade source, target, Manifest, and Lock must describe one compatible capability");if(!s&&__(a.version,n.version)<=0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade target must be newer than the locked release");let c=await k_(Xn.resolve(e.projectRoot)),d={...t,...e.targetTemplate===void 0?{}:{template:e.targetTemplate},capabilities:t.capabilities.map(P=>P.capabilityId===n.capabilityId?{capabilityId:a.capabilityId,version:a.version}:P)},l=new Map(e.targetRelease.contents);a.assets.some(P=>P.path==="package.json")&&l.set("package.json",Ci(d,e.targetRelease));for(let P of a.assets)P.renderer==="application-config-contract-v1"&&l.set(P.path,Si(d)),P.renderer==="application-config-binding-v1"&&l.set(P.path,ji(d));let p,m=c,u="package.json",f;if(a.schemaVersion===2&&a.availability.maturity!=="withdrawn"&&(a.packageSources?.length??0)>0){if(e.packageSource===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Profile transition requires verified Package Source facts");let P=l.get("package.json");if(P===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");let K=await Oi(Xn.join(c,"package.json")),re=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:c,unitRoot:c,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"};m=re.transactionRoot,u=re.mode==="pnpm-shared-lockfile"?`${re.unitRelativeRoot}/package.json`:"package.json",f=re.lockfilePath;let Be={release:a,registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections,consumerProfile:a.consumerProfile,packageJson:K,desiredBasePackageJson:P,...e.packageSource.currentLockfile===void 0?{}:{currentLockfile:e.packageSource.currentLockfile},generatedAt:e.generatedAt,expiresAt:e.expiresAt};try{let Qe=re.mode==="pnpm-shared-lockfile"?(e.packageChannel==="development"?Di:Ni)({...Be,topology:{mode:re.mode,unitRelativeRoot:re.unitRelativeRoot,unitImporterId:re.unitImporterId,lockfilePath:re.lockfilePath,workspaceManifestPath:re.workspaceManifestPath,workspaceManifestDigest:re.workspaceManifestDigest},preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Pi:Ri)({...Be,lockResolution:e.packageSource.lockResolution});p=_i(Qe),l.set("package.json",Qe.desiredPackageJson),l.set(f,Qe.desiredLockfile)}catch(Qe){throw Qe instanceof Y?new M("CONSUMER_PROFILE_UNSUPPORTED",Qe.code):Qe}}let g=new Map(o.assets.filter(P=>P.path!==hr).map(P=>[P.path,P.digest])),h=new Map(a.assets.filter(P=>P.path!==hr).map(P=>{let K=l.get(P.path);if(K===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade target asset content is unavailable",P.path);return[P.path,v(K)]})),w=[...new Set([...g.keys(),...h.keys()])].sort(),_=[],b=[];for(let P of w){let K=await E_(c,P);_.push(K);let re=g.get(P),Be=h.get(P),Qe=a.assets.find(Ym=>Ym.path===P);if(Qe?.ownership==="seed-file"&&K.exists&&K.digest!==void 0){h.set(P,K.digest),l.set(P,await Oi(Xn.join(c,...P.split("/")))),b.push({path:P,kind:"replace",ownership:"seed-file",baseDigest:K.digest,desiredDigest:K.digest});continue}if(re===void 0){if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Target asset digest is unavailable",P);b.push({path:P,kind:"create",ownership:Qe?.ownership??"owned-file",desiredDigest:Be})}else Be===void 0?b.push({path:P,kind:"remove",ownership:"owned-file",baseDigest:re}):b.push({path:P,kind:"replace",ownership:Qe?.ownership??"owned-file",baseDigest:re,desiredDigest:Be})}if(p!==void 0&&f!==void 0){let P=e.packageSource?.currentLockfile;if(P===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Transition lockfile preimage is unavailable");let K=l.get(f);_.push({path:f,exists:!0,digest:v(P)}),b.push({path:f,kind:"replace",ownership:"owned-file",baseDigest:v(P),desiredDigest:v(K)})}let A=await Oi(Xn.join(c,hr)),y=Buffer.from(`${JSON.stringify(d,null,2)}
39
+ `);_.push({path:hr,exists:!0,digest:v(A)}),b.push({path:hr,kind:"replace",ownership:"owned-file",baseDigest:v(A),desiredDigest:v(y)});let k={schemaVersion:1,capabilityId:a.capabilityId,version:a.version,integrity:a.integrity,assets:a.assets.filter(P=>P.path!==hr).map(P=>({path:P.path,ownership:P.ownership,desiredDigest:h.get(P.path)})),verifiers:a.verifiers.map(({id:P})=>({id:P,kind:"command"}))},S=m===c?b:b.map(P=>P.path===f?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),O=m===c?_:_.map(P=>P.path===f?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),ie=Ne({action:"upgrade",capability:k,changes:S,observedAssets:O,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...p===void 0?{}:{packageAdoption:p}});l.set(hr,y);let $=new Map;for(let P of ie.operations){if(P.disposition!=="ready"||P.kind==="remove")continue;let K=m===c?"":`${e.packageSource.topology.unitRelativeRoot}/`,re=P.path===f?P.path:P.path.startsWith(K)?P.path.slice(K.length):P.path,Be=l.get(re);if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade desired content is unavailable",P.path);$.set(P.path,Be)}return{sourceLock:r,targetManifest:d,release:e.targetRelease,plan:ie,desiredContents:$,transactionRoot:m}}import{link as A_,mkdir as R_,open as vf,readFile as st,readdir as P_,realpath as ct,rm as N_,unlink as D_}from"node:fs/promises";import le from"node:path";var j=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="DeliveryError"}};function _e(e){return/^sha256:[a-f0-9]{64}$/.test(e)}function If(e){return v(E(e))}function Jc(e){if(!_e(e.project.lockDigest)||!_e(e.project.appliedPlanId)||!_e(e.artifact.digest))throw new j("DELIVERY_PRECONDITION_FAILED","Delivery identities must use canonical SHA-256 digests");if(Date.parse(e.expiresAt)<=Date.parse(e.createdAt)||Number.isNaN(Date.parse(e.createdAt)))throw new j("DELIVERY_PRECONDITION_FAILED","Delivery plan expiry must follow creation time");if(e.kind==="npm-publish"&&(e.artifact.type!=="npm-package"||e.target.adapterId!=="registry.npmjs"||e.risk!=="irreversible-publish")||e.kind==="application-deploy"&&(e.artifact.type!=="node-application"&&e.artifact.type!=="web-application"||e.target.adapterId!=="deployment.local-docker"||e.risk!=="local-reversible-deployment")||e.kind==="artifact-publication"&&(e.artifact.type!=="published-package"||e.target.adapterId!=="publication.offline-web"&&e.target.adapterId!=="publication.hosted-static"||(e.target.adapterId==="publication.offline-web"?e.risk!=="local-reversible-publication":e.risk!=="external-reversible-publication"))||e.kind==="hosted-static"&&(e.artifact.type!=="web-bundle"||e.target.adapterId!=="publication.hosted-static"||e.risk!=="external-reversible-publication"))throw new j("DELIVERY_PROJECT_UNSUPPORTED","Delivery kind, artifact, target, and risk must be compatible");if(e.kind==="npm-publish"&&e.publication!==void 0){let r=e.publication,n=r.execution;if(r.mode!=="staged"||r.access!=="public"||r.authentication!=="trusted-publishing"||r.trustedAction!=="stage-only"||r.provenance!=="required"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.tag)||n?.provider!=="github-actions"&&n?.provider!=="gitlab-ci"||!n.repository||!n.workflow||!n.ref||Object.values(n).some(a=>typeof a!="string"||a.length>512||/[\u0000-\u001f\u007f]/.test(a)))throw new j("DELIVERY_PRECONDITION_FAILED","npm publication policy is invalid")}if(e.kind!=="npm-publish"&&e.publication!==void 0)throw new j("DELIVERY_PRECONDITION_FAILED","Publication policy is only valid for npm delivery");let t={schemaVersion:e.kind==="npm-publish"&&e.publication!==void 0?2:1,...e,state:"reviewable"};return{...t,planId:If(t)}}function Uc(e){let t=e;if(t?.schemaVersion!==1&&t?.schemaVersion!==2||t.state!=="reviewable")throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan is invalid or has been modified");if(t.schemaVersion===2&&(t.kind!=="npm-publish"||t.publication===void 0)||t.schemaVersion===1&&t.publication!==void 0)throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan schema and publication policy do not match");let{planId:r,...n}=t;if(If(n)!==r)throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan is invalid or has been modified");return Jc({kind:t.kind,project:t.project,artifact:t.artifact,target:t.target,risk:t.risk,createdAt:t.createdAt,expiresAt:t.expiresAt,...t.publication===void 0?{}:{publication:t.publication}})}function bf(e){if(!_e(e.planId)||!_e(e.artifactDigest)||!/^[A-Za-z0-9._:-]{1,256}$/.test(e.stageId)||Number.isNaN(Date.parse(e.createdAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record identities are invalid");let t={schemaVersion:1,...e,status:"registry-accepted"};return{...t,recordId:v(E(t))}}function kf(e){if(!_e(e.planId)||!_e(e.artifactDigest)||Number.isNaN(Date.parse(e.startedAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record identities are invalid");let t={schemaVersion:1,...e,status:"remote-write-started"};return{...t,recordId:v(E(t))}}function Ti(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="remote-write-started"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record is invalid or has been modified");return t}function Fc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="registry-accepted"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record is invalid or has been modified");return t}function _f(e){if(!_e(e.planId)||!_e(e.artifactDigest)||!/^[A-Za-z0-9._:-]{1,256}$/.test(e.stageId)||Number.isNaN(Date.parse(e.reviewedAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record identities are invalid");let t={schemaVersion:1,...e,status:"artifact-digest-verified"};return{...t,recordId:v(E(t))}}function zc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="artifact-digest-verified"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record is invalid or has been modified");return t}function xi(e){if(!_e(e.planId)||!_e(e.artifactDigest)||e.externalIdentity.length===0)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt identities are invalid");if("npm"in e){let r=e.npm;if(e.adapterId!=="registry.npmjs"||r===void 0||r.stageId.length===0||r.registry!=="https://registry.npmjs.org"||r.tarballDigest!==e.artifactDigest||r.access!=="public"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.tag)||r.provenance!=="registry-attested"||!_e(r.attestationUrlDigest))throw new j("DELIVERY_RECEIPT_INVALID","Verified npm Receipt facts are incomplete or inconsistent");let n={schemaVersion:2,...e,status:"verified"};return{...n,receiptId:v(E(n))}}if(e.kind==="npm-publish"||e.kind==="application-deploy"&&e.adapterId!=="deployment.local-docker"||e.kind==="artifact-publication"&&e.adapterId!=="publication.offline-web"&&e.adapterId!=="publication.hosted-static"||e.kind==="hosted-static"&&(e.adapterId!=="publication.hosted-static"||e.details.renderMode!=="csr"))throw new j("DELIVERY_RECEIPT_INVALID","Application or artifact Delivery Receipt facts are invalid");let t={schemaVersion:1,...e,status:"verified"};return{...t,receiptId:v(E(t))}}function Bc(e){let t=e,{receiptId:r,...n}=t??{};if(t?.schemaVersion!==1&&t?.schemaVersion!==2||t.status!=="verified"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt is invalid or has been modified");let{receiptId:a,schemaVersion:i,status:o,...s}=t;return xi(s)}async function S_(e){let t=await vf(e,"r");try{await t.sync()}finally{await t.close()}}async function Zn(e,t){let r=le.dirname(e);await R_(r,{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`,a=await vf(n,"wx",384);try{await a.writeFile(`${E(t)}
40
+ `,"utf8"),await a.sync()}finally{await a.close()}try{await A_(n,e),await D_(n),await S_(r)}catch(i){throw await N_(n,{force:!0}),i}}async function Ef(e){let t=await ct(le.resolve(e.projectRoot)),r=Uc(e.plan),n=le.join(t,".dyyto","delivery","plans",`${r.planId}.json`);try{await Zn(n,r)}catch(a){if(a.code!=="EEXIST")throw a;if(E(Uc(JSON.parse(await st(n,"utf8"))))!==E(r))throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan content does not match its identity")}return r}async function Ft(e){if(!_e(e.planId))throw new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan identity is invalid");let t=await ct(le.resolve(e.projectRoot));try{let r=Uc(JSON.parse(await st(le.join(t,".dyyto","delivery","plans",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan identity does not match its path");return r}catch(r){throw r.code==="ENOENT"?new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan was not found"):r}}async function Gc(e){let t=await ct(le.resolve(e.projectRoot)),r=Bc(e.receipt),n=await Ft({projectRoot:t,planId:r.planId});if(r.kind!==n.kind||r.adapterId!==n.target.adapterId||r.artifactDigest!==n.artifact.digest||r.target!==n.target.location)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt does not match its immutable Plan");if(r.schemaVersion===2){let i=await Yr({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.publication===void 0||i===null||r.npm.stageId!==i.stageId||r.npm.tarballDigest!==i.artifactDigest||r.npm.tag!==n.publication.tag||r.npm.access!==n.publication.access)throw new j("DELIVERY_RECEIPT_INVALID","Verified npm Receipt does not match its Plan and Stage Record")}let a=le.join(t,".dyyto","delivery","receipts",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=Bc(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Receipt already exists for this Plan");return o}return r}async function Qn(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt Plan identity is invalid");let t=await ct(le.resolve(e.projectRoot));try{let r=Bc(JSON.parse(await st(le.join(t,".dyyto","delivery","receipts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Receipt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Af(e){let t=await ct(le.resolve(e.projectRoot)),r=Ti(e.record),n=await Ft({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record does not match an npm Plan v2");let a=le.join(t,".dyyto","delivery","attempts",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=Ti(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Attempt Record already exists for this Plan");return o}return r}async function Rf(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Plan identity is invalid");let t=await ct(le.resolve(e.projectRoot));try{let r=Ti(JSON.parse(await st(le.join(t,".dyyto","delivery","attempts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Attempt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Pf(e){let t=await ct(le.resolve(e.projectRoot)),r=le.join(t,".dyyto","delivery","attempts"),n;try{n=await P_(r)}catch(a){if(a.code==="ENOENT")return null;throw a}for(let a of n.sort()){if(!a.endsWith(".json"))continue;let i=Ti(JSON.parse(await st(le.join(r,a),"utf8")));if((await Ft({projectRoot:t,planId:i.planId})).artifact.identity!==e.artifactIdentity)continue;let[s,c]=await Promise.all([Yr({projectRoot:t,planId:i.planId}),Qn({projectRoot:t,planId:i.planId})]);if(s===null&&c===null)return i}return null}async function Nf(e){let t=await ct(le.resolve(e.projectRoot)),r=Fc(e.record),n=await Ft({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||n.publication===void 0||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record does not match an npm Plan v2");let a=le.join(t,".dyyto","delivery","stages",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=Fc(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Record already exists for this Plan");return o}return r}async function Yr(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Plan identity is invalid");let t=await ct(le.resolve(e.projectRoot));try{let r=Fc(JSON.parse(await st(le.join(t,".dyyto","delivery","stages",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Df(e){let t=await ct(le.resolve(e.projectRoot)),r=zc(e.record),n=await Yr({projectRoot:t,planId:r.planId});if(n===null||r.stageId!==n.stageId||r.artifactDigest!==n.artifactDigest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record does not match its immutable Stage Record");let a=le.join(t,".dyyto","delivery","stage-reviews",`${r.planId}.json`);try{await Zn(a,r)}catch(i){if(i.code!=="EEXIST")throw i;let o=zc(JSON.parse(await st(a,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Review Record already exists for this Plan");return o}return r}async function Sf(e){if(!_e(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Plan identity is invalid");let t=await ct(le.resolve(e.projectRoot));try{let r=zc(JSON.parse(await st(le.join(t,".dyyto","delivery","stage-reviews",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage Review identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}import{readFile as Kf,readdir as gE}from"node:fs/promises";import Yc from"node:path";import{mkdir as Wc,open as qi,readFile as ta,readdir as Jf,rename as Ui,rm as Gf}from"node:fs/promises";import ve from"node:path";var j_=44;var jf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$_=new Uint8Array(64),Of=new Uint8Array(128);for(let e=0;e<jf.length;e++){let t=jf.charCodeAt(e);$_[e]=t,Of[t]=e}function ea(e,t){let r=0,n=0,a=0;do{let o=e.next();a=Of[o],r|=(a&31)<<n,n+=5}while(a&32);let i=r&1;return r>>>=1,i&&(r=-2147483648|-r),t+r}function $f(e,t){return e.pos>=t?!1:e.peek()!==j_}var kN=1024*16;var O_=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:r}=this,n=t.indexOf(e,r);return n===-1?t.length:n}};function Cf(e){let{length:t}=e,r=new O_(e),n=[],a=0,i=0,o=0,s=0,c=0;do{let d=r.indexOf(";"),l=[],p=!0,m=0;for(a=0;r.pos<d;){let u;a=ea(r,a),a<m&&(p=!1),m=a,$f(r,d)?(i=ea(r,i),o=ea(r,o),s=ea(r,s),$f(r,d)?(c=ea(r,c),u=[a,i,o,s,c]):u=[a,i,o,s]):u=[a],l.push(u),r.pos++}p||C_(l),n.push(l),r.pos=d+1}while(r.pos<=t);return n}function C_(e){e.sort(T_)}function T_(e,t){return e[0]-t[0]}var x_=/^[\w+.-]+:\/\//,L_=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,V_=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function M_(e){return x_.test(e)}function q_(e){return e.startsWith("//")}function Lf(e){return e.startsWith("/")}function U_(e){return e.startsWith("file:")}function Tf(e){return/^[.?#]/.test(e)}function Li(e){let t=L_.exec(e);return Vf(t[1],t[2]||"",t[3],t[4]||"",t[5]||"/",t[6]||"",t[7]||"")}function F_(e){let t=V_.exec(e),r=t[2];return Vf("file:","",t[1]||"","",Lf(r)?r:"/"+r,t[3]||"",t[4]||"")}function Vf(e,t,r,n,a,i,o){return{scheme:e,user:t,host:r,port:n,path:a,query:i,hash:o,type:7}}function xf(e){if(q_(e)){let r=Li("http:"+e);return r.scheme="",r.type=6,r}if(Lf(e)){let r=Li("http://foo.com"+e);return r.scheme="",r.host="",r.type=5,r}if(U_(e))return F_(e);if(M_(e))return Li(e);let t=Li("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function z_(e){if(e.endsWith("/.."))return e;let t=e.lastIndexOf("/");return e.slice(0,t+1)}function B_(e,t){Mf(t,t.type),e.path==="/"?e.path=t.path:e.path=z_(t.path)+e.path}function Mf(e,t){let r=t<=4,n=e.path.split("/"),a=1,i=0,o=!1;for(let c=1;c<n.length;c++){let d=n[c];if(!d){o=!0;continue}if(o=!1,d!=="."){if(d===".."){i?(o=!0,i--,a--):r&&(n[a++]=d);continue}n[a++]=d,i++}}let s="";for(let c=1;c<a;c++)s+="/"+n[c];(!s||o&&!s.endsWith("/.."))&&(s+="/"),e.path=s}function qf(e,t){if(!e&&!t)return"";let r=xf(e),n=r.type;if(t&&n!==7){let i=xf(t),o=i.type;switch(n){case 1:r.hash=i.hash;case 2:r.query=i.query;case 3:case 4:B_(r,i);case 5:r.user=i.user,r.host=i.host,r.port=i.port;case 6:r.scheme=i.scheme}o>n&&(n=o)}Mf(r,n);let a=r.query+r.hash;switch(n){case 2:case 3:return a;case 4:{let i=r.path.slice(1);return i?Tf(t||e)&&!Tf(i)?"./"+i+a:i+a:a||"."}case 5:return r.path+a;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+a}}function J_(e){if(!e)return"";let t=e.lastIndexOf("/");return e.slice(0,t+1)}function G_(e,t){let r=J_(e),n=t?t+"/":"";return a=>qf(n+(a||""),r)}var zt=0,W_=1,K_=2,Y_=3,H_=4;function X_(e,t){let r=Uf(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n<e.length;n=Uf(e,n+1))e[n]=Q_(e[n],t);return e}function Uf(e,t){for(let r=t;r<e.length;r++)if(!Z_(e[r]))return r;return e.length}function Z_(e){for(let t=1;t<e.length;t++)if(e[t][zt]<e[t-1][zt])return!1;return!0}function Q_(e,t){return t||(e=e.slice()),e.sort(eE)}function eE(e,t){return e[zt]-t[zt]}var Mi=!1;function tE(e,t,r,n){for(;r<=n;){let a=r+(n-r>>1),i=e[a][zt]-t;if(i===0)return Mi=!0,a;i<0?r=a+1:n=a-1}return Mi=!1,r-1}function rE(e,t,r){for(let n=r+1;n<e.length&&e[n][zt]===t;r=n++);return r}function nE(e,t,r){for(let n=r-1;n>=0&&e[n][zt]===t;r=n--);return r}function aE(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function iE(e,t,r,n){let{lastKey:a,lastNeedle:i,lastIndex:o}=r,s=0,c=e.length-1;if(n===a){if(t===i)return Mi=o!==-1&&e[o][zt]===t,o;t>=i?s=o===-1?0:o:c=o}return r.lastKey=n,r.lastNeedle=t,r.lastIndex=tE(e,t,s,c)}function oE(e){return typeof e=="string"?JSON.parse(e):e}var sE="`line` must be greater than 0 (lines start at line 1)",cE="`column` must be greater than or equal to 0 (columns start at column 0)",Ff=-1,lE=1,zf=class{constructor(e,t){let r=typeof e=="string";if(!r&&e._decodedMemo)return e;let n=oE(e),{version:a,file:i,names:o,sourceRoot:s,sources:c,sourcesContent:d}=n;this.version=a,this.file=i,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=d,this.ignoreList=n.ignoreList||n.x_google_ignoreList||void 0;let l=G_(t,s);this.resolvedSources=c.map(l);let{mappings:p}=n;if(typeof p=="string")this._encoded=p,this._decoded=void 0;else if(Array.isArray(p))this._encoded=void 0,this._decoded=X_(p,r);else throw n.sections?new Error("TraceMap passed sectioned source map, please use FlattenMap export instead"):new Error(`invalid source map: ${JSON.stringify(n)}`);this._decodedMemo=aE(),this._bySources=void 0,this._bySourceMemos=void 0}};function dE(e){var t;return(t=e)._decoded||(t._decoded=Cf(e._encoded))}function Bf(e,t){let{line:r,column:n,bias:a}=t;if(r--,r<0)throw new Error(sE);if(n<0)throw new Error(cE);let i=dE(e);if(r>=i.length)return Vi(null,null,null,null);let o=i[r],s=pE(o,e._decodedMemo,r,n,a||lE);if(s===-1)return Vi(null,null,null,null);let c=o[s];if(c.length===1)return Vi(null,null,null,null);let{names:d,resolvedSources:l}=e;return Vi(l[c[W_]],c[K_]+1,c[Y_],c.length===5?d[c[H_]]:null)}function Vi(e,t,r,n){return{source:e,line:t,column:r,name:n}}function pE(e,t,r,n,a){let i=iE(e,n,t,r);return Mi?i=(a===Ff?rE:nE)(e,n,i):a===Ff&&i++,i===-1||i===e.length?-1:i}var fe=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="RuntimeObservabilityError"}},Kc=/^sha256:[a-f0-9]{64}$/,Wf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uE=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/,Fi=(e,t)=>Object.keys(e).every(r=>t.includes(r)),ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hr=(e,t)=>e.replace(/[\u0000-\u001f\u007f]/g," ").replace(/([a-z]+:\/\/)[^/@\s]+@/gi,"$1").slice(0,t);function fE(e){if(!ra(e)||!Fi(e,["schemaVersion","eventId","occurredAt","applicationId","releaseId","deploymentId","kind","error","page","traceparent"]))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error Envelope contains unknown fields");if(!ra(e.error)||!ra(e.page)||!Fi(e.error,["type","message","frames"])||!Fi(e.page,["origin","path"]))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error Envelope structure is invalid");if(e.schemaVersion!==1||typeof e.eventId!="string"||!Wf.test(e.eventId)||typeof e.occurredAt!="string"||Number.isNaN(Date.parse(e.occurredAt))||typeof e.applicationId!="string"||e.applicationId.length<1||e.applicationId.length>128)throw new fe("RUNTIME_ERROR_INVALID","Runtime Error Envelope identity is invalid");if(!["uncaught-error","unhandled-rejection","reported-error"].includes(e.kind))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error kind is invalid");for(let n of[e.releaseId,e.deploymentId])if(n!==void 0&&(typeof n!="string"||!Kc.test(n)))throw new fe("RUNTIME_ERROR_IDENTITY_UNKNOWN","Runtime Error correlation identity is invalid");if(e.traceparent!==void 0&&(typeof e.traceparent!="string"||!uE.test(e.traceparent)))throw new fe("RUNTIME_ERROR_INVALID","traceparent is invalid");if(typeof e.error.type!="string"||typeof e.error.message!="string"||!Array.isArray(e.error.frames)||e.error.frames.length>50||typeof e.page.origin!="string"||typeof e.page.path!="string")throw new fe("RUNTIME_ERROR_INVALID","Runtime Error content is invalid");if(e.error.message.length>4096||e.error.type.length>256||e.page.path.length>2048)throw new fe("RUNTIME_ERROR_TOO_LARGE","Runtime Error content exceeds a hard limit");let t=e.error.frames.map(n=>{if(!ra(n)||!Fi(n,["file","line","column","function"])||typeof n.file!="string"||n.file.length>2048)throw new fe("RUNTIME_ERROR_INVALID","Runtime Error stack frame is invalid");for(let a of[n.line,n.column])if(a!==void 0&&(!Number.isSafeInteger(a)||Number(a)<1))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error stack location is invalid");if(n.function!==void 0&&(typeof n.function!="string"||n.function.length>256))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error stack function is invalid");return n}),r;try{r=new URL(e.page.origin)}catch{throw new fe("RUNTIME_ERROR_INVALID","Runtime Error page origin is invalid")}if(r.origin!==e.page.origin||!e.page.path.startsWith("/")||e.page.path.includes("?")||e.page.path.includes("#"))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error page must contain only origin and path");return{...e,error:{...e.error,frames:t}}}function mE(e,t,r="unknown"){let n=e.error.frames.map(o=>({file:Hr(o.file,2048),...o.line===void 0?{}:{line:o.line},...o.column===void 0?{}:{column:o.column},...o.function===void 0?{}:{function:Hr(o.function,256)}})),a={type:Hr(e.error.type,256),message:Hr(e.error.message,4096),frames:n},i=v(E({type:a.type,message:a.message,frames:n.slice(0,5).map(({file:o,line:s,column:c})=>({file:o,line:s,column:c}))}));return{schemaVersion:1,eventId:e.eventId,occurredAt:e.occurredAt,receivedAt:t,applicationId:Hr(e.applicationId,128),...e.releaseId===void 0?{}:{releaseId:e.releaseId},...e.deploymentId===void 0?{}:{deploymentId:e.deploymentId},kind:e.kind,error:a,page:{origin:e.page.origin,path:Hr(e.page.path,2048)},...e.traceparent===void 0?{}:{traceparent:e.traceparent},fingerprint:i,state:e.releaseId===void 0?"persisted":"map-missing",correlation:r}}var yr=class{workspaceRoot;adapterId="observability.local";#e=Promise.resolve();constructor(t){this.workspaceRoot=t}directory(){return ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","events")}releases(){return ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","releases")}async accept(t,r){let n=fE(t);if(!r.allowedOrigins.includes(n.page.origin))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error origin is not registered");let a=r.resolveCorrelation===void 0?"unknown":await r.resolveCorrelation(n),i=mE(n,r.receivedAt,a);return this.#t(async()=>{let o=this.directory();await Wc(o,{recursive:!0,mode:448});let s=ve.join(o,`${i.eventId}.json`);try{let m=JSON.parse(await ta(s,"utf8")),u={...m,correlation:m.correlation??"unknown"};if(E({...u,receivedAt:i.receivedAt})!==E(i))throw new fe("RUNTIME_ERROR_INVALID","eventId is already used for different content");return{eventId:i.eventId,state:u.state,duplicate:!0}}catch(m){if(m.code!=="ENOENT")throw m}let c=`${s}.tmp-${process.pid}-${crypto.randomUUID()}`,d=await qi(c,"wx",384);try{await d.writeFile(`${E(i)}
41
+ `,"utf8"),await d.sync()}finally{await d.close()}await Ui(c,s);let l=await qi(o,"r");try{await l.sync()}finally{await l.close()}await this.rotate(),i.releaseId!==void 0&&await this.resymbolicate(i.releaseId);let p=JSON.parse(await ta(s,"utf8"));return{eventId:i.eventId,state:p.state,duplicate:!1}})}#t(t){let r=this.#e.then(t,t);return this.#e=r.catch(()=>{}),r}async quarantine(t){let r=ve.join(this.directory(),t),n=ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","quarantine");await Wc(n,{recursive:!0,mode:448}),await Ui(r,ve.join(n,`${Date.now()}-${t}`))}async all(){let t=await Jf(this.directory()).catch(()=>[]),r=[];for(let n of t){if(!n.endsWith(".json")){n.includes(".tmp-")&&await this.quarantine(n).catch(()=>{});continue}try{let a=JSON.parse(await ta(ve.join(this.directory(),n),"utf8"));if(a.eventId!==n.slice(0,-5))throw new Error("identity mismatch");r.push({...a,correlation:a.correlation??"unknown"})}catch{await this.quarantine(n).catch(()=>{})}}return r.sort((n,a)=>a.occurredAt.localeCompare(n.occurredAt)||n.eventId.localeCompare(a.eventId))}selected(t,r){return t.filter(n=>(!r.applicationId||n.applicationId===r.applicationId)&&(!r.releaseId||n.releaseId===r.releaseId)&&(!r.deploymentId||n.deploymentId===r.deploymentId))}cursor(t,r){let n=E({v:1,offset:t,snapshot:r});return Buffer.from(E({content:n,digest:v(n)})).toString("base64url")}parseCursor(t,r){try{let n=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(typeof n.content!="string"||n.digest!==v(n.content))throw new Error("tampered");let a=JSON.parse(n.content);if(a.v!==1||!Number.isSafeInteger(a.offset)||a.offset<0||a.snapshot!==r)throw new Error("expired");return a.offset}catch{throw new fe("OBSERVABILITY_CURSOR_EXPIRED","Runtime Error query cursor is invalid or expired")}}async list(t){let r=Math.max(1,Math.min(t.limit??100,100)),n=this.selected(await this.all(),t),a=v(E(n.map(s=>s.eventId))),i=t.cursor===void 0?0:this.parseCursor(t.cursor,a),o=n.slice(i,i+r);return{events:o,...i+o.length<n.length?{nextCursor:this.cursor(i+o.length,a)}:{}}}async get(t){if(!Wf.test(t))throw new fe("RUNTIME_ERROR_INVALID","Runtime Error eventId is invalid");let r=`${t}.json`;try{let n=JSON.parse(await ta(ve.join(this.directory(),r),"utf8"));if(n.eventId!==t)throw new Error("identity mismatch");return{...n,correlation:n.correlation??"unknown"}}catch(n){if(n.code==="ENOENT")return null;throw await this.quarantine(r).catch(()=>{}),new fe("OBSERVABILITY_STORE_DAMAGED","Runtime Error record is damaged and has been quarantined")}}async summary(t){let r=this.selected(await this.all(),t),n=new Map;for(let a of r){let i=n.get(a.fingerprint);i?i.count+=1:n.set(a.fingerprint,{count:1,latestAt:a.occurredAt,event:a})}return{total:r.length,groups:[...n.entries()].map(([a,i])=>({fingerprint:a,...i}))}}async rotate(){let t=await this.all(),n=t.reduce((a,i)=>Math.max(a,Date.parse(i.receivedAt)),0)-10080*60*1e3;for(let a of t.slice(1e4))await Gf(ve.join(this.directory(),`${a.eventId}.json`),{force:!0});for(let a of t.slice(0,1e4))Date.parse(a.receivedAt)<n&&await Gf(ve.join(this.directory(),`${a.eventId}.json`),{force:!0})}async registerSourceMap(t){if(!Kc.test(t.releaseId)||!Kc.test(t.assetDigest)||!/^[A-Za-z0-9._/-]+\.js$/.test(t.asset)||t.asset.includes("..")||!ra(t.map)||"sourcesContent"in t.map)throw new fe("RUNTIME_ERROR_INVALID","Source Map registration is invalid or contains sourcesContent");let r=Buffer.from(E(t.map)),n=v(r),a=ve.join(this.releases(),t.releaseId);await Wc(a,{recursive:!0,mode:448});let i=v(t.asset),o=ve.join(a,`${i}.json`),s={releaseId:t.releaseId,asset:t.asset,assetDigest:t.assetDigest,mapDigest:n,registeredAt:t.registeredAt},c=await qi(`${o}.tmp`,"w",384);try{await c.writeFile(`${E({registration:s,map:t.map})}
42
+ `),await c.sync()}finally{await c.close()}return await Ui(`${o}.tmp`,o),await this.resymbolicate(t.releaseId),s}async resymbolicate(t){let r=await Jf(ve.join(this.releases(),t)).catch(()=>[]),n=[];for(let a of r)try{n.push(JSON.parse(await ta(ve.join(this.releases(),t,a),"utf8")))}catch{}for(let a of(await this.all()).filter(i=>i.releaseId===t&&i.state==="map-missing")){let i=!1,o=a.error.frames.map(l=>{let p=n.find(m=>new URL(l.file,"http://local").pathname.endsWith(`/${m.registration.asset}`));if(!p||l.line===void 0||l.column===void 0)return l;try{let m=Bf(new zf(p.map),{line:l.line,column:Math.max(0,l.column-1)});return m.source===null||m.line===null||m.column===null?l:(i=!0,{...l,source:m.source.replace(/^file:\/\//,""),sourceLine:m.line,sourceColumn:m.column+1})}catch{return l}});if(!i)continue;let s={...a,error:{...a.error,frames:o},state:"symbolicated"},c=ve.join(this.directory(),`${a.eventId}.json`),d=await qi(`${c}.tmp`,"w",384);try{await d.writeFile(`${E(s)}
43
+ `),await d.sync()}finally{await d.close()}await Ui(`${c}.tmp`,c)}}};var Ue=(e,t,r,n,a)=>({code:e,severity:t,fact:r,message:n,...a===void 0?{}:{action:a}});async function na(e){if(e.lock.capabilities.length===0||e.lock.capabilities.some(r=>r.evidenceIds.length===0))return[Ue("EVIDENCE_INVALID","critical","evidence","\u5DF2\u9A8C\u8BC1\u9501\u7F3A\u5C11\u5B8C\u6574\u8BC1\u636E\u5F15\u7528\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u4E8B\u52A1\u672A\u5B8C\u6210\uFF0C\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\u3002")];for(let r of e.lock.capabilities)for(let n of r.evidenceIds)try{let a=$n(JSON.parse(await Kf(Yc.join(e.projectRoot,".dyyto","evidence",`${n}.json`),"utf8")));if(a.evidenceId!==n||a.capabilityId!==r.capabilityId||a.capabilityVersion!==r.version||a.capabilityIntegrity!==r.integrity||a.projectStateDigest!==r.projectStateDigest||a.result!=="passed")return[Ue("EVIDENCE_INVALID","critical","evidence","\u91C7\u7528\u8BC1\u636E\u4E0E\u5DF2\u9A8C\u8BC1\u9501\u7684\u8EAB\u4EFD\u6216\u5DE5\u7A0B\u72B6\u6001\u4E0D\u4E00\u81F4\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u73B0\u573A\u5DF2\u53D8\u5316\uFF0C\u5148\u68C0\u67E5\u5E76\u91CD\u65B0\u89C4\u5212\u3002")]}catch{return[Ue("EVIDENCE_INVALID","critical","evidence","\u91C7\u7528\u8BC1\u636E\u7F3A\u5931\u3001\u635F\u574F\u6216\u4E0D\u7B26\u5408\u5951\u7EA6\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u4E8B\u52A1\u672A\u5B8C\u6210\uFF0C\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\u3002")]}let t=e.lock.capabilities.reduce((r,n)=>r+n.evidenceIds.length,0);return[Ue("EVIDENCE_VALID","info","evidence",`\u5DF2\u6838\u9A8C ${e.lock.capabilities.length} \u9879\u80FD\u529B\u7684 ${t} \u6761\u91C7\u7528\u8BC1\u636E\u3002`)]}function Hc(e){return e==="adopted"?[]:e==="planned"?[Ue("ADOPTION_PLANNED","warning","lock","\u80FD\u529B\u91C7\u7528\u4ECD\u5904\u4E8E\u8BA1\u5212\u9636\u6BB5\u3002","\u5BA1\u9605\u5E76\u6279\u51C6\u7CBE\u786E Plan\u3002")]:e==="applied-unverified"?[Ue("VERIFICATION_REQUIRED","warning","evidence","\u53D8\u66F4\u5DF2\u5E94\u7528\u4F46\u5C1A\u672A\u5F62\u6210\u9A8C\u8BC1\u8BC1\u636E\u3002","\u8FD0\u884C\u9A8C\u8BC1\u5E76\u63D0\u4EA4\u91C7\u7528\u9501\u3002")]:e==="drifted"?[Ue("REPOSITORY_DRIFT","warning","repository","\u5DE5\u7A0B\u73B0\u573A\u4E0E\u5DF2\u9501\u5B9A\u4E8B\u5B9E\u4E0D\u4E00\u81F4\u3002","\u68C0\u67E5\u5DEE\u5F02\u5E76\u91CD\u65B0\u89C4\u5212\uFF0C\u5E73\u53F0\u4E0D\u4F1A\u8986\u76D6\u7528\u6237\u4FEE\u6539\u3002")]:e==="recovery-required"?[Ue("RECOVERY_REQUIRED","critical","recovery","\u68C0\u6D4B\u5230\u672A\u5B8C\u6210\u7684\u6301\u4E45\u5316\u4E8B\u52A1\u3002","\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\uFF0C\u518D\u7EE7\u7EED\u5176\u4ED6\u64CD\u4F5C\u3002")]:[Ue("FACT_INVALID","critical","manifest","\u5DE5\u7A0B\u5355\u5143\u4E8B\u5B9E\u65E0\u6CD5\u5B89\u5168\u8BFB\u53D6\u3002","\u4FEE\u590D\u8BE5\u5355\u5143\u7684 Manifest \u6216\u5143\u6570\u636E\u540E\u91CD\u65B0\u8BCA\u65AD\u3002")]}async function Yf(e){try{let r=JSON.parse(await Kf(Yc.join(e.workspaceRoot,".dyyto","observability","config.json"),"utf8"));if(!Array.isArray(r.applications)||!r.applications.includes(e.applicationId))return[Ue("OBSERVABILITY_NOT_CONFIGURED","warning","repository","\u5F53\u524D Web \u5E94\u7528\u5C1A\u672A\u914D\u7F6E\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u3002","\u767B\u8BB0\u5E94\u7528 Origin\uFF0C\u5E76\u542F\u52A8\u672C\u5730\u91C7\u96C6\u7AEF\u3002")]}catch{return[Ue("OBSERVABILITY_NOT_CONFIGURED","warning","repository","\u5F53\u524D Web \u5E94\u7528\u5C1A\u672A\u914D\u7F6E\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u3002","\u767B\u8BB0\u5E94\u7528 Origin\uFF0C\u5E76\u542F\u52A8\u672C\u5730\u91C7\u96C6\u7AEF\u3002")]}await new yr(e.workspaceRoot).list({applicationId:e.applicationId});let t=(await gE(Yc.join(e.workspaceRoot,".dyyto","observability","quarantine")).catch(()=>[])).length;return t>0?[Ue("OBSERVABILITY_STORE_DAMAGED","critical","repository",`\u8FD0\u884C\u65F6\u9519\u8BEF\u672C\u5730\u5B58\u50A8\u5DF2\u9694\u79BB ${t} \u6761\u635F\u574F\u8BB0\u5F55\uFF0C\u5065\u5EB7\u4E8B\u4EF6\u4ECD\u53EF\u67E5\u8BE2\u3002`,"\u68C0\u67E5\u672C\u673A\u78C1\u76D8\u72B6\u6001\uFF0C\u5E76\u663E\u5F0F\u5904\u7406\u9694\u79BB\u8BB0\u5F55\u3002")]:[Ue("OBSERVABILITY_CONFIGURED","info","repository","\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u914D\u7F6E\u4E0E\u672C\u5730\u5B58\u50A8\u53EF\u8BFB\u53D6\u3002")]}function Hf(e){let t=e.units.map(n=>{let a=n.findings.some(i=>i.severity==="critical")?"blocked":n.findings.some(i=>i.severity==="warning")?"attention":"healthy";return{...n,status:a}}),r={total:t.length,healthy:t.filter(n=>n.status==="healthy").length,attention:t.filter(n=>n.status==="attention").length,blocked:t.filter(n=>n.status==="blocked").length};return{schemaVersion:1,workspace:e.workspace,generatedAt:e.generatedAt,status:r.blocked>0?"blocked":r.attention>0?"attention":"healthy",summary:r,units:t}}import{readFile as aa,realpath as Xf}from"node:fs/promises";import wr from"node:path";var ae=class extends Error{code;constructor(t,r){super(r),this.code=t}};async function Zf(e){let t=await Xf(wr.resolve(e.projectRoot)),r=W(e.manifest),n=e.release.release,a=e.currentLock.capabilities.find(m=>m.capabilityId===n.capabilityId&&m.version===n.version);if(!a||a.packageAdoption!==void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Asset-only removal requires an adopted Capability without package ownership");let i=W({...r,capabilities:r.capabilities.filter(m=>m.capabilityId!==n.capabilityId)}),o=Buffer.from(`${JSON.stringify(i,null,2)}
44
+ `),s=await ia(t,"project-capabilities.json");if(!s.exists||s.digest===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","Project manifest is unavailable");let c=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:s.digest,desiredDigest:v(o)},...a.assets.map(m=>({path:m.path,kind:"remove",ownership:m.ownership??"owned-file",baseDigest:m.digest}))],d=await Promise.all(c.map(m=>ia(t,m.path))),l={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:a.assets.map(m=>({path:m.path,ownership:m.ownership??"owned-file",desiredDigest:m.digest})),verifiers:n.verifiers.map(m=>({id:m.id,kind:"file-digest"}))};return{plan:Ne({action:"remove",capability:l,changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),manifest:i,desiredContents:new Map([["project-capabilities.json",o]]),transactionRoot:t,removedSources:[]}}async function ia(e,t){try{let r=await aa(wr.join(e,...t.split("/")));return{path:t,exists:!0,digest:v(r)}}catch(r){if(r.code==="ENOENT")return{path:t,exists:!1};throw r}}async function Xc(e){if(e.release.release.schemaVersion===2&&e.release.release.packageSources.length>0&&e.packageSource===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires verified package source facts");let t=await Xf(wr.resolve(e.projectRoot)),r=W(e.manifest),n=e.release.release,a=e.packageSource?.topology,i=a?.transactionRoot??t,o=k=>a?.mode==="pnpm-shared-lockfile"?`${a.unitRelativeRoot}/${k}`:k;if(n.kind!=="engineering-feature"||n.consumerProfile!=="any-project")throw new ae("CAPABILITY_KIND_UNSUPPORTED","Only an addable engineering feature can use this lifecycle");if(r.capabilities.some(k=>k.capabilityId===n.capabilityId))throw new ae("CAPABILITY_ALREADY_SELECTED","The capability is already selected by this project");let s=r.profile?.id,c=s==="typescript-library"?"blank-typescript-library":s,d=n.dependencies?.profiles??[],l=e.currentLock.capabilities.find(k=>k.consumerProfile===c);if(c===void 0||!d.includes(c)||l===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The project profile does not satisfy this capability dependency");if((n.dependencies?.capabilities??[]).some(k=>!r.capabilities.some(S=>S.capabilityId===k)||!e.currentLock.capabilities.some(S=>S.capabilityId===k)))throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","A required project capability is not adopted and verified");let m=W({...r,capabilities:[...r.capabilities,{capabilityId:n.capabilityId,version:n.version}]}),u=o("project-capabilities.json"),f=Buffer.from(`${JSON.stringify(m,null,2)}
45
+ `),g=await ia(i,u);if(!g.exists||g.digest===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The project manifest is unavailable");let h=[{path:u,kind:"replace",ownership:"owned-file",baseDigest:g.digest,desiredDigest:v(f)}],w=new Map([[u,f]]),_;if(n.schemaVersion===2&&n.packageSources.length>0){if(e.packageSource===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires verified package source facts");let k;try{k=await aa(wr.join(t,"package.json"))}catch{throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","\u9879\u76EE package.json \u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u751F\u6210\u5305\u91C7\u7528\u8BA1\u5212")}try{let S=e.packageSource.currentLockfile??await aa(wr.join(t,"pnpm-lock.yaml")).catch(re=>re.code==="ENOENT"?void 0:Promise.reject(re)),O=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"},ie=O.mode==="pnpm-shared-lockfile",$={mode:O.mode,unitRelativeRoot:O.unitRelativeRoot,unitImporterId:O.unitImporterId,lockfilePath:O.lockfilePath,...O.workspaceManifestPath?{workspaceManifestPath:O.workspaceManifestPath,workspaceManifestDigest:O.workspaceManifestDigest}:{}},P={registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections};if(ie&&(!e.packageSource.resolutionEvidence||!e.packageSource.resolutionWorkerReleaseId))throw new Y("PACKAGE_SOURCE_POLICY_VIOLATION");let K=ie?(e.packageChannel==="development"?Di:Ni)({release:n,...P,consumerProfile:c,packageJson:k,currentLockfile:S,generatedAt:e.generatedAt,expiresAt:e.expiresAt,topology:$,preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Pi:Ri)({release:n,...P,lockResolution:e.packageSource.lockResolution,consumerProfile:c,packageJson:k,...S===void 0?{}:{currentLockfile:S},generatedAt:e.generatedAt,expiresAt:e.expiresAt});_=_i(K),h.push({path:o("package.json"),kind:"replace",ownership:"owned-file",baseDigest:K.packageJsonPreimageDigest,desiredDigest:K.desiredPackageJsonDigest}),w.set(o("package.json"),K.desiredPackageJson),h.push({path:O.lockfilePath,kind:S===void 0?"create":"replace",ownership:"owned-file",...S===void 0?{}:{baseDigest:v(S)},desiredDigest:K.desiredLockfileDigest}),w.set(O.lockfilePath,K.desiredLockfile)}catch(S){throw S instanceof Y?new ae("CAPABILITY_PACKAGE_SOURCE_INVALID",S.code):S}}for(let k of n.assets){let S=e.release.contents.get(k.path);if(S===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Capability asset content is unavailable");let O=k.renderer==="application-config-contract-v1"?Si(r):k.renderer==="application-config-binding-v1"?ji(r):S;if(k.ownership==="managed-region"){if(k.regionId===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Managed region identity is unavailable");let ie;try{ie=await aa(wr.join(t,...k.path.split("/")))}catch{throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The managed shared file is unavailable")}let $=Buffer.from(hu({source:ie.toString("utf8"),regionId:k.regionId,content:Buffer.from(O).toString("utf8")}));h.push({path:o(k.path),kind:"merge",ownership:"managed-region",regionId:k.regionId,baseDigest:v(ie),desiredDigest:v($)}),w.set(o(k.path),$)}else{let ie=await ia(t,k.path);if(k.ownership==="seed-file"&&ie.exists){let $=await aa(wr.join(t,...k.path.split("/")));h.push({path:o(k.path),kind:"create",ownership:"seed-file",desiredDigest:v($)}),w.set(o(k.path),$)}else h.push({path:o(k.path),kind:"create",ownership:k.ownership,desiredDigest:v(O)}),w.set(o(k.path),O)}}let b=await Promise.all(h.map(k=>ia(i,k.path))),A={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:h.filter(k=>k.path!==u&&k.path!==a?.lockfilePath).map(k=>({path:a?.mode==="pnpm-shared-lockfile"?k.path.slice(a.unitRelativeRoot.length+1):k.path,ownership:k.ownership,desiredDigest:k.desiredDigest})),verifiers:n.verifiers.map(k=>({id:k.id,kind:"file-digest"}))};return{plan:Ne({action:"adopt",capability:A,changes:h,observedAssets:b,generatedAt:e.generatedAt,expiresAt:e.expiresAt,..._===void 0?{}:{packageAdoption:_}}),manifest:m,desiredContents:w,transactionRoot:i,dependency:{profile:c,satisfied:!0}}}var Qf=Ir(rr(),1);var hE={$id:"https://schemas.dyyto.dev/platform/solution-catalog-entry-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","solutionId","version","integrity","title","summary","maturity","members","integration","exit"],properties:{schemaVersion:{const:1},solutionId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:dt},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},maturity:{enum:["guided","automated"]},members:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","role","required"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},role:{type:"string",minLength:1,maxLength:80},required:{type:"boolean"}}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","steps","verification","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},steps:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["label","command"],properties:{label:{type:"string",minLength:1,maxLength:80},command:{type:"string",minLength:1,maxLength:2e3}}}},verification:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:1e3}},result:{type:"string",minLength:1,maxLength:400}}},exit:{type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string",minLength:1,maxLength:400}}}}},eD=new Qf.Ajv2020({allErrors:!0,strict:!0}).compile(hE);var am=Ir(rr(),1);import{readFile as yE,realpath as wE}from"node:fs/promises";import em from"node:path";var tm="^[a-z0-9]+(?:[.-][a-z0-9]+)*$",rm="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)[^\\u0000]+$",vE={$id:"https://schemas.dyyto.dev/platform/example-recipe-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","recipeId","version","integrity","title","locale","rootProfile","capabilities","expectedEntrypoint","verifiers","manualAcceptance","cleanup"],properties:{schemaVersion:{const:1},recipeId:{type:"string",pattern:tm},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:dt},title:{type:"string",minLength:1,maxLength:80},locale:{const:"zh-CN"},rootProfile:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128}}},capabilities:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","channel"],properties:{capabilityId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},channel:{const:"development"}}}},expectedEntrypoint:{type:"string",pattern:rm,maxLength:240},verifiers:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",pattern:tm}},manualAcceptance:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:240}},cleanup:{type:"object",additionalProperties:!1,required:["ownedStateDirectories"],properties:{ownedStateDirectories:{type:"array",maxItems:8,uniqueItems:!0,items:{type:"string",pattern:rm,maxLength:240}}}}}},nm=new am.Ajv2020({allErrors:!0,strict:!0}).compile(vE),vr=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function IE(e){return v(E(e))}function bE(e){if(!nm(e))throw new vr("EXAMPLE_RECIPE_INVALID",nm.errors??[]);let t=e,r=[t.rootProfile.capabilityId,...t.capabilities.map(n=>n.capabilityId)];if(new Set(r).size!==r.length||t.capabilities.some(n=>n.version.includes("workspace:")||n.capabilityId.includes("ai-education-poc")))throw new vr("EXAMPLE_RECIPE_INVALID");return t}async function im(e){let t=await wE(em.resolve(e)),r;try{r=bE(JSON.parse(await yE(em.join(t,"recipe.json"),"utf8")))}catch(i){throw i instanceof vr?i:new vr("EXAMPLE_RECIPE_INVALID")}let{integrity:n,...a}=r;if(IE(a)!==n)throw new vr("EXAMPLE_RECIPE_INTEGRITY_MISMATCH");return r}var cm=Ir(rr(),1);import{readFile as kE,realpath as _E}from"node:fs/promises";import om from"node:path";var EE={$id:"https://schemas.dyyto.dev/platform/engineering-template-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","templateId","version","integrity","title","summary","status","profile","parameters","commands","technology","support","integration","metrics"],properties:{schemaVersion:{const:1},templateId:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:dt},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},status:{enum:["candidate","recommended","deprecated"]},profile:{type:"object",additionalProperties:!1,required:["id","capability"],properties:{id:{type:"string",pattern:H},capability:{type:"string",pattern:`${H.slice(1,-1)}@[0-9]+\\.[0-9]+\\.[0-9]+$`}}},parameters:{type:"array",minItems:0,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","required","description"],properties:{id:{type:"string",pattern:"^[a-z][A-Za-z0-9]*$"},required:{type:"boolean"},description:{type:"string",minLength:1,maxLength:160}}}},commands:{type:"object",minProperties:1,additionalProperties:!1,properties:{dev:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},build:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},test:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},package:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"}}},technology:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","version","policy","verifiedAt","rationale","alternative","exit"],properties:{id:{type:"string",pattern:H},version:{type:"string",minLength:1,maxLength:64},policy:{enum:["recommended","allowed"]},verifiedAt:{type:"string",format:"date"},rationale:{type:"string",minLength:1,maxLength:240},alternative:{type:"string",minLength:1,maxLength:160},exit:{type:"string",minLength:1,maxLength:240}}}},support:{type:"object",additionalProperties:!1,required:["owner","tier","supportedFrom","supportedUntil","upgradeCadence","eolNoticeDays"],properties:{owner:{type:"string",pattern:H},tier:{const:"production"},supportedFrom:{type:"string",format:"date"},supportedUntil:{type:"string",format:"date"},upgradeCadence:{type:"string",minLength:1,maxLength:80},eolNoticeDays:{type:"integer",minimum:30,maximum:730}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","createCommand","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},createCommand:{type:"string",minLength:1,maxLength:2e3},result:{type:"string",minLength:1,maxLength:400}}},metrics:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["time-to-green-build","time-to-first-business-commit","manual-engineering-edits","upgrade-conflicts"]}}}},sm=new cm.Ajv2020({allErrors:!0,strict:!0,formats:{date:/^\d{4}-\d{2}-\d{2}$/}}).compile(EE),At=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function AE(e){return v(E(e))}function RE(e){if(!sm(e))throw new At("TEMPLATE_INVALID",sm.errors??[]);let t=e;if(new Set(t.parameters.map(r=>r.id)).size!==t.parameters.length||new Set(t.technology.map(r=>r.id)).size!==t.technology.length)throw new At("TEMPLATE_INVALID");if(Date.parse(t.support.supportedUntil)<=Date.parse(t.support.supportedFrom))throw new At("TEMPLATE_INVALID");return t}async function oa(e,t=new Date){let r=await _E(om.resolve(e)),n;try{n=RE(JSON.parse(await kE(om.join(r,"template.json"),"utf8")))}catch(o){throw o instanceof At?o:new At("TEMPLATE_INVALID")}let{integrity:a,...i}=n;if(AE(i)!==a)throw new At("TEMPLATE_INTEGRITY_MISMATCH");if(n.status==="recommended"&&Date.parse(n.support.supportedUntil)<t.getTime())throw new At("TEMPLATE_SUPPORT_EXPIRED");return n}import{readFile as lm}from"node:fs/promises";import dm from"node:path";var PE=/^[A-Z][A-Z0-9_]*$/u,NE=/(?:API_KEY|ACCESS_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|DATABASE_URL|POSTGRES_URL)$/u;function DE(e){let t=new Map;for(let r of e.split(/\r?\n/u)){let n=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(r.trim());if(!n||!PE.test(n[1]))continue;let a=n[1],i=n[2].trim();t.set(a,{name:a,requirement:i.length===0?"conditional":"optional",secret:NE.test(a),configured:!1,source:".env.example",configuredSource:null})}return[...t.values()]}async function pm(e){let t=await lm(dm.join(e.projectRoot,".env.example"),"utf8").then(()=>".env.example").catch(()=>null),r=t?await lm(dm.join(e.projectRoot,t),"utf8"):"",n=await $i({projectRoot:e.projectRoot}).catch(()=>null);return{commands:["dev","build","test","package"].flatMap(i=>e.commands[i]?[{id:i,script:e.commands[i],mode:i==="dev"?"managed-process":"foreground-task"}]:[]),environment:n?n.entries.map(i=>({name:i.name,requirement:i.required?"conditional":"optional",secret:i.kind!=="value",configured:i.configured,source:"application-config-contract",configuredSource:"APP_CONFIG_DIR",display:i.display,...i.fingerprint?{fingerprint:i.fingerprint}:{}})):DE(r),environmentExample:t,productionValidation:{contract:!0,live:["provider-read","oss-write-read-delete"]}}}var um={change:new Set(["plan","apply","upgrade","recover","baseline-next","add-package","add-application","add-feature"]),quality:new Set(["inspect","verify","doctor","maintenance","test","build"]),delivery:new Set(["package","delivery-plan","delivery-apply","delivery-inspect"])},fm=new Set(["queued","running","succeeded","failed","outcome-unknown","cancelled"]);function mm(e,t){if(!um[t.plane]||t.state&&!fm.has(t.state)||t.limit!==void 0&&(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>200))throw new Error("OPERATION_FILTER_INVALID");let r=um[t.plane],n=t.from?Date.parse(t.from):null,a=t.to?Date.parse(t.to):null;if(n!==null&&Number.isNaN(n)||a!==null&&Number.isNaN(a)||n!==null&&a!==null&&n>a)throw new Error("OPERATION_FILTER_INVALID");let i=e.filter(d=>r.has(d.operation)),o=[...new Map(i.map(d=>[d.projectId,{id:d.projectId,name:d.projectName}])).values()].sort((d,l)=>d.name.localeCompare(l.name)),s=i.filter(d=>(!t.projectId||d.projectId===t.projectId)&&(!t.state||d.state===t.state)&&(!t.kind||d.operation===t.kind)&&(n===null||Date.parse(d.createdAt)>=n)&&(a===null||Date.parse(d.createdAt)<=a)).sort((d,l)=>l.updatedAt.localeCompare(d.updatedAt)),c={total:s.length,running:s.filter(d=>d.state==="running"||d.state==="queued").length,succeeded:s.filter(d=>d.state==="succeeded").length,attention:s.filter(d=>d.state==="failed"||d.state==="outcome-unknown").length};return Object.freeze({schemaVersion:1,plane:t.plane,summary:Object.freeze(c),facets:Object.freeze({projects:Object.freeze(o),states:Object.freeze([...fm]),kinds:Object.freeze([...r])}),items:Object.freeze(s.slice(0,t.limit??50).map(Object.freeze)),hasMore:s.length>(t.limit??50)})}var sa=class extends Error{code;constructor(t,r){super(r),this.code=t}},Qc=/^sha256:[a-f0-9]{64}$/u,SE=/^sha512-[A-Za-z0-9+/]{86}==$/u,jE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,$E=/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?$/u,OE=/[\u0000-\u001f\u007f]/u;function Xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Zr(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((a,i)=>a===n[i])}function Rt(e,t=500){return typeof e=="string"&&e.length>0&&e.length<=t&&!OE.test(e)}function Zc(e){return Rt(e,500)&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")}function gm(e,t=128){return Array.isArray(e)&&e.length<=t&&e.every(r=>Rt(r,500))&&e.every((r,n)=>n===0||e[n-1]<r)}function CE(e){return e===null?!0:!Xr(e)||!Zr(e,["fileName","digest","integrity","fileCount","unpackedBytes"])?!1:Zc(e.fileName)&&Qc.test(String(e.digest))&&SE.test(String(e.integrity))&&Number.isSafeInteger(e.fileCount)&&Number(e.fileCount)>0&&Number.isSafeInteger(e.unpackedBytes)&&Number(e.unpackedBytes)>0}function TE(e){if(!Xr(e)||!Zr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence"])||e.schemaVersion!==1||e.kind!=="PackageRelease"||!jE.test(e.packageName)||!$E.test(e.version)||!Rt(e.title,120)||!Rt(e.summary,1e3)||!["candidate","stable","deprecated"].includes(e.maturity)||!Xr(e.source)||!Zr(e.source,["repository","path","revision","treeDigest"])||!Rt(e.source.repository)||!Zc(e.source.path)||!Rt(e.source.revision,200)||!Qc.test(String(e.source.treeDigest))||!CE(e.artifact)||!Xr(e.compatibility)||!Zr(e.compatibility,["node","packageManager"])||!Rt(e.compatibility.node,100)||!Rt(e.compatibility.packageManager,100)||!gm(e.exports)||!gm(e.consumerEvidence)||!Xr(e.documentation))return!1;let t=e.documentation.knowledgeRef===void 0?["readme"]:["readme","knowledgeRef"];return!Zr(e.documentation,t)||!Zc(e.documentation.readme)||e.documentation.knowledgeRef!==void 0&&!Rt(e.documentation.knowledgeRef,500)?!1:e.artifact!==null||e.maturity!=="stable"}function xE(e){let t={schemaVersion:1,kind:"PackageRelease",...e,source:Object.freeze({...e.source}),artifact:e.artifact===null?null:Object.freeze({...e.artifact}),compatibility:Object.freeze({...e.compatibility}),exports:Object.freeze([...e.exports]),documentation:Object.freeze({...e.documentation}),consumerEvidence:Object.freeze([...e.consumerEvidence])};if(!TE(t))throw new sa("PACKAGE_RELEASE_INVALID","PackageRelease \u5185\u5BB9\u65E0\u6548");return Object.freeze({...t,releaseDigest:v(E(t))})}function hm(e){if(!Xr(e)||!Zr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence","releaseDigest"])||!Qc.test(String(e.releaseDigest)))throw new sa("PACKAGE_RELEASE_INVALID","PackageRelease \u7ED3\u6784\u65E0\u6548");let{releaseDigest:t,schemaVersion:r,kind:n,...a}=e,i=xE(a);if(i.releaseDigest!==t)throw new sa("PACKAGE_RELEASE_MODIFIED","PackageRelease \u5DF2\u88AB\u4FEE\u6539");return i}import{lstat as LE,readFile as VE,realpath as ME}from"node:fs/promises";import ym from"node:path";async function wm(e){let t=await ME(ym.resolve(e.projectRoot)),r=new Set(e.excludeCapabilityIds??[]),n=new Map,a=[...e.lock.capabilities].sort((o,s)=>o.committedAt.localeCompare(s.committedAt)||o.capabilityId.localeCompare(s.capabilityId));for(let o of a)if(!r.has(o.capabilityId))for(let s of o.assets){let c=s.ownership??"owned-file",d=`${s.path}\0`;if(c==="managed-region")n.delete(d);else for(let p of n.keys())p.startsWith(d)&&n.delete(p);let l=c==="managed-region"?`${d}${s.regionId??""}`:d;n.set(l,{capabilityId:o.capabilityId,path:s.path,digest:s.digest,ownership:c,...s.regionId===void 0?{}:{regionId:s.regionId}})}let i=[];for(let o of[...n.values()].sort((s,c)=>s.path.localeCompare(c.path)||(s.regionId??"").localeCompare(c.regionId??"")||s.capabilityId.localeCompare(c.capabilityId))){let s=ym.join(t,...o.path.split("/")),d=await LE(s).then(async l=>{if(!l.isFile()||l.isSymbolicLink())return;let p=await VE(s);if(o.ownership!=="managed-region")return v(p);if(o.regionId!==void 0)try{return v(Xa(p.toString("utf8"),o.regionId))}catch{return}}).catch(l=>l.code==="ENOENT"?void 0:Promise.reject(l))===o.digest;i.push({capabilityId:o.capabilityId,path:o.path,kind:"create",ownership:o.ownership,...o.regionId===void 0?{}:{regionId:o.regionId},desiredDigest:o.digest,disposition:d?"noop":"conflict",...d?{}:{conflictCode:"BASE_DIGEST_MISMATCH"}})}return i}var el="0.1.23",ca={DEPENDENCIES_NOT_INSTALLED:4,VERIFIER_RUNTIME_INVALID:4},qE=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/u;function vm(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!qE.test(e)}function UE(e){let t={schemaVersion:1,kind:"dyyto-cli-domain-error",code:e.code,message:e.message,exitCode:ca[e.code],...e.nextStep===void 0?{}:{nextStep:e.nextStep}},r=FE(t);if(r===null)throw new TypeError("CLI domain error input is invalid");return r}function FE(e){try{if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype)return null;let t=Object.getOwnPropertyDescriptors(e);if(Reflect.ownKeys(t).some(s=>typeof s=="symbol"))return null;let r=Object.keys(t).sort(),n="nextStep"in t?["code","exitCode","kind","message","nextStep","schemaVersion"]:["code","exitCode","kind","message","schemaVersion"];if(r.length!==n.length||r.some((s,c)=>s!==n[c])||Object.values(t).some(s=>!("value"in s)))return null;let a=s=>t[s]?.value,i=a("code");if(a("schemaVersion")!==1||a("kind")!=="dyyto-cli-domain-error"||typeof i!="string"||!(i in ca)||a("exitCode")!==ca[i]||!vm(a("message"),500))return null;let o=a("nextStep");return o!==void 0&&!vm(o,500)?null:Object.freeze({schemaVersion:1,kind:"dyyto-cli-domain-error",code:i,message:a("message"),exitCode:4,...o===void 0?{}:{nextStep:o}})}catch{return null}}var Ce=class extends Error{code;exitCode;nextStep;domainError;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.exitCode=t.exitCode,this.nextStep=t.nextStep,this.domainError=t.code in ca&&t.exitCode===ca[t.code]?UE({code:t.code,message:t.message,...t.nextStep===void 0?{}:{nextStep:t.nextStep}}):void 0}};var Im=`Dyyto Engineering Platform CLI
45
46
 
46
47
  Usage:
47
48
  dyyto <command> [options]
@@ -54,7 +55,7 @@ Commands:
54
55
  dyyto docs show --id ID \u8BFB\u53D6npm\u5305\u5185\u7A33\u5B9A\u6587\u6863
55
56
  dyyto create Initialize a project manifest and plan
56
57
  dyyto scaffold example Plan or apply a Catalog-driven example under .examples
57
- dyyto retrofit Safely initialize a manifest in an existing pnpm workspace
58
+ dyyto retrofit \u4E3A\u65E2\u6709Workspace\u6216\u663E\u5F0FProfile\u9879\u76EE\u751F\u6210Manifest Plan
58
59
  dyyto baseline Plan seed-file adoption for a historical Next.js project
59
60
  dyyto dev Run the template's supported foreground development server
60
61
  dyyto build Run the template's supported build command
@@ -94,86 +95,86 @@ Options:
94
95
  --json Emit one machine-readable JSON object
95
96
  --help Show help
96
97
  --version Show version
97
- `;import{lstat as DS,readFile as UE,readdir as FE}from"node:fs/promises";import bm from"node:path";var Im={"workspace-node-application":"foundation.workspace-node-application@1.1.0","workspace-web-application":"foundation.workspace-web-application@1.1.0","workspace-expo-application":"foundation.workspace-expo-application@1.0.0","nextjs-full-stack-application":"foundation.nextjs-full-stack-application@1.0.0"};function km(e,t="package"){let r=t==="fixture"?"fixtures":"packages";return new RegExp(`^${r}/[a-z0-9][a-z0-9._-]*$`).test(e)?void 0:`Package path must be exactly ${r}/<lowercase-slug>.`}function _m(e,t,r){if(!(t in Im))return"Add application requires a supported --profile.";let n=Im[t];if(r!==n)return`Add application with profile ${t} requires --capability ${n}.`;if(!/^apps\/[a-z0-9][a-z0-9._-]*$/.test(e))return/^services\/[a-z0-9][a-z0-9._-]*$/.test(e)?t==="workspace-node-application"?void 0:"Service applications require profile workspace-node-application.":"Application path must be exactly apps/<lowercase-slug> or services/<lowercase-slug>."}async function zi(e,t,r){for(let n of await FE(bm.join(e,t),{withFileTypes:!0}).catch(()=>[]))if(!(!n.isDirectory()||n.isSymbolicLink()))try{if(JSON.parse(await UE(bm.join(e,t,n.name,"project-capabilities.json"),"utf8")).profile?.parameters?.name===r)return!0}catch(a){if(a.code!=="ENOENT")throw a}return!1}async function Em(e,t){return await zi(e,"apps",t)||await zi(e,"services",t)}import{lstat as Am,mkdir as rl,readFile as Rm,realpath as tl,rm as zE,writeFile as Pm}from"node:fs/promises";import Fe from"node:path";var ze=class extends Error{constructor(r,n){super(r,n===void 0?void 0:{cause:n});this.code=r}code},BE=e=>E(e),Nm=e=>v(BE(e));async function Dm(e,t){let r=await tl(Fe.resolve(e)),n=Fe.join(r,".examples");await rl(n,{recursive:!0});let a=await tl(n),i=Fe.resolve(r,t);if(Fe.dirname(i)!==a||Fe.basename(i).startsWith(".")||Fe.basename(i).length<1)throw new ze("SCAFFOLD_ARGUMENT_INVALID");if(await Am(i).then(()=>!0).catch(o=>o.code==="ENOENT"?!1:Promise.reject(o)))throw new ze("SCAFFOLD_TARGET_CONFLICT");return{workspaceRoot:r,output:i,outputRelativePath:Fe.relative(r,i)}}async function Sm(e){let t=e.artifactFallbackBundles??[];if(!/^sha256:[a-f0-9]{64}$/u.test(e.artifactBundle)||t.some(c=>!/^sha256:[a-f0-9]{64}$/u.test(c))||new Set([e.artifactBundle,...t]).size!==1+t.length||!Number.isSafeInteger(e.artifactPort)||e.artifactPort<1||e.artifactPort>65535)throw new ze("SCAFFOLD_ARGUMENT_INVALID");let r=await Dm(e.workspaceRoot,e.output),n=e.now??new Date().toISOString(),a={schemaVersion:1,state:"reviewable",recipeId:e.recipe.recipeId,recipeVersion:e.recipe.version,recipeIntegrity:e.recipe.integrity,workspaceRoot:r.workspaceRoot,outputRelativePath:r.outputRelativePath,locale:e.recipe.locale,channel:"development",artifactBundle:e.artifactBundle,artifactFallbackBundles:t,artifactPort:e.artifactPort,generatedAt:n,expiresAt:new Date(Date.parse(n)+30*6e4).toISOString()},i={...a,planId:Nm(a)},o=Fe.join(r.workspaceRoot,".dyyto","scaffold-plans");await rl(o,{recursive:!0});let s=Fe.join(o,`${i.planId}.json`);return await Pm(s,`${E(i)}
98
- `,{flag:"wx",mode:384}).catch(async c=>{if(c.code!=="EEXIST"||await Rm(s,"utf8")!==`${E(i)}
99
- `)throw new ze("SCAFFOLD_PLAN_INVALID")}),i}async function JE(e,t){if(!/^sha256:[a-f0-9]{64}$/u.test(t))throw new ze("SCAFFOLD_PLAN_INVALID");let r=await tl(Fe.resolve(e)),n;try{n=JSON.parse(await Rm(Fe.join(r,".dyyto","scaffold-plans",`${t}.json`),"utf8"))}catch{throw new ze("SCAFFOLD_PLAN_NOT_FOUND")}let{planId:a,...i}=n;if(a!==t||Nm(i)!==t||n.workspaceRoot!==r||Date.parse(n.expiresAt)<=Date.now())throw new ze("SCAFFOLD_PLAN_INVALID");return n}async function jm(e){let t=await JE(e.workspaceRoot,e.approvedPlanId);if(t.recipeId!==e.recipe.recipeId||t.recipeVersion!==e.recipe.version||t.recipeIntegrity!==e.recipe.integrity)throw new ze("SCAFFOLD_PLAN_INVALID");let r=await Dm(t.workspaceRoot,t.outputRelativePath),n;try{n=await e.execute(r.output,t)}catch(s){throw await Am(r.output).then(()=>!0).catch(()=>!1)&&await zE(r.output,{recursive:!0,force:!0}),new ze("SCAFFOLD_APPLY_FAILED",s)}let a={schemaVersion:1,scaffoldPlanId:t.planId,recipeIntegrity:t.recipeIntegrity,outputRelativePath:t.outputRelativePath,state:"adopted",receipts:n},i=v(E(a)),o=Fe.join(t.workspaceRoot,".dyyto","scaffold-evidence");return await rl(o,{recursive:!0}),await Pm(Fe.join(o,`${i}.json`),`${E({...a,evidenceId:i})}
100
- `,{flag:"wx",mode:384}),{evidenceId:i,output:r.output,receipts:n}}import{lstat as la,readFile as nl,readdir as GE,realpath as al}from"node:fs/promises";import le from"node:path";var $m={capabilities:le.resolve(import.meta.dirname,"catalog"),packages:le.resolve(import.meta.dirname,"package-releases")};function WE(e){let t=new Map;for(let[r,n]of e.split(/\r?\n/u).entries()){let a=n.trim();if(a===""||a.startsWith("#"))continue;if(a.startsWith("export "))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u4F7F\u7528 export`);let i=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(a);if(!i)throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u662F\u4E25\u683C KEY=VALUE \u683C\u5F0F`);if(t.has(i[1]))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u5305\u542B\u91CD\u590D\u53D8\u91CF ${i[1]}`);let o=i[2].trim();if((o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),/[`$][({]?/u.test(o))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u547D\u4EE4\u6216\u53D8\u91CF\u5C55\u5F00`);t.set(i[1],o)}return t}async function Om(e,t){let r=await la(e);if(!r.isFile()||r.isSymbolicLink()||r.nlink!==1)throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u975E\u94FE\u63A5\u6587\u4EF6`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-385)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80600`)}async function Bi(e,t){let r=await la(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u76EE\u5F55\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-449)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80700`);return al(e)}async function KE(e){let t=e;for(;;){if(await la(le.join(t,".git")).then(()=>!0).catch(n=>n.code==="ENOENT"?!1:Promise.reject(n)))throw new Error(`IDP_CONFIG_DIR \u5FC5\u987B\u4F4D\u4E8E Git \u4ED3\u5E93\u5916\uFF1A${t}`);let r=le.dirname(t);if(r===t)return;t=r}}async function YE(e){if(!le.isAbsolute(e))throw new Error("IDP_CONFIG_DIR \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let t=await Bi(e,"IDP_CONFIG_DIR");await KE(t);let r=await Bi(le.join(t,"components"),"components"),n=await Bi(le.join(r,"dyyto"),"Dyyto \u914D\u7F6E\u76EE\u5F55"),a=le.relative(t,n);if(a.startsWith("..")||le.isAbsolute(a))throw new Error("Dyyto \u914D\u7F6E\u76EE\u5F55\u8D8A\u8FC7 IDP_CONFIG_DIR");let i=le.join(n,".env");await Om(i,"Dyyto \u7EC4\u4EF6 .env");let o=WE(await nl(i,"utf8")).get("DYYTO_PACKAGE_CATALOG_DIRS_FILE");if(o===void 0||o==="")return[];if(le.isAbsolute(o)||o.includes("\0")||/[*?{}[\]]/u.test(o))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u662F\u7EC4\u4EF6\u76EE\u5F55\u5185\u7684\u666E\u901A\u76F8\u5BF9\u6587\u4EF6\u8DEF\u5F84");let s=le.resolve(n,o),c=le.relative(n,s);if(c===""||c.startsWith("..")||le.isAbsolute(c))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u4F4D\u4E8E\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55\u5185");let d=n;for(let u of c.split(le.sep).slice(0,-1))d=await Bi(le.join(d,u),"Package Catalog Binding \u7236\u76EE\u5F55");let l=await al(le.dirname(s)),p=le.relative(n,l);if(p.startsWith("..")||le.isAbsolute(p))throw new Error("Package Catalog Binding \u89E3\u6790\u540E\u8D8A\u8FC7\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55");await Om(s,"Package Catalog Binding");let f=[];for(let u of(await nl(s,"utf8")).split(/\r?\n/u)){let m=u.trim();if(m===""||m.startsWith("#"))continue;if(!le.isAbsolute(m))throw new Error("Package Catalog Binding \u4E2D\u7684\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let g=await la(m);if(!g.isDirectory()||g.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");let h=await al(m),w=await la(h);if(!w.isDirectory()||w.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");f.includes(h)||f.push(h)}return f.sort()}async function HE(){let e=process.env.IDP_CONFIG_DIR,t=e===void 0?[]:await YE(e);return{capabilities:$m.capabilities,packages:[$m.packages,...t]}}async function Ji(e){return(await GE(e,{withFileTypes:!0})).filter(t=>t.isDirectory()&&!t.isSymbolicLink()).map(t=>t.name).sort()}function XE(e,t){let r=i=>i.split("-",1)[0].split(".").map(Number),n=r(e),a=r(t);for(let i=0;i<3;i+=1){let o=(n[i]??0)-(a[i]??0);if(o!==0)return o}return e.localeCompare(t)}function ZE(e){let t=e.schemaVersion===2?e.availability.maturity:"legacy-unverified",r="consumerProfile"in e?e.consumerProfile:"\u591A\u79CD\u5DE5\u7A0B Profile";return{kind:"capability",ref:`capability:${e.capabilityId}@${e.version}`,id:e.capabilityId,version:e.version,title:e.capabilityId,summary:`\u9002\u7528\u4E8E ${r} \u7684\u5DE5\u7A0B\u80FD\u529B\u53D1\u884C\u3002`,maturity:t,integrity:e.integrity}}function QE(e){return{kind:"package",ref:`package:${e.packageName}@${e.version}`,id:e.packageName,version:e.version,title:e.title,summary:e.summary,maturity:e.maturity,integrity:e.releaseDigest}}async function eA(e){let t=[];for(let r of await Ji(e))for(let n of await Ji(le.join(e,r))){let a=`capability:${r}@${n}`;t.push(me(le.join(e,r,n)).then(i=>({entry:{item:ZE(i.release),release:i.release}})).catch(()=>({diagnostic:{ref:a,code:"CATALOG_RELEASE_INVALID",message:"Capability \u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function tA(e){let t=[];for(let r of await Ji(e))for(let n of await Ji(le.join(e,r))){let a=le.join(e,r,n,"release.json"),i=`package:${r}@${n}`;t.push(nl(a,"utf8").then(o=>{let s=gm(JSON.parse(o));return{entry:{item:QE(s),release:s}}}).catch(()=>({diagnostic:{ref:i,code:"CATALOG_RELEASE_INVALID",message:"PackageRelease \u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function Cm(e){let t=e??await HE(),r=typeof t.packages=="string"?[t.packages]:[...t.packages],[n,...a]=await Promise.all([eA(t.capabilities),...r.map(tA)]),i=[...n.entries,...a.flatMap(d=>d.entries)].sort((d,l)=>d.item.ref.localeCompare(l.item.ref)),o=[],s=new Set,c=[];for(let d of i)s.has(d.item.ref)?c.push({ref:d.item.ref,code:"CATALOG_RELEASE_DUPLICATE",message:"\u591A\u4E2A Catalog Source \u58F0\u660E\u4E86\u540C\u4E00\u4E0D\u53EF\u53D8\u53D1\u884C ref"}):(s.add(d.item.ref),o.push(d));return{entries:o,diagnostics:[...n.diagnostics,...a.flatMap(d=>d.diagnostics),...c].sort((d,l)=>d.ref.localeCompare(l.ref))}}async function Tm(e){let t=(e.query??"").trim().toLocaleLowerCase("zh-CN"),r=await Cm(e.roots),n=new Map;for(let{item:o}of r.entries){if(e.kind!==void 0&&o.kind!==e.kind)continue;let s=[o.id,o.version,o.title,o.summary,o.maturity].join(" ").toLocaleLowerCase("zh-CN");if(t!==""&&!s.includes(t))continue;let c=`${o.kind}:${o.id}`,d=n.get(c);(d===void 0||XE(d.version,o.version)<0)&&n.set(c,o)}let a=[...n.values()].sort((o,s)=>o.ref.localeCompare(s.ref)),i=e.limit??50;return{query:t,total:a.length,items:a.slice(0,i),diagnostics:r.diagnostics}}async function xm(e){let t=e.ref.startsWith("package:")||e.ref.startsWith("capability:")?e.ref:`${e.ref.startsWith("@")?"package":"capability"}:${e.ref}`,r=await Cm(e.roots),n=r.entries.find(({item:i})=>i.ref===t),a=r.diagnostics.find(i=>i.ref===t);if(a?.code==="CATALOG_RELEASE_DUPLICATE")throw new Error(`\u53D1\u884C ref \u5728\u591A\u4E2A Catalog Source \u4E2D\u91CD\u590D\uFF1A${e.ref}`);if(n===void 0&&a!==void 0)throw new Error(`\u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C\uFF1A${e.ref}`);if(n===void 0)throw new Error(`\u76EE\u5F55\u4E2D\u4E0D\u5B58\u5728\u53D1\u884C\uFF1A${e.ref}`);return n}var da={"typescript-library":"foundation.typescript-quality@1.0.0","standalone-npm-package":"foundation.standalone-npm-package@1.2.0","workspace-root":"foundation.workspace-root@1.1.0","workspace-npm-package":"foundation.workspace-npm-package@1.2.0","workspace-node-application":"foundation.workspace-node-application@1.1.0","workspace-web-application":"foundation.workspace-web-application@1.1.0","workspace-expo-application":"foundation.workspace-expo-application@1.0.0","react-component-library":"foundation.react-component-library@1.1.0","workspace-react-component-library":"foundation.workspace-react-component-library@1.2.0","nextjs-full-stack-application":"foundation.nextjs-full-stack-application@1.0.0"},qm=aA(rA),iA=new Set(["template.typescript-library@1.0.0","template.typescript-library@1.1.0","template.react-component-library@1.0.0","template.react-component-library@1.1.0","template.nextjs-full-stack-application@1.0.0","template.expo-react-native-application@1.0.0","template.node-api-application@1.0.0","template.workspace-root@1.0.0","template.workspace-root@1.1.0","template.workspace-root@1.2.0","template.workspace-npm-package@1.0.0","template.workspace-react-component-library@1.0.0","template.workspace-react-component-library@1.1.0","template.workspace-react-component-library@1.2.0","template.web-frontend-application@1.0.0"]),Um=(e,t)=>e==="foundation.workspace-root"&&t==="1.4.0"?{id:"template.workspace-root",version:"1.1.0"}:e==="foundation.workspace-root"&&t==="1.5.0"?{id:"template.workspace-root",version:"1.2.0"}:void 0,Gi={"workspace-npm-package":{id:"template.workspace-npm-package",version:"1.0.0"},"react-component-library":{id:"template.workspace-react-component-library",version:"1.2.0"},"workspace-web-application":{id:"template.web-frontend-application",version:"1.0.0"},"workspace-node-application":{id:"template.node-api-application",version:"1.0.0"},"workspace-expo-application":{id:"template.expo-react-native-application",version:"1.0.0"},"nextjs-full-stack-application":{id:"template.nextjs-full-stack-application",version:"1.0.0"}};function Fm(e){return e.capabilities.flatMap(t=>t.assets).filter(t=>t.ownership!=="seed-file")}async function Wi(e,t,r,n){if(t.release.schemaVersion!==2||t.release.packageSources.length===0)return;if(r.packageSourceProvider===void 0)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires a trusted Package Source Provider");let a=await ee(N.join(e,"package.json")),i=await r.packageSourceProvider.inspect({projectRoot:e,release:t.release}),{resolvePnpmLock:o}=await import("./optional-runtime.js"),s=await Wr(e),c=await ee(N.join(s.transactionRoot,s.lockfilePath)).catch(p=>p.code==="ENOENT"?void 0:Promise.reject(p));if(s.mode==="pnpm-shared-lockfile"){if(!c)throw new ne("CAPABILITY_PACKAGE_SOURCE_INVALID","Workspace shared lockfile is unavailable");if(!r.resolutionWorkerProvider)throw new ne("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package adoption requires verified Resolution Worker Evidence");let p=Hn({release:t.release,packageJson:n??a}),f=new Date,u=new Date(f.getTime()+1800*1e3).toISOString(),m=await r.resolutionWorkerProvider.resolveWorkspace({topology:s,desiredPackageJson:p,currentLockfile:c,sources:t.release.packageSources,registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings,generatedAt:f.toISOString(),expiresAt:u});return{...i,lockResolution:{lockfile:m.evidence.desiredLockfile,packages:m.evidence.packageFacts.filter(g=>g.managed).map(({registryId:g,packageName:h,version:w,integrity:_})=>({registryId:g,packageName:h,version:w,integrity:_}))},resolutionEvidence:m.evidence,resolutionWorkerReleaseId:m.workerReleaseId,topology:s,currentLockfile:c,preservedImporterDigests:m.preservedImporterDigests}}let d=Cc({release:t.release,packageJson:n??a}),l=await o({desiredPackageJson:d,...c===void 0?{}:{currentLockfile:c},sources:t.release.packageSources,registries:i.registryConfigs,endpointBindings:i.endpointBindings});return{...i,lockResolution:l,topology:s,...c===void 0?{}:{currentLockfile:c},preservedImporterDigests:[]}}async function zm(e,t,r,n){let a=r.capabilities.find(I=>I.capabilityId===t.release.capabilityId&&I.version===t.release.version);if(a&&!a.packageAdoption){let I=JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8")),A=new Date;return Xf({projectRoot:e,manifest:I,release:t,currentLock:r,generatedAt:A.toISOString(),expiresAt:new Date(A.getTime()+30*6e4).toISOString()})}if(t.release.schemaVersion!==2||n.packageSourceProvider===void 0)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires a trusted Package Source Provider");if(!a?.packageAdoption)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires Lock v2 ownership facts");let i=await n.packageSourceProvider.inspect({projectRoot:e,release:t.release}),o=await ee(N.join(e,"package.json")),s=await ee(N.join(e,"project-capabilities.json")),c=await Wr(e),d=await ee(N.join(c.transactionRoot,c.lockfilePath)),l=new Set(r.capabilities.filter(I=>I!==a).flatMap(I=>I.packageAdoption?.sources.map(A=>A.packageName)??[])),p=a.packageAdoption.sources.filter(I=>!l.has(I.packageName)),f=c.mode==="pnpm-shared-lockfile"?xc({packageJson:o,remove:p}):Tc({packageJson:o,remove:p}),u=r.capabilities.filter(I=>I!==a).flatMap(I=>I.packageAdoption?.sources??[]),m=new Date,g=new Date(m.getTime()+1800*1e3).toISOString();if(c.mode==="pnpm-shared-lockfile"){if(!n.resolutionWorkerProvider)throw new ne("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package removal requires verified Resolution Worker Evidence");let I=await n.resolutionWorkerProvider.resolveWorkspace({topology:c,desiredPackageJson:f,currentLockfile:d,sources:u,registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings,generatedAt:m.toISOString(),expiresAt:g}),A=[`${c.unitRelativeRoot}/project-capabilities.json`,`${c.unitRelativeRoot}/package.json`,c.lockfilePath,...a.assets.map(k=>`${c.unitRelativeRoot}/${k.path}`)],y=await Promise.all(A.map(async k=>ee(N.join(c.transactionRoot,...k.split("/"))).then(S=>({path:k,exists:!0,digest:v(S)})).catch(S=>S.code==="ENOENT"?{path:k,exists:!1}:Promise.reject(S))));return{...nf({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,endpointBindings:i.endpointBindings,observedAssets:y,topology:c,transactionRoot:c.transactionRoot,preservedImporterDigests:I.preservedImporterDigests,resolutionEvidence:I.evidence,resolutionWorkerReleaseId:I.workerReleaseId,remainingSources:u,generatedAt:m.toISOString(),expiresAt:g}),registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings}}let{resolvePnpmLock:h}=await import("./optional-runtime.js"),w=await h({desiredPackageJson:f,currentLockfile:d,sources:u,registrySources:[...u,...a.packageAdoption.sources],registries:i.registryConfigs,endpointBindings:i.endpointBindings}),_=await Promise.all(["project-capabilities.json","package.json","pnpm-lock.yaml",...a.assets.map(I=>I.path)].map(async I=>ee(N.join(e,...I.split("/"))).then(A=>({path:I,exists:!0,digest:v(A)})).catch(A=>A.code==="ENOENT"?{path:I,exists:!1}:Promise.reject(A))));return{...rf({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,desiredLockfile:w.lockfile,endpointBindings:i.endpointBindings,observedAssets:_,generatedAt:m.toISOString(),expiresAt:g}),registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings}}function z(e){return e.includes("--json")?"json":"human"}function b(e){throw new Ce({code:"CLI_ARGUMENT_INVALID",message:e,exitCode:2,nextStep:"Run dyyto --help."})}function Ee(e,t){return!/^[a-z0-9][a-z0-9.-]*$/u.test(e)||!/^\d+\.\d+\.\d+$/u.test(t)?b("The selected capability release identifier is invalid."):N.resolve(import.meta.dirname,"catalog",e,t)}function Ki(e,t){return iA.has(`${e}@${t}`)?N.resolve(import.meta.dirname,"templates",e,t):b("The selected template release is not bundled with this CLI.")}function oA(e,t){return!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(e)||!/^\d+\.\d+\.\d+$/.test(t)?b("The selected example recipe identity or version is invalid."):N.resolve(import.meta.dirname,"recipes",e,t)}function Z(e){let t=N.relative(process.cwd(),e);return t.length>0&&t!==".."&&!t.startsWith(`..${N.sep}`)?t:N.basename(e)}async function Yi(e){let t=JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8")),r=t.capabilities?.[0];if(r===void 0)return b("Project manifest must select one capability.");let n=await me(Ee(r.capabilityId,r.version)),a=await Ne(e).catch(()=>null),i=new Date,s=await(t.profile?.id==="standalone-npm-package"?Bn:t.profile?.id==="react-component-library"?Jn:t.profile?.id==="nextjs-full-stack-application"?Kr:t.profile?.id==="workspace-npm-package"?Gn:t.profile?.id==="workspace-node-application"?Wn:t.profile?.id==="workspace-web-application"?Kn:t.profile?.id==="workspace-expo-application"?Yn:ti)({projectRoot:e,manifest:t,release:n,...a===null?{}:{currentLock:a},generatedAt:i.toISOString(),expiresAt:new Date(i.getTime()+1800*1e3).toISOString()});return dr({projectRoot:e,plan:s.plan,now:i.toISOString()})}async function Bm(e){let t;try{t=se({args:[...e],allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},profile:{type:"string"},template:{type:"string"},capability:{type:"string"},name:{type:"string"},version:{type:"string"},license:{type:"string"},"publish-access":{type:"string"},repository:{type:"string"}}})}catch{return b("Create arguments are invalid.")}if(t.positionals.length!==1)return b("Create requires exactly one directory.");let r=t.values.template,n;if(typeof r=="string"){let[g,h]=r.split("@");n=await oa(Ki(g,h))}let a=n?.profile.id??t.values.profile;if(a!=="typescript-library"&&a!=="standalone-npm-package"&&a!=="react-component-library"&&a!=="nextjs-full-stack-application"&&a!=="workspace-root")return b("Create requires a supported --profile.");let i=t.values.capability,o=a==="workspace-root"&&i==="foundation.workspace-root@1.0.0"||a==="standalone-npm-package"&&i==="foundation.standalone-npm-package@1.0.0",s=n?.profile.capability??(o?i:da[a]);if(n!==void 0&&s.split("@")[0]!==da[a].split("@")[0])return b(`Template ${n.templateId} is adopted with dyyto add, not dyyto create.`);if(n===void 0&&i!==s)return b(`Create requires --capability ${s}.`);if(n!==void 0&&i!==void 0)return b("Create with --template does not accept --capability.");let[c,d]=s.split("@"),l={};if(a==="standalone-npm-package"||a==="react-component-library"){let g=t.values.name,h=t.values.version,w=t.values.license,_=t.values["publish-access"],I=t.values.repository;if([g,h,w,_].some(A=>typeof A!="string")||d==="1.1.0"&&typeof I!="string")return b(`Standalone npm package requires --name, --version, --license, --publish-access${d==="1.1.0"?", and --repository":""}.`);l={name:String(g),version:String(h),license:String(w),publishAccess:String(_),...typeof I=="string"?{repository:I}:{}}}else if(a==="nextjs-full-stack-application"){if(typeof t.values.name!="string")return b("Next.js application requires --name.");l={name:t.values.name}}let p={schemaVersion:1,...n===void 0?{}:{template:{id:n.templateId,version:n.version}},profile:{id:a,parameters:l},capabilities:[{capabilityId:c,version:d}]};(a==="standalone-npm-package"||a==="react-component-library")&&qt(K(p),a),a==="nextjs-full-stack-application"&&pr(K(p));let f=await hi({projectRoot:t.positionals[0],manifest:p}),u=await Yi(f.projectRoot),m=Z(f.projectRoot);return{outputMode:z(e),human:`Project '${m}' initialized.
98
+ `;import{lstat as jS,readFile as zE,readdir as BE}from"node:fs/promises";import km from"node:path";var bm={"workspace-node-application":"foundation.workspace-node-application@1.1.0","workspace-web-application":"foundation.workspace-web-application@1.1.0","workspace-expo-application":"foundation.workspace-expo-application@1.0.0","nextjs-full-stack-application":"foundation.nextjs-full-stack-application@1.0.0"};function _m(e,t="package"){let r=t==="fixture"?"fixtures":"packages";return new RegExp(`^${r}/[a-z0-9][a-z0-9._-]*$`).test(e)?void 0:`Package path must be exactly ${r}/<lowercase-slug>.`}function Em(e,t,r){if(!(t in bm))return"Add application requires a supported --profile.";let n=bm[t];if(r!==n)return`Add application with profile ${t} requires --capability ${n}.`;if(!/^apps\/[a-z0-9][a-z0-9._-]*$/.test(e))return/^services\/[a-z0-9][a-z0-9._-]*$/.test(e)?t==="workspace-node-application"?void 0:"Service applications require profile workspace-node-application.":"Application path must be exactly apps/<lowercase-slug> or services/<lowercase-slug>."}async function zi(e,t,r){for(let n of await BE(km.join(e,t),{withFileTypes:!0}).catch(()=>[]))if(!(!n.isDirectory()||n.isSymbolicLink()))try{if(JSON.parse(await zE(km.join(e,t,n.name,"project-capabilities.json"),"utf8")).profile?.parameters?.name===r)return!0}catch(a){if(a.code!=="ENOENT")throw a}return!1}async function Am(e,t){return await zi(e,"apps",t)||await zi(e,"services",t)}import{lstat as Rm,mkdir as rl,readFile as Pm,realpath as tl,rm as JE,writeFile as Nm}from"node:fs/promises";import Fe from"node:path";var ze=class extends Error{constructor(r,n){super(r,n===void 0?void 0:{cause:n});this.code=r}code},GE=e=>E(e),Dm=e=>v(GE(e));async function Sm(e,t){let r=await tl(Fe.resolve(e)),n=Fe.join(r,".examples");await rl(n,{recursive:!0});let a=await tl(n),i=Fe.resolve(r,t);if(Fe.dirname(i)!==a||Fe.basename(i).startsWith(".")||Fe.basename(i).length<1)throw new ze("SCAFFOLD_ARGUMENT_INVALID");if(await Rm(i).then(()=>!0).catch(o=>o.code==="ENOENT"?!1:Promise.reject(o)))throw new ze("SCAFFOLD_TARGET_CONFLICT");return{workspaceRoot:r,output:i,outputRelativePath:Fe.relative(r,i)}}async function jm(e){let t=e.artifactFallbackBundles??[];if(!/^sha256:[a-f0-9]{64}$/u.test(e.artifactBundle)||t.some(c=>!/^sha256:[a-f0-9]{64}$/u.test(c))||new Set([e.artifactBundle,...t]).size!==1+t.length||!Number.isSafeInteger(e.artifactPort)||e.artifactPort<1||e.artifactPort>65535)throw new ze("SCAFFOLD_ARGUMENT_INVALID");let r=await Sm(e.workspaceRoot,e.output),n=e.now??new Date().toISOString(),a={schemaVersion:1,state:"reviewable",recipeId:e.recipe.recipeId,recipeVersion:e.recipe.version,recipeIntegrity:e.recipe.integrity,workspaceRoot:r.workspaceRoot,outputRelativePath:r.outputRelativePath,locale:e.recipe.locale,channel:"development",artifactBundle:e.artifactBundle,artifactFallbackBundles:t,artifactPort:e.artifactPort,generatedAt:n,expiresAt:new Date(Date.parse(n)+30*6e4).toISOString()},i={...a,planId:Dm(a)},o=Fe.join(r.workspaceRoot,".dyyto","scaffold-plans");await rl(o,{recursive:!0});let s=Fe.join(o,`${i.planId}.json`);return await Nm(s,`${E(i)}
99
+ `,{flag:"wx",mode:384}).catch(async c=>{if(c.code!=="EEXIST"||await Pm(s,"utf8")!==`${E(i)}
100
+ `)throw new ze("SCAFFOLD_PLAN_INVALID")}),i}async function WE(e,t){if(!/^sha256:[a-f0-9]{64}$/u.test(t))throw new ze("SCAFFOLD_PLAN_INVALID");let r=await tl(Fe.resolve(e)),n;try{n=JSON.parse(await Pm(Fe.join(r,".dyyto","scaffold-plans",`${t}.json`),"utf8"))}catch{throw new ze("SCAFFOLD_PLAN_NOT_FOUND")}let{planId:a,...i}=n;if(a!==t||Dm(i)!==t||n.workspaceRoot!==r||Date.parse(n.expiresAt)<=Date.now())throw new ze("SCAFFOLD_PLAN_INVALID");return n}async function $m(e){let t=await WE(e.workspaceRoot,e.approvedPlanId);if(t.recipeId!==e.recipe.recipeId||t.recipeVersion!==e.recipe.version||t.recipeIntegrity!==e.recipe.integrity)throw new ze("SCAFFOLD_PLAN_INVALID");let r=await Sm(t.workspaceRoot,t.outputRelativePath),n;try{n=await e.execute(r.output,t)}catch(s){throw await Rm(r.output).then(()=>!0).catch(()=>!1)&&await JE(r.output,{recursive:!0,force:!0}),new ze("SCAFFOLD_APPLY_FAILED",s)}let a={schemaVersion:1,scaffoldPlanId:t.planId,recipeIntegrity:t.recipeIntegrity,outputRelativePath:t.outputRelativePath,state:"adopted",receipts:n},i=v(E(a)),o=Fe.join(t.workspaceRoot,".dyyto","scaffold-evidence");return await rl(o,{recursive:!0}),await Nm(Fe.join(o,`${i}.json`),`${E({...a,evidenceId:i})}
101
+ `,{flag:"wx",mode:384}),{evidenceId:i,output:r.output,receipts:n}}import{lstat as la,readFile as nl,readdir as KE,realpath as al}from"node:fs/promises";import de from"node:path";var Om={capabilities:de.resolve(import.meta.dirname,"catalog"),packages:de.resolve(import.meta.dirname,"package-releases")};function YE(e){let t=new Map;for(let[r,n]of e.split(/\r?\n/u).entries()){let a=n.trim();if(a===""||a.startsWith("#"))continue;if(a.startsWith("export "))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u4F7F\u7528 export`);let i=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(a);if(!i)throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u662F\u4E25\u683C KEY=VALUE \u683C\u5F0F`);if(t.has(i[1]))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u5305\u542B\u91CD\u590D\u53D8\u91CF ${i[1]}`);let o=i[2].trim();if((o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),/[`$][({]?/u.test(o))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u547D\u4EE4\u6216\u53D8\u91CF\u5C55\u5F00`);t.set(i[1],o)}return t}async function Cm(e,t){let r=await la(e);if(!r.isFile()||r.isSymbolicLink()||r.nlink!==1)throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u975E\u94FE\u63A5\u6587\u4EF6`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-385)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80600`)}async function Bi(e,t){let r=await la(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u76EE\u5F55\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-449)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80700`);return al(e)}async function HE(e){let t=e;for(;;){if(await la(de.join(t,".git")).then(()=>!0).catch(n=>n.code==="ENOENT"?!1:Promise.reject(n)))throw new Error(`IDP_CONFIG_DIR \u5FC5\u987B\u4F4D\u4E8E Git \u4ED3\u5E93\u5916\uFF1A${t}`);let r=de.dirname(t);if(r===t)return;t=r}}async function XE(e){if(!de.isAbsolute(e))throw new Error("IDP_CONFIG_DIR \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let t=await Bi(e,"IDP_CONFIG_DIR");await HE(t);let r=await Bi(de.join(t,"components"),"components"),n=await Bi(de.join(r,"dyyto"),"Dyyto \u914D\u7F6E\u76EE\u5F55"),a=de.relative(t,n);if(a.startsWith("..")||de.isAbsolute(a))throw new Error("Dyyto \u914D\u7F6E\u76EE\u5F55\u8D8A\u8FC7 IDP_CONFIG_DIR");let i=de.join(n,".env");await Cm(i,"Dyyto \u7EC4\u4EF6 .env");let o=YE(await nl(i,"utf8")).get("DYYTO_PACKAGE_CATALOG_DIRS_FILE");if(o===void 0||o==="")return[];if(de.isAbsolute(o)||o.includes("\0")||/[*?{}[\]]/u.test(o))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u662F\u7EC4\u4EF6\u76EE\u5F55\u5185\u7684\u666E\u901A\u76F8\u5BF9\u6587\u4EF6\u8DEF\u5F84");let s=de.resolve(n,o),c=de.relative(n,s);if(c===""||c.startsWith("..")||de.isAbsolute(c))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u4F4D\u4E8E\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55\u5185");let d=n;for(let u of c.split(de.sep).slice(0,-1))d=await Bi(de.join(d,u),"Package Catalog Binding \u7236\u76EE\u5F55");let l=await al(de.dirname(s)),p=de.relative(n,l);if(p.startsWith("..")||de.isAbsolute(p))throw new Error("Package Catalog Binding \u89E3\u6790\u540E\u8D8A\u8FC7\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55");await Cm(s,"Package Catalog Binding");let m=[];for(let u of(await nl(s,"utf8")).split(/\r?\n/u)){let f=u.trim();if(f===""||f.startsWith("#"))continue;if(!de.isAbsolute(f))throw new Error("Package Catalog Binding \u4E2D\u7684\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let g=await la(f);if(!g.isDirectory()||g.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");let h=await al(f),w=await la(h);if(!w.isDirectory()||w.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");m.includes(h)||m.push(h)}return m.sort()}async function ZE(){let e=process.env.IDP_CONFIG_DIR,t=e===void 0?[]:await XE(e);return{capabilities:Om.capabilities,packages:[Om.packages,...t]}}async function Ji(e){return(await KE(e,{withFileTypes:!0})).filter(t=>t.isDirectory()&&!t.isSymbolicLink()).map(t=>t.name).sort()}function QE(e,t){let r=i=>i.split("-",1)[0].split(".").map(Number),n=r(e),a=r(t);for(let i=0;i<3;i+=1){let o=(n[i]??0)-(a[i]??0);if(o!==0)return o}return e.localeCompare(t)}function eA(e){let t=e.schemaVersion===2?e.availability.maturity:"legacy-unverified",r="consumerProfile"in e?e.consumerProfile:"\u591A\u79CD\u5DE5\u7A0B Profile";return{kind:"capability",ref:`capability:${e.capabilityId}@${e.version}`,id:e.capabilityId,version:e.version,title:e.capabilityId,summary:`\u9002\u7528\u4E8E ${r} \u7684\u5DE5\u7A0B\u80FD\u529B\u53D1\u884C\u3002`,maturity:t,integrity:e.integrity}}function tA(e){return{kind:"package",ref:`package:${e.packageName}@${e.version}`,id:e.packageName,version:e.version,title:e.title,summary:e.summary,maturity:e.maturity,integrity:e.releaseDigest}}async function rA(e){let t=[];for(let r of await Ji(e))for(let n of await Ji(de.join(e,r))){let a=`capability:${r}@${n}`;t.push(me(de.join(e,r,n)).then(i=>({entry:{item:eA(i.release),release:i.release}})).catch(()=>({diagnostic:{ref:a,code:"CATALOG_RELEASE_INVALID",message:"Capability \u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function nA(e){let t=[];for(let r of await Ji(e))for(let n of await Ji(de.join(e,r))){let a=de.join(e,r,n,"release.json"),i=`package:${r}@${n}`;t.push(nl(a,"utf8").then(o=>{let s=hm(JSON.parse(o));return{entry:{item:tA(s),release:s}}}).catch(()=>({diagnostic:{ref:i,code:"CATALOG_RELEASE_INVALID",message:"PackageRelease \u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function Tm(e){let t=e??await ZE(),r=typeof t.packages=="string"?[t.packages]:[...t.packages],[n,...a]=await Promise.all([rA(t.capabilities),...r.map(nA)]),i=[...n.entries,...a.flatMap(d=>d.entries)].sort((d,l)=>d.item.ref.localeCompare(l.item.ref)),o=[],s=new Set,c=[];for(let d of i)s.has(d.item.ref)?c.push({ref:d.item.ref,code:"CATALOG_RELEASE_DUPLICATE",message:"\u591A\u4E2A Catalog Source \u58F0\u660E\u4E86\u540C\u4E00\u4E0D\u53EF\u53D8\u53D1\u884C ref"}):(s.add(d.item.ref),o.push(d));return{entries:o,diagnostics:[...n.diagnostics,...a.flatMap(d=>d.diagnostics),...c].sort((d,l)=>d.ref.localeCompare(l.ref))}}async function xm(e){let t=(e.query??"").trim().toLocaleLowerCase("zh-CN"),r=await Tm(e.roots),n=new Map;for(let{item:o}of r.entries){if(e.kind!==void 0&&o.kind!==e.kind)continue;let s=[o.id,o.version,o.title,o.summary,o.maturity].join(" ").toLocaleLowerCase("zh-CN");if(t!==""&&!s.includes(t))continue;let c=`${o.kind}:${o.id}`,d=n.get(c);(d===void 0||QE(d.version,o.version)<0)&&n.set(c,o)}let a=[...n.values()].sort((o,s)=>o.ref.localeCompare(s.ref)),i=e.limit??50;return{query:t,total:a.length,items:a.slice(0,i),diagnostics:r.diagnostics}}async function Lm(e){let t=e.ref.startsWith("package:")||e.ref.startsWith("capability:")?e.ref:`${e.ref.startsWith("@")?"package":"capability"}:${e.ref}`,r=await Tm(e.roots),n=r.entries.find(({item:i})=>i.ref===t),a=r.diagnostics.find(i=>i.ref===t);if(a?.code==="CATALOG_RELEASE_DUPLICATE")throw new Error(`\u53D1\u884C ref \u5728\u591A\u4E2A Catalog Source \u4E2D\u91CD\u590D\uFF1A${e.ref}`);if(n===void 0&&a!==void 0)throw new Error(`\u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C\uFF1A${e.ref}`);if(n===void 0)throw new Error(`\u76EE\u5F55\u4E2D\u4E0D\u5B58\u5728\u53D1\u884C\uFF1A${e.ref}`);return n}var da={"typescript-library":"foundation.typescript-quality@1.0.0","standalone-npm-package":"foundation.standalone-npm-package@1.2.0","workspace-root":"foundation.workspace-root@1.1.0","workspace-npm-package":"foundation.workspace-npm-package@1.2.0","workspace-node-application":"foundation.workspace-node-application@1.1.0","workspace-web-application":"foundation.workspace-web-application@1.1.0","workspace-expo-application":"foundation.workspace-expo-application@1.0.0","react-component-library":"foundation.react-component-library@1.1.0","workspace-react-component-library":"foundation.workspace-react-component-library@1.2.0","nextjs-full-stack-application":"foundation.nextjs-full-stack-application@1.0.0"},Um=oA(aA),sA=new Set(["template.typescript-library@1.0.0","template.typescript-library@1.1.0","template.react-component-library@1.0.0","template.react-component-library@1.1.0","template.nextjs-full-stack-application@1.0.0","template.expo-react-native-application@1.0.0","template.node-api-application@1.0.0","template.workspace-root@1.0.0","template.workspace-root@1.1.0","template.workspace-root@1.2.0","template.workspace-npm-package@1.0.0","template.workspace-react-component-library@1.0.0","template.workspace-react-component-library@1.1.0","template.workspace-react-component-library@1.2.0","template.web-frontend-application@1.0.0"]),Fm=(e,t)=>e==="foundation.workspace-root"&&t==="1.4.0"?{id:"template.workspace-root",version:"1.1.0"}:e==="foundation.workspace-root"&&t==="1.5.0"?{id:"template.workspace-root",version:"1.2.0"}:void 0,Gi={"workspace-npm-package":{id:"template.workspace-npm-package",version:"1.0.0"},"react-component-library":{id:"template.workspace-react-component-library",version:"1.2.0"},"workspace-web-application":{id:"template.web-frontend-application",version:"1.0.0"},"workspace-node-application":{id:"template.node-api-application",version:"1.0.0"},"workspace-expo-application":{id:"template.expo-react-native-application",version:"1.0.0"},"nextjs-full-stack-application":{id:"template.nextjs-full-stack-application",version:"1.0.0"}};function zm(e){return e.capabilities.flatMap(t=>t.assets).filter(t=>t.ownership!=="seed-file")}async function Wi(e,t,r,n){if(t.release.schemaVersion!==2||t.release.packageSources.length===0)return;if(r.packageSourceProvider===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires a trusted Package Source Provider");let a=await ee(N.join(e,"package.json")),i=await r.packageSourceProvider.inspect({projectRoot:e,release:t.release}),{resolvePnpmLock:o}=await import("./optional-runtime.js"),s=await Wr(e),c=await ee(N.join(s.transactionRoot,s.lockfilePath)).catch(p=>p.code==="ENOENT"?void 0:Promise.reject(p));if(s.mode==="pnpm-shared-lockfile"){if(!c)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Workspace shared lockfile is unavailable");if(!r.resolutionWorkerProvider)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package adoption requires verified Resolution Worker Evidence");let p=Hn({release:t.release,packageJson:n??a}),m=new Date,u=new Date(m.getTime()+1800*1e3).toISOString(),f=await r.resolutionWorkerProvider.resolveWorkspace({topology:s,desiredPackageJson:p,currentLockfile:c,sources:t.release.packageSources,registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings,generatedAt:m.toISOString(),expiresAt:u});return{...i,lockResolution:{lockfile:f.evidence.desiredLockfile,packages:f.evidence.packageFacts.filter(g=>g.managed).map(({registryId:g,packageName:h,version:w,integrity:_})=>({registryId:g,packageName:h,version:w,integrity:_}))},resolutionEvidence:f.evidence,resolutionWorkerReleaseId:f.workerReleaseId,topology:s,currentLockfile:c,preservedImporterDigests:f.preservedImporterDigests}}let d=Cc({release:t.release,packageJson:n??a}),l=await o({desiredPackageJson:d,...c===void 0?{}:{currentLockfile:c},sources:t.release.packageSources,registries:i.registryConfigs,endpointBindings:i.endpointBindings});return{...i,lockResolution:l,topology:s,...c===void 0?{}:{currentLockfile:c},preservedImporterDigests:[]}}async function Bm(e,t,r,n){let a=r.capabilities.find(b=>b.capabilityId===t.release.capabilityId&&b.version===t.release.version);if(a&&!a.packageAdoption){let b=JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8")),A=new Date;return Zf({projectRoot:e,manifest:b,release:t,currentLock:r,generatedAt:A.toISOString(),expiresAt:new Date(A.getTime()+30*6e4).toISOString()})}if(t.release.schemaVersion!==2||n.packageSourceProvider===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires a trusted Package Source Provider");if(!a?.packageAdoption)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires Lock v2 ownership facts");let i=await n.packageSourceProvider.inspect({projectRoot:e,release:t.release}),o=await ee(N.join(e,"package.json")),s=await ee(N.join(e,"project-capabilities.json")),c=await Wr(e),d=await ee(N.join(c.transactionRoot,c.lockfilePath)),l=new Set(r.capabilities.filter(b=>b!==a).flatMap(b=>b.packageAdoption?.sources.map(A=>A.packageName)??[])),p=a.packageAdoption.sources.filter(b=>!l.has(b.packageName)),m=c.mode==="pnpm-shared-lockfile"?xc({packageJson:o,remove:p}):Tc({packageJson:o,remove:p}),u=r.capabilities.filter(b=>b!==a).flatMap(b=>b.packageAdoption?.sources??[]),f=new Date,g=new Date(f.getTime()+1800*1e3).toISOString();if(c.mode==="pnpm-shared-lockfile"){if(!n.resolutionWorkerProvider)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package removal requires verified Resolution Worker Evidence");let b=await n.resolutionWorkerProvider.resolveWorkspace({topology:c,desiredPackageJson:m,currentLockfile:d,sources:u,registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings,generatedAt:f.toISOString(),expiresAt:g}),A=[`${c.unitRelativeRoot}/project-capabilities.json`,`${c.unitRelativeRoot}/package.json`,c.lockfilePath,...a.assets.map(k=>`${c.unitRelativeRoot}/${k.path}`)],y=await Promise.all(A.map(async k=>ee(N.join(c.transactionRoot,...k.split("/"))).then(S=>({path:k,exists:!0,digest:v(S)})).catch(S=>S.code==="ENOENT"?{path:k,exists:!1}:Promise.reject(S))));return{...af({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,endpointBindings:i.endpointBindings,observedAssets:y,topology:c,transactionRoot:c.transactionRoot,preservedImporterDigests:b.preservedImporterDigests,resolutionEvidence:b.evidence,resolutionWorkerReleaseId:b.workerReleaseId,remainingSources:u,generatedAt:f.toISOString(),expiresAt:g}),registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings}}let{resolvePnpmLock:h}=await import("./optional-runtime.js"),w=await h({desiredPackageJson:m,currentLockfile:d,sources:u,registrySources:[...u,...a.packageAdoption.sources],registries:i.registryConfigs,endpointBindings:i.endpointBindings}),_=await Promise.all(["project-capabilities.json","package.json","pnpm-lock.yaml",...a.assets.map(b=>b.path)].map(async b=>ee(N.join(e,...b.split("/"))).then(A=>({path:b,exists:!0,digest:v(A)})).catch(A=>A.code==="ENOENT"?{path:b,exists:!1}:Promise.reject(A))));return{...nf({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,desiredLockfile:w.lockfile,endpointBindings:i.endpointBindings,observedAssets:_,generatedAt:f.toISOString(),expiresAt:g}),registryConfigs:i.registryConfigs,endpointBindings:i.endpointBindings}}function z(e){return e.includes("--json")?"json":"human"}function I(e){throw new Ce({code:"CLI_ARGUMENT_INVALID",message:e,exitCode:2,nextStep:"Run dyyto --help."})}function Ee(e,t){return!/^[a-z0-9][a-z0-9.-]*$/u.test(e)||!/^\d+\.\d+\.\d+$/u.test(t)?I("The selected capability release identifier is invalid."):N.resolve(import.meta.dirname,"catalog",e,t)}function Ki(e,t){return sA.has(`${e}@${t}`)?N.resolve(import.meta.dirname,"templates",e,t):I("The selected template release is not bundled with this CLI.")}function cA(e,t){return!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(e)||!/^\d+\.\d+\.\d+$/.test(t)?I("The selected example recipe identity or version is invalid."):N.resolve(import.meta.dirname,"recipes",e,t)}function Z(e){let t=N.relative(process.cwd(),e);return t.length>0&&t!==".."&&!t.startsWith(`..${N.sep}`)?t:N.basename(e)}async function Yi(e){let t=JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8")),r=t.capabilities?.[0];if(r===void 0)return I("Project manifest must select one capability.");let n=await me(Ee(r.capabilityId,r.version)),a=await De(e).catch(()=>null),i=new Date,s=await(t.profile?.id==="standalone-npm-package"?Bn:t.profile?.id==="react-component-library"?Jn:t.profile?.id==="nextjs-full-stack-application"?Kr:t.profile?.id==="workspace-npm-package"?Gn:t.profile?.id==="workspace-node-application"?Wn:t.profile?.id==="workspace-web-application"?Kn:t.profile?.id==="workspace-expo-application"?Yn:ti)({projectRoot:e,manifest:t,release:n,...a===null?{}:{currentLock:a},generatedAt:i.toISOString(),expiresAt:new Date(i.getTime()+1800*1e3).toISOString()});return dr({projectRoot:e,plan:s.plan,now:i.toISOString()})}async function Jm(e){let t;try{t=ce({args:[...e],allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},profile:{type:"string"},template:{type:"string"},capability:{type:"string"},name:{type:"string"},version:{type:"string"},license:{type:"string"},"publish-access":{type:"string"},repository:{type:"string"}}})}catch{return I("Create arguments are invalid.")}if(t.positionals.length!==1)return I("Create requires exactly one directory.");let r=t.values.template,n;if(typeof r=="string"){let[g,h]=r.split("@");n=await oa(Ki(g,h))}let a=n?.profile.id??t.values.profile;if(a!=="typescript-library"&&a!=="standalone-npm-package"&&a!=="react-component-library"&&a!=="nextjs-full-stack-application"&&a!=="workspace-root")return I("Create requires a supported --profile.");let i=t.values.capability,o=a==="workspace-root"&&i==="foundation.workspace-root@1.0.0"||a==="standalone-npm-package"&&i==="foundation.standalone-npm-package@1.0.0",s=n?.profile.capability??(o?i:da[a]);if(n!==void 0&&s.split("@")[0]!==da[a].split("@")[0])return I(`Template ${n.templateId} is adopted with dyyto add, not dyyto create.`);if(n===void 0&&i!==s)return I(`Create requires --capability ${s}.`);if(n!==void 0&&i!==void 0)return I("Create with --template does not accept --capability.");let[c,d]=s.split("@"),l={};if(a==="standalone-npm-package"||a==="react-component-library"){let g=t.values.name,h=t.values.version,w=t.values.license,_=t.values["publish-access"],b=t.values.repository;if([g,h,w,_].some(A=>typeof A!="string")||d==="1.1.0"&&typeof b!="string")return I(`Standalone npm package requires --name, --version, --license, --publish-access${d==="1.1.0"?", and --repository":""}.`);l={name:String(g),version:String(h),license:String(w),publishAccess:String(_),...typeof b=="string"?{repository:b}:{}}}else if(a==="nextjs-full-stack-application"){if(typeof t.values.name!="string")return I("Next.js application requires --name.");l={name:t.values.name}}let p={schemaVersion:1,...n===void 0?{}:{template:{id:n.templateId,version:n.version}},profile:{id:a,parameters:l},capabilities:[{capabilityId:c,version:d}]};(a==="standalone-npm-package"||a==="react-component-library")&&Ut(W(p),a),a==="nextjs-full-stack-application"&&pr(W(p));let m=await hi({projectRoot:t.positionals[0],manifest:p}),u=await Yi(m.projectRoot),f=Z(m.projectRoot);return{outputMode:z(e),human:`Project '${f}' initialized.
101
102
  Plan: ${u.planId}
102
103
  State: ${u.state}
103
- Next: dyyto apply --project ${m} --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"create",result:{project:m,profile:a,...n===void 0?{}:{template:`${n.templateId}@${n.version}`},capability:s,plan:u}}}}async function sA(e){let[t,...r]=e,n;try{n=se({args:r,allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"},"documentation-only":{type:"boolean"}}})}catch{return b("Retrofit arguments are invalid.")}if(t!=="plan"&&t!=="apply")return b("Retrofit requires plan or apply.");if(typeof n.values.project!="string")return b("Retrofit requires --project <directory>.");let a=await me(Ee("foundation.workspace-root","1.2.0")),i=new Date,o=await Tu({projectRoot:n.values.project,capabilityIntegrity:a.release.integrity,generatedAt:i.toISOString(),expiresAt:new Date(i.getTime()+1800*1e3).toISOString(),...n.values["documentation-only"]===!0?{documentationOnly:!0}:{}}),s=Z(o.projectRoot);if(t==="plan"){if(n.values.approve!==void 0)return b("Retrofit plan does not accept --approve.");let p=await dr({projectRoot:o.projectRoot,plan:o.plan,now:i.toISOString()});return{outputMode:z(e),human:`Project: ${s}
104
- Plan: ${p.planId}
105
- State: ${p.state}
104
+ Next: dyyto apply --project ${f} --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"create",result:{project:f,profile:a,...n===void 0?{}:{template:`${n.templateId}@${n.version}`},capability:s,plan:u}}}}async function lA(e){let[t,...r]=e,n;try{n=ce({args:r,allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"},profile:{type:"string"},capability:{type:"string"},"documentation-only":{type:"boolean"}}})}catch{return I("Retrofit arguments are invalid.")}if(t!=="plan"&&t!=="apply")return I("Retrofit requires plan or apply.");if(typeof n.values.project!="string")return I("Retrofit requires --project <directory>.");if(n.values.capability!==void 0&&typeof n.values.capability!="string")return I("Retrofit --capability is invalid.");if(n.values.profile!==void 0&&typeof n.values.profile!="string")return I("Retrofit --profile is invalid.");let a=n.values.capability??"foundation.workspace-root@1.2.0",i=/^([a-z][a-z0-9.-]*)@([0-9A-Za-z.-]+)$/u.exec(a);if(!i)return I("Retrofit --capability is invalid.");let o=await me(Ee(i[1],i[2])),s=n.values.profile??"workspace-root";if(o.release.consumerProfile!==s)return I("Retrofit profile and capability are incompatible.");let c=new Date,d=s==="workspace-root"?await xu({projectRoot:n.values.project,capabilityIntegrity:o.release.integrity,generatedAt:c.toISOString(),expiresAt:new Date(c.getTime()+1800*1e3).toISOString(),...n.values["documentation-only"]===!0?{documentationOnly:!0}:{}}):await Tu({projectRoot:n.values.project,manifest:{schemaVersion:1,profile:{id:s,parameters:{}},capabilities:[{capabilityId:i[1],version:i[2]}]},capabilityIntegrity:o.release.integrity,generatedAt:c.toISOString(),expiresAt:new Date(c.getTime()+1800*1e3).toISOString()}),l=Z(d.projectRoot);if(t==="plan"){if(n.values.approve!==void 0)return I("Retrofit plan does not accept --approve.");let f=await dr({projectRoot:d.projectRoot,plan:d.plan,now:c.toISOString()});return{outputMode:z(e),human:`Project: ${l}
105
+ Plan: ${f.planId}
106
+ State: ${f.state}
106
107
  Files: project-capabilities.json
107
- Next: dyyto retrofit apply --project ${s} --approve ${p.planId}${n.values["documentation-only"]===!0?" --documentation-only":""}`,value:{schemaVersion:1,ok:!0,command:"retrofit-plan",result:{project:s,plan:p}}}}if(typeof n.values.approve!="string")return b("Retrofit apply requires --approve <planId>.");let c=await Un({projectRoot:o.projectRoot,planId:n.values.approve}),d=await Br({projectRoot:o.projectRoot,plan:c,approvedPlanId:n.values.approve,desiredContents:o.desiredContents,now:i.toISOString()}),l=await Jr(d);return{outputMode:z(e),human:`Project: ${s}
108
- Plan: ${c.planId}
109
- State: ${l.state}
110
- Files applied: ${l.operations.length}`,value:{schemaVersion:1,ok:!0,command:"retrofit-apply",result:{project:s,planId:c.planId,transaction:l}}}}async function cA(e,t){let r;try{r=se({args:[...t],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return b(`${e} arguments are invalid.`)}if(typeof r.values.project!="string")return b(`${e} requires --project.`);let n=await lt(N.resolve(r.values.project)),a=K(JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")));if(a.template===void 0)return b("The project does not declare an engineering template.");let i=await oa(Ki(a.template.id,a.template.version)),o=i.commands[e];if(o===void 0)return b(`Template ${i.templateId} does not support ${e}.`);let s=o==="npm.pack-dry-run"?["pnpm","pack","--dry-run"]:["pnpm","run",o],c=Date.now();if(e==="dev"){if(await new Promise((u,m)=>{let g=nA("corepack",s,{cwd:n,env:{...process.env,NO_COLOR:"1"},stdio:"inherit"}),h=()=>g.kill("SIGINT"),w=()=>g.kill("SIGTERM");process.once("SIGINT",h),process.once("SIGTERM",w),g.once("error",m),g.once("close",_=>{process.off("SIGINT",h),process.off("SIGTERM",w),u(_??1)})})!==0)throw new Ce({code:"CLI_INTERNAL_ERROR",message:"The development server stopped with an error.",exitCode:1});let f={template:`${i.templateId}@${i.version}`,command:o,durationMs:Date.now()-c,stdout:""};return{outputMode:z(t),human:`dev completed for '${Z(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:f}}}let d=await qm("corepack",s,{cwd:n,env:{...process.env,NO_COLOR:"1"},timeout:3e5,maxBuffer:4*1024*1024}),l={template:`${i.templateId}@${i.version}`,command:o,durationMs:Date.now()-c,stdout:d.stdout.trim()};return{outputMode:z(t),human:`${e} completed for '${Z(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:l}}}async function lA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},path:{type:"string"},name:{type:"string"},version:{type:"string"},license:{type:"string"},"publish-access":{type:"string"},repository:{type:"string"},capability:{type:"string"},kind:{type:"string"},profile:{type:"string"}}})}catch{return b("Add package arguments are invalid.")}if([t.values.workspace,t.values.path,t.values.name,t.values.version,t.values.license,t.values["publish-access"],t.values.repository].some(_=>typeof _!="string"))return b("Add package requires workspace, path, name, version, license, publish access, and repository.");let n=t.values.profile??"workspace-npm-package";if(n!=="workspace-npm-package"&&n!=="react-component-library")return b("Add package requires a supported --profile.");let a=n==="react-component-library"?da["workspace-react-component-library"]:da["workspace-npm-package"];if(t.values.capability!==a)return b(`Add package requires --capability ${a}.`);if(t.values.kind!==void 0&&t.values.kind!=="fixture")return b("Add package --kind only accepts fixture.");let i=t.values.kind==="fixture"?"fixture":"package",o=String(t.values.path),s=km(o,i);if(s!==void 0)return b(s);let c=await lt(N.resolve(String(t.values.workspace))),d=JSON.parse(await ee(N.join(c,"project-capabilities.json"),"utf8"));if(d.profile?.id!=="workspace-root")return b("The selected directory is not a Dyyto workspace root.");let l=d.capabilities?.[0];if(l?.capabilityId!=="foundation.workspace-root")return b("Workspace root capability is invalid.");let p=await Ne(c);if(p===null){let _=await me(Ee(l.capabilityId,l.version)),I=new Date;if((await ei({projectRoot:c,release:_,generatedAt:I.toISOString(),expiresAt:new Date(I.getTime()+1800*1e3).toISOString()})).state!=="applied-unverified")return b("Workspace root must be applied before adding a package.")}if(p!==null){try{await ir({projectRoot:c,expectedAssets:Fm(p)})}catch{return b("Workspace root locked assets have drifted; adding a package is blocked.")}if((await na({projectRoot:c,lock:p})).some(I=>I.code!=="EVIDENCE_VALID"))return b("Workspace root adoption evidence is invalid; adding a package is blocked.")}if(await zi(c,i==="fixture"?"fixtures":"packages",String(t.values.name)))return b("A workspace package already uses this npm name.");let[f,u]=a.split("@"),m={schemaVersion:1,...Gi[n]===void 0?{}:{template:Gi[n]},profile:{id:n,parameters:{name:String(t.values.name),version:String(t.values.version),license:String(t.values.license),publishAccess:String(t.values["publish-access"]),repository:String(t.values.repository)}},capabilities:[{capabilityId:f,version:u}]};qt(K(m),n);let g=await hi({projectRoot:N.join(c,...o.split("/")),manifest:m}),h=await Yi(g.projectRoot),w=Z(g.projectRoot);return{outputMode:z(e),human:`Workspace package '${o}' initialized.
108
+ Next: dyyto retrofit apply --project ${l} --approve ${f.planId}${n.values["documentation-only"]===!0?" --documentation-only":""}`,value:{schemaVersion:1,ok:!0,command:"retrofit-plan",result:{project:l,plan:f}}}}if(typeof n.values.approve!="string")return I("Retrofit apply requires --approve <planId>.");let p=await Un({projectRoot:d.projectRoot,planId:n.values.approve}),m=await Br({projectRoot:d.projectRoot,plan:p,approvedPlanId:n.values.approve,desiredContents:d.desiredContents,now:c.toISOString()}),u=await Jr(m);return{outputMode:z(e),human:`Project: ${l}
109
+ Plan: ${p.planId}
110
+ State: ${u.state}
111
+ Files applied: ${u.operations.length}`,value:{schemaVersion:1,ok:!0,command:"retrofit-apply",result:{project:l,planId:p.planId,transaction:u}}}}async function dA(e,t){let r;try{r=ce({args:[...t],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return I(`${e} arguments are invalid.`)}if(typeof r.values.project!="string")return I(`${e} requires --project.`);let n=await lt(N.resolve(r.values.project)),a=W(JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")));if(a.template===void 0)return I("The project does not declare an engineering template.");let i=await oa(Ki(a.template.id,a.template.version)),o=i.commands[e];if(o===void 0)return I(`Template ${i.templateId} does not support ${e}.`);let s=o==="npm.pack-dry-run"?["pnpm","pack","--dry-run"]:["pnpm","run",o],c=Date.now();if(e==="dev"){if(await new Promise((u,f)=>{let g=iA("corepack",s,{cwd:n,env:{...process.env,NO_COLOR:"1"},stdio:"inherit"}),h=()=>g.kill("SIGINT"),w=()=>g.kill("SIGTERM");process.once("SIGINT",h),process.once("SIGTERM",w),g.once("error",f),g.once("close",_=>{process.off("SIGINT",h),process.off("SIGTERM",w),u(_??1)})})!==0)throw new Ce({code:"CLI_INTERNAL_ERROR",message:"The development server stopped with an error.",exitCode:1});let m={template:`${i.templateId}@${i.version}`,command:o,durationMs:Date.now()-c,stdout:""};return{outputMode:z(t),human:`dev completed for '${Z(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:m}}}let d=await Um("corepack",s,{cwd:n,env:{...process.env,NO_COLOR:"1"},timeout:3e5,maxBuffer:4*1024*1024}),l={template:`${i.templateId}@${i.version}`,command:o,durationMs:Date.now()-c,stdout:d.stdout.trim()};return{outputMode:z(t),human:`${e} completed for '${Z(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:l}}}async function pA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},path:{type:"string"},name:{type:"string"},version:{type:"string"},license:{type:"string"},"publish-access":{type:"string"},repository:{type:"string"},capability:{type:"string"},kind:{type:"string"},profile:{type:"string"}}})}catch{return I("Add package arguments are invalid.")}if([t.values.workspace,t.values.path,t.values.name,t.values.version,t.values.license,t.values["publish-access"],t.values.repository].some(_=>typeof _!="string"))return I("Add package requires workspace, path, name, version, license, publish access, and repository.");let n=t.values.profile??"workspace-npm-package";if(n!=="workspace-npm-package"&&n!=="react-component-library")return I("Add package requires a supported --profile.");let a=n==="react-component-library"?da["workspace-react-component-library"]:da["workspace-npm-package"];if(t.values.capability!==a)return I(`Add package requires --capability ${a}.`);if(t.values.kind!==void 0&&t.values.kind!=="fixture")return I("Add package --kind only accepts fixture.");let i=t.values.kind==="fixture"?"fixture":"package",o=String(t.values.path),s=_m(o,i);if(s!==void 0)return I(s);let c=await lt(N.resolve(String(t.values.workspace))),d=JSON.parse(await ee(N.join(c,"project-capabilities.json"),"utf8"));if(d.profile?.id!=="workspace-root")return I("The selected directory is not a Dyyto workspace root.");let l=d.capabilities?.[0];if(l?.capabilityId!=="foundation.workspace-root")return I("Workspace root capability is invalid.");let p=await De(c);if(p===null){let _=await me(Ee(l.capabilityId,l.version)),b=new Date;if((await ei({projectRoot:c,release:_,generatedAt:b.toISOString(),expiresAt:new Date(b.getTime()+1800*1e3).toISOString()})).state!=="applied-unverified")return I("Workspace root must be applied before adding a package.")}if(p!==null){try{await or({projectRoot:c,expectedAssets:zm(p)})}catch{return I("Workspace root locked assets have drifted; adding a package is blocked.")}if((await na({projectRoot:c,lock:p})).some(b=>b.code!=="EVIDENCE_VALID"))return I("Workspace root adoption evidence is invalid; adding a package is blocked.")}if(await zi(c,i==="fixture"?"fixtures":"packages",String(t.values.name)))return I("A workspace package already uses this npm name.");let[m,u]=a.split("@"),f={schemaVersion:1,...Gi[n]===void 0?{}:{template:Gi[n]},profile:{id:n,parameters:{name:String(t.values.name),version:String(t.values.version),license:String(t.values.license),publishAccess:String(t.values["publish-access"]),repository:String(t.values.repository)}},capabilities:[{capabilityId:m,version:u}]};Ut(W(f),n);let g=await hi({projectRoot:N.join(c,...o.split("/")),manifest:f}),h=await Yi(g.projectRoot),w=Z(g.projectRoot);return{outputMode:z(e),human:`Workspace package '${o}' initialized.
111
112
  Plan: ${h.planId}
112
113
  State: ${h.state}
113
- Next: dyyto apply --project ${w} --approve ${h.planId}`,value:{schemaVersion:1,ok:!0,command:"add-package",result:{project:w,workspace:Z(c),path:o,plan:h}}}}async function dA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},path:{type:"string"},name:{type:"string"},profile:{type:"string"},capability:{type:"string"}}})}catch{return b("Add application arguments are invalid.")}if([t.values.workspace,t.values.path,t.values.name].some(w=>typeof w!="string"))return b("Add application requires workspace, path, and name.");let r=t.values.profile??"workspace-node-application";if(r!=="workspace-node-application"&&r!=="workspace-web-application"&&r!=="workspace-expo-application"&&r!=="nextjs-full-stack-application")return b("Add application requires a supported --profile.");let n=r,a=da[n],i=String(t.values.path),o=_m(i,n,typeof t.values.capability=="string"?t.values.capability:void 0);if(o!==void 0)return b(o);let s=await lt(N.resolve(String(t.values.workspace))),c=JSON.parse(await ee(N.join(s,"project-capabilities.json"),"utf8"));if(c.profile?.id!=="workspace-root")return b("The selected directory is not a Dyyto workspace root.");let d=c.capabilities?.[0];if(d?.capabilityId!=="foundation.workspace-root"||!["1.1.0","1.2.0","1.3.0","1.4.0","1.5.0"].includes(d.version))return b("Workspace applications require a supported foundation.workspace-root release.");if(i.startsWith("services/")&&!["1.3.0","1.4.0","1.5.0"].includes(d.version))return b("Workspace service applications require foundation.workspace-root@1.3.0 or newer.");let l=await Ne(s);if(l===null){let w=await me(Ee(d.capabilityId,d.version)),_=new Date;if((await ei({projectRoot:s,release:w,generatedAt:_.toISOString(),expiresAt:new Date(_.getTime()+1800*1e3).toISOString()})).state!=="applied-unverified")return b("Workspace root must be applied before adding an application.")}if(l!==null){try{await ir({projectRoot:s,expectedAssets:Fm(l)})}catch{return b("Workspace root locked assets have drifted; adding an application is blocked.")}if((await na({projectRoot:s,lock:l})).some(_=>_.code!=="EVIDENCE_VALID"))return b("Workspace root adoption evidence is invalid; adding an application is blocked.")}if(await Em(s,String(t.values.name)))return b("A workspace application already uses this name.");let[p,f]=a.split("@"),u={schemaVersion:1,...Gi[n]===void 0?{}:{template:Gi[n]},profile:{id:n,parameters:{name:String(t.values.name)}},capabilities:[{capabilityId:p,version:f}]};pr(K(u));let m=await hi({projectRoot:N.join(s,...i.split("/")),manifest:u}),g=await Yi(m.projectRoot),h=Z(m.projectRoot);return{outputMode:z(e),human:`Workspace application '${i}' initialized.
114
+ Next: dyyto apply --project ${w} --approve ${h.planId}`,value:{schemaVersion:1,ok:!0,command:"add-package",result:{project:w,workspace:Z(c),path:o,plan:h}}}}async function uA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},path:{type:"string"},name:{type:"string"},profile:{type:"string"},capability:{type:"string"}}})}catch{return I("Add application arguments are invalid.")}if([t.values.workspace,t.values.path,t.values.name].some(w=>typeof w!="string"))return I("Add application requires workspace, path, and name.");let r=t.values.profile??"workspace-node-application";if(r!=="workspace-node-application"&&r!=="workspace-web-application"&&r!=="workspace-expo-application"&&r!=="nextjs-full-stack-application")return I("Add application requires a supported --profile.");let n=r,a=da[n],i=String(t.values.path),o=Em(i,n,typeof t.values.capability=="string"?t.values.capability:void 0);if(o!==void 0)return I(o);let s=await lt(N.resolve(String(t.values.workspace))),c=JSON.parse(await ee(N.join(s,"project-capabilities.json"),"utf8"));if(c.profile?.id!=="workspace-root")return I("The selected directory is not a Dyyto workspace root.");let d=c.capabilities?.[0];if(d?.capabilityId!=="foundation.workspace-root"||!["1.1.0","1.2.0","1.3.0","1.4.0","1.5.0"].includes(d.version))return I("Workspace applications require a supported foundation.workspace-root release.");if(i.startsWith("services/")&&!["1.3.0","1.4.0","1.5.0"].includes(d.version))return I("Workspace service applications require foundation.workspace-root@1.3.0 or newer.");let l=await De(s);if(l===null){let w=await me(Ee(d.capabilityId,d.version)),_=new Date;if((await ei({projectRoot:s,release:w,generatedAt:_.toISOString(),expiresAt:new Date(_.getTime()+1800*1e3).toISOString()})).state!=="applied-unverified")return I("Workspace root must be applied before adding an application.")}if(l!==null){try{await or({projectRoot:s,expectedAssets:zm(l)})}catch{return I("Workspace root locked assets have drifted; adding an application is blocked.")}if((await na({projectRoot:s,lock:l})).some(_=>_.code!=="EVIDENCE_VALID"))return I("Workspace root adoption evidence is invalid; adding an application is blocked.")}if(await Am(s,String(t.values.name)))return I("A workspace application already uses this name.");let[p,m]=a.split("@"),u={schemaVersion:1,...Gi[n]===void 0?{}:{template:Gi[n]},profile:{id:n,parameters:{name:String(t.values.name)}},capabilities:[{capabilityId:p,version:m}]};pr(W(u));let f=await hi({projectRoot:N.join(s,...i.split("/")),manifest:u}),g=await Yi(f.projectRoot),h=Z(f.projectRoot);return{outputMode:z(e),human:`Workspace application '${i}' initialized.
114
115
  Plan: ${g.planId}
115
116
  State: ${g.state}
116
- Next: dyyto apply --project ${h} --approve ${g.planId}`,value:{schemaVersion:1,ok:!0,command:"add-application",result:{project:h,workspace:Z(s),path:i,plan:g}}}}async function Jm(e,t){let r;try{r=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"},channel:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return b("Add feature arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.capability!="string")return b("Add feature requires --project and --capability.");if(r.values.channel!==void 0&&r.values.channel!=="development")return b("--channel only accepts development; omit it for production.");let n=await lt(N.resolve(r.values.project)),a=JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")),i=await Ne(n);if(i===null)return b("Add feature requires an adopted project with a verified Profile Lock.");let[o,s]=Hi(r.values.capability),c=await me(Ee(o,s)),d=new Date,l;try{let u=await Wi(n,c,t);l=await Xc({projectRoot:n,manifest:a,release:c,currentLock:i,generatedAt:d.toISOString(),expiresAt:new Date(d.getTime()+1800*1e3).toISOString(),...r.values.channel==="development"?{packageChannel:"development"}:{},...u===void 0?{}:{packageSource:u}})}catch(u){throw u instanceof ne?new Ce({code:u.code,message:u.message,exitCode:3,nextStep:"Review the selected project Profile and current capabilities."}):u}let p=await dr({projectRoot:n,plan:l.plan,now:d.toISOString(),transactionRoot:l.transactionRoot}),f=Z(n);return{outputMode:z(e),human:`Project: ${f}
117
+ Next: dyyto apply --project ${h} --approve ${g.planId}`,value:{schemaVersion:1,ok:!0,command:"add-application",result:{project:h,workspace:Z(s),path:i,plan:g}}}}async function Gm(e,t){let r;try{r=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"},channel:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return I("Add feature arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.capability!="string")return I("Add feature requires --project and --capability.");if(r.values.channel!==void 0&&r.values.channel!=="development")return I("--channel only accepts development; omit it for production.");let n=await lt(N.resolve(r.values.project)),a=JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")),i=await De(n);if(i===null)return I("Add feature requires an adopted project with a verified Profile Lock.");let[o,s]=Hi(r.values.capability),c=await me(Ee(o,s)),d=new Date,l;try{let u=await Wi(n,c,t);l=await Xc({projectRoot:n,manifest:a,release:c,currentLock:i,generatedAt:d.toISOString(),expiresAt:new Date(d.getTime()+1800*1e3).toISOString(),...r.values.channel==="development"?{packageChannel:"development"}:{},...u===void 0?{}:{packageSource:u}})}catch(u){throw u instanceof ae?new Ce({code:u.code,message:u.message,exitCode:3,nextStep:"Review the selected project Profile and current capabilities."}):u}let p=await dr({projectRoot:n,plan:l.plan,now:d.toISOString(),transactionRoot:l.transactionRoot}),m=Z(n);return{outputMode:z(e),human:`Project: ${m}
117
118
  Feature: ${o}@${s}
118
119
  Dependency: ${l.dependency.profile} satisfied
119
120
  Plan: ${p.planId}
120
121
  State: ${p.state}
121
- Next: dyyto apply --project ${f} --approve ${p.planId}`,value:{schemaVersion:1,ok:!0,command:"add-feature",result:{project:f,capability:r.values.capability,dependency:l.dependency,plan:p}}}}async function pA(e,t){let r;try{r=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-port":{type:"string"}}})}catch{return b("Remove feature arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.capability!="string")return b("Remove feature requires --project and --capability.");let n=await lt(N.resolve(r.values.project)),a=await Ne(n);if(a===null)return b("Remove feature requires a verified Lock.");let[i,o]=Hi(r.values.capability),s=await me(Ee(i,o)),c=await zm(n,s,a,t),d=await dr({projectRoot:n,plan:c.plan,now:new Date().toISOString(),..."transactionRoot"in c?{transactionRoot:c.transactionRoot}:{}}),l=Z(n);return{outputMode:z(e),human:`Project: ${l}
122
+ Next: dyyto apply --project ${m} --approve ${p.planId}`,value:{schemaVersion:1,ok:!0,command:"add-feature",result:{project:m,capability:r.values.capability,dependency:l.dependency,plan:p}}}}async function fA(e,t){let r;try{r=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-port":{type:"string"}}})}catch{return I("Remove feature arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.capability!="string")return I("Remove feature requires --project and --capability.");let n=await lt(N.resolve(r.values.project)),a=await De(n);if(a===null)return I("Remove feature requires a verified Lock.");let[i,o]=Hi(r.values.capability),s=await me(Ee(i,o)),c=await Bm(n,s,a,t),d=await dr({projectRoot:n,plan:c.plan,now:new Date().toISOString(),..."transactionRoot"in c?{transactionRoot:c.transactionRoot}:{}}),l=Z(n);return{outputMode:z(e),human:`Project: ${l}
122
123
  \u79FB\u9664\u80FD\u529B\uFF1A${i}@${o}
123
124
  \u72EC\u5360\u5305\uFF1A${c.removedSources.map(p=>`${p.packageName}@${p.version}`).join("\u3001")||"\u65E0\uFF08\u5171\u4EAB\u5305\u5C06\u4FDD\u7559\uFF09"}
124
125
  Plan: ${d.planId}
125
126
  State: ${d.state}
126
- Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"remove-feature",result:{project:l,capability:r.values.capability,removedSources:c.removedSources,plan:d}}}}async function uA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return b("Plan arguments are invalid.")}if(typeof t.values.project!="string")return b("Plan requires --project <directory>.");let r=N.resolve(t.values.project),n=await Yi(r),a=Z(r),i=n.state==="reviewable"?`Next: dyyto apply --project ${a} --approve ${n.planId}`:"Resolve the reported conflicts before applying.";return{outputMode:z(e),human:`Project: ${a}
127
+ Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"remove-feature",result:{project:l,capability:r.values.capability,removedSources:c.removedSources,plan:d}}}}async function mA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return I("Plan arguments are invalid.")}if(typeof t.values.project!="string")return I("Plan requires --project <directory>.");let r=N.resolve(t.values.project),n=await Yi(r),a=Z(r),i=n.state==="reviewable"?`Next: dyyto apply --project ${a} --approve ${n.planId}`:"Resolve the reported conflicts before applying.";return{outputMode:z(e),human:`Project: ${a}
127
128
  Plan: ${n.planId}
128
129
  State: ${n.state}
129
- ${i}`,value:{schemaVersion:1,ok:!0,command:"plan",result:{project:a,plan:n}}}}function Hi(e){let t=e.lastIndexOf("@");return t<=0||t===e.length-1?b("Capability selection must be capabilityId@version."):[e.slice(0,t),e.slice(t+1)]}async function fA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"}}})}catch{return b("Baseline arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.capability!="string")return b("Baseline requires --project and --capability.");let r=N.resolve(t.values.project);if(await Ne(r)!==null)return b("Baseline is only for a historical project without a Lock.");let[n,a]=Hi(t.values.capability),i=await me(Ee(n,a)),o=JSON.parse(await ee(N.join(r,"project-capabilities.json"),"utf8")),s=new Date,c=await Dc({projectRoot:r,manifest:o,release:i,generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()}),d=await dr({projectRoot:r,plan:c.plan,now:s.toISOString()}),l=Z(r);return{outputMode:z(e),human:`Project: ${l}
130
+ ${i}`,value:{schemaVersion:1,ok:!0,command:"plan",result:{project:a,plan:n}}}}function Hi(e){let t=e.lastIndexOf("@");return t<=0||t===e.length-1?I("Capability selection must be capabilityId@version."):[e.slice(0,t),e.slice(t+1)]}async function gA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"}}})}catch{return I("Baseline arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.capability!="string")return I("Baseline requires --project and --capability.");let r=N.resolve(t.values.project);if(await De(r)!==null)return I("Baseline is only for a historical project without a Lock.");let[n,a]=Hi(t.values.capability),i=await me(Ee(n,a)),o=JSON.parse(await ee(N.join(r,"project-capabilities.json"),"utf8")),s=new Date,c=await Dc({projectRoot:r,manifest:o,release:i,generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()}),d=await dr({projectRoot:r,plan:c.plan,now:s.toISOString()}),l=Z(r);return{outputMode:z(e),human:`Project: ${l}
130
131
  Baseline: ${n}@${a}
131
132
  Plan: ${d.planId}
132
133
  State: ${d.state}
133
134
  Preserved seed files: ${d.operations.filter(p=>p.ownership==="seed-file"&&p.disposition==="noop").length}
134
- Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"baseline",result:{project:l,plan:d}}}}async function mA(e,t){let r;try{r=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},to:{type:"string"},repository:{type:"string"},channel:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-port":{type:"string"}}})}catch{return b("Upgrade arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.to!="string")return b("Upgrade requires --project <directory> and --to <capabilityId@version>.");if(r.values.channel!==void 0&&r.values.channel!=="development")return b("--channel only accepts development; omit it for production.");let n=N.resolve(r.values.project),a=JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")),[i,o]=Hi(r.values.to),s=a.capabilities?.find(k=>k.capabilityId===i);if(s===void 0)return b(`Upgrade requires ${i} to be adopted by the project.`);let c=await Ne(n);if(c===null)return b("Upgrade requires an adopted project with a verified Lock.");let d=(a.profile.id==="standalone-npm-package"||a.profile.id==="workspace-npm-package")&&o==="1.1.0";if(d){if(typeof r.values.repository!="string")return b("npm package upgrade to 1.1.0 requires --repository.");a={...a,profile:{...a.profile,parameters:{...a.profile.parameters,repository:r.values.repository}}}}else if(r.values.repository!==void 0)return b("--repository is only valid for an npm package upgrade to 1.1.0.");let l=await me(Ee(s.capabilityId,s.version)),p=await me(Ee(i,o)),f={...a,capabilities:a.capabilities.map(k=>k.capabilityId===i?{capabilityId:i,version:o}:k)},u=p.release.schemaVersion===2&&p.release.availability.maturity!=="withdrawn"&&p.release.packageSources.length>0,m=u?Ci(f,p):void 0,g=u?await Wi(n,p,t,m):void 0,h=Um(i,o),w=new Date,_=await qc({projectRoot:n,manifest:a,currentLock:c,sourceRelease:l,targetRelease:p,...h===void 0?{}:{targetTemplate:h},generatedAt:w.toISOString(),expiresAt:new Date(w.getTime()+1800*1e3).toISOString(),...r.values.channel==="development"?{packageChannel:"development"}:{},...g===void 0?{}:{packageSource:g}}),I=await dr({projectRoot:n,plan:_.plan,now:w.toISOString(),transactionRoot:_.transactionRoot}),A=Z(n),y=I.state==="reviewable"?`Next: dyyto apply --project ${A} --approve ${I.planId}${d?` --repository ${r.values.repository}`:""}`:"Resolve the reported conflicts before applying.";return{outputMode:z(e),human:`Project: ${A}
135
+ Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"baseline",result:{project:l,plan:d}}}}async function hA(e,t){let r;try{r=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},to:{type:"string"},repository:{type:"string"},channel:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-port":{type:"string"}}})}catch{return I("Upgrade arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.to!="string")return I("Upgrade requires --project <directory> and --to <capabilityId@version>.");if(r.values.channel!==void 0&&r.values.channel!=="development")return I("--channel only accepts development; omit it for production.");let n=N.resolve(r.values.project),a=JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")),[i,o]=Hi(r.values.to),s=a.capabilities?.find(k=>k.capabilityId===i);if(s===void 0)return I(`Upgrade requires ${i} to be adopted by the project.`);let c=await De(n);if(c===null)return I("Upgrade requires an adopted project with a verified Lock.");let d=(a.profile.id==="standalone-npm-package"||a.profile.id==="workspace-npm-package")&&o==="1.1.0";if(d){if(typeof r.values.repository!="string")return I("npm package upgrade to 1.1.0 requires --repository.");a={...a,profile:{...a.profile,parameters:{...a.profile.parameters,repository:r.values.repository}}}}else if(r.values.repository!==void 0)return I("--repository is only valid for an npm package upgrade to 1.1.0.");let l=await me(Ee(s.capabilityId,s.version)),p=await me(Ee(i,o)),m={...a,capabilities:a.capabilities.map(k=>k.capabilityId===i?{capabilityId:i,version:o}:k)},u=p.release.schemaVersion===2&&p.release.availability.maturity!=="withdrawn"&&p.release.packageSources.length>0,f=u?Ci(m,p):void 0,g=u?await Wi(n,p,t,f):void 0,h=Fm(i,o),w=new Date,_=await qc({projectRoot:n,manifest:a,currentLock:c,sourceRelease:l,targetRelease:p,...h===void 0?{}:{targetTemplate:h},generatedAt:w.toISOString(),expiresAt:new Date(w.getTime()+1800*1e3).toISOString(),...r.values.channel==="development"?{packageChannel:"development"}:{},...g===void 0?{}:{packageSource:g}}),b=await dr({projectRoot:n,plan:_.plan,now:w.toISOString(),transactionRoot:_.transactionRoot}),A=Z(n),y=b.state==="reviewable"?`Next: dyyto apply --project ${A} --approve ${b.planId}${d?` --repository ${r.values.repository}`:""}`:"Resolve the reported conflicts before applying.";return{outputMode:z(e),human:`Project: ${A}
135
136
  Upgrade: ${s.version} -> ${o}
136
- Plan: ${I.planId}
137
- State: ${I.state}
138
- ${y}`,value:{schemaVersion:1,ok:!0,command:"upgrade",result:{project:A,source:`${s.capabilityId}@${s.version}`,target:r.values.to,plan:I}}}}async function il(e,t){let r;try{r=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"},repository:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return b("Apply arguments are invalid.")}if(typeof r.values.project!="string")return b("Apply requires --project <directory>.");if(typeof r.values.approve!="string")return b("Apply requires --approve <planId>.");let n=N.resolve(r.values.project),a=JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")),i=a.capabilities?.[0];if(i===void 0)return b("Project manifest must select one capability.");let o=await Un({projectRoot:n,planId:r.values.approve}),s=new Date,c,d,l;if(o.action==="remove"){let u=await Ne(n);if(u===null)return b("Remove apply requires the verified Lock.");let m=await zm(n,await me(Ee(o.capability.capabilityId,o.capability.version)),u,t);c=m,d="registryConfigs"in m?m.registryConfigs:void 0,l="endpointBindings"in m?m.endpointBindings:void 0}else if(o.action==="upgrade"){let u=await Ne(n),m=u?.capabilities.find(y=>y.capabilityId===o.capability.capabilityId);if(u===null||m===void 0)return b("Upgrade apply requires the verified source Lock.");if((m.consumerProfile==="standalone-npm-package"||m.consumerProfile==="workspace-npm-package")&&o.capability.version==="1.1.0"){if(typeof r.values.repository!="string")return b("npm package upgrade apply requires the approved --repository value.");a={...a,profile:{...a.profile,parameters:{...a.profile.parameters,repository:r.values.repository}}}}else if(r.values.repository!==void 0)return b("--repository is not valid for this apply operation.");let g=await me(Ee(o.capability.capabilityId,o.capability.version)),h={...a,capabilities:a.capabilities.map(y=>y.capabilityId===o.capability.capabilityId?{capabilityId:o.capability.capabilityId,version:o.capability.version}:y)},w=g.release.schemaVersion===2&&g.release.availability.maturity!=="withdrawn"&&g.release.packageSources.length>0,_=w?Ci(h,g):void 0,I=w?await Wi(n,g,t,_):void 0;d=I?.registryConfigs,l=I?.endpointBindings;let A=Um(o.capability.capabilityId,o.capability.version);c=await qc({projectRoot:n,manifest:a,currentLock:u,sourceRelease:await me(Ee(m.capabilityId,m.version)),targetRelease:g,...A===void 0?{}:{targetTemplate:A},generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o.packageAdoption?.sourceChannel==="development"?{packageChannel:"development"}:{},...I===void 0?{}:{packageSource:I}})}else if(o.action==="adopt"&&a.profile?.id==="nextjs-full-stack-application"&&a.capabilities?.[0]?.capabilityId===o.capability.capabilityId&&a.capabilities?.[0]?.version!==o.capability.version)c=await Dc({projectRoot:n,manifest:a,release:await me(Ee(o.capability.capabilityId,o.capability.version)),generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()});else if(a.capabilities?.some(u=>u.capabilityId===o.capability.capabilityId&&u.version===o.capability.version)){let u=await me(Ee(i.capabilityId,i.version)),m=await Ne(n).catch(()=>null);c=await(a.profile?.id==="standalone-npm-package"?Bn:a.profile?.id==="react-component-library"?Jn:a.profile?.id==="nextjs-full-stack-application"?Kr:a.profile?.id==="workspace-npm-package"?Gn:a.profile?.id==="workspace-node-application"?Wn:a.profile?.id==="workspace-web-application"?Kn:a.profile?.id==="workspace-expo-application"?Yn:ti)({projectRoot:n,manifest:a,release:u,...m===null?{}:{currentLock:m},generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()})}else{let u=await Ne(n);if(u===null)return b("Feature apply requires the verified Profile Lock.");let m=await me(Ee(o.capability.capabilityId,o.capability.version)),g=await Wi(n,m,t);d=g?.registryConfigs,l=g?.endpointBindings,c=await Xc({projectRoot:n,manifest:a,release:m,currentLock:u,generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o.packageAdoption?.sourceChannel==="development"?{packageChannel:"development"}:{},...g===void 0?{}:{packageSource:g}})}let p;if(o.packageAdoption!==void 0){if(d===void 0)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package adoption requires a trusted Package Source Provider");let{createPnpmPackageManagerPort:u}=await import("./optional-runtime.js");if(l===void 0)throw new ne("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package adoption requires Endpoint Bindings");p=await af({projectRoot:c.transactionRoot??n,plan:o,approvedPlanId:r.values.approve,desiredContents:c.desiredContents,now:new Date().toISOString(),packageManager:u({registries:d,endpointBindings:l,...t.packageStoreRoot===void 0?{}:{storeRoot:t.packageStoreRoot}})})}else{let u=await Br({projectRoot:n,plan:o,approvedPlanId:r.values.approve,desiredContents:c.desiredContents,now:new Date().toISOString()});p=await Jr(u)}let f=Z(n);return{outputMode:z(e),human:`Project: ${f}
137
+ Plan: ${b.planId}
138
+ State: ${b.state}
139
+ ${y}`,value:{schemaVersion:1,ok:!0,command:"upgrade",result:{project:A,source:`${s.capabilityId}@${s.version}`,target:r.values.to,plan:b}}}}async function il(e,t){let r;try{r=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"},repository:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return I("Apply arguments are invalid.")}if(typeof r.values.project!="string")return I("Apply requires --project <directory>.");if(typeof r.values.approve!="string")return I("Apply requires --approve <planId>.");let n=N.resolve(r.values.project),a=JSON.parse(await ee(N.join(n,"project-capabilities.json"),"utf8")),i=a.capabilities?.[0];if(i===void 0)return I("Project manifest must select one capability.");let o=await Un({projectRoot:n,planId:r.values.approve}),s=new Date,c,d,l;if(o.action==="remove"){let u=await De(n);if(u===null)return I("Remove apply requires the verified Lock.");let f=await Bm(n,await me(Ee(o.capability.capabilityId,o.capability.version)),u,t);c=f,d="registryConfigs"in f?f.registryConfigs:void 0,l="endpointBindings"in f?f.endpointBindings:void 0}else if(o.action==="upgrade"){let u=await De(n),f=u?.capabilities.find(y=>y.capabilityId===o.capability.capabilityId);if(u===null||f===void 0)return I("Upgrade apply requires the verified source Lock.");if((f.consumerProfile==="standalone-npm-package"||f.consumerProfile==="workspace-npm-package")&&o.capability.version==="1.1.0"){if(typeof r.values.repository!="string")return I("npm package upgrade apply requires the approved --repository value.");a={...a,profile:{...a.profile,parameters:{...a.profile.parameters,repository:r.values.repository}}}}else if(r.values.repository!==void 0)return I("--repository is not valid for this apply operation.");let g=await me(Ee(o.capability.capabilityId,o.capability.version)),h={...a,capabilities:a.capabilities.map(y=>y.capabilityId===o.capability.capabilityId?{capabilityId:o.capability.capabilityId,version:o.capability.version}:y)},w=g.release.schemaVersion===2&&g.release.availability.maturity!=="withdrawn"&&g.release.packageSources.length>0,_=w?Ci(h,g):void 0,b=w?await Wi(n,g,t,_):void 0;d=b?.registryConfigs,l=b?.endpointBindings;let A=Fm(o.capability.capabilityId,o.capability.version);c=await qc({projectRoot:n,manifest:a,currentLock:u,sourceRelease:await me(Ee(f.capabilityId,f.version)),targetRelease:g,...A===void 0?{}:{targetTemplate:A},generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o.packageAdoption?.sourceChannel==="development"?{packageChannel:"development"}:{},...b===void 0?{}:{packageSource:b}})}else if(o.action==="adopt"&&a.profile?.id==="nextjs-full-stack-application"&&a.capabilities?.[0]?.capabilityId===o.capability.capabilityId&&a.capabilities?.[0]?.version!==o.capability.version)c=await Dc({projectRoot:n,manifest:a,release:await me(Ee(o.capability.capabilityId,o.capability.version)),generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()});else if(a.capabilities?.some(u=>u.capabilityId===o.capability.capabilityId&&u.version===o.capability.version)){let u=await me(Ee(i.capabilityId,i.version)),f=await De(n).catch(()=>null);c=await(a.profile?.id==="standalone-npm-package"?Bn:a.profile?.id==="react-component-library"?Jn:a.profile?.id==="nextjs-full-stack-application"?Kr:a.profile?.id==="workspace-npm-package"?Gn:a.profile?.id==="workspace-node-application"?Wn:a.profile?.id==="workspace-web-application"?Kn:a.profile?.id==="workspace-expo-application"?Yn:ti)({projectRoot:n,manifest:a,release:u,...f===null?{}:{currentLock:f},generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()})}else{let u=await De(n);if(u===null)return I("Feature apply requires the verified Profile Lock.");let f=await me(Ee(o.capability.capabilityId,o.capability.version)),g=await Wi(n,f,t);d=g?.registryConfigs,l=g?.endpointBindings,c=await Xc({projectRoot:n,manifest:a,release:f,currentLock:u,generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o.packageAdoption?.sourceChannel==="development"?{packageChannel:"development"}:{},...g===void 0?{}:{packageSource:g}})}let p;if(o.packageAdoption!==void 0){if(d===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package adoption requires a trusted Package Source Provider");let{createPnpmPackageManagerPort:u}=await import("./optional-runtime.js");if(l===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package adoption requires Endpoint Bindings");p=await of({projectRoot:c.transactionRoot??n,plan:o,approvedPlanId:r.values.approve,desiredContents:c.desiredContents,now:new Date().toISOString(),packageManager:u({registries:d,endpointBindings:l,...t.packageStoreRoot===void 0?{}:{storeRoot:t.packageStoreRoot}})})}else{let u=await Br({projectRoot:n,plan:o,approvedPlanId:r.values.approve,desiredContents:c.desiredContents,now:new Date().toISOString()});p=await Jr(u)}let m=Z(n);return{outputMode:z(e),human:`Project: ${m}
139
140
  Plan: ${o.planId}
140
141
  State: ${p.state}
141
142
  Files applied: ${p.operations.length}
142
- `+(o.packageAdoption===void 0?`Next: cd ${f} && corepack pnpm install`:`Next: dyyto verify --project ${f}`),value:{schemaVersion:1,ok:!0,command:"apply",result:{project:f,planId:o.planId,transaction:p}}}}async function gA(e,t){let r;try{r=se({args:[...e],allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},output:{type:"string"},locale:{type:"string"},channel:{type:"string"},approve:{type:"string"},"recipe-version":{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return b("Scaffold example arguments are invalid.")}if(r.positionals.length!==1||typeof r.values.output!="string"||r.values.locale!=="zh-CN"||r.values.channel!=="development"||typeof r.values["recipe-version"]!="string"||typeof r.values["artifact-workspace"]!="string"||typeof r.values["artifact-bundle"]!="string"||typeof r.values["artifact-port"]!="string")return b("Scaffold example requires recipe, --recipe-version, --output, --locale zh-CN, --channel development and exact Artifact source arguments.");let n=r.positionals[0];if(typeof n!="string")return b("Scaffold example recipe identifier is invalid.");let a=await am(oA(n,r.values["recipe-version"])),i=Number(r.values["artifact-port"]),o=r.values["artifact-workspace"],s=r.values["artifact-bundle"],c=r.values["artifact-fallback-bundle"],d=Array.isArray(c)?c.filter(u=>typeof u=="string"):[],l=r.values.approve;if(l===void 0){let u=await Sm({workspaceRoot:o,output:r.values.output,recipe:a,artifactBundle:s,artifactFallbackBundles:d,artifactPort:i});return{outputMode:z(e),human:`\u793A\u4F8B\uFF1A${a.title}
143
+ `+(o.packageAdoption===void 0?`Next: cd ${m} && corepack pnpm install`:`Next: dyyto verify --project ${m}`),value:{schemaVersion:1,ok:!0,command:"apply",result:{project:m,planId:o.planId,transaction:p}}}}async function yA(e,t){let r;try{r=ce({args:[...e],allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},output:{type:"string"},locale:{type:"string"},channel:{type:"string"},approve:{type:"string"},"recipe-version":{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return I("Scaffold example arguments are invalid.")}if(r.positionals.length!==1||typeof r.values.output!="string"||r.values.locale!=="zh-CN"||r.values.channel!=="development"||typeof r.values["recipe-version"]!="string"||typeof r.values["artifact-workspace"]!="string"||typeof r.values["artifact-bundle"]!="string"||typeof r.values["artifact-port"]!="string")return I("Scaffold example requires recipe, --recipe-version, --output, --locale zh-CN, --channel development and exact Artifact source arguments.");let n=r.positionals[0];if(typeof n!="string")return I("Scaffold example recipe identifier is invalid.");let a=await im(cA(n,r.values["recipe-version"])),i=Number(r.values["artifact-port"]),o=r.values["artifact-workspace"],s=r.values["artifact-bundle"],c=r.values["artifact-fallback-bundle"],d=Array.isArray(c)?c.filter(u=>typeof u=="string"):[],l=r.values.approve;if(l===void 0){let u=await jm({workspaceRoot:o,output:r.values.output,recipe:a,artifactBundle:s,artifactFallbackBundles:d,artifactPort:i});return{outputMode:z(e),human:`\u793A\u4F8B\uFF1A${a.title}
143
144
  Plan\uFF1A${u.planId}
144
145
  \u72B6\u6001\uFF1A\u7B49\u5F85\u9636\u6BB5\u6279\u51C6
145
- Next\uFF1A\u91CD\u590D\u672C\u547D\u4EE4\u5E76\u6DFB\u52A0 --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-plan",result:{plan:u}}}}if(typeof l!="string")return b("Scaffold example --approve must be an exact Plan ID.");let p=["--artifact-workspace",o,"--artifact-bundle",s,...d.flatMap(u=>["--artifact-fallback-bundle",u]),"--artifact-port",String(i)],f;try{f=await jm({workspaceRoot:o,approvedPlanId:l,recipe:a,execute:async(u,m)=>{if(m.artifactBundle!==s||JSON.stringify(m.artifactFallbackBundles)!==JSON.stringify(d)||m.artifactPort!==i)throw new Error("SCAFFOLD_SOURCE_PLAN_MISMATCH");let g=[],w=(await Bm([u,"--profile","nextjs-full-stack-application","--capability",`${a.rootProfile.capabilityId}@${a.rootProfile.version}`,"--name",a.recipeId])).value.result.plan.planId;await il(["--project",u,"--approve",w],t),g.push(w),await qm("corepack",["pnpm","install","--no-frozen-lockfile","--ignore-scripts"],{cwd:u,env:{...process.env,CI:"true",NO_COLOR:"1",pnpm_config_store_dir:N.join(o,".dyyto","resolution-worker","store","shared")},timeout:3e5,maxBuffer:4*1024*1024}),await ol(["--project",u]);for(let _ of a.capabilities){let I=`${_.capabilityId}@${_.version}`;try{let y=(await Jm(["--project",u,"--capability",I,"--channel",_.channel,...p],t)).value.result.plan.planId;await il(["--project",u,"--approve",y,...p],t),await ol(["--project",u]),g.push(y)}catch(A){throw new Error(`SCAFFOLD_CAPABILITY_FAILED:${I}:${A instanceof Error?A.message:"UNKNOWN"}`,{cause:A})}}return g}})}catch(u){let m=u instanceof ze&&u.cause instanceof Error?u.cause.message:"SCAFFOLD_APPLY_FAILED";throw new Ce({code:"SCAFFOLD_APPLY_FAILED",message:`\u793A\u4F8B\u811A\u624B\u67B6\u6267\u884C\u5931\u8D25\uFF1A${m}`,exitCode:1,nextStep:"\u68C0\u67E5\u5931\u8D25\u7684 Capability \u4E0E\u4E8B\u52A1 Evidence\uFF0C\u4FEE\u590D\u540E\u91CD\u65B0\u751F\u6210 Plan\u3002"})}return{outputMode:z(e),human:`\u793A\u4F8B\u5DF2\u751F\u6210\uFF1A${N.relative(process.cwd(),f.output)}
146
- Evidence\uFF1A${f.evidenceId}
147
- \u72B6\u6001\uFF1Aadopted`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-apply",result:f}}}function pa(e,t){let r;try{r=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return b(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?b(`${t} requires --project <directory>.`):{projectRoot:N.resolve(r.values.project),outputMode:z(e)}}async function ol(e){let{projectRoot:t,outputMode:r}=pa(e,"Verify"),n=JSON.parse(await ee(N.join(t,"project-capabilities.json"),"utf8")),a=await Ne(t),i=await Wr(t).catch(()=>{}),o;try{let h=a?.capabilities.map(_=>_.appliedPlanId)??[],w=a?.capabilities.map(_=>_.capabilityId)??[];try{o=await yi(t,h,t,w)}catch(_){if(!(_ instanceof ke)||_.code!=="PLAN_NOT_FOUND"||i===void 0)throw _;o=await yi(t,h,i.transactionRoot,w)}}catch(h){if(!(h instanceof ke)||h.code!=="PLAN_NOT_FOUND"||a===null)throw h;let _=(await sl(["--project",t,"--json"])).value.result,I=await na({projectRoot:t,lock:a});if(_.state!=="adopted"||I.some(y=>y.code!=="EVIDENCE_VALID"))throw new Ce({code:"VERIFICATION_STATE_INVALID",message:"The adopted project has drifted or its verification evidence is invalid.",exitCode:4,nextStep:"Run dyyto inspect and dyyto doctor before creating a new plan."});let A=Z(t);return{outputMode:r,human:`Project: ${A}
146
+ Next\uFF1A\u91CD\u590D\u672C\u547D\u4EE4\u5E76\u6DFB\u52A0 --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-plan",result:{plan:u}}}}if(typeof l!="string")return I("Scaffold example --approve must be an exact Plan ID.");let p=["--artifact-workspace",o,"--artifact-bundle",s,...d.flatMap(u=>["--artifact-fallback-bundle",u]),"--artifact-port",String(i)],m;try{m=await $m({workspaceRoot:o,approvedPlanId:l,recipe:a,execute:async(u,f)=>{if(f.artifactBundle!==s||JSON.stringify(f.artifactFallbackBundles)!==JSON.stringify(d)||f.artifactPort!==i)throw new Error("SCAFFOLD_SOURCE_PLAN_MISMATCH");let g=[],w=(await Jm([u,"--profile","nextjs-full-stack-application","--capability",`${a.rootProfile.capabilityId}@${a.rootProfile.version}`,"--name",a.recipeId])).value.result.plan.planId;await il(["--project",u,"--approve",w],t),g.push(w),await Um("corepack",["pnpm","install","--no-frozen-lockfile","--ignore-scripts"],{cwd:u,env:{...process.env,CI:"true",NO_COLOR:"1",pnpm_config_store_dir:N.join(o,".dyyto","resolution-worker","store","shared")},timeout:3e5,maxBuffer:4*1024*1024}),await ol(["--project",u]);for(let _ of a.capabilities){let b=`${_.capabilityId}@${_.version}`;try{let y=(await Gm(["--project",u,"--capability",b,"--channel",_.channel,...p],t)).value.result.plan.planId;await il(["--project",u,"--approve",y,...p],t),await ol(["--project",u]),g.push(y)}catch(A){throw new Error(`SCAFFOLD_CAPABILITY_FAILED:${b}:${A instanceof Error?A.message:"UNKNOWN"}`,{cause:A})}}return g}})}catch(u){let f=u instanceof ze&&u.cause instanceof Error?u.cause.message:"SCAFFOLD_APPLY_FAILED";throw new Ce({code:"SCAFFOLD_APPLY_FAILED",message:`\u793A\u4F8B\u811A\u624B\u67B6\u6267\u884C\u5931\u8D25\uFF1A${f}`,exitCode:1,nextStep:"\u68C0\u67E5\u5931\u8D25\u7684 Capability \u4E0E\u4E8B\u52A1 Evidence\uFF0C\u4FEE\u590D\u540E\u91CD\u65B0\u751F\u6210 Plan\u3002"})}return{outputMode:z(e),human:`\u793A\u4F8B\u5DF2\u751F\u6210\uFF1A${N.relative(process.cwd(),m.output)}
147
+ Evidence\uFF1A${m.evidenceId}
148
+ \u72B6\u6001\uFF1Aadopted`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-apply",result:m}}}function pa(e,t){let r;try{r=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return I(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?I(`${t} requires --project <directory>.`):{projectRoot:N.resolve(r.values.project),outputMode:z(e)}}async function ol(e){let{projectRoot:t,outputMode:r}=pa(e,"Verify"),n=JSON.parse(await ee(N.join(t,"project-capabilities.json"),"utf8")),a=await De(t),i=await Wr(t).catch(()=>{}),o;try{let h=a?.capabilities.map(_=>_.appliedPlanId)??[],w=a?.capabilities.map(_=>_.capabilityId)??[];try{o=await yi(t,h,t,w)}catch(_){if(!(_ instanceof ge)||_.code!=="PLAN_NOT_FOUND"||i===void 0)throw _;o=await yi(t,h,i.transactionRoot,w)}}catch(h){if(!(h instanceof ge)||h.code!=="PLAN_NOT_FOUND"||a===null)throw h;let _=(await sl(["--project",t,"--json"])).value.result,b=await na({projectRoot:t,lock:a});if(_.state!=="adopted"||b.some(y=>y.code!=="EVIDENCE_VALID"))throw new Ce({code:"VERIFICATION_STATE_INVALID",message:"The adopted project has drifted or its verification evidence is invalid.",exitCode:4,nextStep:"Run dyyto inspect and dyyto doctor before creating a new plan."});let A=Z(t);return{outputMode:r,human:`Project: ${A}
148
149
  State: adopted
149
150
  Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:A,state:"adopted",reused:!0,lock:a}}}}let s=await me(Ee(o.capability.capabilityId,o.capability.version)),c=o.packageAdoption===void 0?void 0:i?.transactionRoot;if(a?.capabilities.some(h=>h.appliedPlanId===o.planId)){let h=Z(t);return{outputMode:r,human:`Project: ${h}
150
151
  State: adopted
151
- Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:h,state:"adopted",reused:!0}}}}if(o.action==="remove"){if(a===null)return b("Remove verification requires the previous verified Lock.");let h=a.capabilities.find($=>$.capabilityId===o.capability.capabilityId&&$.version===o.capability.version);if(h===void 0){let $=Z(t);return{outputMode:r,human:`Project: ${$}
152
+ Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:h,state:"adopted",reused:!0}}}}if(o.action==="remove"){if(a===null)return I("Remove verification requires the previous verified Lock.");let h=a.capabilities.find($=>$.capabilityId===o.capability.capabilityId&&$.version===o.capability.version);if(h===void 0){let $=Z(t);return{outputMode:r,human:`Project: ${$}
152
153
  State: removed
153
- Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:$,state:"removed",reused:!0,lock:a}}}}let w=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",_=new Map(o.operations.flatMap($=>$.desiredDigest===void 0||!$.path.startsWith(w)?[]:[[$.path.slice(w.length),$.desiredDigest]])),I=a.capabilities.filter($=>$!==h),A=[...I].filter($=>$.packageAdoption!==void 0).sort(($,P)=>$.committedAt.localeCompare(P.committedAt)).at(-1)?.packageAdoption,y=I.flatMap($=>$.assets).map($=>({...$,digest:_.get($.path)??($.path==="package.json"?A?.packageJsonDigest:void 0)??$.digest})),{executeRemovalVerification:k}=await import("./optional-runtime.js"),S=await k({projectRoot:t,release:s,remainingAssets:y,removedPaths:h.assets.map($=>$.path)}),O=await Ic({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:S.results,committedAt:new Date().toISOString(),previousLock:a,expectedAssets:y}),ae=Z(t);return{outputMode:r,human:`Project: ${ae}
154
+ Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:$,state:"removed",reused:!0,lock:a}}}}let w=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",_=new Map(o.operations.flatMap($=>$.desiredDigest===void 0||!$.path.startsWith(w)?[]:[[$.path.slice(w.length),$.desiredDigest]])),b=a.capabilities.filter($=>$!==h),A=[...b].filter($=>$.packageAdoption!==void 0).sort(($,P)=>$.committedAt.localeCompare(P.committedAt)).at(-1)?.packageAdoption,y=b.flatMap($=>$.assets).map($=>({...$,digest:_.get($.path)??($.path==="package.json"?A?.packageJsonDigest:void 0)??$.digest})),{executeRemovalVerification:k}=await import("./optional-runtime.js"),S=await k({projectRoot:t,release:s,remainingAssets:y,removedPaths:h.assets.map($=>$.path)}),O=await Ic({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:S.results,committedAt:new Date().toISOString(),previousLock:a,expectedAssets:y}),ie=Z(t);return{outputMode:r,human:`Project: ${ie}
154
155
  State: removed
155
156
  ${S.summaries.map($=>`${$.verifierId}: ${$.result}`).join(`
156
- `)}`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:ae,state:"removed",verifiers:S.summaries,lock:O}}}}let d=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",l=(s.release.kind==="engineering-feature"?s.release.assets.map(h=>({path:h.path,desiredDigest:h.ownership==="managed-region"?h.digest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.action==="upgrade"?s.release.assets.map(h=>({path:h.path,desiredDigest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.operations).map(({path:h,desiredDigest:w,ownership:_,regionId:I})=>w===void 0?b("Applied plan is missing a desired asset digest."):{path:h,digest:w,ownership:_==="managed-region"?"managed-region":_==="seed-file"?"seed-file":"owned-file",...I===void 0?{}:{regionId:I}}),{executeVerification:p}=await import("./optional-runtime.js"),f=await p({projectRoot:t,release:s,expectedAssets:l}),u=o.action==="adopt"&&o.operations.every(h=>h.disposition==="noop")&&a?.capabilities.some(h=>h.capabilityId===o.capability.capabilityId)===!0,m=await vc({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:f.results,committedAt:new Date().toISOString(),expectedAssets:l,...(o.action==="upgrade"||s.release.kind==="engineering-feature"||u)&&a!==null?{previousLock:a}:{}}),g=Z(t);return{outputMode:r,human:`Project: ${g}
157
+ `)}`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:ie,state:"removed",verifiers:S.summaries,lock:O}}}}let d=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",l=(s.release.kind==="engineering-feature"?s.release.assets.map(h=>({path:h.path,desiredDigest:h.ownership==="managed-region"?h.digest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.action==="upgrade"?s.release.assets.map(h=>({path:h.path,desiredDigest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.operations).map(({path:h,desiredDigest:w,ownership:_,regionId:b})=>w===void 0?I("Applied plan is missing a desired asset digest."):{path:h,digest:w,ownership:_==="managed-region"?"managed-region":_==="seed-file"?"seed-file":"owned-file",...b===void 0?{}:{regionId:b}}),{executeVerification:p}=await import("./optional-runtime.js"),m=await p({projectRoot:t,release:s,expectedAssets:l}),u=o.action==="adopt"&&o.operations.every(h=>h.disposition==="noop")&&a?.capabilities.some(h=>h.capabilityId===o.capability.capabilityId)===!0,f=await vc({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:m.results,committedAt:new Date().toISOString(),expectedAssets:l,...(o.action==="upgrade"||s.release.kind==="engineering-feature"||u)&&a!==null?{previousLock:a}:{}}),g=Z(t);return{outputMode:r,human:`Project: ${g}
157
158
  State: adopted
158
- `+f.summaries.map(h=>`${h.verifierId}: ${h.result}`).join(`
159
- `),value:{schemaVersion:1,ok:!0,command:"verify",result:{project:g,state:"adopted",verifiers:f.summaries,lock:m}}}}async function sl(e){let{projectRoot:t,outputMode:r}=pa(e,"Inspect"),n=await Ac(t),a=Z(t);if(n.required)return{outputMode:r,human:`Project: ${a}
159
+ `+m.summaries.map(h=>`${h.verifierId}: ${h.result}`).join(`
160
+ `),value:{schemaVersion:1,ok:!0,command:"verify",result:{project:g,state:"adopted",verifiers:m.summaries,lock:f}}}}async function sl(e){let{projectRoot:t,outputMode:r}=pa(e,"Inspect"),n=await Ac(t),a=Z(t);if(n.required)return{outputMode:r,human:`Project: ${a}
160
161
  State: recovery-required
161
162
  Transaction: ${n.kind}
162
- Next: dyyto recover --project ${a}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:a,state:"recovery-required",recovery:n}}};let i=JSON.parse(await ee(N.join(t,"project-capabilities.json"),"utf8")),o=i.capabilities?.[0];if(o===void 0)return b("Project manifest must select one capability.");let s=await me(Ee(o.capabilityId,o.version)),c=await Ne(t);try{let A=await yi(t,c?.capabilities.map(y=>y.appliedPlanId)??[],t,c?.capabilities.map(y=>y.capabilityId)??[]);if(A.action==="upgrade"||A.action==="adopt")return{outputMode:r,human:`Project: ${a}
163
+ Next: dyyto recover --project ${a}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:a,state:"recovery-required",recovery:n}}};let i=JSON.parse(await ee(N.join(t,"project-capabilities.json"),"utf8")),o=i.capabilities?.[0];if(o===void 0)return I("Project manifest must select one capability.");let s=await me(Ee(o.capabilityId,o.version)),c=await De(t);try{let A=await yi(t,c?.capabilities.map(y=>y.appliedPlanId)??[],t,c?.capabilities.map(y=>y.capabilityId)??[]);if(A.action==="upgrade"||A.action==="adopt")return{outputMode:r,human:`Project: ${a}
163
164
  State: applied-unverified
164
165
  Plan: ${A.planId}
165
- Next: dyyto verify --project ${a}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:a,state:"applied-unverified",operations:A.operations,lock:c}}}}catch{}let d=new Date,l={projectRoot:t,release:s,...c===null?{}:{currentLock:c},generatedAt:d.toISOString(),expiresAt:new Date(d.getTime()+1800*1e3).toISOString()},p=i.profile?.id==="standalone-npm-package"?await zu({...l,manifest:i}):i.profile?.id==="react-component-library"?await Bu({...l,manifest:i}):i.profile?.id==="nextjs-full-stack-application"?await Ju({...l,manifest:i}):i.profile?.id==="workspace-npm-package"?await Gu({...l,manifest:i}):i.profile?.id==="workspace-node-application"?await Wu({...l,manifest:i}):i.profile?.id==="workspace-web-application"?await Ku({...l,manifest:i}):i.profile?.id==="workspace-expo-application"?await Yu({...l,manifest:i}):await ei(l),f=c===null?void 0:[...c.capabilities].filter(A=>A.packageAdoption!==void 0).sort((A,y)=>A.committedAt.localeCompare(y.committedAt)).at(-1)?.packageAdoption?.packageJsonDigest,u=f===void 0?void 0:await ee(N.join(t,"package.json")).then(v).catch(()=>{}),m=p.operations.map(A=>A.path==="package.json"&&u===f?{...A,desiredDigest:f,disposition:"noop",conflictCode:void 0}:A),g=c===null?[]:await ym({projectRoot:t,lock:c,excludeCapabilityIds:[o.capabilityId]}),h=g.some(A=>A.disposition==="conflict"),w=f!==void 0&&m.every(A=>A.disposition==="noop")?{...p,state:"adopted"}:p,_={...w,state:h?"drifted":w.state,operations:[...m,...g]},I=c?.capabilities.flatMap(A=>A.packageAdoption?.sources.map(y=>({capabilityId:A.capabilityId,registryId:y.registryId,packageName:y.packageName,version:y.version,integrity:y.integrity}))??[])??[];return{outputMode:r,human:`Project: ${a}
166
+ Next: dyyto verify --project ${a}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:a,state:"applied-unverified",operations:A.operations,lock:c}}}}catch{}let d=new Date,l={projectRoot:t,release:s,...c===null?{}:{currentLock:c},generatedAt:d.toISOString(),expiresAt:new Date(d.getTime()+1800*1e3).toISOString()},p=i.profile?.id==="standalone-npm-package"?await Bu({...l,manifest:i}):i.profile?.id==="react-component-library"?await Ju({...l,manifest:i}):i.profile?.id==="nextjs-full-stack-application"?await Gu({...l,manifest:i}):i.profile?.id==="workspace-npm-package"?await Wu({...l,manifest:i}):i.profile?.id==="workspace-node-application"?await Ku({...l,manifest:i}):i.profile?.id==="workspace-web-application"?await Yu({...l,manifest:i}):i.profile?.id==="workspace-expo-application"?await Hu({...l,manifest:i}):await ei(l),m=c===null?void 0:[...c.capabilities].filter(A=>A.packageAdoption!==void 0).sort((A,y)=>A.committedAt.localeCompare(y.committedAt)).at(-1)?.packageAdoption?.packageJsonDigest,u=m===void 0?void 0:await ee(N.join(t,"package.json")).then(v).catch(()=>{}),f=p.operations.map(A=>A.path==="package.json"&&u===m?{...A,desiredDigest:m,disposition:"noop",conflictCode:void 0}:A),g=c===null?[]:await wm({projectRoot:t,lock:c,excludeCapabilityIds:[o.capabilityId]}),h=g.some(A=>A.disposition==="conflict"),w=m!==void 0&&f.every(A=>A.disposition==="noop")?{...p,state:"adopted"}:p,_={...w,state:h?"drifted":w.state,operations:[...f,...g]},b=c?.capabilities.flatMap(A=>A.packageAdoption?.sources.map(y=>({capabilityId:A.capabilityId,registryId:y.registryId,packageName:y.packageName,version:y.version,integrity:y.integrity}))??[])??[];return{outputMode:r,human:`Project: ${a}
166
167
  State: ${_.state}
167
168
  `+_.operations.map(A=>`${A.path}: ${A.disposition}`).join(`
168
- `)+(I.length===0?"":`
169
+ `)+(b.length===0?"":`
169
170
  \u5305\u6765\u6E90\uFF1A
170
- ${I.map(A=>`- ${A.packageName}@${A.version}\uFF08Registry: ${A.registryId}\uFF0C\u5B8C\u6574\u6027\u5DF2\u9501\u5B9A\uFF09`).join(`
171
- `)}`),value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:a,..._,lock:c,packageSources:I}}}}async function hA(e){let{projectRoot:t,outputMode:r}=pa(e,"Recover"),n=await qu({projectRoot:t,now:new Date().toISOString()}),a=Z(t);return{outputMode:r,human:n.kind==="none"?`Project: ${a}
171
+ ${b.map(A=>`- ${A.packageName}@${A.version}\uFF08Registry: ${A.registryId}\uFF0C\u5B8C\u6574\u6027\u5DF2\u9501\u5B9A\uFF09`).join(`
172
+ `)}`),value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:a,..._,lock:c,packageSources:b}}}}async function wA(e){let{projectRoot:t,outputMode:r}=pa(e,"Recover"),n=await Uu({projectRoot:t,now:new Date().toISOString()}),a=Z(t);return{outputMode:r,human:n.kind==="none"?`Project: ${a}
172
173
  Recovery: not-required`:`Project: ${a}
173
174
  Recovery: ${n.kind}
174
- State: ${n.state}`,value:{schemaVersion:1,ok:!0,command:"recover",result:{project:a,recovery:n}}}}function Gm(e,t){let r;try{r=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},command:{type:"string"},after:{type:"string"}}})}catch{return b(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?b(`${t} requires --project.`):{parsed:r,projectRoot:N.resolve(r.values.project),outputMode:z(e)}}async function yA(e,t){let{parsed:r,projectRoot:n,outputMode:a}=Gm(t,"Lifecycle"),i=r.values.command;if((e==="start"||e==="restart")&&i!=="dev")return b("Lifecycle start/restart requires the supported --command dev.");try{let{projectProcessLogs:o,projectProcessStatus:s,startProjectProcess:c,stopProjectProcess:d}=await import("./optional-runtime.js"),l;if(e==="status")l=await s(n);else if(e==="logs"){let f=r.values.after===void 0?0:Number(r.values.after);if(!Number.isSafeInteger(f)||f<0)return b("Lifecycle logs --after must be a non-negative integer cursor.");l=await o(n,f)}else if(e==="start")await Lm(n,"dev"),l=await c(n,"dev");else if(e==="stop")l=await d(n);else if(e==="restart")await Lm(n,"dev"),await d(n),l=await c(n,"dev");else return b("Lifecycle action must be start, stop, restart, status, or logs.");let p=Z(n);return{outputMode:a,human:`Project: ${p}
175
+ State: ${n.state}`,value:{schemaVersion:1,ok:!0,command:"recover",result:{project:a,recovery:n}}}}function Wm(e,t){let r;try{r=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},command:{type:"string"},after:{type:"string"}}})}catch{return I(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?I(`${t} requires --project.`):{parsed:r,projectRoot:N.resolve(r.values.project),outputMode:z(e)}}async function vA(e,t){let{parsed:r,projectRoot:n,outputMode:a}=Wm(t,"Lifecycle"),i=r.values.command;if((e==="start"||e==="restart")&&i!=="dev")return I("Lifecycle start/restart requires the supported --command dev.");try{let{projectProcessLogs:o,projectProcessStatus:s,startProjectProcess:c,stopProjectProcess:d}=await import("./optional-runtime.js"),l;if(e==="status")l=await s(n);else if(e==="logs"){let m=r.values.after===void 0?0:Number(r.values.after);if(!Number.isSafeInteger(m)||m<0)return I("Lifecycle logs --after must be a non-negative integer cursor.");l=await o(n,m)}else if(e==="start")await Vm(n,"dev"),l=await c(n,"dev");else if(e==="stop")l=await d(n);else if(e==="restart")await Vm(n,"dev"),await d(n),l=await c(n,"dev");else return I("Lifecycle action must be start, stop, restart, status, or logs.");let p=Z(n);return{outputMode:a,human:`Project: ${p}
175
176
  Lifecycle: ${e}
176
- State: ${"state"in l?l.state:"available"}`,value:{schemaVersion:1,ok:!0,command:`lifecycle-${e}`,result:{project:p,...l,projectRoot:void 0}}}}catch(o){let s=typeof o=="object"&&o!==null&&"code"in o?String(o.code):"PROJECT_PROCESS_FAILED";throw new Ce({code:s,message:o instanceof Error?o.message:"Project lifecycle operation failed.",exitCode:4,nextStep:"Inspect lifecycle status and project logs before retrying."})}}async function Lm(e,t){let r=K(JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8")));if(r.template===void 0)throw new Ce({code:"PROJECT_COMMAND_UNSUPPORTED",message:"Managed lifecycle requires a formal Template Release.",exitCode:4,nextStep:"Use the project's standard package script directly or adopt a supported Template."});if((await oa(Ki(r.template.id,r.template.version))).commands[t]!==t)throw new Ce({code:"PROJECT_COMMAND_UNSUPPORTED",message:"The selected Template does not declare the requested lifecycle command.",exitCode:4,nextStep:"Choose a command declared by the project's Template Release."})}async function wA(e){let{projectRoot:t,outputMode:r}=Gm(e,"Integrations"),{projectIntegrations:n}=await import("./optional-runtime.js"),a=await n(t),i=Z(t),o=a.details.flatMap(d=>[`${d.title} (${d.capabilityId}@${d.version}) [${d.status}]`,` ${d.purpose}`,...d.packages.map(l=>` package ${l.packageName}@${l.version} [${l.state}]`),...d.packages.flatMap(l=>l.imports.map(p=>` import { ${p.symbol} } from '${p.importFrom}'${p.referencePath?` -> ${p.referencePath}`:""}`)),...d.codeAssets.map(l=>` asset ${l.sourcePath} -> ${l.targetPath} (${l.ownership})`)]),s=d=>a.platformDependencies.filter(l=>l.source===d).length,c=a.platformDependencies.map(d=>` platform ${d.packageName} ${d.version} [${d.source}]`);return{outputMode:r,human:`Project: ${i}
177
+ State: ${"state"in l?l.state:"available"}`,value:{schemaVersion:1,ok:!0,command:`lifecycle-${e}`,result:{project:p,...l,projectRoot:void 0}}}}catch(o){let s=typeof o=="object"&&o!==null&&"code"in o?String(o.code):"PROJECT_PROCESS_FAILED";throw new Ce({code:s,message:o instanceof Error?o.message:"Project lifecycle operation failed.",exitCode:4,nextStep:"Inspect lifecycle status and project logs before retrying."})}}async function Vm(e,t){let r=W(JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8")));if(r.template===void 0)throw new Ce({code:"PROJECT_COMMAND_UNSUPPORTED",message:"Managed lifecycle requires a formal Template Release.",exitCode:4,nextStep:"Use the project's standard package script directly or adopt a supported Template."});if((await oa(Ki(r.template.id,r.template.version))).commands[t]!==t)throw new Ce({code:"PROJECT_COMMAND_UNSUPPORTED",message:"The selected Template does not declare the requested lifecycle command.",exitCode:4,nextStep:"Choose a command declared by the project's Template Release."})}async function IA(e){let{projectRoot:t,outputMode:r}=Wm(e,"Integrations"),{projectIntegrations:n}=await import("./optional-runtime.js"),a=await n(t),i=Z(t),o=a.details.flatMap(d=>[`${d.title} (${d.capabilityId}@${d.version}) [${d.status}]`,` ${d.purpose}`,...d.packages.map(l=>` package ${l.packageName}@${l.version} [${l.state}]`),...d.packages.flatMap(l=>l.imports.map(p=>` import { ${p.symbol} } from '${p.importFrom}'${p.referencePath?` -> ${p.referencePath}`:""}`)),...d.codeAssets.map(l=>` asset ${l.sourcePath} -> ${l.targetPath} (${l.ownership})`)]),s=d=>a.platformDependencies.filter(l=>l.source===d).length,c=a.platformDependencies.map(d=>` platform ${d.packageName} ${d.version} [${d.source}]`);return{outputMode:r,human:`Project: ${i}
177
178
  Declared: ${a.declared.length}
178
179
  Locked: ${a.locked.length}
179
180
  Verified: ${a.verified.length}
@@ -181,7 +182,7 @@ Findings: ${a.findings.length}
181
182
  Unmanaged platform dependencies: ${a.platformDependencies.length} (workspace ${s("workspace")} / registry ${s("registry")} / other ${s("other")})
182
183
 
183
184
  ${[...o,...c].join(`
184
- `)}`,value:{schemaVersion:1,ok:!0,command:"integrations",result:{project:i,...a,projectRoot:void 0}}}}async function vA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},source:{type:"string"},registry:{type:"string"},approve:{type:"string"},verify:{type:"string"},install:{type:"boolean"}}})}catch{return b("Packages switch arguments are invalid.")}if(typeof t.values.project!="string")return b("Packages switch requires --project.");let r=[t.values.approve,t.values.verify].filter(m=>typeof m=="string").length;if(r>1)return b("Packages switch accepts only one of --approve or --verify.");let{applyAndInstallPackageSourceSwitch:n,applyPackageSourceSwitch:a,switchProjectPackageSources:i,verifyPackageSourceSwitch:o,PackageSourceSwitchError:s}=await import("./optional-runtime.js"),c=t.values.source??"workspace";if(r===0&&c!=="workspace"&&c!=="public"&&c!=="private")return b("Packages switch requires --source workspace|public|private.");let d=N.resolve(t.values.project),l=await(typeof t.values.approve=="string"?t.values.install===!0?n({projectRoot:d,approvedPlanId:t.values.approve}):a({projectRoot:d,approvedPlanId:t.values.approve}):typeof t.values.verify=="string"?o({projectRoot:d,planId:t.values.verify}):i({projectRoot:d,scope:"@aipt/",source:c,...typeof t.values.registry=="string"?{registry:t.values.registry}:{}})).catch(m=>{throw m instanceof s?new Ce({code:m.code,message:m.message,exitCode:4,nextStep:"Run dyyto packages switch --help."}):m}),p=Z(l.projectRoot),f=l.changes.map(m=>` ${m.field} ${m.packageName}: ${m.from} -> ${m.to}`),u=l.state==="reviewable"?`\u5BA1\u6838\u4E0D\u53EF\u53D8 Plan \u540E\u4F7F\u7528 --approve ${l.planId} \u7CBE\u786E\u6279\u51C6\u3002`:l.state==="applied"?`\u4F7F\u7528 --verify ${l.planId} \u9A8C\u8BC1\u3002`:"Package source manifest \u5DF2\u4E0E\u6279\u51C6\u7684 Plan \u4E00\u81F4\u3002";return{outputMode:z(e),human:`\u9879\u76EE\uFF1A${p}
185
+ `)}`,value:{schemaVersion:1,ok:!0,command:"integrations",result:{project:i,...a,projectRoot:void 0}}}}async function bA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},source:{type:"string"},registry:{type:"string"},approve:{type:"string"},verify:{type:"string"},install:{type:"boolean"}}})}catch{return I("Packages switch arguments are invalid.")}if(typeof t.values.project!="string")return I("Packages switch requires --project.");let r=[t.values.approve,t.values.verify].filter(f=>typeof f=="string").length;if(r>1)return I("Packages switch accepts only one of --approve or --verify.");let{applyAndInstallPackageSourceSwitch:n,applyPackageSourceSwitch:a,switchProjectPackageSources:i,verifyPackageSourceSwitch:o,PackageSourceSwitchError:s}=await import("./optional-runtime.js"),c=t.values.source??"workspace";if(r===0&&c!=="workspace"&&c!=="public"&&c!=="private")return I("Packages switch requires --source workspace|public|private.");let d=N.resolve(t.values.project),l=await(typeof t.values.approve=="string"?t.values.install===!0?n({projectRoot:d,approvedPlanId:t.values.approve}):a({projectRoot:d,approvedPlanId:t.values.approve}):typeof t.values.verify=="string"?o({projectRoot:d,planId:t.values.verify}):i({projectRoot:d,scope:"@aipt/",source:c,...typeof t.values.registry=="string"?{registry:t.values.registry}:{}})).catch(f=>{throw f instanceof s?new Ce({code:f.code,message:f.message,exitCode:4,nextStep:"Run dyyto packages switch --help."}):f}),p=Z(l.projectRoot),m=l.changes.map(f=>` ${f.field} ${f.packageName}: ${f.from} -> ${f.to}`),u=l.state==="reviewable"?`\u5BA1\u6838\u4E0D\u53EF\u53D8 Plan \u540E\u4F7F\u7528 --approve ${l.planId} \u7CBE\u786E\u6279\u51C6\u3002`:l.state==="applied"?`\u4F7F\u7528 --verify ${l.planId} \u9A8C\u8BC1\u3002`:"Package source manifest \u5DF2\u4E0E\u6279\u51C6\u7684 Plan \u4E00\u81F4\u3002";return{outputMode:z(e),human:`\u9879\u76EE\uFF1A${p}
185
186
  \u6765\u6E90\uFF1A${l.source}
186
187
  Registry\uFF1A${l.registry??"workspace protocol"}
187
188
  \u72B6\u6001\uFF1A${l.state}
@@ -190,27 +191,27 @@ Packages\uFF1A${l.packages.length}
190
191
  \u53D8\u66F4\uFF1A${l.changes.length}
191
192
  \u5DF2\u5199\u5165\uFF1A${l.written?"\u662F":"\u5426"}
192
193
 
193
- ${f.join(`
194
- `)}${f.length>0?`
194
+ ${m.join(`
195
+ `)}${m.length>0?`
195
196
 
196
- `:""}\u4E0B\u4E00\u6B65\uFF1A${u}`,value:{schemaVersion:1,ok:!0,command:"packages switch",result:{project:p,source:l.source,registry:l.registry,state:l.state,planId:l.planId,packages:l.packages,changes:l.changes,written:l.written,...l.installVerified===void 0?{}:{installVerified:l.installVerified},...l.lockfileDigest===void 0?{}:{lockfileDigest:l.lockfileDigest}}}}}async function IA(e){let{projectRoot:t,outputMode:r}=pa(e,"Inspect"),n=K(JSON.parse(await ee(N.join(t,"project-capabilities.json"),"utf8")));if(n.template===void 0)throw new Ce({code:"PROJECT_MAINTENANCE_UNAVAILABLE",message:"Project maintenance requires a formal Template Release.",exitCode:4,nextStep:"Adopt a supported engineering template."});let a=await oa(Ki(n.template.id,n.template.version)),i=await dm({projectRoot:t,commands:a.commands}),o=Z(t);return{outputMode:r,human:`Project: ${o}
197
+ `:""}\u4E0B\u4E00\u6B65\uFF1A${u}`,value:{schemaVersion:1,ok:!0,command:"packages switch",result:{project:p,source:l.source,registry:l.registry,state:l.state,planId:l.planId,packages:l.packages,changes:l.changes,written:l.written,...l.installVerified===void 0?{}:{installVerified:l.installVerified},...l.lockfileDigest===void 0?{}:{lockfileDigest:l.lockfileDigest}}}}}async function kA(e){let{projectRoot:t,outputMode:r}=pa(e,"Inspect"),n=W(JSON.parse(await ee(N.join(t,"project-capabilities.json"),"utf8")));if(n.template===void 0)throw new Ce({code:"PROJECT_MAINTENANCE_UNAVAILABLE",message:"Project maintenance requires a formal Template Release.",exitCode:4,nextStep:"Adopt a supported engineering template."});let a=await oa(Ki(n.template.id,n.template.version)),i=await pm({projectRoot:t,commands:a.commands}),o=Z(t);return{outputMode:r,human:`Project: ${o}
197
198
  Commands: ${i.commands.map(s=>s.id).join(", ")}
198
- Environment: ${i.environment.filter(s=>s.configured).length}/${i.environment.length} configured`,value:{schemaVersion:1,ok:!0,command:"maintenance",result:{project:o,template:`${a.templateId}@${a.version}`,...i}}}}async function bA(e){let{projectRoot:t,outputMode:r}=pa(e,"Inspect"),n=await $i({projectRoot:t}).catch(a=>{throw new Ce({code:a instanceof Error&&"code"in a?String(a.code):"APPLICATION_CONFIG_UNAVAILABLE",message:a instanceof Error?a.message:"\u5E94\u7528\u914D\u7F6E\u4E0D\u53EF\u7528\u3002",exitCode:4,nextStep:"\u8BBE\u7F6E\u8BE5\u9879\u76EE\u72EC\u4EAB\u7684\u7EDD\u5BF9APP_CONFIG_DIR\uFF0C\u5E76\u7531\u90E8\u7F72\u63A7\u5236\u9762\u5B8C\u6210config init\u3002"})});return{outputMode:r,human:`\u5E94\u7528\uFF1A${n.application}
199
+ Environment: ${i.environment.filter(s=>s.configured).length}/${i.environment.length} configured`,value:{schemaVersion:1,ok:!0,command:"maintenance",result:{project:o,template:`${a.templateId}@${a.version}`,...i}}}}async function _A(e){let{projectRoot:t,outputMode:r}=pa(e,"Inspect"),n=await $i({projectRoot:t}).catch(a=>{throw new Ce({code:a instanceof Error&&"code"in a?String(a.code):"APPLICATION_CONFIG_UNAVAILABLE",message:a instanceof Error?a.message:"\u5E94\u7528\u914D\u7F6E\u4E0D\u53EF\u7528\u3002",exitCode:4,nextStep:"\u8BBE\u7F6E\u8BE5\u9879\u76EE\u72EC\u4EAB\u7684\u7EDD\u5BF9APP_CONFIG_DIR\uFF0C\u5E76\u7531\u90E8\u7F72\u63A7\u5236\u9762\u5B8C\u6210config init\u3002"})});return{outputMode:r,human:`\u5E94\u7528\uFF1A${n.application}
199
200
  \u73AF\u5883\uFF1A${n.environment}
200
201
  Config Dir\uFF1A${n.configDirectory}
201
202
  \u5DF2\u914D\u7F6E\uFF1A${n.entries.filter(a=>a.configured).length}/${n.entries.length}
202
203
  ${n.entries.map(a=>`${a.name}: ${a.display}`).join(`
203
- `)}`,value:{schemaVersion:1,ok:!0,command:"config-inspect",result:n}}}async function kA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},plane:{type:"string"},state:{type:"string"},kind:{type:"string"},limit:{type:"string"}}})}catch{return b("Operations arguments are invalid.")}if(typeof t.values.project!="string"||!["change","quality","delivery"].includes(t.values.plane))return b("Operations requires --project and --plane change|quality|delivery.");let r=await lt(N.resolve(t.values.project)),n=Z(r),a=[];for(let o of await Mm(N.join(r,".dyyto","workbench","tasks")).catch(()=>[]))if(o.endsWith(".json"))try{let s=JSON.parse(await ee(N.join(r,".dyyto","workbench","tasks",o),"utf8"));s.taskId&&typeof s.operation=="string"&&typeof s.state=="string"&&typeof s.createdAt=="string"&&typeof s.updatedAt=="string"&&a.push({id:s.taskId,projectId:".",projectName:n,operation:s.operation,state:s.state,createdAt:s.createdAt,updatedAt:s.updatedAt,...s.correlationId?{correlationId:s.correlationId}:{}})}catch{}let i=fm(a,{plane:t.values.plane,...typeof t.values.state=="string"?{state:t.values.state}:{},...typeof t.values.kind=="string"?{kind:t.values.kind}:{},...typeof t.values.limit=="string"?{limit:Number(t.values.limit)}:{}});return{outputMode:z(e),human:`Project: ${n}
204
+ `)}`,value:{schemaVersion:1,ok:!0,command:"config-inspect",result:n}}}async function EA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},plane:{type:"string"},state:{type:"string"},kind:{type:"string"},limit:{type:"string"}}})}catch{return I("Operations arguments are invalid.")}if(typeof t.values.project!="string"||!["change","quality","delivery"].includes(t.values.plane))return I("Operations requires --project and --plane change|quality|delivery.");let r=await lt(N.resolve(t.values.project)),n=Z(r),a=[];for(let o of await qm(N.join(r,".dyyto","workbench","tasks")).catch(()=>[]))if(o.endsWith(".json"))try{let s=JSON.parse(await ee(N.join(r,".dyyto","workbench","tasks",o),"utf8"));s.taskId&&typeof s.operation=="string"&&typeof s.state=="string"&&typeof s.createdAt=="string"&&typeof s.updatedAt=="string"&&a.push({id:s.taskId,projectId:".",projectName:n,operation:s.operation,state:s.state,createdAt:s.createdAt,updatedAt:s.updatedAt,...s.correlationId?{correlationId:s.correlationId}:{}})}catch{}let i=mm(a,{plane:t.values.plane,...typeof t.values.state=="string"?{state:t.values.state}:{},...typeof t.values.kind=="string"?{kind:t.values.kind}:{},...typeof t.values.limit=="string"?{limit:Number(t.values.limit)}:{}});return{outputMode:z(e),human:`Project: ${n}
204
205
  Operations: ${i.plane}
205
206
  Total: ${i.summary.total}
206
- Attention: ${i.summary.attention}`,value:{schemaVersion:1,ok:!0,command:"operations",result:{project:n,...i}}}}async function _A(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"}}})}catch{return b("Doctor arguments are invalid.")}if(typeof t.values.workspace!="string")return b("Doctor requires --workspace.");let r=await lt(N.resolve(t.values.workspace));if(K(JSON.parse(await ee(N.join(r,"project-capabilities.json"),"utf8"))).profile?.id!=="workspace-root")return b("Doctor requires a workspace-root project.");let a=[{unit:".",kind:"root",projectRoot:r}];for(let s of["packages","apps"])for(let c of await Mm(N.join(r,s),{withFileTypes:!0}).catch(()=>[])){if(!c.isDirectory()||c.isSymbolicLink())continue;let d=N.join(r,s,c.name);try{await ee(N.join(d,"project-capabilities.json"))}catch{continue}a.push({unit:`${s}/${c.name}`,kind:s==="packages"?"package":"application",projectRoot:d})}let i=[];for(let s of a){let c="invalid",d;try{let p=(await sl(["--project",s.projectRoot,"--json"])).value.result;c=p.state??"invalid",d=Hc(c),c==="adopted"&&p.lock!==null&&typeof p.lock=="object"?d.push(...await na({projectRoot:s.projectRoot,lock:p.lock})):c==="adopted"&&d.push({code:"EVIDENCE_INVALID",severity:"critical",fact:"evidence",message:"\u5DF2\u91C7\u7528\u5355\u5143\u7F3A\u5C11\u53EF\u6838\u9A8C\u7684\u91C7\u7528\u9501\u3002",action:"\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\u5E76\u63D0\u4EA4\u91C7\u7528\u9501\u3002"})}catch{d=Hc("invalid")}try{let l=K(JSON.parse(await ee(N.join(s.projectRoot,"project-capabilities.json"),"utf8")));l.profile?.id==="workspace-web-application"&&d.push(...await Kf({workspaceRoot:r,applicationId:String(l.profile.parameters.name)}))}catch{}i.push({unit:s.unit,kind:s.kind,state:c,findings:d})}let o=Yf({workspace:N.basename(r),generatedAt:new Date().toISOString(),units:i});return{outputMode:z(e),human:`Workspace: ${o.workspace}
207
+ Attention: ${i.summary.attention}`,value:{schemaVersion:1,ok:!0,command:"operations",result:{project:n,...i}}}}async function AA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"}}})}catch{return I("Doctor arguments are invalid.")}if(typeof t.values.workspace!="string")return I("Doctor requires --workspace.");let r=await lt(N.resolve(t.values.workspace));if(W(JSON.parse(await ee(N.join(r,"project-capabilities.json"),"utf8"))).profile?.id!=="workspace-root")return I("Doctor requires a workspace-root project.");let a=[{unit:".",kind:"root",projectRoot:r}];for(let s of["packages","apps"])for(let c of await qm(N.join(r,s),{withFileTypes:!0}).catch(()=>[])){if(!c.isDirectory()||c.isSymbolicLink())continue;let d=N.join(r,s,c.name);try{await ee(N.join(d,"project-capabilities.json"))}catch{continue}a.push({unit:`${s}/${c.name}`,kind:s==="packages"?"package":"application",projectRoot:d})}let i=[];for(let s of a){let c="invalid",d;try{let p=(await sl(["--project",s.projectRoot,"--json"])).value.result;c=p.state??"invalid",d=Hc(c),c==="adopted"&&p.lock!==null&&typeof p.lock=="object"?d.push(...await na({projectRoot:s.projectRoot,lock:p.lock})):c==="adopted"&&d.push({code:"EVIDENCE_INVALID",severity:"critical",fact:"evidence",message:"\u5DF2\u91C7\u7528\u5355\u5143\u7F3A\u5C11\u53EF\u6838\u9A8C\u7684\u91C7\u7528\u9501\u3002",action:"\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\u5E76\u63D0\u4EA4\u91C7\u7528\u9501\u3002"})}catch{d=Hc("invalid")}try{let l=W(JSON.parse(await ee(N.join(s.projectRoot,"project-capabilities.json"),"utf8")));l.profile?.id==="workspace-web-application"&&d.push(...await Yf({workspaceRoot:r,applicationId:String(l.profile.parameters.name)}))}catch{}i.push({unit:s.unit,kind:s.kind,state:c,findings:d})}let o=Hf({workspace:N.basename(r),generatedAt:new Date().toISOString(),units:i});return{outputMode:z(e),human:`Workspace: ${o.workspace}
207
208
  Status: ${o.status}
208
209
  Units: ${o.summary.total}
209
210
  Healthy: ${o.summary.healthy}
210
211
  Attention: ${o.summary.attention}
211
212
  Blocked: ${o.summary.blocked}
212
213
  `+o.units.map(s=>`${s.unit}: ${s.status} (${s.findings.map(c=>c.code).join(", ")})`).join(`
213
- `),value:{schemaVersion:1,ok:!0,command:"doctor",result:o}}}async function cl(e){let{LocalDockerDeploymentAdapter:t,NpmjsPublisherAdapter:r,HostedStaticPublicationAdapter:n}=await import("./optional-runtime.js");return e==="npm-publish"?new r:e==="application-deploy"?new t:e==="hosted-static"?new n:b("Delivery kind must be npm-publish, application-deploy, or hosted-static.")}function Vm(e){return e.length<=16?e:`${e.slice(0,12)}\u2026`}async function Wm(e){let t=K(JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8"))),r=await Ne(e),n=r?.capabilities[0];if(r===null||n===void 0||r.capabilities.length!==1)return b("Delivery requires one adopted capability Lock.");if(t.profile===void 0||t.capabilities[0]?.capabilityId!==n.capabilityId||t.capabilities[0]?.version!==n.version)return b("Manifest and verified Lock must identify the same adopted capability.");let a=n.assets.filter(i=>!i.path.startsWith("src/"));return await ir({projectRoot:e,expectedAssets:a}),{manifest:t,lock:r,locked:n,lockDigest:v(E(r))}}async function EA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},kind:{type:"string"},provider:{type:"string"},repository:{type:"string"},workflow:{type:"string"},ref:{type:"string"},environment:{type:"string"}}})}catch{return b("Delivery plan arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.kind!="string")return b("Delivery plan requires --project and --kind.");let r=N.resolve(t.values.project),n=await Wm(r),i=await(await cl(t.values.kind)).prepare({projectRoot:r,profile:n.manifest.profile.id,parameters:n.manifest.profile.parameters});if(t.values.kind==="npm-publish"&&await Rf({projectRoot:r,artifactIdentity:i.artifact.identity})!==null)throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","An earlier Delivery Plan started a remote write for this exact npm version without a resolved Registry outcome");let o=t.values.kind==="npm-publish"?(()=>{let l=t.values.provider,p=t.values.repository,f=t.values.workflow,u=t.values.ref;if(l!=="github-actions"&&l!=="gitlab-ci"||typeof p!="string"||typeof f!="string"||typeof u!="string")throw new j("DELIVERY_PRECONDITION_FAILED","Secure npm Delivery Plan requires --provider, --repository, --workflow and --ref.");return{mode:"staged",access:"public",tag:"latest",authentication:"trusted-publishing",trustedAction:"stage-only",provenance:"required",execution:{provider:l,repository:p,workflow:f,ref:u,...typeof t.values.environment=="string"?{environment:t.values.environment}:{}}}})():void 0;if(o!==void 0){let l=JSON.parse(await ee(N.join(r,"package.json"),"utf8")),p=typeof l.repository=="string"?l.repository:l.repository!==null&&typeof l.repository=="object"?l.repository.url:void 0,f=`https://${o.execution.provider==="github-actions"?"github.com":"gitlab.com"}/${o.execution.repository}`;if(p!==f)throw new j("NPM_PROVENANCE_REQUIRED","package.json repository does not match the trusted publishing repository identity")}let s=new Date,c=Jc({kind:t.values.kind,project:{profile:n.manifest.profile.id,lockDigest:n.lockDigest,appliedPlanId:n.locked.appliedPlanId},artifact:i.artifact,target:i.target,risk:t.values.kind==="npm-publish"?"irreversible-publish":t.values.kind==="hosted-static"?"external-reversible-publication":"local-reversible-deployment",createdAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o===void 0?{}:{publication:o}});await _f({projectRoot:r,plan:c});let d=Z(r);return{outputMode:z(e),human:`Project: ${d}
214
+ `),value:{schemaVersion:1,ok:!0,command:"doctor",result:o}}}async function cl(e){let{LocalDockerDeploymentAdapter:t,NpmjsPublisherAdapter:r,HostedStaticPublicationAdapter:n}=await import("./optional-runtime.js");return e==="npm-publish"?new r:e==="application-deploy"?new t:e==="hosted-static"?new n:I("Delivery kind must be npm-publish, application-deploy, or hosted-static.")}function Mm(e){return e.length<=16?e:`${e.slice(0,12)}\u2026`}async function Km(e){let t=W(JSON.parse(await ee(N.join(e,"project-capabilities.json"),"utf8"))),r=await De(e),n=r?.capabilities[0];if(r===null||n===void 0||r.capabilities.length!==1)return I("Delivery requires one adopted capability Lock.");if(t.profile===void 0||t.capabilities[0]?.capabilityId!==n.capabilityId||t.capabilities[0]?.version!==n.version)return I("Manifest and verified Lock must identify the same adopted capability.");let a=n.assets.filter(i=>!i.path.startsWith("src/"));return await or({projectRoot:e,expectedAssets:a}),{manifest:t,lock:r,locked:n,lockDigest:v(E(r))}}async function RA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},kind:{type:"string"},provider:{type:"string"},repository:{type:"string"},workflow:{type:"string"},ref:{type:"string"},environment:{type:"string"}}})}catch{return I("Delivery plan arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.kind!="string")return I("Delivery plan requires --project and --kind.");let r=N.resolve(t.values.project),n=await Km(r),i=await(await cl(t.values.kind)).prepare({projectRoot:r,profile:n.manifest.profile.id,parameters:n.manifest.profile.parameters});if(t.values.kind==="npm-publish"&&await Pf({projectRoot:r,artifactIdentity:i.artifact.identity})!==null)throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","An earlier Delivery Plan started a remote write for this exact npm version without a resolved Registry outcome");let o=t.values.kind==="npm-publish"?(()=>{let l=t.values.provider,p=t.values.repository,m=t.values.workflow,u=t.values.ref;if(l!=="github-actions"&&l!=="gitlab-ci"||typeof p!="string"||typeof m!="string"||typeof u!="string")throw new j("DELIVERY_PRECONDITION_FAILED","Secure npm Delivery Plan requires --provider, --repository, --workflow and --ref.");return{mode:"staged",access:"public",tag:"latest",authentication:"trusted-publishing",trustedAction:"stage-only",provenance:"required",execution:{provider:l,repository:p,workflow:m,ref:u,...typeof t.values.environment=="string"?{environment:t.values.environment}:{}}}})():void 0;if(o!==void 0){let l=JSON.parse(await ee(N.join(r,"package.json"),"utf8")),p=typeof l.repository=="string"?l.repository:l.repository!==null&&typeof l.repository=="object"?l.repository.url:void 0,m=`https://${o.execution.provider==="github-actions"?"github.com":"gitlab.com"}/${o.execution.repository}`;if(p!==m)throw new j("NPM_PROVENANCE_REQUIRED","package.json repository does not match the trusted publishing repository identity")}let s=new Date,c=Jc({kind:t.values.kind,project:{profile:n.manifest.profile.id,lockDigest:n.lockDigest,appliedPlanId:n.locked.appliedPlanId},artifact:i.artifact,target:i.target,risk:t.values.kind==="npm-publish"?"irreversible-publish":t.values.kind==="hosted-static"?"external-reversible-publication":"local-reversible-deployment",createdAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o===void 0?{}:{publication:o}});await Ef({projectRoot:r,plan:c});let d=Z(r);return{outputMode:z(e),human:`Project: ${d}
214
215
  Delivery: ${c.kind}
215
216
  Artifact: ${c.artifact.identity}
216
217
  Target: ${c.target.location}
@@ -222,20 +223,20 @@ Execution: ${c.publication.execution.provider}:${c.publication.execution.reposit
222
223
  Approval: maintainer 2FA required outside Dyyto`}
223
224
  Plan: ${c.planId}
224
225
  State: reviewable
225
- Next: dyyto delivery apply --project ${d} --approve ${c.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-plan",result:{project:d,plan:c}}}}async function AA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"}}})}catch{return b("Delivery apply arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.approve!="string")return b("Delivery apply requires --project and --approve <planId>.");let r=N.resolve(t.values.project),n=await Ut({projectRoot:r,planId:t.values.approve}),a=await Qn({projectRoot:r,planId:n.planId}),i=Z(r);if(a!==null)return{outputMode:z(e),human:`Project: ${i}
226
+ Next: dyyto delivery apply --project ${d} --approve ${c.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-plan",result:{project:d,plan:c}}}}async function PA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"}}})}catch{return I("Delivery apply arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.approve!="string")return I("Delivery apply requires --project and --approve <planId>.");let r=N.resolve(t.values.project),n=await Ft({projectRoot:r,planId:t.values.approve}),a=await Qn({projectRoot:r,planId:n.planId}),i=Z(r);if(a!==null)return{outputMode:z(e),human:`Project: ${i}
226
227
  Delivery: verified
227
228
  Receipt: ${a.receiptId}`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:i,reused:!0,receipt:a}}};let o=n.kind==="npm-publish"?await Yr({projectRoot:r,planId:n.planId}):null;if(o!==null)return{outputMode:z(e),human:`Project: ${i}
228
229
  Delivery: staged
229
- Stage: ${Vm(o.stageId)}
230
- State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:i,reused:!0,state:"staged",record:o}}};if((n.kind==="npm-publish"?await Af({projectRoot:r,planId:n.planId}):null)!==null)throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","This Plan already started a remote stage write without a committed Stage Record");if(Date.parse(n.expiresAt)<=Date.now())throw new j("DELIVERY_PLAN_EXPIRED","Delivery Plan has expired");let c=await Wm(r);if(c.lockDigest!==n.project.lockDigest||c.locked.appliedPlanId!==n.project.appliedPlanId)throw new j("DELIVERY_PRECONDITION_FAILED","Adoption Lock changed after Delivery Plan approval");let d=await cl(n.kind),l=await d.prepare({projectRoot:r,profile:c.manifest.profile.id,parameters:c.manifest.profile.parameters});if(E(l.artifact)!==E(n.artifact)||E(l.target)!==E(n.target))throw new j("DELIVERY_PRECONDITION_FAILED","Artifact or target changed after Delivery Plan approval");let p=await d.execute({projectRoot:r,plan:n,...n.kind==="npm-publish"?{onRemoteWriteStarting:async()=>{await Ef({projectRoot:r,record:bf({planId:n.planId,artifactDigest:n.artifact.digest,startedAt:new Date().toISOString()})})}}:{}});if(n.kind==="npm-publish"){let u=If({planId:n.planId,stageId:p.externalIdentity,artifactDigest:n.artifact.digest,createdAt:new Date().toISOString()});return await Pf({projectRoot:r,record:u}),{outputMode:z(e),human:`Project: ${i}
230
+ Stage: ${Mm(o.stageId)}
231
+ State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:i,reused:!0,state:"staged",record:o}}};if((n.kind==="npm-publish"?await Rf({projectRoot:r,planId:n.planId}):null)!==null)throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","This Plan already started a remote stage write without a committed Stage Record");if(Date.parse(n.expiresAt)<=Date.now())throw new j("DELIVERY_PLAN_EXPIRED","Delivery Plan has expired");let c=await Km(r);if(c.lockDigest!==n.project.lockDigest||c.locked.appliedPlanId!==n.project.appliedPlanId)throw new j("DELIVERY_PRECONDITION_FAILED","Adoption Lock changed after Delivery Plan approval");let d=await cl(n.kind),l=await d.prepare({projectRoot:r,profile:c.manifest.profile.id,parameters:c.manifest.profile.parameters});if(E(l.artifact)!==E(n.artifact)||E(l.target)!==E(n.target))throw new j("DELIVERY_PRECONDITION_FAILED","Artifact or target changed after Delivery Plan approval");let p=await d.execute({projectRoot:r,plan:n,...n.kind==="npm-publish"?{onRemoteWriteStarting:async()=>{await Af({projectRoot:r,record:kf({planId:n.planId,artifactDigest:n.artifact.digest,startedAt:new Date().toISOString()})})}}:{}});if(n.kind==="npm-publish"){let u=bf({planId:n.planId,stageId:p.externalIdentity,artifactDigest:n.artifact.digest,createdAt:new Date().toISOString()});return await Nf({projectRoot:r,record:u}),{outputMode:z(e),human:`Project: ${i}
231
232
  Delivery: staged
232
- Stage: ${Vm(u.stageId)}
233
- State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:i,state:"staged",record:u}}}}if(n.kind==="application-deploy"&&(await d.inspect({projectRoot:r,plan:n})).state!=="verified")throw new j("DELIVERY_EXECUTION_UNKNOWN","Docker deployment outcome could not be verified");let f=xi({planId:n.planId,kind:n.kind,adapterId:n.target.adapterId,artifactDigest:n.artifact.digest,target:n.target.location,externalIdentity:p.externalIdentity,completedAt:new Date().toISOString(),details:p.details});return await Gc({projectRoot:r,receipt:f}),{outputMode:z(e),human:`Project: ${i}
233
+ Stage: ${Mm(u.stageId)}
234
+ State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:i,state:"staged",record:u}}}}if(n.kind==="application-deploy"&&(await d.inspect({projectRoot:r,plan:n})).state!=="verified")throw new j("DELIVERY_EXECUTION_UNKNOWN","Docker deployment outcome could not be verified");let m=xi({planId:n.planId,kind:n.kind,adapterId:n.target.adapterId,artifactDigest:n.artifact.digest,target:n.target.location,externalIdentity:p.externalIdentity,completedAt:new Date().toISOString(),details:p.details});return await Gc({projectRoot:r,receipt:m}),{outputMode:z(e),human:`Project: ${i}
234
235
  Delivery: verified
235
- Receipt: ${f.receiptId}
236
- External: ${f.externalIdentity}`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:i,receipt:f}}}}async function RA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},plan:{type:"string"},"stage-artifact":{type:"string"}}})}catch{return b("Delivery inspect arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.plan!="string")return b("Delivery inspect requires --project and --plan <planId>.");let r=N.resolve(t.values.project),n=await Ut({projectRoot:r,planId:t.values.plan}),a=await Qn({projectRoot:r,planId:n.planId}),i=Z(r);if(a!==null)return{outputMode:z(e),human:`Project: ${i}
236
+ Receipt: ${m.receiptId}
237
+ External: ${m.externalIdentity}`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:i,receipt:m}}}}async function NA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},plan:{type:"string"},"stage-artifact":{type:"string"}}})}catch{return I("Delivery inspect arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.plan!="string")return I("Delivery inspect requires --project and --plan <planId>.");let r=N.resolve(t.values.project),n=await Ft({projectRoot:r,planId:t.values.plan}),a=await Qn({projectRoot:r,planId:n.planId}),i=Z(r);if(a!==null)return{outputMode:z(e),human:`Project: ${i}
237
238
  Delivery: verified
238
- Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:i,state:"verified",plan:n,receipt:a}}};let o=n.kind==="npm-publish"?await Yr({projectRoot:r,planId:n.planId}):null,s=n.kind==="npm-publish"?await Df({projectRoot:r,planId:n.planId}):null;if(typeof t.values["stage-artifact"]=="string"){if(n.kind!=="npm-publish"||o===null)throw new j("DELIVERY_PRECONDITION_FAILED","Stage artifact review requires an existing npm Stage Record");let d=v(await ee(N.resolve(t.values["stage-artifact"])));if(d!==n.artifact.digest||d!==o.artifactDigest)throw new j("DELIVERY_PRECONDITION_FAILED","Reviewed stage artifact does not match the approved Delivery Plan");s=kf({planId:n.planId,stageId:o.stageId,artifactDigest:d,reviewedAt:new Date().toISOString()}),await Nf({projectRoot:r,record:s})}let c=await(await cl(n.kind)).inspect({projectRoot:r,plan:n});if(n.kind==="npm-publish"&&o!==null&&c.state==="verified"){if(n.schemaVersion!==2||n.publication===void 0||c.details.artifactDigest!==n.artifact.digest||c.details.provenance!=="registry-attestation-present"||c.details.provenanceUrlDigest===void 0)throw new j("NPM_PROVENANCE_REQUIRED","Registry inspection did not prove the approved npm artifact and provenance");let d=xi({planId:n.planId,kind:n.kind,adapterId:"registry.npmjs",artifactDigest:n.artifact.digest,target:n.target.location,externalIdentity:n.artifact.identity,completedAt:new Date().toISOString(),npm:{stageId:o.stageId,registry:"https://registry.npmjs.org",tarballDigest:n.artifact.digest,access:n.publication.access,tag:n.publication.tag,provenance:"registry-attested",attestationUrlDigest:c.details.provenanceUrlDigest}});return await Gc({projectRoot:r,receipt:d}),{outputMode:z(e),human:`Project: ${i}
239
+ Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:i,state:"verified",plan:n,receipt:a}}};let o=n.kind==="npm-publish"?await Yr({projectRoot:r,planId:n.planId}):null,s=n.kind==="npm-publish"?await Sf({projectRoot:r,planId:n.planId}):null;if(typeof t.values["stage-artifact"]=="string"){if(n.kind!=="npm-publish"||o===null)throw new j("DELIVERY_PRECONDITION_FAILED","Stage artifact review requires an existing npm Stage Record");let d=v(await ee(N.resolve(t.values["stage-artifact"])));if(d!==n.artifact.digest||d!==o.artifactDigest)throw new j("DELIVERY_PRECONDITION_FAILED","Reviewed stage artifact does not match the approved Delivery Plan");s=_f({planId:n.planId,stageId:o.stageId,artifactDigest:d,reviewedAt:new Date().toISOString()}),await Df({projectRoot:r,record:s})}let c=await(await cl(n.kind)).inspect({projectRoot:r,plan:n});if(n.kind==="npm-publish"&&o!==null&&c.state==="verified"){if(n.schemaVersion!==2||n.publication===void 0||c.details.artifactDigest!==n.artifact.digest||c.details.provenance!=="registry-attestation-present"||c.details.provenanceUrlDigest===void 0)throw new j("NPM_PROVENANCE_REQUIRED","Registry inspection did not prove the approved npm artifact and provenance");let d=xi({planId:n.planId,kind:n.kind,adapterId:"registry.npmjs",artifactDigest:n.artifact.digest,target:n.target.location,externalIdentity:n.artifact.identity,completedAt:new Date().toISOString(),npm:{stageId:o.stageId,registry:"https://registry.npmjs.org",tarballDigest:n.artifact.digest,access:n.publication.access,tag:n.publication.tag,provenance:"registry-attested",attestationUrlDigest:c.details.provenanceUrlDigest}});return await Gc({projectRoot:r,receipt:d}),{outputMode:z(e),human:`Project: ${i}
239
240
  Delivery: verified
240
241
  Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:i,state:"verified",plan:n,stage:o,review:s,receipt:d,adapter:c}}}}if(n.kind==="npm-publish"&&o!==null){let d=c.state==="absent"||c.state==="staged"?"approval-pending":c.state;return{outputMode:z(e),human:`Project: ${i}
241
242
  Delivery: staged
@@ -243,17 +244,17 @@ Plan: ${n.planId}
243
244
  Artifact review: ${s===null?"pending":"verified"}
244
245
  State: ${d}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:i,state:d,plan:n,stage:o,review:s,receipt:null,adapter:c}}}}if(n.kind==="npm-publish"&&c.state==="verified")throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","Live npm artifact is visible but no immutable Stage Record exists for this Plan");return{outputMode:z(e),human:`Project: ${i}
245
246
  Delivery: ${c.state}
246
- Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:i,state:c.state,plan:n,receipt:null,adapter:c}}}}async function PA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},application:{type:"string"},limit:{type:"string"},cursor:{type:"string"}}})}catch{return b("Observe errors arguments are invalid.")}if(typeof t.values.workspace!="string")return b("Observe errors requires --workspace.");let r=await lt(N.resolve(t.values.workspace)),n=new yr(r),a={...typeof t.values.application=="string"?{applicationId:t.values.application}:{},...typeof t.values.limit=="string"?{limit:Number(t.values.limit)}:{},...typeof t.values.cursor=="string"?{cursor:t.values.cursor}:{}},[i,o]=await Promise.all([n.list(a),n.summary(a)]);return{outputMode:z(e),human:i.events.length===0?"\u672A\u53D1\u73B0\u8FD0\u884C\u65F6\u9519\u8BEF\u3002":i.events.map(s=>`${s.occurredAt} ${s.applicationId} ${s.error.type}: ${s.error.message} (${s.state}, ${s.correlation})`).join(`
247
- `),value:{schemaVersion:1,ok:!0,command:"observe-errors",result:{...i,summary:o}}}}async function NA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},id:{type:"string"}}})}catch{return b("Observe error arguments are invalid.")}if(typeof t.values.workspace!="string"||typeof t.values.id!="string")return b("Observe error requires --workspace and --id.");let r=await new yr(await lt(N.resolve(t.values.workspace))).get(t.values.id);if(r===null)throw new Ce({code:"RUNTIME_ERROR_NOT_FOUND",message:"Runtime Error Event was not found.",exitCode:4,nextStep:"List recent errors and verify the event ID."});return{outputMode:z(e),human:`${r.error.type}: ${r.error.message}
247
+ Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:i,state:c.state,plan:n,receipt:null,adapter:c}}}}async function DA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},application:{type:"string"},limit:{type:"string"},cursor:{type:"string"}}})}catch{return I("Observe errors arguments are invalid.")}if(typeof t.values.workspace!="string")return I("Observe errors requires --workspace.");let r=await lt(N.resolve(t.values.workspace)),n=new yr(r),a={...typeof t.values.application=="string"?{applicationId:t.values.application}:{},...typeof t.values.limit=="string"?{limit:Number(t.values.limit)}:{},...typeof t.values.cursor=="string"?{cursor:t.values.cursor}:{}},[i,o]=await Promise.all([n.list(a),n.summary(a)]);return{outputMode:z(e),human:i.events.length===0?"\u672A\u53D1\u73B0\u8FD0\u884C\u65F6\u9519\u8BEF\u3002":i.events.map(s=>`${s.occurredAt} ${s.applicationId} ${s.error.type}: ${s.error.message} (${s.state}, ${s.correlation})`).join(`
248
+ `),value:{schemaVersion:1,ok:!0,command:"observe-errors",result:{...i,summary:o}}}}async function SA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},id:{type:"string"}}})}catch{return I("Observe error arguments are invalid.")}if(typeof t.values.workspace!="string"||typeof t.values.id!="string")return I("Observe error requires --workspace and --id.");let r=await new yr(await lt(N.resolve(t.values.workspace))).get(t.values.id);if(r===null)throw new Ce({code:"RUNTIME_ERROR_NOT_FOUND",message:"Runtime Error Event was not found.",exitCode:4,nextStep:"List recent errors and verify the event ID."});return{outputMode:z(e),human:`${r.error.type}: ${r.error.message}
248
249
  State: ${r.state}
249
250
  Correlation: ${r.correlation}
250
251
  Release: ${r.releaseId??"unknown"}
251
- Deployment: ${r.deploymentId??"unknown"}`,value:{schemaVersion:1,ok:!0,command:"observe-error",result:{event:r}}}}async function DA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},workspace:{type:"string"}}})}catch{return b("Observe release register arguments are invalid.")}if(typeof t.values.project!="string")return b("Observe release register requires --project.");let r=await lt(N.resolve(t.values.project)),n=await lt(N.resolve(typeof t.values.workspace=="string"?t.values.workspace:N.join(r,"../.."))),{registerWebRelease:a}=await import("./optional-runtime.js"),i=await a({workspaceRoot:n,projectRoot:r});return{outputMode:z(e),human:`Release: ${i.releaseId}
252
+ Deployment: ${r.deploymentId??"unknown"}`,value:{schemaVersion:1,ok:!0,command:"observe-error",result:{event:r}}}}async function jA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},workspace:{type:"string"}}})}catch{return I("Observe release register arguments are invalid.")}if(typeof t.values.project!="string")return I("Observe release register requires --project.");let r=await lt(N.resolve(t.values.project)),n=await lt(N.resolve(typeof t.values.workspace=="string"?t.values.workspace:N.join(r,"../.."))),{registerWebRelease:a}=await import("./optional-runtime.js"),i=await a({workspaceRoot:n,projectRoot:r});return{outputMode:z(e),human:`Release: ${i.releaseId}
252
253
  Source Maps: ${i.registrations.length}
253
- \u516C\u5F00\u4EA7\u7269\u5DF2\u79FB\u9664 .map \u6587\u4EF6\u3002`,value:{schemaVersion:1,ok:!0,command:"observe-release-register",result:i}}}async function SA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},query:{type:"string"},kind:{type:"string"},limit:{type:"string"}}})}catch{return b("Catalog search \u53C2\u6570\u65E0\u6548\u3002")}let r=t.values.kind;if(r!==void 0&&r!=="all"&&r!=="package"&&r!=="capability")return b("Catalog search --kind \u53EA\u63A5\u53D7 all\u3001package \u6216 capability\u3002");let n=t.values.limit===void 0?50:Number(t.values.limit);if(!Number.isSafeInteger(n)||n<1||n>200)return b("Catalog search --limit \u5FC5\u987B\u662F 1 \u5230 200 \u7684\u6574\u6570\u3002");let a=await Tm({...typeof t.values.query=="string"?{query:t.values.query}:{},...r==="package"||r==="capability"?{kind:r}:{},limit:n}),i=a.items.length===0?"\u76EE\u5F55\u4E2D\u6CA1\u6709\u5339\u914D\u7684\u5DE5\u7A0B\u80FD\u529B\u3002":a.items.map(o=>`${o.ref}
254
+ \u516C\u5F00\u4EA7\u7269\u5DF2\u79FB\u9664 .map \u6587\u4EF6\u3002`,value:{schemaVersion:1,ok:!0,command:"observe-release-register",result:i}}}async function $A(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},query:{type:"string"},kind:{type:"string"},limit:{type:"string"}}})}catch{return I("Catalog search \u53C2\u6570\u65E0\u6548\u3002")}let r=t.values.kind;if(r!==void 0&&r!=="all"&&r!=="package"&&r!=="capability")return I("Catalog search --kind \u53EA\u63A5\u53D7 all\u3001package \u6216 capability\u3002");let n=t.values.limit===void 0?50:Number(t.values.limit);if(!Number.isSafeInteger(n)||n<1||n>200)return I("Catalog search --limit \u5FC5\u987B\u662F 1 \u5230 200 \u7684\u6574\u6570\u3002");let a=await xm({...typeof t.values.query=="string"?{query:t.values.query}:{},...r==="package"||r==="capability"?{kind:r}:{},limit:n}),i=a.items.length===0?"\u76EE\u5F55\u4E2D\u6CA1\u6709\u5339\u914D\u7684\u5DE5\u7A0B\u80FD\u529B\u3002":a.items.map(o=>`${o.ref}
254
255
  ${o.summary}
255
256
  \u6210\u719F\u5EA6\uFF1A${o.maturity}`).join(`
256
- `);return{outputMode:z(e),human:i,value:{schemaVersion:1,ok:!0,command:"catalog-search",result:a}}}async function jA(e){let t;try{t=se({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},ref:{type:"string"}}})}catch{return b("Catalog show \u53C2\u6570\u65E0\u6548\u3002")}if(typeof t.values.ref!="string"||t.values.ref.trim()==="")return b("Catalog show \u9700\u8981 --ref\u3002");let r=await xm({ref:t.values.ref});return{outputMode:z(e),human:`${r.item.ref}
257
+ `);return{outputMode:z(e),human:i,value:{schemaVersion:1,ok:!0,command:"catalog-search",result:a}}}async function OA(e){let t;try{t=ce({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},ref:{type:"string"}}})}catch{return I("Catalog show \u53C2\u6570\u65E0\u6548\u3002")}if(typeof t.values.ref!="string"||t.values.ref.trim()==="")return I("Catalog show \u9700\u8981 --ref\u3002");let r=await Lm({ref:t.values.ref});return{outputMode:z(e),human:`${r.item.ref}
257
258
  ${r.item.summary}
258
259
  \u6210\u719F\u5EA6\uFF1A${r.item.maturity}
259
- \u5B8C\u6574\u6027\uFF1A${r.item.integrity}`,value:{schemaVersion:1,ok:!0,command:"catalog-show",result:r}}}async function XS(e,t={}){let r=e[0]==="--"?e.slice(1):e,n=z(r);if(r[0]==="--version"&&r.every(o=>o==="--version"||o==="--json"))return{outputMode:n,human:el,value:{schemaVersion:1,ok:!0,command:"version",result:{version:el}}};if(r.length===0||r[0]==="--help"||r[0]==="-h")return{outputMode:n,human:vm,value:{schemaVersion:1,ok:!0,command:"help",result:{usage:"dyyto <command> [options]"}}};let[a,...i]=r;return a==="catalog"&&i[0]==="search"?SA(i.slice(1)):a==="catalog"&&i[0]==="show"?jA(i.slice(1)):a==="create"?Bm(i):a==="scaffold"&&i[0]==="example"?gA(i.slice(1),t):a==="retrofit"?sA(i):a==="dev"||a==="build"||a==="test"||a==="package"?cA(a,i):a==="add"&&i[0]==="package"?lA(i.slice(1)):a==="add"&&i[0]==="application"?dA(i.slice(1)):a==="add"&&i[0]==="feature"?Jm(i.slice(1),t):a==="remove"&&i[0]==="feature"?pA(i.slice(1),t):a==="plan"?uA(i):a==="upgrade"?mA(i,t):a==="apply"?il(i,t):a==="verify"?ol(i):a==="inspect"?sl(i):a==="doctor"?_A(i):a==="recover"?hA(i):a==="lifecycle"&&typeof i[0]=="string"?yA(i[0],i.slice(1)):a==="packages"&&i[0]==="switch"?vA(i.slice(1)):a==="integrations"?wA(i):a==="maintenance"?IA(i):a==="config"&&i[0]==="inspect"?bA(i.slice(1)):a==="operations"?kA(i):a==="baseline"?fA(i):a==="delivery"&&i[0]==="plan"?EA(i.slice(1)):a==="delivery"&&i[0]==="apply"?AA(i.slice(1)):a==="delivery"&&i[0]==="inspect"?RA(i.slice(1)):a==="observe"&&i[0]==="errors"?PA(i.slice(1)):a==="observe"&&i[0]==="error"?NA(i.slice(1)):a==="observe"&&i[0]==="release"&&i[1]==="register"?DA(i.slice(2)):b(`Unknown command '${a}'.`)}export{XS as runApplication};
260
+ \u5B8C\u6574\u6027\uFF1A${r.item.integrity}`,value:{schemaVersion:1,ok:!0,command:"catalog-show",result:r}}}async function QS(e,t={}){let r=e[0]==="--"?e.slice(1):e,n=z(r);if(r[0]==="--version"&&r.every(o=>o==="--version"||o==="--json"))return{outputMode:n,human:el,value:{schemaVersion:1,ok:!0,command:"version",result:{version:el}}};if(r.length===0||r[0]==="--help"||r[0]==="-h")return{outputMode:n,human:Im,value:{schemaVersion:1,ok:!0,command:"help",result:{usage:"dyyto <command> [options]"}}};let[a,...i]=r;return a==="catalog"&&i[0]==="search"?$A(i.slice(1)):a==="catalog"&&i[0]==="show"?OA(i.slice(1)):a==="create"?Jm(i):a==="scaffold"&&i[0]==="example"?yA(i.slice(1),t):a==="retrofit"?lA(i):a==="dev"||a==="build"||a==="test"||a==="package"?dA(a,i):a==="add"&&i[0]==="package"?pA(i.slice(1)):a==="add"&&i[0]==="application"?uA(i.slice(1)):a==="add"&&i[0]==="feature"?Gm(i.slice(1),t):a==="remove"&&i[0]==="feature"?fA(i.slice(1),t):a==="plan"?mA(i):a==="upgrade"?hA(i,t):a==="apply"?il(i,t):a==="verify"?ol(i):a==="inspect"?sl(i):a==="doctor"?AA(i):a==="recover"?wA(i):a==="lifecycle"&&typeof i[0]=="string"?vA(i[0],i.slice(1)):a==="packages"&&i[0]==="switch"?bA(i.slice(1)):a==="integrations"?IA(i):a==="maintenance"?kA(i):a==="config"&&i[0]==="inspect"?_A(i.slice(1)):a==="operations"?EA(i):a==="baseline"?gA(i):a==="delivery"&&i[0]==="plan"?RA(i.slice(1)):a==="delivery"&&i[0]==="apply"?PA(i.slice(1)):a==="delivery"&&i[0]==="inspect"?NA(i.slice(1)):a==="observe"&&i[0]==="errors"?DA(i.slice(1)):a==="observe"&&i[0]==="error"?SA(i.slice(1)):a==="observe"&&i[0]==="release"&&i[1]==="register"?jA(i.slice(2)):I(`Unknown command '${a}'.`)}export{QS as runApplication};